问:
Laravel display image from path which is in database
So use is uploading a logo and it's path is stored in a database like this:

C:\xampp\htdocs\laravel\public\logo\1496912432.jpg

I am displaying the image like this:

```<code><img class="images" id="image" src="{{$business->image}}" />
</code>```

However I get this error:

```<code>Not allowed to load local resource: file:///C:/xampp/htdocs/laravel/public/logo/1496912432.jpg
</code>```

How can this problem be solved?

//edit

Controller:

```<code>public function image(Request $request) {
    if($request->hasFile('img'))
    {
        $image = Input::file('img');
        $filename = time() . '.' . $image->getClientOriginalExtension();
        $path = public_path('logo/' . $filename);
        Image::make($image->getRealPath())->fit(303, 200)->save($path);
        $file = $request->file('img');
        $session = session()->get('key');
        $update_image = Business::find($session);
        $update_image->image = $path;
        $update_image->save();
        return ['url' => url('logo/' . $filename)];
    }
</code>```

答:
Use Laravel file() to store files https://laravel.com/docs/5.4/requests#files

Store the $path to your db

```<code>$path = $request->photo->store('logo');
</code>```

the $request->photo is depending on your input file attribute name. In your case, it should be $request->img.

the above code will create a folder (if not exist), namely "logo" and store to that folder with random string file name.

Also check your configuration for file, located at /config/filesystem.php. Default is set to public

Use asset function to get the full path from public folder

```<code><img class="images" id="image" src="{{ asset($business->image }}" />
</code>```

Body:
So use is uploading a logo and it's path is stored in a database like this:

C:\xampp\htdocs\laravel\public\logo\1496912432.jpg

I am displaying the image like this:

image}}" />

However I get this error:

Not allowed to load local resource: file:///C:/xampp/htdocs/laravel/public/logo/1496912432.jpg

How can this problem be solved?

//edit

Controller:

public function image(Request $request) {
    if($request->hasFile('img'))
    {
        $image = Input::file('img');
        $filename = time() . '.' . $image->getClientOriginalExtension();
        $path = public_path('logo/' . $filename);
        Image::make($image->getRealPath())->fit(303, 200)->save($path);
        $file = $request->file('img');
        $session = session()->get('key');
        $update_image = Business::find($session);
        $update_image->image = $path;
        $update_image->save();
        return ['url' => url('logo/' . $filename)];
    }

Body:
Use Laravel file() to store files https://laravel.com/docs/5.4/requests#files

Store the $path to your db

$path = $request->photo->store('logo');

the $request->photo is depending on your input file attribute name. In your case, it should be $request->img.

the above code will create a folder (if not exist), namely "logo" and store to that folder with random string file name.

Also check your configuration for file, located at /config/filesystem.php. Default is set to public

Use asset function to get the full path from public folder

<img class="images" id="image" src="{{ asset($business->image }}" />


来源: stackexchange

问:
How can I update swift from 3.1 to 3.2, but not to 4.0
I have checked the question related to how to find the current Swift version by the command swift --version, but how can I upgrade my Swift version from 3.1 to 3.2? (because the Xcode 9 only supports Swift 4.0 & Swift 3.2)

To build successfully both in Xcode 8 & Xcode 9, it's better to upgrade Swift from 3.1 to 3.2. But how?

My target was to make sure build successfully both in Xcode 8 & Xcode 9, So that publish with Xcode 8 would be OK, and try out the feature of Xcode 9 is OK too. So I will not upgrade code to swift 4.0 yet until Xcode 9.0 official edition is published.

After my test, I can't convert my code from swift 3.1 to 3.2 by Xcode 8.3.3's 'edit->convert' function.

The reason why I try to convert the code to Swift 3.2 is that I will get error of "Module compiled with Swift 3.1 cannot be imported in Swift 4.0" if I build the code with Xcode 9.

答:
From Option Menu: Edit -> Convert -> To Current Swift Syntax

Above steps help you to convert into current swift syntax.

ContentLicense: CC BY-SA 3.0


问:
kernel-space user-space communication with netlink
My objective is to have an array or list in kernel memory at all times, so that it is always accessible from kernel-space. To do this, I am using netlink sockets as recommended here. I follow this example, which shows how to send a string. I am not sure as to how to send an array of struct or list of structs in sockets.

```<code>typedef struct {
    int fiveDollarBills;
    int denDollarBills;
} Bills;
</code>```

Is it possible to send a list or array using netlink?

答:
NetLink itself doesn't care whether the data is a string, an integer, a struct, etc. It just takes a void* and a length and copy's the data without looking at it. You can cast your struct to a void* and use sizeof to determine the length and send that data over netlink.

On the other end, you just need to get the void* and length, verify the length is what it is supposed to be, and cast the void* back to a pointer to your struct. The two important things to verify are:

Both the UserSpace and KernelSpace code agree on the memory layout of the structure. This means compiling both against the same .h and making sure that the compile options are such that memory layout and alignment are the same.

The Struct will be transferred as just a raw memory copy, theres no intelligence for fixing up pointers, so your struct can not contain any pointers, etc.

The other option is rather than sending the raw data accross, to "serialize" the data yourself by converting it to, from a string in a known format. This would allow you to handle more complex data structures at the expense of extra CPU and memory overhead

ContentLicense: CC BY-SA 2.5

Body:
My objective is to have an array or list in kernel memory at all times, so that it is always accessible from kernel-space. To do this, I am using netlink sockets as recommended here. I follow this example, which shows how to send a string. I am not sure as to how to send an array of struct or list of structs in sockets.

typedef struct {
    int fiveDollarBills;
    int denDollarBills;
} Bills;

Is it possible to send a list or array using netlink?


问:
Javascript: nice human readable join of list
Having a list (array) of tags ['tag1', 'tag2', 'tag3'] I want to generate a nice title like: Content tagged tag1, tag2 and tag3.

For the moment I have:

```<code>"Content tagged " + tags_titles.join(" and ");
</code>```

with the result:
Content tagged tag1 and tag2 and tag3

I know it's a simple question, but I am curious if there is a nice solution for this case.

答:
You could get the two last elements and join them with ' and ' and put it as last element back into the array and later join all elements with ', ' for getting a nice string.

Methods

Array#concat, joins two arrays and returns a new array

Array#splice, for getting the last two elemensts of the array

Array#join, joins an array with the given spacer.

This proposal works for any length of an array, even with one or two elements.

function nice([...array]) {
    return array.concat(array.splice(-2, 2).join(' and ')).join(', ');
}

console.log("Content tagged " + nice(['tag1']));
console.log("Content tagged " + nice(['tag1', 'tag2']));
console.log("Content tagged " + nice(['tag1', 'tag2', 'tag3']));```

Body:
Having a list (array) of tags ['tag1', 'tag2', 'tag3'] I want to generate a nice title like: Content tagged tag1, tag2 and tag3.

For the moment I have:

"Content tagged " + tags_titles.join(" and ");

with the result:
Content tagged tag1 and tag2 and tag3

I know it's a simple question, but I am curious if there is a nice solution for this case.

ContentLicense: CC BY-SA 4.0


问:
How to decide where to execute our business logic?
As we are writing our web application we come across multiple decision regarding the execution of our business logic.

Our stack include mongodb database and mongoose on top of our nodejs powered backend.

How should we decide whether to execute a specific computation in our backend code, or build a query for the database?

Simple example: we have a collection of vehicles. We want to calculate the average number of seats.

Should we pull all of the data and compute the result in the application, or should we create a query (aggregation) for the database to execute?

Pros (execute on DB)

faster in terms of network traffic for large collections

probably more efficient

Cons

coupled to the DB

harder to test

答:
I would build an abstraction into the application - so something like someBusinessLayerClass.getAverageNumberOfSeats() (or whatever the equivalent syntax in Node would be).  That can then delegate the call to the database in the production system, while it can be mocked/stubbed for testing.  If you want to test it end-to-end, use an integration test.

This particular requirement, in my view, comes down to querying data - and one could argue that it's fine to give that responsibility to the database.  However, if you're implementing logic for an actual business rule (lets say you need to validate that a particular vehicle can be rented to a particular driver, based on licence category and accident history), then it should live in the business logic layer.


问:
While loop is causing items to disappear
I am working on an Android project using c# and xamarin (Visual Studio). My idea is to mute the phone whenever it connects to a wifi. So I have one textview and one button and those are my codes till now:

```<code>AudioManager audioManager = (AudioManager)GetSystemService(Context.AudioService);
ConnectivityManager connManager = (ConnectivityManager)GetSystemService(Context.ConnectivityService);
        NetworkInfo mWifi = connManager.GetNetworkInfo(ConnectivityType.Wifi);
            while (mWifi.IsConnectedOrConnecting)
        {
            audioManager.RingerMode = RingerMode.Silent;
        }
</code>```

My codes are working great but with some bugs: When the phone is connected to wifi, it mute but also all my items in my layout are disappearing. And when the phone is not connected to wifi, it doesn't mute but all my items are still in their place. Why is this happening ?
In addition, I want the program to run in the background so that whenever the phone is connected to a wifi, it mute. To do that I have created this service class but it doesn't seems to work:

```<code>  [Service]
public class DemoService : Service
{
    public override IBinder OnBind(Intent intent)
    {
        throw new NotImplementedException();
    }

    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        var t = new Thread(() =>
        {
            Log.Debug("DemoService", "Doing work");
            Thread.Sleep(5000);
            Log.Debug("DemoService", "Work complete");
            StopSelf();
        }
        );
        t.Start();
        return StartCommandResult.Sticky;
    }
</code>```

Any help would be greatly appreciated!
Thank you

答:
You can use BroadcastReceiver to receive  action: android.net.wifi.STATE_CHANGE to detect the connecting or connected.

WifiReceiver.cs:

```<code>[BroadcastReceiver(Enabled =true)]
[IntentFilter( new [] { "android.net.wifi.STATE_CHANGE"})]
public class WifiReceiver : BroadcastReceiver
{

    public override void OnReceive(Context context, Intent intent)
    {
       NetworkInfo info=intent.GetParcelableExtra(WifiManager.ExtraNetworkInfo) as NetworkInfo;
        if (info != null && info.IsConnected)
        {

            ConnectivityManager manager =(ConnectivityManager) context.GetSystemService(Context.ConnectivityService);
            NetworkInfo netInfo = (NetworkInfo)manager.GetNetworkInfo(ConnectivityType.Wifi);
            AudioManager audioManager = (AudioManager)context.GetSystemService(Context.AudioService);

            if (netInfo.IsConnectedOrConnecting)
            {
                Toast.MakeText(context, "Wifi is connected", ToastLength.Short).Show();
                audioManager.RingerMode = RingerMode.Silent;
            }
            else
            {
                audioManager.RingerMode = RingerMode.Normal;
            }

        }
    }
}
</code>```

Body:
I am working on an Android project using c# and xamarin (Visual Studio). My idea is to mute the phone whenever it connects to a wifi. So I have one textview and one button and those are my codes till now:

AudioManager audioManager = (AudioManager)GetSystemService(Context.AudioService);
ConnectivityManager connManager = (ConnectivityManager)GetSystemService(Context.ConnectivityService);
        NetworkInfo mWifi = connManager.GetNetworkInfo(ConnectivityType.Wifi);
            while (mWifi.IsConnectedOrConnecting)
        {
            audioManager.RingerMode = RingerMode.Silent;
        }

My codes are working great but with some bugs: When the phone is connected to wifi, it mute but also all my items in my layout are disappearing. And when the phone is not connected to wifi, it doesn't mute but all my items are still in their place. Why is this happening ?
In addition, I want the program to run in the background so that whenever the phone is connected to a wifi, it mute. To do that I have created this service class but it doesn't seems to work:

  [Service]
public class DemoService : Service
{
    public override IBinder OnBind(Intent intent)
    {
        throw new NotImplementedException();
    }

    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        var t = new Thread(() =>
        {
            Log.Debug("DemoService", "Doing work");
            Thread.Sleep(5000);
            Log.Debug("DemoService", "Work complete");
            StopSelf();
        }
        );
        t.Start();
        return StartCommandResult.Sticky;
    }

Any help would be greatly appreciated!
Thank you

Body:
You can use BroadcastReceiver to receive  action: android.net.wifi.STATE_CHANGE to detect the connecting or connected.

WifiReceiver.cs:

[BroadcastReceiver(Enabled =true)]
[IntentFilter( new [] { "android.net.wifi.STATE_CHANGE"})]
public class WifiReceiver : BroadcastReceiver
{

    public override void OnReceive(Context context, Intent intent)
    {
       NetworkInfo info=intent.GetParcelableExtra(WifiManager.ExtraNetworkInfo) as NetworkInfo;
        if (info != null && info.IsConnected)
        {

            ConnectivityManager manager =(ConnectivityManager) context.GetSystemService(Context.ConnectivityService);
            NetworkInfo netInfo = (NetworkInfo)manager.GetNetworkInfo(ConnectivityType.Wifi);
            AudioManager audioManager = (AudioManager)context.GetSystemService(Context.AudioService);

            if (netInfo.IsConnectedOrConnecting)
            {
                Toast.MakeText(context, "Wifi is connected", ToastLength.Short).Show();
                audioManager.RingerMode = RingerMode.Silent;
            }
            else
            {
                audioManager.RingerMode = RingerMode.Normal;
            }

        }
    }
}


问:
IntelliJ IDEA Debugger does not show null element in a list
I have a list in which the first element is null. IntelliJ debugger correctly shows the list size as 5, but it shows only 1,2,3,4 elements. It would be nice to see that element with the index 0 is null (it took me some time to figure out my problems while debugging because it did not show that). Is it possible to force IntelliJ to show this?

Here is a screenshot, where the size is 5 and the elements shown are only 1-4 because the first element is null:

答: Null array elements are hidden by default, you can disable it here:


问:
Create a master detail page in apex with two details
I just wanna know how to create a master detail with two editable details or master detail with a sub detail page in apex, i cant figure it out.

Please help me.

答:
Create one master Interactive grid.
Create another Interactive grid and there is an option under Master Detail called master region and choose the first grid you created.
Then choose the column that has the foreign key back to the first grid. There is a option on the column under master detail called Master column and choose the column in the first grid the foreign links to.</p>


问:
C# - Lambda vs nested loops
Is is possible to convert following into a simpler more readable linq or lambda expression?

```<code>Dictionary<int, int> selectedProgramTierCombo = new Dictionary<int,int>();
foreach (int mainTierID in doc.TierID)
{
    foreach (PriceProgram priceProgram in doc.CommitmentProgram.PricingPrograms)
    {
        foreach (ProgramTier progTier in priceProgram.Tiers)
        {
            if (progTier.TierID == mainTierID )
            {
                selectedProgramTierCombo.Add(priceProgram.ProgramID, progTier.TierID);
            }
        }
    }
}
</code>```

Essentially doc.TierID is a an array (int[]) of TierIDs that client is currently on. Also the doc object contains a CommitmentProgram object which contains a list of PriceProgram. So, All I am trying to do is get the PriceProgram.ProgramID for each TierID.

The relationship between PriceProgram and TierID is that each PriceProgram has a list of tiers (ProgramTier object) and ProgramTier oject contains the corresponding TierID that we already have.

Let me know if my explaination doesn't make sense and I'll try to elaborate.

Edit

Jon,
I am getting The name 'priceProgram' does not exist in the current context error when I try to compile what you have suggested:

```<code>Dictionary<int, int> selectedProgramTierCombo =
    (from mainTierID in doc.TierID
     from priceProgram in doc.CommitmentProgram.PricingPrograms
     **join progTier in priceProgram.Tiers on mainTierID equals progTier.TierID**
     select new { priceProgram.ProgramID, progTier.TierID })
    .ToDictionary(x => x.ProgramID, x => x.TierID);
</code>```

答:
Jon's answer is the right idea, just needs to be rearranged in order to compile. Here are two options. </p>

```<code>var dict = (from mainTierID in doc.TierID
            join f in
                (from priceProgram in doc.CommitmentProgram.PricingPrograms
                    from progTier in priceProgram.Tiers
                    select new { priceProgram.ProgramID, progTier.TierID })
                on mainTierID equals f.TierID
            select f).ToDictionary(f => f.ProgramID, f => f.TierID);

var dict2 = (from priceProgram in doc.CommitmentProgram.PricingPrograms
                from progTier in priceProgram.Tiers
                join mainTierID in doc.TierID on progTier.TierID equals mainTierID
                select new { priceProgram.ProgramID, progTier.TierID })
            .ToDictionary(x => x.ProgramID, x => x.TierID);
</code>```

Title: C# - Lambda vs nested loops

Body:
Is is possible to convert following into a simpler more readable linq or lambda expression?

Dictionary<int, int> selectedProgramTierCombo = new Dictionary<int,int>();
foreach (int mainTierID in doc.TierID)
{
    foreach (PriceProgram priceProgram in doc.CommitmentProgram.PricingPrograms)
    {
        foreach (ProgramTier progTier in priceProgram.Tiers)
        {
            if (progTier.TierID == mainTierID )
            {
                selectedProgramTierCombo.Add(priceProgram.ProgramID, progTier.TierID);
            }
        }
    }
}

Essentially doc.TierID is a an array (int[]) of TierIDs that client is currently on. Also the doc object contains a CommitmentProgram object which contains a list of PriceProgram. So, All I am trying to do is get the PriceProgram.ProgramID for each TierID.

The relationship between PriceProgram and TierID is that each PriceProgram has a list of tiers (ProgramTier object) and ProgramTier oject contains the corresponding TierID that we already have.

Let me know if my explaination doesn't make sense and I'll try to elaborate.

Edit

Jon,
I am getting The name 'priceProgram' does not exist in the current context error when I try to compile what you have suggested:

Dictionary<int, int> selectedProgramTierCombo =
    (from mainTierID in doc.TierID
     from priceProgram in doc.CommitmentProgram.PricingPrograms
     **join progTier in priceProgram.Tiers on mainTierID equals progTier.TierID**
     select new { priceProgram.ProgramID, progTier.TierID })
    .ToDictionary(x => x.ProgramID, x => x.TierID);

Body:
Jon's answer is the right idea, just needs to be rearranged in order to compile. Here are two options.

var dict = (from mainTierID in doc.TierID
            join f in
                (from priceProgram in doc.CommitmentProgram.PricingPrograms
                    from progTier in priceProgram.Tiers
                    select new { priceProgram.ProgramID, progTier.TierID })
                on mainTierID equals f.TierID
            select f).ToDictionary(f => f.ProgramID, f => f.TierID);

var dict2 = (from priceProgram in doc.CommitmentProgram.PricingPrograms
                from progTier in priceProgram.Tiers
                join mainTierID in doc.TierID on progTier.TierID equals mainTierID
                select new { priceProgram.ProgramID, progTier.TierID })
            .ToDictionary(x => x.ProgramID, x => x.TierID);


问:
Set AUTO_INCREMENT in all tables within a MySQL DB to the largest inserted increment value
Is it possible to set AUTO_INCREMENT value for all tables within a database to the latest insert value?

UPDATE
For example if my table had 1000 records with increment values from 1..1000 and I have deleted last 900 records the last increment value in the field would be 100. I would like to set the AUTO_INCREMENT to the 101. And this for all tables within DB.

答:
Is it possible to set AUTO_INCREMENT value for all tables within a database to the latest insert value?

The value of AUTO_INCREMENT is actually the next available value, i.e. maximum value plus 1.

If your tables use the InnoDB engine then all you have to do is to restart the MySQL server (not the computer but just the MySQL service).

The documentation explains how the value of AUTO_INCREMENT it stored (in memory, not on disc) and restored when the service starts:

To initialize an auto-increment counter after a server restart, InnoDB executes the equivalent of the following statement on the first insert into a table containing an AUTO_INCREMENT column.

```<code>SELECT MAX(ai_col) FROM table_name FOR UPDATE;
</code>```

InnoDB increments the value retrieved by the statement and assigns it to the column and to the auto-increment counter for the table. By default, the value is incremented by 1.

Body:
Is it possible to set AUTO_INCREMENT value for all tables within a database to the latest insert value?

The value of AUTO_INCREMENT is actually the next available value, i.e. maximum value plus 1.

If your tables use the InnoDB engine then all you have to do is to restart the MySQL server (not the computer but just the MySQL service).

The documentation explains how the value of AUTO_INCREMENT it stored (in memory, not on disc) and restored when the service starts:

To initialize an auto-increment counter after a server restart, InnoDB executes the equivalent of the following statement on the first insert into a table containing an AUTO_INCREMENT column.

SELECT MAX(ai_col) FROM table_name FOR UPDATE;

InnoDB increments the value retrieved by the statement and assigns it to the column and to the auto-increment counter for the table. By default, the value is incremented by 1.


问:
What is the best way to write a contract for CSS usage in Web Development?
Our Dev team had been developing enterprise web page more than 2 years ago.  We are curious to know what is the best way to write a contract for CSS usage.  For example, if we have a COMP, how we agree on a contract so our developers and our designers agree and we don't have to go back.

Is there a tool that is available for this type of technical writing?

What is the threadhold of information put in the CSS versus on the HTML page?  Some of our designers thing that some things should go directly into the HTML page.  The general opinion is that everything that is style should go in a CSS and all else in the html.

Thanks for your input.

答:
If I have style that is for a one time, single use page, I will consider putting it in the header of that page, as my templating system allows for that.

However you should never use inline styles.  Even if you do a page with a  block in it for a one off.  That way should you find that you "one time" item becomes a site wide style, you can simply move the CSS into the external CSS file and not edit the content.

OwnerDisplayName: Geo

OwnerDisplayName: MrChrister


问:
Smarty getting substring of a var with strpos as start and strlen as end
I am having issue formatting variables in smarty.  I was wondering what is the best way to do it.  Basically i have a string "ABC | DEFGH" i want smarty to get the substring of "DEFGH"  How would i go about doing this?

```<code>{$var|substr:strpos:"|":strlen}
</code>```

doesn't work

答:
Just solved this without setting var back in PHP, and by using the built-in function wrappers.

Assuming that: $var = "ABC|DEFGH";

```<code>{assign var="bar_at" value=$var|strpos:"|"}
<li>{$var}</li>
<li>{$var|substr:0:$bar_at}</li>
<li>{$var|substr:$bar_at+1}</li>
</code>```

This will print:

ABC|DEFGH

ABC

DEFGH

Body:
I am having issue formatting variables in smarty.  I was wondering what is the best way to do it.  Basically i have a string "ABC | DEFGH" i want smarty to get the substring of "DEFGH"  How would i go about doing this?

{$var|substr:strpos:"|":strlen}

doesn't work

Body:
Just solved this without setting var back in PHP, and by using the built-in function wrappers.

Assuming that: $var = "ABC|DEFGH";

{assign var="bar_at" value=$var|strpos:"|"}
<li>{$var}</li>
<li>{$var|substr:0:$bar_at}</li>
<li>{$var|substr:$bar_at+1}</li>

This will print:

ABC|DEFGH

ABC

DEFGH


问:
How to speed up the following WPF UI code
I am trying to understand why my following WPF C# code, that I use to display a kind of grid view of my input information, is so slow, and especially how to improve it in order to speed up the controls rendering.

I have the following input, that can vary according to the user selection:

```<code>public class Field
{
    public string Key;
    public Tuple<string, bool> Value;
}

var fields = new List<Field>();
// fill fields...
</code>```

And for each field I create a control that is inserted into a VirtualizingStackPanel:

```<code>StackPanelFields.Children.Clear();
foreach (var f in fields)
    StackPanelFields.Children.Add(GetFieldControl(f.Key, f.Value));

private Grid GetFieldControl(string name, Tuple<string, bool> value)
{
    Debug.Assert(!String.IsNullOrWhiteSpace(name));
    Debug.Assert(value != null);

    // two-column grid
    var grid = new Grid();
    grid.ColumnDefinitions.Add(new ColumnDefinition());
    grid.ColumnDefinitions.Add(new ColumnDefinition());

    var color = value.Item2 ? Brushes.Black : Brushes.Red;

    var nameTextblock = new TextBlock { Text = name, Margin = new Thickness(5, 0, 0, 5), Foreground = color };
    grid.Children.Add(nameTextblock);

    // value
    var valueTextBox = new TextBox
    {
        Text = value.Item1,
        Foreground = color,
        TextWrapping = TextWrapping.Wrap,
        IsReadOnly = true,
        BorderThickness = new Thickness(0)
    };

    Grid.SetColumn(valueTextBox, 1);
    grid.Children.Add(valueTextBox);

    return grid;
}
</code>```

The number of fields is between 1000-2000 on average. On my machine filling up the VirtualizingStackPanel can require even more than 1 second; I haven't measured this time, but it is clear that it's very slow for the user.

答:
I have no problems presenting 1.000.000 items (and even more) and it will take more time to create the data collection then presenting it.

Model class

```<code>public class Field : ObservableObject
{
    private string _name;
    private string _value;
    private bool _flag;

    public string Name { get => _name; set => Set(ref _name, value); }
    public string Value { get => _value; set => Set(ref _value, value); }
    public bool Flag { get => _flag; set => Set(ref _flag, value); }
}
</code>```

MainViewModel

```<code>public class MainViewModel : ViewModelBase
{
    private int _fieldcount;
    private ObservableCollection<Models.Field> _fields;

    public MainViewModel()
    {
        if (IsInDesignMode)
        {
            _fieldcount = 100;
        }
        else
        {
            _fieldcount = 1000000;
        }

        Initialize();

    }

    private void Initialize()
    {
        var fieldquery = Enumerable.Range(1, _fieldcount).Select(e => new Models.Field { Name = $"Field {e}", Value = $"Value {e}", Flag = false, });
        Fields = new ObservableCollection<Models.Field>(fieldquery);
    }

    public ObservableCollection<Models.Field> Fields { get => _fields; set => Set(ref _fields, value); }

}
</code>```

The View

```<code><Window x:Class="WpfApp6.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:models="clr-namespace:WpfApp6.Models"
        xmlns:local="clr-namespace:WpfApp6"
        mc:Ignorable="d"
        DataContext="{Binding Source={StaticResource Locator}, Path=Main}"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ItemsControl VirtualizingStackPanel.IsVirtualizing="True"
                      ScrollViewer.CanContentScroll="True"
                      ItemsSource="{Binding Path=Fields}">
            <ItemsControl.ItemTemplate>
                <DataTemplate DataType="{x:Type models:Field}">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>
                        <TextBlock Grid.Column="0" Text="{Binding Name}" />
                        <TextBox Grid.Column="1" Text="{Binding Value}" IsReadOnly="True"/>
                    </Grid>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <VirtualizingStackPanel />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.Template>
                <ControlTemplate>
                    <Border BorderThickness="{TemplateBinding Border.BorderThickness}"
                            Padding="{TemplateBinding Control.Padding}"
                            BorderBrush="{TemplateBinding Border.BorderBrush}"
                            Background="{TemplateBinding Panel.Background}"
                            SnapsToDevicePixels="True">
                        <ScrollViewer Padding="{TemplateBinding Control.Padding}" Focusable="False">
                            <ItemsPresenter SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
                        </ScrollViewer>
                    </Border>
                </ControlTemplate>
            </ItemsControl.Template>
        </ItemsControl>
    </Grid>
</Window>
</code>```

The whole project is here

Body:
I am trying to understand why my following WPF C# code, that I use to display a kind of grid view of my input information, is so slow, and especially how to improve it in order to speed up the controls rendering.

I have the following input, that can vary according to the user selection:

public class Field
{
    public string Key;
    public Tuple<string, bool> Value;
}

var fields = new List<Field>();
// fill fields...

And for each field I create a control that is inserted into a VirtualizingStackPanel:

StackPanelFields.Children.Clear();
foreach (var f in fields)
    StackPanelFields.Children.Add(GetFieldControl(f.Key, f.Value));

private Grid GetFieldControl(string name, Tuple<string, bool> value)
{
    Debug.Assert(!String.IsNullOrWhiteSpace(name));
    Debug.Assert(value != null);

    // two-column grid
    var grid = new Grid();
    grid.ColumnDefinitions.Add(new ColumnDefinition());
    grid.ColumnDefinitions.Add(new ColumnDefinition());

    var color = value.Item2 ? Brushes.Black : Brushes.Red;

    var nameTextblock = new TextBlock { Text = name, Margin = new Thickness(5, 0, 0, 5), Foreground = color };
    grid.Children.Add(nameTextblock);

    // value
    var valueTextBox = new TextBox
    {
        Text = value.Item1,
        Foreground = color,
        TextWrapping = TextWrapping.Wrap,
        IsReadOnly = true,
        BorderThickness = new Thickness(0)
    };

    Grid.SetColumn(valueTextBox, 1);
    grid.Children.Add(valueTextBox);

    return grid;
}

The number of fields is between 1000-2000 on average. On my machine filling up the VirtualizingStackPanel can require even more than 1 second; I haven't measured this time, but it is clear that it's very slow for the user.

Body:
I have no problems presenting 1.000.000 items (and even more) and it will take more time to create the data collection then presenting it.

Model class

public class Field : ObservableObject
{
    private string _name;
    private string _value;
    private bool _flag;

    public string Name { get => _name; set => Set(ref _name, value); }
    public string Value { get => _value; set => Set(ref _value, value); }
    public bool Flag { get => _flag; set => Set(ref _flag, value); }
}

MainViewModel

public class MainViewModel : ViewModelBase
{
    private int _fieldcount;
    private ObservableCollection<Models.Field> _fields;

    public MainViewModel()
    {
        if (IsInDesignMode)
        {
            _fieldcount = 100;
        }
        else
        {
            _fieldcount = 1000000;
        }

        Initialize();

    }

    private void Initialize()
    {
        var fieldquery = Enumerable.Range(1, _fieldcount).Select(e => new Models.Field { Name = $"Field {e}", Value = $"Value {e}", Flag = false, });
        Fields = new ObservableCollection<Models.Field>(fieldquery);
    }

    public ObservableCollection<Models.Field> Fields { get => _fields; set => Set(ref _fields, value); }

}

The View

<Window x:Class="WpfApp6.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:models="clr-namespace:WpfApp6.Models"
        xmlns:local="clr-namespace:WpfApp6"
        mc:Ignorable="d"
        DataContext="{Binding Source={StaticResource Locator}, Path=Main}"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ItemsControl VirtualizingStackPanel.IsVirtualizing="True"
                      ScrollViewer.CanContentScroll="True"
                      ItemsSource="{Binding Path=Fields}">
            <ItemsControl.ItemTemplate>
                <DataTemplate DataType="{x:Type models:Field}">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>
                        <TextBlock Grid.Column="0" Text="{Binding Name}" />
                        <TextBox Grid.Column="1" Text="{Binding Value}" IsReadOnly="True"/>
                    </Grid>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <VirtualizingStackPanel />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.Template>
                <ControlTemplate>
                    <Border BorderThickness="{TemplateBinding Border.BorderThickness}"
                            Padding="{TemplateBinding Control.Padding}"
                            BorderBrush="{TemplateBinding Border.BorderBrush}"
                            Background="{TemplateBinding Panel.Background}"
                            SnapsToDevicePixels="True">
                        <ScrollViewer Padding="{TemplateBinding Control.Padding}" Focusable="False">
                            <ItemsPresenter SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
                        </ScrollViewer>
                    </Border>
                </ControlTemplate>
            </ItemsControl.Template>
        </ItemsControl>
    </Grid>
</Window>

The whole project is here


问:
How to inject a bean to another bean declaration in another class?
```<code>file-a.java

package com.abcd.common;
import com.xyz.HCStrategy;
import com.xyz.DHC;

@Configuration
public class HCConfig {
    @Bean
    public HCStrategy dHC() {
        return new DHC();
    }
}

file-b.java

package com.abcd.app;
public class SCConfig {
   @Bean
   public meow() {
     //I want to call dHC here
   }

}
</code>```

One way is to create an autowire for HCConfig and then use the object to call dHC. However, I want to directly auto wire dHC from file-b and use it without creating an object of HCConfig. I can autowire HCStrategy, but it does not work since it is an import and not my own class.

答:
I'm not 100% certain what it is you want to achieve, but it sounds like you just need HCStrategy whithin SCConfig. In your code SCConfig isn't actually a Spring Configuration because @Configuration is missing. Unless of course you don't use component scanning here but an import. If HCConfig is importet, HCStrategy is in your application context thus you can autowire it like in the example below in SCConfig.</p>

```<code>file-a.java

package com.abcd.common;
import com.xyz.HCStrategy;
import com.xyz.DHC;

@Configuration
public class HCConfig {

    @Bean
    public HCStrategy dHC() {
        return new DHC();
    }
}

file-b.java

package com.abcd.app;

@Configuration
public class SCConfig {

    @Bean
    public meow(HCStrategy hcsStrategy) {
      ...
   }
}
</code>```

Body:
file-a.java

package com.abcd.common;
import com.xyz.HCStrategy;
import com.xyz.DHC;

@Configuration
public class HCConfig {
    @Bean
    public HCStrategy dHC() {
        return new DHC();
    }
}

file-b.java

package com.abcd.app;
public class SCConfig {
   @Bean
   public meow() {
     //I want to call dHC here
   }

}

One way is to create an autowire for HCConfig and then use the object to call dHC. However, I want to directly auto wire dHC from file-b and use it without creating an object of HCConfig. I can autowire HCStrategy, but it does not work since it is an import and not my own class.

Body:
I'm not 100% certain what it is you want to achieve, but it sounds like you just need HCStrategy whithin SCConfig. In your code SCConfig isn't actually a Spring Configuration because @Configuration is missing. Unless of course you don't use component scanning here but an import. If HCConfig is importet, HCStrategy is in your application context thus you can autowire it like in the example below in SCConfig.

file-a.java

package com.abcd.common;
import com.xyz.HCStrategy;
import com.xyz.DHC;

@Configuration
public class HCConfig {

    @Bean
    public HCStrategy dHC() {
        return new DHC();
    }
}

file-b.java

package com.abcd.app;

@Configuration
public class SCConfig {

    @Bean
    public meow(HCStrategy hcsStrategy) {
      ...
   }
}


问:
JQGrid, Telerik, DataTables etc. Which one is good?
Telerik

http://www.telerik.com/products/aspnet-mvc.aspx

JqGrid
http://www.trirand.com/blog/

DataTables
http://www.datatables.net

Any other free grid which you think is better.

So which one is easy, powerful to use. ASP.NET MVC.

答:
You'd probably find this interesting: jQuery Grid Recommendations

We've been developing an app for the past few months using jqGrid and it is great.

You'll see on StackOverflow there are over 1000 JqGrid tagged questions - so this site alone is a great resource available to you when using JqGrid.


问:
Word Macro to insert footer
I'm looking to run a Word macro which inserts a footer with filename and date and page number.

The following macro inserts file name, date and page number in the body of the document. How to rewrite for it to insert this in the footer? Greatly appreciate your help :)

'AddFooter Macro

```<code>Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
    "FILENAME  \p ", PreserveFormatting:=True
Selection.HomeKey Unit:=wdLine
Selection.TypeParagraph
Selection.MoveUp Unit:=wdLine, Count:=1
Selection.TypeText Text:=vbTab
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
    "PAGE  \* Arabic ", PreserveFormatting:=True
Selection.TypeText Text:=vbTab
Selection.InsertDateTime DateTimeFormat:="M/d/yyyy H:mm", InsertAsField:= _
    True, DateLanguage:=wdEnglishUS, CalendarType:=wdCalendarWestern, _
    InsertAsFullWidth:=False
Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
Selection.Font.Size = 8
Selection.MoveDown Unit:=wdLine, Count:=1
Selection.HomeKey Unit:=wdLine, Extend:=wdExtend
Selection.Font.Size = 8
</code>```

End Sub`

答:
This is how I did it:</p>

```<code>Sub AddFooter()

Dim Filename As String
Dim Sec As Section

Filename = ThisDocument.FullName

For Each Sec In ActiveDocument.Sections
    With Sec.Footers(wdHeaderFooterPrimary)
        .Range.InsertDateTime DateTimeFormat:="M/d/yyyy H:mm", InsertAsField:= _
            True, DateLanguage:=wdEnglishUS, CalendarType:=wdCalendarWestern
        .Range.Text = .Range.Text & Filename
        .PageNumbers.Add
    End With
Next Sec

End Sub
</code>```

Title: Word Macro to insert footer

Body:
I'm looking to run a Word macro which inserts a footer with filename and date and page number.

The following macro inserts file name, date and page number in the body of the document. How to rewrite for it to insert this in the footer? Greatly appreciate your help :)

'AddFooter Macro

Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
    "FILENAME  \p ", PreserveFormatting:=True
Selection.HomeKey Unit:=wdLine
Selection.TypeParagraph
Selection.MoveUp Unit:=wdLine, Count:=1
Selection.TypeText Text:=vbTab
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
    "PAGE  \* Arabic ", PreserveFormatting:=True
Selection.TypeText Text:=vbTab
Selection.InsertDateTime DateTimeFormat:="M/d/yyyy H:mm", InsertAsField:= _
    True, DateLanguage:=wdEnglishUS, CalendarType:=wdCalendarWestern, _
    InsertAsFullWidth:=False
Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
Selection.Font.Size = 8
Selection.MoveDown Unit:=wdLine, Count:=1
Selection.HomeKey Unit:=wdLine, Extend:=wdExtend
Selection.Font.Size = 8

End Sub`

Body:
This is how I did it:

Sub AddFooter()

Dim Filename As String
Dim Sec As Section

Filename = ThisDocument.FullName

For Each Sec In ActiveDocument.Sections
    With Sec.Footers(wdHeaderFooterPrimary)
        .Range.InsertDateTime DateTimeFormat:="M/d/yyyy H:mm", InsertAsField:= _
            True, DateLanguage:=wdEnglishUS, CalendarType:=wdCalendarWestern
        .Range.Text = .Range.Text & Filename
        .PageNumbers.Add
    End With
Next Sec

End Sub


问:
Get unique list of top level element names in XML column of SQL table
I have a query which returns a column of XML values, for simplicity let's say this query is:

```<code>select top 1000 XmlColumn from MyTable
</code>```

This returns a column with 1000 values, these contain XML.

I would like to extract the element name from only the top level element. So then I can transform these into a table of distinct element names.

How can I do this in one query?

答:
```<code> select  XmlColumn.value('local-name(/*[1])','varchar(100)')
 from MyTable
</code>```

Body:
I have a query which returns a column of XML values, for simplicity let's say this query is:

select top 1000 XmlColumn from MyTable

This returns a column with 1000 values, these contain XML.

I would like to extract the element name from only the top level element. So then I can transform these into a table of distinct element names.

How can I do this in one query?


问:
Packaging java project
I have one java project with two class. One of them is with main method. I also have two files one of them is a.properties and second one i b.xls. The way I want to export this project is in one executable jar but withour these two files(a.properties and b.xls) being compressed inside this executable jar. The reason for this is, user who run this project should able to change the properties file(a.properties) and also excel file(b.xls). I also want to include the libraries I have used for this project.

I am using Eclipse helios and jdk 1.6.

I really appreciate if somebody will provide me the steps for this. I already tried the Export option with executable jar but it compress everything including two files.

Thanks

答:
Packaging is usually done by an ANT script. Inside of Eclipse you can simplify such a scribt by using the compiled class files generated by Eclipse:

Save the following file as build.xml, adapt your filenames and run it as Ant Build.
It will a file named package.zip which includes the created jar and (outside of the jar) your two additional files.

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project default="pack">
    <target name="pack">
        <jar destfile="myprog.jar">
            <manifest>
                <attribute name="Main-Class" value="com.example.myapp.Main" />
                <attribute name="Class-Path" value="."/>
            </manifest>
            <fileset dir="bin" defaultexcludes="true">
                <include name="**/*.class" />
            </fileset>
        </jar>
        <zip destfile="package.zip">
            <fileset dir=".">
                <include name="myprog.jar" />
                <include name="myprog.properties" />
                <include name="myprog.xls" />
            </fileset>
        </zip>
    </target>
</project>
</code>```

Title: Packaging java project

Body:
Packaging is usually done by an ANT script. Inside of Eclipse you can simplify such a scribt by using the compiled class files generated by Eclipse:

Save the following file as build.xml, adapt your filenames and run it as Ant Build.
It will a file named package.zip which includes the created jar and (outside of the jar) your two additional files.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project default="pack">
    <target name="pack">
        <jar destfile="myprog.jar">
            <manifest>
                <attribute name="Main-Class" value="com.example.myapp.Main" />
                <attribute name="Class-Path" value="."/>
            </manifest>
            <fileset dir="bin" defaultexcludes="true">
                <include name="**/*.class" />
            </fileset>
        </jar>
        <zip destfile="package.zip">
            <fileset dir=".">
                <include name="myprog.jar" />
                <include name="myprog.properties" />
                <include name="myprog.xls" />
            </fileset>
        </zip>
    </target>
</project>


问:
Why doesn't empty() work on input in search bar?
When clicking theinviteButton, the input search bar should clear out, but it doesn't work with my current code.

Am I targeting the element incorrectly?

 $("#inviteButton").click(function(){
  var userName = $("#searchUser").val();
  if (userName.trim() != "") {
    if (userName == myUserName) {
    $("#connectToBox").append("You can't invite yourself");
    $("#searchUser").empty(); // Doesn't work
   } else {
    socket.emit("checkUserConnect", userName, function(data){
     if (data.result === undefined) {
      console.log("No name");
      $("#connectToBox").append("User does not exist");
      $("#searchUser").empty(); // Doesn't work
     } else {
      console.log("name exists");
      $("#searchUser").empty(); // Doesn't work
      $("#connectToBox").append("Invite send");
      UserID = data.result.id;
      socket.emit("connectToUser", myUserName, UserID, currentConversation);
     }
     });
   }
  }
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="connectToBox">
    <label for="search-2">Type in username</label>
    <input type="search" name="search-2" id="searchUser" value="">
    Connect
   </div></code>```

答:
To empty an input field you would normally use:

$('#searchUser').val('')

Empty is used to clear away child nodes from elements like divs or p tags, but not for inputs.

Reason for that is that the text within an input is not represented as a child node of the element and instead stored on an html attribute of the input tag. Hence .empty() does not work for clearing the value.

Body:
When clicking theinviteButton, the input search bar should clear out, but it doesn't work with my current code.

Am I targeting the element incorrectly?

 $("#inviteButton").click(function(){
  var userName = $("#searchUser").val();
  if (userName.trim() != "") {
    if (userName == myUserName) {
    $("#connectToBox").append("You can't invite yourself");
    $("#searchUser").empty(); // Doesn't work
   } else {
    socket.emit("checkUserConnect", userName, function(data){
     if (data.result === undefined) {
      console.log("No name");
      $("#connectToBox").append("User does not exist");
      $("#searchUser").empty(); // Doesn't work
     } else {
      console.log("name exists");
      $("#searchUser").empty(); // Doesn't work
      $("#connectToBox").append("Invite send");
      UserID = data.result.id;
      socket.emit("connectToUser", myUserName, UserID, currentConversation);
     }
     });
   }
  }
 });

    Type in username
    <input type="search" name="search-2" id="searchUser" value="">
    Connect


问:
How to store variable from option value to controller and save it in database with Laravel?
I'm trying to save variables from my view to controller and then save it in databases but im getting MethodNotAllowedHttpException.

Here are my view

```<code><form method="POST" action="{{ route('absensi.store') }}">

      <div class="form-group">
        <label name="nim"><h3>NIM :</h3></label>
        <select name ="mahasiswasn" class="selectpicker" data-live-search="true" data-width="500px" title="Choose the Student Number">
        @foreach($nim as $nm)
          <option value="{{ $nm->nim }}">{{ $nm->nim}}</option>
        @endforeach
      </select>
      </div>

      <div class="form-group">
        <label name="matkul"><h3> MK :</h3></label>
        <select name ="matkulsn" class="selectpicker" data-live-search="true" data-width="500px" title="Choose the subject">
        @foreach($matkul as $mkl)
          <option value="{{ $mkl->nama }}">{{ $mkl->nama}}</option>
        @endforeach
      </select>
      </div>

      <div class="form-group">
        <label name="hari">Hari :</label>
        <input id="hari" name="hari" class="form-control">
      </div>

      <div class="form-group">
        <label name="status">Status :</label>
        <input id="status" name="status" class="form-control">
      </div>

      <input type="submit" value="Add Absensi " class="btn btn-success btn-lg btn-block">
      <input type="hidden" name="_token" value="{{ Session::token() }}">

    </form>
</code>```

My Controller (AbsensiController)

```<code>public function store(Request $request)
    {
           $this->validate($request,array(
                'nim' =>'required',
                'matkul' =>'required',
                'hari' =>'required',
                'status' =>'required'
                ));

            //store in database
            $post = new PostAbsensi;

            $post->nim = $request->get('mahasiswasn');
            $post->mk = $request->get('matkulsn');
            $post->hari = $request->get('hari');
            $post->status = $request->get('status');

            $post->save();

            Session::flash('success','data successfully saved!');

            return redirect()->route('absensi.show', $post->id);
    }
</code>```

My Routes :

```<code>Route::resource('absensi','AbsensiController');
</code>```

Please Help, thank you for your attention.

Edit :

Here are my other view(IndexAbsensi)

```<code><form method="POST" action="{{ url('absensi.create') }}">
                      <input type="submit" value=" + Tambah Absensi " class="btn btn-success btn-lg btn-block">
                      <input type="hidden" name="_token" value="{{ csrf_token() }}">
  </form>
</code>```

so my thought is that when i press the button it will go to the AbsensiController@create and then return my form view, however im also getting Methodnotallowedhttpexception with this.

答:
@Ahmad you are wrong store method uses post route. see https://laravel.com/docs/5.4/controllers#restful-partial-resource-routes

@Riki Every thing looks fine in code maybe you are overwriting route or naem of route or something like this.
can you run php artisan route:list by this you can see which method is for this route.

or you can use <form method="POST" action="{{ url('absensi') }}">

and in controller you also can use

```<code>$this->validate($request->all(),array(
            'nim' =>'required',
            'matkul' =>'required',
            'hari' =>'required',
            'status' =>'required'
            ));
</code>```

Body:
I'm trying to save variables from my view to controller and then save it in databases but im getting MethodNotAllowedHttpException.

Here are my view

<form method="POST" action="{{ route('absensi.store') }}">

NIM :

        <select name ="mahasiswasn" class="selectpicker" data-live-search="true" data-width="500px" title="Choose the Student Number">
        @foreach($nim as $nm)
          <option value="{{ $nm->nim }}">{{ $nm->nim}}</option>
        @endforeach
      </select>

 MK :

        <select name ="matkulsn" class="selectpicker" data-live-search="true" data-width="500px" title="Choose the subject">
        @foreach($matkul as $mkl)
          <option value="{{ $mkl->nama }}">{{ $mkl->nama}}</option>
        @endforeach
      </select>

        Hari :
        <input id="hari" name="hari" class="form-control">

        Status :
        <input id="status" name="status" class="form-control">

      <input type="submit" value="Add Absensi " class="btn btn-success btn-lg btn-block">
      <input type="hidden" name="_token" value="{{ Session::token() }}">

    </form>

My Controller (AbsensiController)

public function store(Request $request)
    {
           $this->validate($request,array(
                'nim' =>'required',
                'matkul' =>'required',
                'hari' =>'required',
                'status' =>'required'
                ));

            //store in database
            $post = new PostAbsensi;

            $post->nim = $request->get('mahasiswasn');
            $post->mk = $request->get('matkulsn');
            $post->hari = $request->get('hari');
            $post->status = $request->get('status');

            $post->save();

            Session::flash('success','data successfully saved!');

            return redirect()->route('absensi.show', $post->id);
    }

My Routes :

Route::resource('absensi','AbsensiController');

Please Help, thank you for your attention.

Edit :

Here are my other view(IndexAbsensi)

<form method="POST" action="{{ url('absensi.create') }}">
                      <input type="submit" value=" + Tambah Absensi " class="btn btn-success btn-lg btn-block">
                      <input type="hidden" name="_token" value="{{ csrf_token() }}">
  </form>

so my thought is that when i press the button it will go to the AbsensiController@create and then return my form view, however im also getting Methodnotallowedhttpexception with this.

Body:
@Ahmad you are wrong store method uses post route. see https://laravel.com/docs/5.4/controllers#restful-partial-resource-routes

@Riki Every thing looks fine in code maybe you are overwriting route or naem of route or something like this.
can you run php artisan route:list by this you can see which method is for this route.

or you can use <form method="POST" action="{{ url('absensi') }}">

and in controller you also can use

$this->validate($request->all(),array(
            'nim' =>'required',
            'matkul' =>'required',
            'hari' =>'required',
            'status' =>'required'
            ));


问:
Date and Time Saving via any method
So I'm trying to make an app for a friend of mine who is a hardcore workout junkie, and I'm stuck on one part of the app.

I'm attempting to make it automatically save the date and time of every single one of his workouts, so he can look back and see the last time he worked out and how often he did over the month and things like that.

However, I have no idea how to go about this. My knowledge of SharedPreferences is subpar, and I am unable to integrate Google Calendar. Is there any other way for something like this to happen?

If not, could someone help me with the SharedPreferences portion?

Thank you.

答:
Here I have created a design for you. you can make necessary changes according to your requirement.

```<code>//Create a dbHelper class like this

public class DatabaseNew extends SQLiteOpenHelper {
    private static final String TAG = "DataBase";

    public DatabaseNew(Context context){
        super(context,DATABASE_NAME,null,DATABASE_VERSION);
    }
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "Module1";
    private static final String USERTABLE = "USER_INFO";
    private static final String KEY_ID = "id";
    private static final String WORKOUT = "WORKOUT";
    private static final String WORKOUT_TIME = "WORKOUT_TIME";

    private static final String CREATE_TABLE_USER = "CREATE TABLE IF NOT EXISTS "
            + USERTABLE + "(" + KEY_ID + " INTEGER PRIMARY KEY," + WORKOUT + " TEXT,"
            + WORKOUT_TIME + " TEXT"+");";

    private static final String SQL_DELETE_ENTRIES =
            "DROP TABLE IF EXISTS " + USERTABLE;

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.e(TAG,"Inside onCreate: creating table");
        db.execSQL(CREATE_TABLE_USER);
    }

    //to save workout name and time in db
    public void saveData(String workout, String time){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues data = new ContentValues();
        data.put(WORKOUT,workout);
        data.put(WORKOUT_TIME,time);
        db.insert(USERTABLE,null,data);
        db.close();
    }

    //to get workout name and time from db
    public List<HashMap<String,String>> getData(){
        List<HashMap<String,String>> userData = new ArrayList<>();
        String selectQuery = "SELECT  * FROM " + USERTABLE ;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
                HashMap<String,String> dataMap = new HashMap<>();
                dataMap.put(WORKOUT,cursor.getString(cursor.getColumnIndex(WORKOUT)));
                dataMap.put(WORKOUT_TIME,cursor.getString(cursor.getColumnIndex(WORKOUT_TIME)));
                userData.add(dataMap);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return userData;

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.e(TAG,"Inside onUpgrade");
        db.execSQL(SQL_DELETE_ENTRIES);
        onCreate(db);
    }
}
</code>```

//Then inside your activity

```<code> @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        //Initializing the db
        DatabaseNew db = new DatabaseNew(this);
        //sending dummy data you can send actual workout and time like this
        db.saveData("pull up","30 mins");
        db.saveData("push up","40 mins");
        db.saveData("Leg up","30 mins");
        db.saveData("crunches","30 mins");
        db.saveData("Bench Press","30 mins");

        //to retrieve data from data base
        List<HashMap<String,String>> data = db.getData();
        for (HashMap<String,String> a : data){
            Log.e("TestActivity"," "+"Workout : "+a.get("WORKOUT")
                    +" "+"Time : "+a.get("WORKOUT_TIME"));
        }
    }
</code>```

Hope it helps!!!

Title: Date and Time Saving via any method

Body:
Here I have created a design for you. you can make necessary changes according to your requirement.

//Create a dbHelper class like this

public class DatabaseNew extends SQLiteOpenHelper {
    private static final String TAG = "DataBase";

    public DatabaseNew(Context context){
        super(context,DATABASE_NAME,null,DATABASE_VERSION);
    }
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "Module1";
    private static final String USERTABLE = "USER_INFO";
    private static final String KEY_ID = "id";
    private static final String WORKOUT = "WORKOUT";
    private static final String WORKOUT_TIME = "WORKOUT_TIME";

    private static final String CREATE_TABLE_USER = "CREATE TABLE IF NOT EXISTS "
            + USERTABLE + "(" + KEY_ID + " INTEGER PRIMARY KEY," + WORKOUT + " TEXT,"
            + WORKOUT_TIME + " TEXT"+");";

    private static final String SQL_DELETE_ENTRIES =
            "DROP TABLE IF EXISTS " + USERTABLE;

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.e(TAG,"Inside onCreate: creating table");
        db.execSQL(CREATE_TABLE_USER);
    }

    //to save workout name and time in db
    public void saveData(String workout, String time){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues data = new ContentValues();
        data.put(WORKOUT,workout);
        data.put(WORKOUT_TIME,time);
        db.insert(USERTABLE,null,data);
        db.close();
    }

    //to get workout name and time from db
    public List<HashMap<String,String>> getData(){
        List<HashMap<String,String>> userData = new ArrayList<>();
        String selectQuery = "SELECT  * FROM " + USERTABLE ;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
                HashMap<String,String> dataMap = new HashMap<>();
                dataMap.put(WORKOUT,cursor.getString(cursor.getColumnIndex(WORKOUT)));
                dataMap.put(WORKOUT_TIME,cursor.getString(cursor.getColumnIndex(WORKOUT_TIME)));
                userData.add(dataMap);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return userData;

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.e(TAG,"Inside onUpgrade");
        db.execSQL(SQL_DELETE_ENTRIES);
        onCreate(db);
    }
}

//Then inside your activity

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        //Initializing the db
        DatabaseNew db = new DatabaseNew(this);
        //sending dummy data you can send actual workout and time like this
        db.saveData("pull up","30 mins");
        db.saveData("push up","40 mins");
        db.saveData("Leg up","30 mins");
        db.saveData("crunches","30 mins");
        db.saveData("Bench Press","30 mins");

        //to retrieve data from data base
        List<HashMap<String,String>> data = db.getData();
        for (HashMap<String,String> a : data){
            Log.e("TestActivity"," "+"Workout : "+a.get("WORKOUT")
                    +" "+"Time : "+a.get("WORKOUT_TIME"));
        }
    }

Hope it helps!!!


问:
Below Code is not printing anything
```<code>#include <iostream>
#include <iterator>
#include <algorithm>

using namespace std;

int ma(float array[], int N)
{
    int k = 0;
    float max = array[k];
    for (int i = 0; i < N; ++i) {
        if (array[i] > max) {
            max = array[i];
            k = i;
        }
    }
    return k;
}

int main()
{
    int t;
    while (t--) {
        int n;
        cin >> n;
        int w[n], p[n];
        for (int i = 0; i < n; i++)
            cin >> w[i];
        for (int i = 0; i < n; i++)
            cin >> p[i];
        float x[n];
        for (int i = 0; i < n; i++)
            x[i] = p[i] / w[i];
        int weigth = 0, profit = 0;
        while (weigth <= 20) {
            // int k=distance(x, max_element(x, x + n));
            // int k=  std::distance(x, max_element(x, x + sizeof(x)/sizeof(x)));
            int k = ma(x, n);
            weigth = weigth + w[k];
            profit = profit + p[k];
            x[k] = p[k] = w[k] = 0;
        }
        cout << weigth << endl
             << profit << endl;
    }
}
</code>```

The above code is not printing anything. If you want the question refer to "catch-the-match":

答:
your code is not even compiling,

you can not do this in C++

```<code>int n;
cin >> n;
int w[n], p[n];
</code>```

because n must be a constant at compiling time, on the other hand doing this:

```<code>int t;
while (t--) {
</code>```

is producing an unpredictable number of iterations in the loop since t is not initialized

Title: Below Code is not printing anything

Body:
#include <iostream>
#include <iterator>
#include <algorithm>

using namespace std;

int ma(float array[], int N)
{
    int k = 0;
    float max = array[k];
    for (int i = 0; i < N; ++i) {
        if (array[i] > max) {
            max = array[i];
            k = i;
        }
    }
    return k;
}

int main()
{
    int t;
    while (t--) {
        int n;
        cin >> n;
        int w[n], p[n];
        for (int i = 0; i < n; i++)
            cin >> w[i];
        for (int i = 0; i < n; i++)
            cin >> p[i];
        float x[n];
        for (int i = 0; i < n; i++)
            x[i] = p[i] / w[i];
        int weigth = 0, profit = 0;
        while (weigth <= 20) {
            // int k=distance(x, max_element(x, x + n));
            // int k=  std::distance(x, max_element(x, x + sizeof(x)/sizeof(x)));
            int k = ma(x, n);
            weigth = weigth + w[k];
            profit = profit + p[k];
            x[k] = p[k] = w[k] = 0;
        }
        cout << weigth << endl
             << profit << endl;
    }
}

The above code is not printing anything. If you want the question refer to "catch-the-match":

Body:
your code is not even compiling,

you can not do this in C++

int n;
cin >> n;
int w[n], p[n];

because n must be a constant at compiling time, on the other hand doing this:

int t;
while (t--) {

is producing an unpredictable number of iterations in the loop since t is not initialized


问:
Delaying not preventing Bash function from simultaneous execution
I need to block the simultaneous calling of highCpuFunction function. I have tried to create a blocking mechanism, but it is not working. How can I do this?

```<code>nameOftheScript="$(basename $0)"
pidOftheScript="$$"

highCpuFunction()
{
    # Function with code causing high CPU usage. Like tar, zip, etc.

    while [  -f /tmp/"$nameOftheScript"*  ];
    do
        sleep 5;
    done
    touch /tmp/"$nameOftheScript"_"$pidOftheScript"

    echo "$(date +%s) I am a Bad function you do not want to call me simultaniously..."
    # Real high CPU usage code for reaching the database and
    # parsing logs. It takes the heck out of the CPU.

    rm -rf /tmp/"$nameOftheScript"_"$pidOftheScript" 2>/dev/null
}

while true
do
   sleep 2
    highCpuFunction
done

# The rest of the code...
</code>```

In short, I want to run highCpuFunction at least with a gap of 5 seconds. Regardless of the instance/user/terminal. I need to allow other users to run this function but in proper sequence and with a gap of at least 5 seconds.

答:
In the following solution the # rest of the script part can be executed only by one process. The test and set is atomic, and there isn't any race condition, whereas test -f file .. touch file, two processes can touch the file.

```<code>try_acquire_lock() {
    local lock_file=$1
    # Noclobber option to fail if the file already exists
    # in a sub-shell to avoid modifying current shell options
    ( set -o noclobber; : >"$lock_file")
}

# Trap to remove the file when the process exits
trap 'rm "$lock_file"' EXIT

lock_file=/tmp/"$nameOftheScript"_"$pidOftheScript"
while ! try_acquire_lock "$lock_file";
do
    echo "failed to acquire lock, sleeping 5sec.."
    sleep 5;
done

# The rest of the script
</code>```

It's not optimal, because the wait is done in a loop with sleep. To improve, one can use inter process communication (FIFO), or operating system notifications or signals.

```<code># Block current shell process
kill -STOP $BASHPID

# Unblock blocked shell process (where <pid> is the id of the blocked process)
kill -CONT <pid>
</code>```

Body:
I need to block the simultaneous calling of highCpuFunction function. I have tried to create a blocking mechanism, but it is not working. How can I do this?

nameOftheScript="$(basename $0)"
pidOftheScript="$$"

highCpuFunction()
{
    # Function with code causing high CPU usage. Like tar, zip, etc.

    while [  -f /tmp/"$nameOftheScript"*  ];
    do
        sleep 5;
    done
    touch /tmp/"$nameOftheScript"_"$pidOftheScript"

    echo "$(date +%s) I am a Bad function you do not want to call me simultaniously..."
    # Real high CPU usage code for reaching the database and
    # parsing logs. It takes the heck out of the CPU.

    rm -rf /tmp/"$nameOftheScript"_"$pidOftheScript" 2>/dev/null
}

while true
do
   sleep 2
    highCpuFunction
done

# The rest of the code...

In short, I want to run highCpuFunction at least with a gap of 5 seconds. Regardless of the instance/user/terminal. I need to allow other users to run this function but in proper sequence and with a gap of at least 5 seconds.

Body:
In the following solution the # rest of the script part can be executed only by one process. The test and set is atomic, and there isn't any race condition, whereas test -f file .. touch file, two processes can touch the file.

try_acquire_lock() {
    local lock_file=$1
    # Noclobber option to fail if the file already exists
    # in a sub-shell to avoid modifying current shell options
    ( set -o noclobber; : >"$lock_file")
}

# Trap to remove the file when the process exits
trap 'rm "$lock_file"' EXIT

lock_file=/tmp/"$nameOftheScript"_"$pidOftheScript"
while ! try_acquire_lock "$lock_file";
do
    echo "failed to acquire lock, sleeping 5sec.."
    sleep 5;
done

# The rest of the script

It's not optimal, because the wait is done in a loop with sleep. To improve, one can use inter process communication (FIFO), or operating system notifications or signals.

# Block current shell process
kill -STOP $BASHPID

# Unblock blocked shell process (where <pid> is the id of the blocked process)
kill -CONT <pid>


问:
Facebook SDK iOS - error while requesting publish permission after opening the session with read permissions
My situation is as follows:

At first, user successfully logs into Facebook by requesting read permissions user_friends and email. I'm using openWithBehavior:FBSessionLoginBehaviorUseSystemAccountIfPresent method to log in. All relevant user data and information about user's FB friends logged in are successfully handled

Then, when user taps a button, publish permission publish_actions needs to be requested. I've read that reauthorizeWithPublishPermissions method is deprecated, so I tried with recommended requestNewPublishPermissions:defaultAudience:completionHandler: method and I ended up with permanently getting error with message:

FBSDKLog: FBSession: a permission request for publish or manage permissions contains unexpected read permissions

So, what am I doing wrong? Should I log out and then again log in by requesting only publish permission?
Or should I set some additional parameter on Application Dashboard? Should I somehow explicitly switch to sandbox since my app is already on AppStore?
(I'm aware that next version of my app has to be reviewed by FB due to requesting publish_actions permission.)

答:
Use the following code after asking for permissions.

```<code>     if ([[FBSDKAccessToken currentAccessToken] hasGranted:@"publish_actions"]) {
         // TODO: publish content.

     } else {
         FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
         [loginManager logInWithPublishPermissions:@[@"publish_actions"]
                                fromViewController:self
                                           handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
                                               //TODO: process error or result.

                                           }];
     }
</code>```

Body:
Use the following code after asking for permissions.

     if ([[FBSDKAccessToken currentAccessToken] hasGranted:@"publish_actions"]) {
         // TODO: publish content.

     } else {
         FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
         [loginManager logInWithPublishPermissions:@[@"publish_actions"]
                                fromViewController:self
                                           handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
                                               //TODO: process error or result.

                                           }];
     }


答:
You can clear the input field by using </p>

```<code>$('#searchUser').val('');
</code>```

Title: Why doesn't empty() work on input in search bar?

Body:
You can clear the input field by using

$('#searchUser').val('');


问:
How can i get the candidates with a hash(number) from a list of nodes, algorithm？
I have a list of nodes-NodeList(each of them is different). and i has a number-N

Here we want to select some nodes as candidate from the list(needed more than half).

Is there any algorithm to achieve this goal. There are some tips:

1. same N(we call it seed), same selection result

2. the number of candidate must be more than half of the list size

3. different seed, different result（as far as possible）.

For example:

List of nodes(NodeList) : [nodeA, nodeB, nodeC,...,nodeZ],  the size of NodeList is 26. Each of node is a address(in akka, you can image it is a string).

And i need a algorithm.

Input:

Seed: a number(int)

NodeList : List of nodes

Output:
 - NodeListResult: according to the seed, we select some nodes from NodeList. maybe [nodeA, nodeB, nodeD, ..., nodeZ]. The size of NodeListResult must be greater than the half of NodeList's size.

答:
use your seed N to initialize a random number generator

halfSize = NodeList / 2

newLength = halfSize * randomNumber() + halfSize

newNodes = []

for(i over newLength) { nowNodes.push(NodeList.removeElement(randomNumber() * NodeList.size)) }


问:
EJB injection in servlet fails
I am trying to inject an EJB stateless bean in to a servlet, but the servlet throws a NullPointerExcetion. I am using JBOSS to deploy the EJB and servlet.

I am relatively new to the Java world, so I am posting the steps I followed.

Interface

```<code>package MavenEJB.Bidding`
import javax.ejb.Local;

@Local
public interface PlaceBid {
 public String AddBid();
}
</code>```

Bean

```<code>package MavenEJB.Bidding;
import javax.ejb.Stateless;
@Stateless(name="PlaceBid")
public class PlaceBidBean implements PlaceBid {
 public PlaceBidBean(){}

 /**
  * Include logic to add the bid
  */

 public String AddBid(){
  return "Placed bid using EJB";
 }
}
</code>```

I created a jar file of the bean using maven and I copied the jar file to "deploy" directory of JBOSS. I am able to see the bean deployed in the JMX console.

Global JNDI Namespace in JMX console

```<code>+- PlaceBid (class: org.jnp.interfaces.NamingContext)
  |   +- local (proxy: $Proxy63 implements interface MavenEJB.Bidding.PlaceBid,interface org.jboss.ejb3.JBossProxy)
</code>```

My servlet code

```<code>public class PlaceBidServlet extends HttpServlet {

    @EJB
    private PlaceBid placeBid;

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/html");

  PrintWriter out = response.getWriter();
     out.println("<HTML>");
     out.println("<HEAD><TITLE>Hello</TITLE></HEAD>");
     out.println("<BODY>");
  out.println("Output from EJB" +placeBid.AddBid());

     //out.println("Output from EJB" );
     out.println("</BODY></HTML>");
 }

....
}
</code>```

When I point to the URL of my servlet, I get NullPointerException. When I comment the bean and print something else, it prints fine. So I am sure the problem is with the EJB Dependency Injection in the servlet.
I tried many solutions suggested else where, nothing really worked, someone please help me.

答:
After a lot of hours I found the problem, I am posting it so someone else can benefit.
The problem is, I was using JBOSS 4.2.3 and as this post http://community.jboss.org/message/410211 suggests jboss 4.2.x does not support EJB injection in servlets.

I used Jboss 5.1, also if both the servlet and EJB are not in a single ear package, one must use mappedName to the EJB Injection. I had the servlets in a WAR and the EJB in a separate Jar. Check this post for more details http://community.jboss.org/message/8196#8196

Title: EJB injection in servlet fails

Body:
I am trying to inject an EJB stateless bean in to a servlet, but the servlet throws a NullPointerExcetion. I am using JBOSS to deploy the EJB and servlet.

I am relatively new to the Java world, so I am posting the steps I followed.

Interface

package MavenEJB.Bidding`
import javax.ejb.Local;

@Local
public interface PlaceBid {
 public String AddBid();
}

Bean

package MavenEJB.Bidding;
import javax.ejb.Stateless;
@Stateless(name="PlaceBid")
public class PlaceBidBean implements PlaceBid {
 public PlaceBidBean(){}

 /**
  * Include logic to add the bid
  */

 public String AddBid(){
  return "Placed bid using EJB";
 }
}

I created a jar file of the bean using maven and I copied the jar file to "deploy" directory of JBOSS. I am able to see the bean deployed in the JMX console.

Global JNDI Namespace in JMX console

+- PlaceBid (class: org.jnp.interfaces.NamingContext)
  |   +- local (proxy: $Proxy63 implements interface MavenEJB.Bidding.PlaceBid,interface org.jboss.ejb3.JBossProxy)

My servlet code

public class PlaceBidServlet extends HttpServlet {

    @EJB
    private PlaceBid placeBid;

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/html");

  PrintWriter out = response.getWriter();
     out.println("");
     out.println("<TITLE>Hello</TITLE>");
     out.println("");
  out.println("Output from EJB" +placeBid.AddBid());

     //out.println("Output from EJB" );
     out.println("");
 }

....
}

When I point to the URL of my servlet, I get NullPointerException. When I comment the bean and print something else, it prints fine. So I am sure the problem is with the EJB Dependency Injection in the servlet.
I tried many solutions suggested else where, nothing really worked, someone please help me.


问:
Finding mean of a vector in a for loop in MATLAB
How do I get the mean of a vector inside a for loop. The vector v depends on k.

```<code>for k = 1:n
   filename = 'file.txt';
   ...
   v = ... %the vector
   result = mean(v, 3); %mean along the 3rd dimension.; didn't work.
end
</code>```

答:
Initialize result as a cell array and keep storing the means. The following should work:

```<code>result = cell(n,1);
for k = 1:n
   filename = 'file.txt';
   ...
   v = ... %the vector
   result{k} = mean(v, 3); %mean along the 3rd dimension.; didn't work.
end
</code>```

Body:
How do I get the mean of a vector inside a for loop. The vector v depends on k.

for k = 1:n
   filename = 'file.txt';
   ...
   v = ... %the vector
   result = mean(v, 3); %mean along the 3rd dimension.; didn't work.
end

Body:
Initialize result as a cell array and keep storing the means. The following should work:

result = cell(n,1);
for k = 1:n
   filename = 'file.txt';
   ...
   v = ... %the vector
   result{k} = mean(v, 3); %mean along the 3rd dimension.; didn't work.
end


问:
ignore prefix (namespace) when unmarshalling xml
I have this XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<s:XXMsg xmlns:s="com:sample:test:msg">
    <s:Header>
        <s:cpyCod>xxx</s:cpyCod>
        <s:appCod>yyy</s:appCod>
    </s:Header>
</s:XXMsg>
</code>```

and I want this to be unmarshalled into the following Java class:

```<code>public class XXHeader
{
    private String cpyCod;
    private String appCod;
}
</code>```

I have written this code:

```<code>    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    inputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
    try
    {
        XMLStreamReader streamReader = inputFactory
            .createXMLStreamReader(Test.class.getClassLoader().getResourceAsStream("xxmsg.xml"));
        while (streamReader.hasNext())
        {
            int next = streamReader.next();
            if (streamReader.getEventType() == XMLStreamReader.START_ELEMENT
                && streamReader.getLocalName().equals("Header"))
            {
                JAXBContext context = JAXBContext.newInstance(XXHeader.class);
                Unmarshaller unmarshaller = context.createUnmarshaller();
                XXHeader xxHeader = unmarshaller.unmarshal(streamReader, XXHeader.class).getValue();
                System.out.println(xxHeader);
                break;
            }
        }
</code>```

I am getting all field values of XXHeader as null. But if I do change the xml and remove the prefixes s: in every element then I get the correct values.

How can I ignore this prefix while unmarshalling to get the correct values?

PS: Use of @XML** annotations in XXHeader class is discouraged.

答:
I am able to do this using StreamReaderDelegate as mentioned here:

```<code>public class XXHeaderXMLReader
    extends StreamReaderDelegate
{

    public XXHeaderXMLReader(XMLStreamReader paramXMLStreamReader)
    {
        super(paramXMLStreamReader);
    }

    @Override
    public String getAttributeNamespace(int paramInt)
    {
        return "";
    }

    @Override
    public String getNamespaceURI()
    {
        return "";
    }

}
</code>```

and adding the line in previous code:

```<code>XMLInputFactory inputFactory = XMLInputFactory.newInstance();
inputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
try
{
    XMLStreamReader streamReader = inputFactory
        .createXMLStreamReader(DocumentTest.class.getClassLoader().getResourceAsStream("xxmsg.xml"));
    while (streamReader.hasNext())
    {
        int next = streamReader.next();
        if (streamReader.getEventType() == XMLStreamReader.START_ELEMENT)
        {
            if (streamReader.getLocalName().equals("Header"))
            {
                JAXBContext context = JAXBContext.newInstance(XXHeader.class);
                Unmarshaller unmarshaller = context.createUnmarshaller();
                XXHeaderXMLReader xxHeaderXMLReader = new XXHeaderXMLReader(streamReader);
                XXHeader xxHeader =
                    unmarshaller.unmarshal(xxHeaderXMLReader, XXHeader.class).getValue();
                System.out.println(xxHeader);
                break;
            }
        }
    }
}
catch (XMLStreamException e)
{
    e.printStackTrace();
}
catch (JAXBException e)
{
    e.printStackTrace();
}
</code>```

Body:
I have this XML:

<?xml version="1.0" encoding="UTF-8"?>
<s:XXMsg xmlns:s="com:sample:test:msg">
    <s:Header>
        <s:cpyCod>xxx</s:cpyCod>
        <s:appCod>yyy</s:appCod>
    </s:Header>
</s:XXMsg>

and I want this to be unmarshalled into the following Java class:

public class XXHeader
{
    private String cpyCod;
    private String appCod;
}

I have written this code:

    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    inputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
    try
    {
        XMLStreamReader streamReader = inputFactory
            .createXMLStreamReader(Test.class.getClassLoader().getResourceAsStream("xxmsg.xml"));
        while (streamReader.hasNext())
        {
            int next = streamReader.next();
            if (streamReader.getEventType() == XMLStreamReader.START_ELEMENT
                && streamReader.getLocalName().equals("Header"))
            {
                JAXBContext context = JAXBContext.newInstance(XXHeader.class);
                Unmarshaller unmarshaller = context.createUnmarshaller();
                XXHeader xxHeader = unmarshaller.unmarshal(streamReader, XXHeader.class).getValue();
                System.out.println(xxHeader);
                break;
            }
        }

I am getting all field values of XXHeader as null. But if I do change the xml and remove the prefixes s: in every element then I get the correct values.

How can I ignore this prefix while unmarshalling to get the correct values?

PS: Use of @XML** annotations in XXHeader class is discouraged.

Body:
I am able to do this using StreamReaderDelegate as mentioned here:

public class XXHeaderXMLReader
    extends StreamReaderDelegate
{

    public XXHeaderXMLReader(XMLStreamReader paramXMLStreamReader)
    {
        super(paramXMLStreamReader);
    }

    @Override
    public String getAttributeNamespace(int paramInt)
    {
        return "";
    }

    @Override
    public String getNamespaceURI()
    {
        return "";
    }

}

and adding the line in previous code:

XMLInputFactory inputFactory = XMLInputFactory.newInstance();
inputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
try
{
    XMLStreamReader streamReader = inputFactory
        .createXMLStreamReader(DocumentTest.class.getClassLoader().getResourceAsStream("xxmsg.xml"));
    while (streamReader.hasNext())
    {
        int next = streamReader.next();
        if (streamReader.getEventType() == XMLStreamReader.START_ELEMENT)
        {
            if (streamReader.getLocalName().equals("Header"))
            {
                JAXBContext context = JAXBContext.newInstance(XXHeader.class);
                Unmarshaller unmarshaller = context.createUnmarshaller();
                XXHeaderXMLReader xxHeaderXMLReader = new XXHeaderXMLReader(streamReader);
                XXHeader xxHeader =
                    unmarshaller.unmarshal(xxHeaderXMLReader, XXHeader.class).getValue();
                System.out.println(xxHeader);
                break;
            }
        }
    }
}
catch (XMLStreamException e)
{
    e.printStackTrace();
}
catch (JAXBException e)
{
    e.printStackTrace();
}


问:
clean up and maintain local maven cached artifact in .m2
I have an .m2 repository on my Jenkins slave which is growing every day, currently it's nearly ~40 GB.

Since I have multiple jobs running and picking dependencies from .m2 I cannot remove everything, but I can see in each repo of .m2 there is an older and useless version of the artefact.

Are there any means of way available in maven so that when a job triggers $mvn install maven will keep the latest version only in the .m2 repo (example versioning x.y.z.w which is incremental) for every repo inside .m2?

答:
If you don't care that external dependencies are pulled in every build, you could use a private Maven repository per job (Maven -> Advanced -> Check 'use private Maven repository') and clean the workspace at the start of your build. The private repository creates a .repository in your workspace, so cleaning your workspace will ensure you start with an empty repository.

Should you have many shared external dependencies, then you may be using even more diskspace, since they are present multiple times in the different repositories. In that case you could write a script that periodically (using a task scheduler like cron) removes unused files from the shared repository, see for example this Stack Overflow answer.

However be cautious with a shared Maven repository! Maven by default is not threadsafe, so concurrent jobs downloading the same artifact might use the incomplete downloads. Consider using the Takari extensions to make your Maven repository thread-safe.


问:
Notification Intent Not starting Actiivty android
I am trying to start an Activity on a Notification Click but it never get started. Below is my code for sending Notification:

```<code>Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.putExtra("Notification", type);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0,notificationIntent, 0);
        Notification n = new Notification.Builder(this)
                .setContentTitle(title)
                .setContentText(type)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pIntent)
                .build();
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        notificationManager.notify(0, n);
</code>```

I never get call to that activity on click of notification.

答:
Call method like this when u want notification

```<code>public void showNotification() {
        PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, ShowNotificationDetailActivity.class), 0);
        Resources r = getResources();
        Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.main)
                .setContentTitle("title")
                .setContentText("Welcome")
                .setContentIntent(pi)
                .setAutoCancel(true)
                .build();
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(0, notification);
    }
</code>```

Create a class like this and give your class in the intent to go to activity

```<code>public class ShowNotificationDetailActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = new Intent(this, Main.class);
        startActivity(intent);
    }
}
</code>```

Body:
I am trying to start an Activity on a Notification Click but it never get started. Below is my code for sending Notification:

Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.putExtra("Notification", type);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0,notificationIntent, 0);
        Notification n = new Notification.Builder(this)
                .setContentTitle(title)
                .setContentText(type)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pIntent)
                .build();
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        notificationManager.notify(0, n);

I never get call to that activity on click of notification.

Body:
Call method like this when u want notification

public void showNotification() {
        PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, ShowNotificationDetailActivity.class), 0);
        Resources r = getResources();
        Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.main)
                .setContentTitle("title")
                .setContentText("Welcome")
                .setContentIntent(pi)
                .setAutoCancel(true)
                .build();
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(0, notification);
    }

Create a class like this and give your class in the intent to go to activity

public class ShowNotificationDetailActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = new Intent(this, Main.class);
        startActivity(intent);
    }
}


问:
text-align in md-grid-tile (Angular Material) doesn't work
text-align in Angular Material <md-grid-tile> doesn't work.

<md-grid-tile>{{video.created}}</md-grid-tile>
<md-grid-tile>{{video.code</md-grid-tile>

<md-grid-tile style="text-align: left;">
   {{ video.title }}
</md-grid-tile>

<md-grid-tile>{{video.playtime}}</md-grid-tile>
```

I want to align text like this:

but text-align in <md-grid-tile> didn't work :(

How can I do it?

答:
for those who have problems getting this example to work in angular2
you might need to add the ::ng-deep selector to the css for the figure

```<code><md-grid-tile class="video-title">
    {{ video.title }}
</md-grid-tile>
</code>```

css

```<code> .video-title > ::ng-deep figure {
     justify-content: flex-start !important;
 }
</code>```

*updated /deep/ to ::ng-deep because /deep/ was deprecated

Body:
text-align in Angular Material <md-grid-tile> doesn't work.

<md-grid-tile>{{video.created}}</md-grid-tile>
<md-grid-tile>{{video.code</md-grid-tile>

<md-grid-tile style="text-align: left;">
   {{ video.title }}
</md-grid-tile>

<md-grid-tile>{{video.playtime}}</md-grid-tile>

I want to align text like this:

but text-align in <md-grid-tile> didn't work :(

How can I do it?

Body:
for those who have problems getting this example to work in angular2
you might need to add the ::ng-deep selector to the css for the figure

<md-grid-tile class="video-title">
    {{ video.title }}
</md-grid-tile>

css

 .video-title > ::ng-deep figure {
     justify-content: flex-start !important;
 }

*updated /deep/ to ::ng-deep because /deep/ was deprecated


问:
I have an rectangle and a text object. I would like "text" to follow "rectangle" when i drag him over the canvas
```<code>fabric.Canvas.prototype.getItemsByName = function(name) {
  var objectList = [],
      objects = this.getObjects();

  for (var i = 0, len = this.size(); i < len; i++) {
    if (objects[i].name && objects[i].name === name) {

         if (objects[i].type && objects[i].type === "text") {
      objectList.push(objects[i]);
            }
    }
  }
  return objectList;
};

var moveHandler = function (evt) {
    var movingObject = evt.target;
    //console.log(movingObject.get('left'), movingObject.get('top'));
  var textToMove = canvas.getItemsByName(objectname);
   textToMove.style.left = movingObject.get('left')+'px';// 'px';
   textToMove.style.top = movingObject.get('top')+'px';// 'px';
};

canvas.on('object:moving', moveHandler);
</code>```

Code  above finds the text object, but still  is not making text to move behind him. What i am doing wrong?

I am using fabric.js.

I have two objects on canvas. And when i am using event i can see coordinates of  moving objects in console. And also i may get prof of existence of text object which i want to follow the rectangle

```<code>(var textToMove = canvas.getItemsByName(objectname));
</code>```

But...  I get next

Uncaught TypeError: Cannot set property 'left' of undefined next to:
  textToMove.style.left = movingObject.get('left')+'px';

What is wrong?

```<code>  var circle1 = new fabric.Circle({
  radius: 10,
  fill: 'green',
  left: 100,
  top: 100,
  id:objectname+"Circle" ,
  name:objectname
});

   var text40 = new fabric.Text(objectname, {
   selectable :false,
   left:100,
   top: 80,
   fontWeight: 'bold',
   fontSize: 12,
   id:objectname+"Text",
   name:objectname
   });
</code>```

答:
```<code> fabric.Canvas.prototype.getItemByName2 = function(objectname) {
  var object = null,
      objects = this.getObjects();

  for (var i = 0, len = this.size(); i < len; i++) {
    if (objects[i].type && objects[i].type === "text"){
        if (objects[i].name && objects[i].name=== objectname) {
          object = objects[i];
         break;
        }
    }
  }
  return object;
};

var moveHandler = function (evt) {
    var movingObject = evt.target;
  var leftx = movingObject.get('left');
  var topy = movingObject.get('top');
  canvas.getItemByName2(objectname).set('left',leftx);
  canvas.getItemByName2(objectname).set('top',topy-20);
};

canvas.on('object:moving', moveHandler);
</code>```

As this is working.
Thank you

Body:
fabric.Canvas.prototype.getItemsByName = function(name) {
  var objectList = [],
      objects = this.getObjects();

  for (var i = 0, len = this.size(); i < len; i++) {
    if (objects[i].name && objects[i].name === name) {

         if (objects[i].type && objects[i].type === "text") {
      objectList.push(objects[i]);
            }
    }
  }
  return objectList;
};

var moveHandler = function (evt) {
    var movingObject = evt.target;
    //console.log(movingObject.get('left'), movingObject.get('top'));
  var textToMove = canvas.getItemsByName(objectname);
   textToMove.style.left = movingObject.get('left')+'px';// 'px';
   textToMove.style.top = movingObject.get('top')+'px';// 'px';
};

canvas.on('object:moving', moveHandler);

Code  above finds the text object, but still  is not making text to move behind him. What i am doing wrong?

I am using fabric.js.

I have two objects on canvas. And when i am using event i can see coordinates of  moving objects in console. And also i may get prof of existence of text object which i want to follow the rectangle

(var textToMove = canvas.getItemsByName(objectname));

But...  I get next

Uncaught TypeError: Cannot set property 'left' of undefined next to:
  textToMove.style.left = movingObject.get('left')+'px';

What is wrong?

  var circle1 = new fabric.Circle({
  radius: 10,
  fill: 'green',
  left: 100,
  top: 100,
  id:objectname+"Circle" ,
  name:objectname
});

   var text40 = new fabric.Text(objectname, {
   selectable :false,
   left:100,
   top: 80,
   fontWeight: 'bold',
   fontSize: 12,
   id:objectname+"Text",
   name:objectname
   });

Body:
 fabric.Canvas.prototype.getItemByName2 = function(objectname) {
  var object = null,
      objects = this.getObjects();

  for (var i = 0, len = this.size(); i < len; i++) {
    if (objects[i].type && objects[i].type === "text"){
        if (objects[i].name && objects[i].name=== objectname) {
          object = objects[i];
         break;
        }
    }
  }
  return object;
};

var moveHandler = function (evt) {
    var movingObject = evt.target;
  var leftx = movingObject.get('left');
  var topy = movingObject.get('top');
  canvas.getItemByName2(objectname).set('left',leftx);
  canvas.getItemByName2(objectname).set('top',topy-20);
};

canvas.on('object:moving', moveHandler);

As this is working.
Thank you