问:
unable to obtain buddypress user avatar url
I am working on a plugin, inside the plugin, I have made a Javascript file in which I want to have the specific user BuddyPress avatar URL assigned to a variable.

My javascript file inside the plugin folder is named: myscript.js.php (so PHP can be executed inside this file).

The code inside the javascript file:

```<code><?php
   header('Content-type: text/javascript');

   $home_dir = preg_replace('^wp-content/plugins/[a-z0-9\-/]+^', '', getcwd());
   include($home_dir . 'wp-load.php');

   $ucurrentid = $current_user->ID;
   $member_id = bp_core_get_userid( $ucurrentid );
   $uphoto = bp_core_fetch_avatar ( array(
       'item_id' =>$ member_id,'html'=>false
   ) );
?>

var uid = <?php echo $current_user->ID ?>;
var uphoto = <?php echo $uphoto ?>;

alert(uphoto);
</code>```

This return the error :
PHP Fatal error:  Call to undefined function  bp_user_avatar()

Why is the function undefined, which BuddyPress file should I include into the code so the function works?

答:
You can try :

```<code>$avatar_link = bp_core_fetch_avatar(array('html' =>  false, 'item_id' =>  $user_id));
$avatar = '<img title="admin" src="' . $avatar_link . '"></img>';

// Display image
echo $avatar
</code>```

You need user ID. Inside loop, you can do :

```<code>$user_id = bp_get_member_user_id();
</code>```

Body:
I am working on a plugin, inside the plugin, I have made a Javascript file in which I want to have the specific user BuddyPress avatar URL assigned to a variable.

My javascript file inside the plugin folder is named: myscript.js.php (so PHP can be executed inside this file).

The code inside the javascript file:

<?php
   header('Content-type: text/javascript');

   $home_dir = preg_replace('^wp-content/plugins/[a-z0-9\-/]+^', '', getcwd());
   include($home_dir . 'wp-load.php');

   $ucurrentid = $current_user->ID;
   $member_id = bp_core_get_userid( $ucurrentid );
   $uphoto = bp_core_fetch_avatar ( array(
       'item_id' =>$ member_id,'html'=>false
   ) );
?>

var uid = <?php echo $current_user->ID ?>;
var uphoto = <?php echo $uphoto ?>;

alert(uphoto);

This return the error :
PHP Fatal error:  Call to undefined function  bp_user_avatar()

Why is the function undefined, which BuddyPress file should I include into the code so the function works?

Body:
You can try :

$avatar_link = bp_core_fetch_avatar(array('html' =>  false, 'item_id' =>  $user_id));
$avatar = '<img title="admin" src="' . $avatar_link . '"></img>';

// Display image
echo $avatar

You need user ID. Inside loop, you can do :

$user_id = bp_get_member_user_id();


来源: stackexchange

问:
How to update a document in documentdb using linq
My json document is like the one mentioned below

```<code>{
"HotelCriteria": {
    "HotelCode": "101671",
    "HotelName": "TestTulip Inn"
},
"RoomTypes": {
    "RoomTypeList": [
        {
            "InvTypeCode": "DLX",
            "Name": "Deluxe",
            "BaseOccupancy": 2,
            "MaxOccupancy": 3,
            "Quantity": 16,
            "IsRoomActive": 1,
            "RoomDescription": "",
            "Availability": 0
        },
        {
            "InvTypeCode": "SUIR",
            "Name": "Suite Room",
            "BaseOccupancy": 2,
            "MaxOccupancy": 3,
            "Quantity": 2,
            "IsRoomActive": 1,
            "RoomDescription": "",
            "Availability": 0
        },
        {
            "InvTypeCode": "SUP",
            "Name": "Superior",
            "BaseOccupancy": 2,
            "MaxOccupancy": 3,
            "Quantity": 35,
            "IsRoomActive": 1,
            "RoomDescription": "",
            "Availability": 0
        }
    ]
},
"id": "ee24e984-a73b-4d22-bc9c-7cf71374362f",
}
</code>```

At later stage i want to update the field Availability to 1 in the above json . How to do using linq?

My sample c# code

```<code>public class HotelCriteria
    {
        public string HotelCode { get; set; }
        public string HotelName { get; set; }
    }
   public class RoomTypeList
    {
        public string InvTypeCode { get; set; }
        public string Name { get; set; }
        public int BaseOccupancy { get; set; }
        public int MaxOccupancy { get; set; }
        public int Quantity { get; set; }
        public int IsRoomActive { get; set; }
        public string RoomDescription { get; set; }
        public int Availability { get; set; }
    }

      public class RoomTypes
    {
        public List<RoomTypeList> RoomTypeList { get; set; }
    }

public class monthwiseinsert
    {
        public HotelCriteria HotelCriteria { get; set; }
        public RoomTypes RoomTypes { get; set; }
    }
</code>```

The method which is used to create the document (This is created from other documents which i have in my collection):

```<code>public IHttpActionResult InventoryInsertDate()
    {
        Database database = GetDatabase("xyz").Result;
        DocumentCollection collection = GetCollection(database, "xyzCollection").Result;
        List<monthwiseinsert> roomtypeavail = new List<monthwiseinsert>();

        var Hotelwithroomtype = (client.CreateDocumentQuery<monthwiseinsert>(collection.SelfLink).Where(x=>x.HotelCriteria.HotelName!=null)
                   ).ToList();
        foreach(var item in Hotelwithroomtype)
        {
            client.CreateDocumentAsync(collection.SelfLink, item);

        }

        return Json("OK");
    }
</code>```

答:
You need to specify the Id of the record you want to update. Change monthwiseinsert to include Id field. Ex-

```<code>public class DocumentDbRecord
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }
}
public class HotelMonthlyRecord : DocumentDbRecord
{
    public HotelCriteria HotelCriteria { get; set; }
    public RoomTypes RoomTypes { get; set; }
}
</code>```

For updating record, you can use UpsertDocumentAsync

```<code>    public async Task UpdateDocumentAsync(string databaseName, string collectionName, int newAvailability)
    {
        var taskList = new List<Task>();
        var collection = await this.GetDocumentCollectionAsync(databaseName, collectionName);
        var hotelRecords = client.CreateDocumentQuery<HotelMonthlyRecord>(collection.SelfLink)
            .Where(x => x.HotelCriteria.HotelName != null)
            .ToList();
        foreach (var item in hotelRecords)
        {
            item.RoomTypes.RoomTypeList.ForEach(i => i.Availability = newAvailability);
            taskList.Add(client.UpsertDocumentAsync(collection.SelfLink, item));
        }

        if (taskList.Any())
        {
            await Task.WhenAll(taskList);
        }
    }
</code>```

Hope this help.

ContentLicense: CC BY-SA 3.0

Body:
My json document is like the one mentioned below

{
"HotelCriteria": {
    "HotelCode": "101671",
    "HotelName": "TestTulip Inn"
},
"RoomTypes": {
    "RoomTypeList": [
        {
            "InvTypeCode": "DLX",
            "Name": "Deluxe",
            "BaseOccupancy": 2,
            "MaxOccupancy": 3,
            "Quantity": 16,
            "IsRoomActive": 1,
            "RoomDescription": "",
            "Availability": 0
        },
        {
            "InvTypeCode": "SUIR",
            "Name": "Suite Room",
            "BaseOccupancy": 2,
            "MaxOccupancy": 3,
            "Quantity": 2,
            "IsRoomActive": 1,
            "RoomDescription": "",
            "Availability": 0
        },
        {
            "InvTypeCode": "SUP",
            "Name": "Superior",
            "BaseOccupancy": 2,
            "MaxOccupancy": 3,
            "Quantity": 35,
            "IsRoomActive": 1,
            "RoomDescription": "",
            "Availability": 0
        }
    ]
},
"id": "ee24e984-a73b-4d22-bc9c-7cf71374362f",
}

At later stage i want to update the field Availability to 1 in the above json . How to do using linq?

My sample c# code

public class HotelCriteria
    {
        public string HotelCode { get; set; }
        public string HotelName { get; set; }
    }
   public class RoomTypeList
    {
        public string InvTypeCode { get; set; }
        public string Name { get; set; }
        public int BaseOccupancy { get; set; }
        public int MaxOccupancy { get; set; }
        public int Quantity { get; set; }
        public int IsRoomActive { get; set; }
        public string RoomDescription { get; set; }
        public int Availability { get; set; }
    }

      public class RoomTypes
    {
        public List<RoomTypeList> RoomTypeList { get; set; }
    }

public class monthwiseinsert
    {
        public HotelCriteria HotelCriteria { get; set; }
        public RoomTypes RoomTypes { get; set; }
    }

The method which is used to create the document (This is created from other documents which i have in my collection):

public IHttpActionResult InventoryInsertDate()
    {
        Database database = GetDatabase("xyz").Result;
        DocumentCollection collection = GetCollection(database, "xyzCollection").Result;
        List<monthwiseinsert> roomtypeavail = new List<monthwiseinsert>();

        var Hotelwithroomtype = (client.CreateDocumentQuery<monthwiseinsert>(collection.SelfLink).Where(x=>x.HotelCriteria.HotelName!=null)
                   ).ToList();
        foreach(var item in Hotelwithroomtype)
        {
            client.CreateDocumentAsync(collection.SelfLink, item);

        }

        return Json("OK");
    }

Body:
You need to specify the Id of the record you want to update. Change monthwiseinsert to include Id field. Ex-

public class DocumentDbRecord
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }
}
public class HotelMonthlyRecord : DocumentDbRecord
{
    public HotelCriteria HotelCriteria { get; set; }
    public RoomTypes RoomTypes { get; set; }
}

For updating record, you can use UpsertDocumentAsync

    public async Task UpdateDocumentAsync(string databaseName, string collectionName, int newAvailability)
    {
        var taskList = new List<Task>();
        var collection = await this.GetDocumentCollectionAsync(databaseName, collectionName);
        var hotelRecords = client.CreateDocumentQuery<HotelMonthlyRecord>(collection.SelfLink)
            .Where(x => x.HotelCriteria.HotelName != null)
            .ToList();
        foreach (var item in hotelRecords)
        {
            item.RoomTypes.RoomTypeList.ForEach(i => i.Availability = newAvailability);
            taskList.Add(client.UpsertDocumentAsync(collection.SelfLink, item));
        }

        if (taskList.Any())
        {
            await Task.WhenAll(taskList);
        }
    }

Hope this help.


问:
Order of operands in C
Say you have x = exp1 + exp2 in c. It might be evaluated by first evaluating exp1 then exp2 and adding the results however it may evaluate exp2 first.

How do you find out which side is evaluated first? I would like to make x = 1/2 depending on which one was evaluated first.

Any ideas?

答:
Okay, you can do it like this:

```<code>#include <stdbool.h>
#include <stdio.h>

static int first(int value)
{
  static bool first = false;
  if (!first)
  {
    first = true;
    return value;
  }
  return 0;
}

int main(void)
{
  const int x = first(1) + first(2);
  printf("got %d\n", x);
}
</code>```

On ideone.com, I got 1.

Note that this proves nothing, since there is no defined behavior here. The C99 draft says (in 6.5 Expressions, paragraph 3):

The grouping of operators and operands is indicated by the
  syntax.72)
  Except as specified later (for the function-call (), &&, ||,
  ?:, and comma operators), the order of evaluation of subexpressions and
  the order in which side effects take place are both unspecified.

Title: Order of operands in C

Body:
Okay, you can do it like this:

#include <stdbool.h>
#include <stdio.h>

static int first(int value)
{
  static bool first = false;
  if (!first)
  {
    first = true;
    return value;
  }
  return 0;
}

int main(void)
{
  const int x = first(1) + first(2);
  printf("got %d\n", x);
}

On ideone.com, I got 1.

Note that this proves nothing, since there is no defined behavior here. The C99 draft says (in 6.5 Expressions, paragraph 3):

The grouping of operators and operands is indicated by the
  syntax.72)
  Except as specified later (for the function-call (), &&, ||,
  ?:, and comma operators), the order of evaluation of subexpressions and
  the order in which side effects take place are both unspecified.


问:
asp.net MVC adding Multiple classes not giving expected result
Code

C#

```<code> public static class MyClass
    {
        public static object Foo = new { @class = "foo" };
        public static object Barbaz = new { @class = "bar baz" };
    }
</code>```

cshtml

```<code><div @MyClass.Foo></div>
<div @MyClass.Barbaz></div>
</code>```

Desired HTML result

```<code><div class="foo"></div>
<div class="foo bar"></div>
</code>```

Actual HTML result

```<code><div {="" class="foo" }=""></div>
</code>```

(works, but looks wrong)

```<code><div {="" class="bar" baz="" }=""></div>
</code>```

(doesn't work, and looks even more wrong)

How should I declare Foo and Barbaz to achieve my desired result?

答:
Do not use objects but strings in properties like this:

```<code>    public static class MyClass
    {
        public static string Foo = "foo";
        public static string Barbaz = "bar baz";
    }
</code>```

and in view set up code:

```<code><div class = "@MyClass.Foo"></div>
<div class="@MyClass.Barbaz"></div>
</code>```

Side note: you will probably need to revise your logic as setting css classes from c# backend is not something you should do very often. Try to avoid that. Instead use flags based on which you will have appropriate css classes applied in view.

Body:
Code

C#

 public static class MyClass
    {
        public static object Foo = new { @class = "foo" };
        public static object Barbaz = new { @class = "bar baz" };
    }

cshtml

Desired HTML result

Actual HTML result

(works, but looks wrong)

(doesn't work, and looks even more wrong)

How should I declare Foo and Barbaz to achieve my desired result?

Body:
Do not use objects but strings in properties like this:

    public static class MyClass
    {
        public static string Foo = "foo";
        public static string Barbaz = "bar baz";
    }

and in view set up code:

<div class = "@MyClass.Foo"></div>
<div class="@MyClass.Barbaz"></div>

Side note: you will probably need to revise your logic as setting css classes from c# backend is not something you should do very often. Try to avoid that. Instead use flags based on which you will have appropriate css classes applied in view.


问:
return separate values from an array in json
I have an instance variable @seats in a controller having value as follows (I checked the value using a byebug breakpoint)

```<code>#<Programmability::Response:0x007fdae0bb84e8 @return_code=0, @outputs=[[2, 4]], @table=#<Programmability::Table:0x007fdae0bb8538 @rows=nil, @columns=["column1", "column2"]>>
</code>```

How do i display the following in JSON

```<code>column1: 2
column2: 4
</code>```

I have the following line in JSON which returns output: [[2, 4]]

```<code>json.output        @seats.blank? ? nil : @seats.outputs
</code>```

答:
Based on this:

I have following line in json which returns output: [[2, 4]]

```<code>json.output        @seats.blank? ? nil : @seats.outputs
</code>```

I'm guessing you are already using jbuilder templates. If so, to get the output you mentioned above, I think you can do something like this in your jbuilder template:

```<code>json.output do
  @seats.outputs.each_with_index |col, ndx|
    json.set! "column#{ndx}", col
  end
end
</code>```

I have not tested this but it would seem to work based on the docs here: https://github.com/rails/jbuilder

Body:
I have an instance variable @seats in a controller having value as follows (I checked the value using a byebug breakpoint)

#<Programmability::Response:0x007fdae0bb84e8 @return_code=0, @outputs=[[2, 4]], @table=#<Programmability::Table:0x007fdae0bb8538 @rows=nil, @columns=["column1", "column2"]>>

How do i display the following in JSON

column1: 2
column2: 4

I have the following line in JSON which returns output: [[2, 4]]

json.output        @seats.blank? ? nil : @seats.outputs

Body:
Based on this:

I have following line in json which returns output: [[2, 4]]

json.output        @seats.blank? ? nil : @seats.outputs

I'm guessing you are already using jbuilder templates. If so, to get the output you mentioned above, I think you can do something like this in your jbuilder template:

json.output do
  @seats.outputs.each_with_index |col, ndx|
    json.set! "column#{ndx}", col
  end
end

I have not tested this but it would seem to work based on the docs here: https://github.com/rails/jbuilder


问:
SalesForce OAuth failed with {"error_description":"authentication failure","error":"invalid_grant"} response
Can't setup SalesForce OAuth for a week with the same error. Don't have any idea anymore :(

What I did:

Create account in salesforce

Create New App, get security key and secret to use in my WebApp

Send GET request to https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=%s&redirect_uri=%s

The request above redirects me to the login page, when I log in

Got the code in my app

Send POST request to https://login.salesforce.com/services/oauth2/token with grant_type, client_id, client_secret, redirect_uri and code form parameters.

Receive HTTP 400 with JSON below:
{"error_description":"authentication failure","error":"invalid_grant"}

Guys, please, tell me what am I doing wrong?
When I use PostMan google plugin with all my credentials all works fine, but when I do requests locally - receive error: {"error_description":"authentication failure","error":"invalid_grant"}

IP relaxation set to Relax IP restrictions callback_uri is with HTTPS

May it be that my IP blocked by SalesForce? Have no idea except this :(

答:
Step 1:
Create an account. You can create a (free) developer account at developer.salesforce.com
Step 2:
Ignore all the landing pages and getting started crap. It’s an endless marketing loop.
Step 3:
Click the “Setup” link

Step 4:
In the lefthand toolbar, under “Create”, click “Apps”

Step 5:
Under “Connected Apps” click “New”

Step 6:
Fill out the form. Important fields are marked below (you can leave the rest blank)

Step 7:
Be advised that Salesforce has crappy availability.

Step 8:
Press continue. You finally have your key (client id) and secret (client secret).

Step 9:
But wait! You’re not done yet.

Make sure IP restrictions are disabled as well, and make sure that Permitted Users is set to “All users may self-authorize.”
If you’re concerned about disabling security, don’t be for now, you just want to get this working for now so you can make API calls. Tighten permissions once you have everything working, one at a time, so you can figure out what setting is giving you authentication errors.

Step 10:
Celebrate! This curl call should succeed:
curl -v https://login.salesforce.com/services/oauth2/token -d “grant_type=password” -d “client_id=YOUR_CLIENT_ID_FROM_STEP_8″ -d “client_secret=YOUR_CLIENT_SECRET_FROM_STEP_8″ -d “username=user@wherever.com” -d “password=foo@bar.com”
Notes:
- You shouldn’t be doing password authorization if you’re building a multi-tenant app, where users need to authorize their own application. Use the Oauth2 workflow for that.

Follow This tutorial.this will solve your login queries.

http://www.calvinfroedge.com/salesforce-how-to-generate-api-credentials/


问:
How to write update query for updating multiple rows into single sql query in ios
I want to write update query for updating multiple rows into single SQL query in Objective-C.

Does anyone knows how i can achieve that ? Please help.

Here is my update query:-

```<code>UPDATE chatDetailTable SET threadId = '584140258203930624', createdByFirstName = 'Poonam', createdByLastName = 'Deshpande', createdById = '201', createdByImgUrl = '', createdByRole = 'teacher', msgType = 'text/plain', msgText = '1111', canEdit = '1', deliverOn = '2017-03-30T12:23:20.73Z', thumbUrl = '', isOwned = '1', replies = '0', mediaPath = '', isFailed = '', read = '1', isSeen = '0', key = '', gmid = '', contact_id = '2', recipientFirstName = 'Indrajit', recipientLastName = 'Joshi', recipientId = '2', recipientImgUrl = '', recipientRole = 'user', isGroup = '0', threadStatus = 'open', mediaUrl = '(null)', status = 'pendingApproval', reviewedById = '0', broadcastId = '584140258136821760' WHERE msgId = '584140258203930625';UPDATE chatDetailTable SET threadId = '584140258266845184', createdByFirstName = 'Poonam', createdByLastName = 'Deshpande', createdById = '201', createdByImgUrl = '', createdByRole = 'teacher', msgType = 'text/plain', msgText = '1111', canEdit = '1', deliverOn = '2017-03-30T12:23:20.73Z', thumbUrl = '', isOwned = '1', replies = '0', mediaPath = '', isFailed = '', read = '1', isSeen = '0', key = '', gmid = '', contact_id = '4', recipientFirstName = 'Hrusikesh', recipientLastName = 'Desai', recipientId = '4', recipientImgUrl = '', recipientRole = 'user', isGroup = '0', threadStatus = 'open', mediaUrl = '(null)', status = 'pendingApproval', reviewedById = '0', broadcastId = '584140258136821760' WHERE msgId = '584140258266845185';UPDATE chatDetailTable SET threadId = '584140258266845186', createdByFirstName = 'Poonam', createdByLastName = 'Deshpande', createdById = '201', createdByImgUrl = '', createdByRole = 'teacher', msgType = 'text/plain', msgText = '1111', canEdit = '1', deliverOn = '2017-03-30T12:23:20.73Z', thumbUrl = '', isOwned = '1', replies = '0', mediaPath = '', isFailed = '', read = '1', isSeen = '0', key = '', gmid = '', contact_id = '1002', recipientFirstName = 'Pramod', recipientLastName = 'Agarwal', recipientId = '1002', recipientImgUrl = '', recipientRole = 'branchAdmin', isGroup = '0', threadStatus = 'open', mediaUrl = '(null)', status = 'pendingApproval', reviewedById = '0', broadcastId = '584140258136821760' WHERE msgId = '584140258333954048';
</code>```

答:
Please try this

You can update only rows you want updating

```<code>"update TableName set fieldName1 = 'value1', fieldName2 = 'value2', fieldName3 ='value3' where id IN(1,2,3)"
</code>```

IN : it update only 1,2 and 3 id's rows only

Hope it work for you

Body:
I want to write update query for updating multiple rows into single SQL query in Objective-C.

Does anyone knows how i can achieve that ? Please help.

Here is my update query:-

UPDATE chatDetailTable SET threadId = '584140258203930624', createdByFirstName = 'Poonam', createdByLastName = 'Deshpande', createdById = '201', createdByImgUrl = '', createdByRole = 'teacher', msgType = 'text/plain', msgText = '1111', canEdit = '1', deliverOn = '2017-03-30T12:23:20.73Z', thumbUrl = '', isOwned = '1', replies = '0', mediaPath = '', isFailed = '', read = '1', isSeen = '0', key = '', gmid = '', contact_id = '2', recipientFirstName = 'Indrajit', recipientLastName = 'Joshi', recipientId = '2', recipientImgUrl = '', recipientRole = 'user', isGroup = '0', threadStatus = 'open', mediaUrl = '(null)', status = 'pendingApproval', reviewedById = '0', broadcastId = '584140258136821760' WHERE msgId = '584140258203930625';UPDATE chatDetailTable SET threadId = '584140258266845184', createdByFirstName = 'Poonam', createdByLastName = 'Deshpande', createdById = '201', createdByImgUrl = '', createdByRole = 'teacher', msgType = 'text/plain', msgText = '1111', canEdit = '1', deliverOn = '2017-03-30T12:23:20.73Z', thumbUrl = '', isOwned = '1', replies = '0', mediaPath = '', isFailed = '', read = '1', isSeen = '0', key = '', gmid = '', contact_id = '4', recipientFirstName = 'Hrusikesh', recipientLastName = 'Desai', recipientId = '4', recipientImgUrl = '', recipientRole = 'user', isGroup = '0', threadStatus = 'open', mediaUrl = '(null)', status = 'pendingApproval', reviewedById = '0', broadcastId = '584140258136821760' WHERE msgId = '584140258266845185';UPDATE chatDetailTable SET threadId = '584140258266845186', createdByFirstName = 'Poonam', createdByLastName = 'Deshpande', createdById = '201', createdByImgUrl = '', createdByRole = 'teacher', msgType = 'text/plain', msgText = '1111', canEdit = '1', deliverOn = '2017-03-30T12:23:20.73Z', thumbUrl = '', isOwned = '1', replies = '0', mediaPath = '', isFailed = '', read = '1', isSeen = '0', key = '', gmid = '', contact_id = '1002', recipientFirstName = 'Pramod', recipientLastName = 'Agarwal', recipientId = '1002', recipientImgUrl = '', recipientRole = 'branchAdmin', isGroup = '0', threadStatus = 'open', mediaUrl = '(null)', status = 'pendingApproval', reviewedById = '0', broadcastId = '584140258136821760' WHERE msgId = '584140258333954048';

Body:
Please try this

You can update only rows you want updating

"update TableName set fieldName1 = 'value1', fieldName2 = 'value2', fieldName3 ='value3' where id IN(1,2,3)"

IN : it update only 1,2 and 3 id's rows only

Hope it work for you


问:
VS2015 application crashes when calling C++ function with delegates
I am using ABBYY's FineReader engine, and when trying to initialize, my application crashes (while debugging). If I run the .exe it works fine.

Declarations:

```<code><DllImport("kernel32.dll")>
Private Shared Function LoadLibrary(dllToLoad As String) As IntPtr
End Function
<DllImport("kernel32.dll")>
Private Shared Function GetProcAddress(hModule As IntPtr, procedureName As String) As IntPtr
End Function
<DllImport("kernel32.dll")>
Private Shared Function FreeLibrary(hModule As IntPtr) As Boolean
End Function

' FREngine.dll functions
<UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet:=CharSet.Unicode)>
Private Delegate Function GetEngineObject(devSN As String, reserved1 As String, reserved2 As String, ByRef engine As FREngine.IEngine) As Integer
<UnmanagedFunctionPointer(CallingConvention.StdCall)>
Private Delegate Function DeinitializeEngine() As Integer
<UnmanagedFunctionPointer(CallingConvention.StdCall)>
Private Delegate Function DllCanUnloadNow() As Integer
</code>```

and to initialize:

```<code> ' Load the FREngine.dll library
    dllHandle = LoadLibrary(enginePath)

    Try
        If dllHandle = IntPtr.Zero Then
            Throw New Exception("Can't load " + enginePath)
        End If

        Dim getEngineObjectPtr As IntPtr = GetProcAddress(dllHandle, "GetEngineObject")
        If getEngineObjectPtr = IntPtr.Zero Then
            Throw New Exception("Can't find GetEngineObject function")
        End If
        Dim deinitializeEnginePtr As IntPtr = GetProcAddress(dllHandle, "DeinitializeEngine")
        If deinitializeEnginePtr = IntPtr.Zero Then
            Throw New Exception("Can't find DeinitializeEngine function")
        End If
        Dim dllCanUnloadNowPtr As IntPtr = GetProcAddress(dllHandle, "DllCanUnloadNow")
        If dllCanUnloadNowPtr = IntPtr.Zero Then
            Throw New Exception("Can't find DllCanUnloadNow function")
        End If

        ' Convert pointers to delegates
        _getEngineObject = DirectCast(Marshal.GetDelegateForFunctionPointer(getEngineObjectPtr, GetType(GetEngineObject)), GetEngineObject)
        _deinitializeEngine = DirectCast(Marshal.GetDelegateForFunctionPointer(deinitializeEnginePtr, GetType(DeinitializeEngine)), DeinitializeEngine)
        _dllCanUnloadNow = DirectCast(Marshal.GetDelegateForFunctionPointer(dllCanUnloadNowPtr, GetType(DllCanUnloadNow)), DllCanUnloadNow)

        ' Call the GetEngineObject function
        Dim hresult As Integer = _getEngineObject(developerSN, Nothing, Nothing, m_engine)
</code>```

The last line is the one that causes the crash (no errors or output). The same code works fine in VS2010, but not in VS2015. What am I missing here?

答: Look into the project properties of your project in VS2010 and apply the same settings in VS2015, Check include library paths and make sure the DLL is located in the right location</p>

Body:
I am using ABBYY's FineReader engine, and when trying to initialize, my application crashes (while debugging). If I run the .exe it works fine.

Declarations:

<DllImport("kernel32.dll")>
Private Shared Function LoadLibrary(dllToLoad As String) As IntPtr
End Function
<DllImport("kernel32.dll")>
Private Shared Function GetProcAddress(hModule As IntPtr, procedureName As String) As IntPtr
End Function
<DllImport("kernel32.dll")>
Private Shared Function FreeLibrary(hModule As IntPtr) As Boolean
End Function

' FREngine.dll functions
<UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet:=CharSet.Unicode)>
Private Delegate Function GetEngineObject(devSN As String, reserved1 As String, reserved2 As String, ByRef engine As FREngine.IEngine) As Integer
<UnmanagedFunctionPointer(CallingConvention.StdCall)>
Private Delegate Function DeinitializeEngine() As Integer
<UnmanagedFunctionPointer(CallingConvention.StdCall)>
Private Delegate Function DllCanUnloadNow() As Integer

and to initialize:

 ' Load the FREngine.dll library
    dllHandle = LoadLibrary(enginePath)

    Try
        If dllHandle = IntPtr.Zero Then
            Throw New Exception("Can't load " + enginePath)
        End If

        Dim getEngineObjectPtr As IntPtr = GetProcAddress(dllHandle, "GetEngineObject")
        If getEngineObjectPtr = IntPtr.Zero Then
            Throw New Exception("Can't find GetEngineObject function")
        End If
        Dim deinitializeEnginePtr As IntPtr = GetProcAddress(dllHandle, "DeinitializeEngine")
        If deinitializeEnginePtr = IntPtr.Zero Then
            Throw New Exception("Can't find DeinitializeEngine function")
        End If
        Dim dllCanUnloadNowPtr As IntPtr = GetProcAddress(dllHandle, "DllCanUnloadNow")
        If dllCanUnloadNowPtr = IntPtr.Zero Then
            Throw New Exception("Can't find DllCanUnloadNow function")
        End If

        ' Convert pointers to delegates
        _getEngineObject = DirectCast(Marshal.GetDelegateForFunctionPointer(getEngineObjectPtr, GetType(GetEngineObject)), GetEngineObject)
        _deinitializeEngine = DirectCast(Marshal.GetDelegateForFunctionPointer(deinitializeEnginePtr, GetType(DeinitializeEngine)), DeinitializeEngine)
        _dllCanUnloadNow = DirectCast(Marshal.GetDelegateForFunctionPointer(dllCanUnloadNowPtr, GetType(DllCanUnloadNow)), DllCanUnloadNow)

        ' Call the GetEngineObject function
        Dim hresult As Integer = _getEngineObject(developerSN, Nothing, Nothing, m_engine)

The last line is the one that causes the crash (no errors or output). The same code works fine in VS2010, but not in VS2015. What am I missing here?


问:
Can you have multiline HTML5 placeholder text in a <textarea>?
I have ghost text in textfields that disappear when you focus on them using HTML5's placeholder attribute:

```<code><input type="text" name="email" placeholder="Enter email"/>
</code>```

I want to use that same mechanism to have multiline placeholder text in a textarea, maybe something like this:

```<code><textarea name="story" placeholder="Enter story\n next line\n more"></textarea>
</code>```

But those \ns show up in the text and don't cause newlines...  Is there a way to have a multiline placeholder?

UPDATE: The only way I got this to work was utilizing the jQuery Watermark plugin, which accepts HTML in the placeholder text:

```<code>$('.textarea_class').watermark('Enter story<br/> * newline', {fallback: false});
</code>```

答:
Watermark solution in the original post works great. Thanks for it.
In case anyone needs it, here is an angular directive for it.</p>

```<code>(function () {
  'use strict';

  angular.module('app')
    .directive('placeholder', function () {
      return {
        restrict: 'A',
        link:     function (scope, element, attributes) {
          if (element.prop('nodeName') === 'TEXTAREA') {
            var placeholderText = attributes.placeholder.trim();

            if (placeholderText.length) {
              // support for both '\n' symbol and an actual newline in the placeholder element
              var placeholderLines = Array.prototype.concat
                .apply([], placeholderText.split('\n').map(line => line.split('\\n')))
                .map(line => line.trim());

              if (placeholderLines.length > 1) {
                element.watermark(placeholderLines.join('<br>\n'));
              }
            }
          }
        }
      };
    });
}());
</code>```

Body:
I have ghost text in textfields that disappear when you focus on them using HTML5's placeholder attribute:

<input type="text" name="email" placeholder="Enter email"/>

I want to use that same mechanism to have multiline placeholder text in a textarea, maybe something like this:

<textarea name="story" placeholder="Enter story\n next line\n more"></textarea>

But those \ns show up in the text and don't cause newlines...  Is there a way to have a multiline placeholder?

UPDATE: The only way I got this to work was utilizing the jQuery Watermark plugin, which accepts HTML in the placeholder text:

$('.textarea_class').watermark('Enter story
 * newline', {fallback: false});

Body:
Watermark solution in the original post works great. Thanks for it.
In case anyone needs it, here is an angular directive for it.

(function () {
  'use strict';

  angular.module('app')
    .directive('placeholder', function () {
      return {
        restrict: 'A',
        link:     function (scope, element, attributes) {
          if (element.prop('nodeName') === 'TEXTAREA') {
            var placeholderText = attributes.placeholder.trim();

            if (placeholderText.length) {
              // support for both '\n' symbol and an actual newline in the placeholder element
              var placeholderLines = Array.prototype.concat
                .apply([], placeholderText.split('\n').map(line => line.split('\\n')))
                .map(line => line.trim());

              if (placeholderLines.length > 1) {
                element.watermark(placeholderLines.join('<br>\n'));
              }
            }
          }
        }
      };
    });
}());


问:
Linefeed when using copy for text files
I have a text file a.txt

```<code>hello
there
</code>```

and a text file b.txt

```<code>how
are
you?
</code>```

By using copy a.txt+b.txt c.txt I get a c.txt

```<code>hello
therehow
are
you?
</code>```

How do I need to change the command to get a new line/linefeed between there and how?

答:
Not very elegant, but it works:

```<code>for %%a in (a.txt,b.txt) do type %%a >>c.txt && echo. >>c.txt
</code>```

There will be a blank line at the end of the last file in the list though.

If you want to use wildcards:

```<code>for /f "tokens=*" %%a in ('dir /b *.txt') do type "%%a" >>c.txt && echo. >>c.txt
</code>```

Title: Linefeed when using copy for text files

Body:
I have a text file a.txt

hello
there

and a text file b.txt

how
are
you?

By using copy a.txt+b.txt c.txt I get a c.txt

hello
therehow
are
you?

How do I need to change the command to get a new line/linefeed between there and how?

Body:
Not very elegant, but it works:

for %%a in (a.txt,b.txt) do type %%a >>c.txt && echo. >>c.txt

There will be a blank line at the end of the last file in the list though.

If you want to use wildcards:

for /f "tokens=*" %%a in ('dir /b *.txt') do type "%%a" >>c.txt && echo. >>c.txt


问:
Read a variable length integer from the supplied InputStream
I was looking a bit above the Netflix Hollow library code (https://github.com/Netflix/hollow) and I found this function to which I can't find any sense (Warning: I don't know much about Java ).
Theoretically, the function returns a variable-length integer from the InputStream.

```<code>/**
 * Read a variable length integer from the supplied InputStream
 */
public static int readVInt(InputStream in) throws IOException {
    byte b = (byte)in.read();

    if(b == (byte) 0x80)
        throw new RuntimeException("Attempting to read null value as int");

    int value = b & 0x7F;
    while ((b & 0x80) != 0) {
      b = (byte)in.read();
      value <<= 7;
      value |= (b & 0x7F);
    }

    return value;
}
</code>```

I comment my doubts:

1) Int value = b & 0x7F : The result of this is always b, right? What's the point?

2) while ((b & 0x80) != 0) : The result of b & 0x80 (If b is an integer digit, that is, coded in decimal from 0 to 9, would be 48-57 in decimal) is always 0. Therefore, will never enter the loop...

答:
The point is: probably they are using their "own" protocol that determines how to write and read values using streams.

And in that protocol, the value 0x80 has the special meaning: "end of value".

Meaning: the "writer" parts writes a sequence of bytes, and then put a 0x80 to signal that no more bytes will be following. And then:

```<code>while ((b & 0x80) != 0) {
</code>```

evaluates to false when 0x8? is read. Meaning: if that first bit is set, then "end of message".

In other words: when you want to read an int from that stream; and the first byte you get is 0x80 - then: "no value for your"; thus the exception.

Then you just reading byte by byte; and you shift those bytes into the result int value - until that 0x80 "end of value" marker byte comes in.

Body:
I was looking a bit above the Netflix Hollow library code (https://github.com/Netflix/hollow) and I found this function to which I can't find any sense (Warning: I don't know much about Java ).
Theoretically, the function returns a variable-length integer from the InputStream.

/**
 * Read a variable length integer from the supplied InputStream
 */
public static int readVInt(InputStream in) throws IOException {
    byte b = (byte)in.read();

    if(b == (byte) 0x80)
        throw new RuntimeException("Attempting to read null value as int");

    int value = b & 0x7F;
    while ((b & 0x80) != 0) {
      b = (byte)in.read();
      value <<= 7;
      value |= (b & 0x7F);
    }

    return value;
}

I comment my doubts:

1) Int value = b & 0x7F : The result of this is always b, right? What's the point?

2) while ((b & 0x80) != 0) : The result of b & 0x80 (If b is an integer digit, that is, coded in decimal from 0 to 9, would be 48-57 in decimal) is always 0. Therefore, will never enter the loop...

Body:
The point is: probably they are using their "own" protocol that determines how to write and read values using streams.

And in that protocol, the value 0x80 has the special meaning: "end of value".

Meaning: the "writer" parts writes a sequence of bytes, and then put a 0x80 to signal that no more bytes will be following. And then:

while ((b & 0x80) != 0) {

evaluates to false when 0x8? is read. Meaning: if that first bit is set, then "end of message".

In other words: when you want to read an int from that stream; and the first byte you get is 0x80 - then: "no value for your"; thus the exception.

Then you just reading byte by byte; and you shift those bytes into the result int value - until that 0x80 "end of value" marker byte comes in.


问:
Push multiple objects at once
How can I do multiple object pushes at once with angularfire2?

Just pushing an array of objects doesn't set keys for each object.

this.af.database.list('/symbols/').push({
  typ: "symbol1",
  // ....
});
this.af.database.list('/symbols/').push({
  typ: "symbol2",
  // ....
});
```

答:
With the regular Firebase JavaScript SDK, you can accomplish this with:

```<code>var updates = {};
updates['/symbols/'+ref.push().key] = {
  typ :"symbol1", ....
};
updates['/symbols/'+ref.push().key] = {
  typ :"symbol2", ....
};
ref.update(updates);
</code>```

Since AngularFire2 is built on top of the normal Firebase JavaScript SDK, they interop perfectly. So you can just use the Firebase JavaScript SDK for this operation.

ContentLicense: CC BY-SA 4.0

Title: Push multiple objects at once

Body:
With the regular Firebase JavaScript SDK, you can accomplish this with:

var updates = {};
updates['/symbols/'+ref.push().key] = {
  typ :"symbol1", ....
};
updates['/symbols/'+ref.push().key] = {
  typ :"symbol2", ....
};
ref.update(updates);

Since AngularFire2 is built on top of the normal Firebase JavaScript SDK, they interop perfectly. So you can just use the Firebase JavaScript SDK for this operation.


问:
How to get the content of a textblock and show it multiple times?
I am trying to make a program that helps me with checking on which lines there are errors on an arma 3 server. It currently looks like this:

I have a few problems. Every time I mark a "bug" and press the show button it comes up with this:

How do i get the content of the textbox? This is my code:

```<code>public partial class MainWindow : Window
{
    public double output = 0;
    public string test1 = "";
    public MainWindow()
    {
        InitializeComponent();
        textOutput.Text = output.ToString();
        textBugs.Text = test1;
    }

    private void buttonDecrease_Click(object sender, RoutedEventArgs e)
    {
        output--;
        textOutput.Text = output.ToString();
    }

    private void buttonIncrease_Click(object sender, RoutedEventArgs e)
    {
        output++;
        textOutput.Text = output.ToString();
    }

    private void buttonReset_Click(object sender, RoutedEventArgs e)
    {
        output = 0;
        test1 = "N/A";
        textOutput.Text = output.ToString();
        textBugs.Text = test1;
    }

    private void buttonBug_Click(object sender, RoutedEventArgs e)
    {
        test1 += textBugs.ContentStart.ToString();
    }

    private void buttonShow_Click(object sender, RoutedEventArgs e)
    {
        textBugs.Text = test1;
    }
}
</code>```

答:
This line is the problem.

```<code>test1 += textBugs.ContentStart.ToString();
</code>```

ContentStart is a property on a RichTextBox with the type TextPointer. You're just assigning the string representation of this type to the string test1.

To get the plain text from the RTB:

```<code>test1 += textBugs.Text;
</code>```

Body:
I am trying to make a program that helps me with checking on which lines there are errors on an arma 3 server. It currently looks like this:

I have a few problems. Every time I mark a "bug" and press the show button it comes up with this:

How do i get the content of the textbox? This is my code:

public partial class MainWindow : Window
{
    public double output = 0;
    public string test1 = "";
    public MainWindow()
    {
        InitializeComponent();
        textOutput.Text = output.ToString();
        textBugs.Text = test1;
    }

    private void buttonDecrease_Click(object sender, RoutedEventArgs e)
    {
        output--;
        textOutput.Text = output.ToString();
    }

    private void buttonIncrease_Click(object sender, RoutedEventArgs e)
    {
        output++;
        textOutput.Text = output.ToString();
    }

    private void buttonReset_Click(object sender, RoutedEventArgs e)
    {
        output = 0;
        test1 = "N/A";
        textOutput.Text = output.ToString();
        textBugs.Text = test1;
    }

    private void buttonBug_Click(object sender, RoutedEventArgs e)
    {
        test1 += textBugs.ContentStart.ToString();
    }

    private void buttonShow_Click(object sender, RoutedEventArgs e)
    {
        textBugs.Text = test1;
    }
}

Body:
This line is the problem.

test1 += textBugs.ContentStart.ToString();

ContentStart is a property on a RichTextBox with the type TextPointer. You're just assigning the string representation of this type to the string test1.

To get the plain text from the RTB:

test1 += textBugs.Text;


问:
laravel in a subfolder - broken routes
I am trying to reloacte my laravel application to a subfolder.

My main page is loading correctly at mysite.com/folder but when I try to login it goes to mysite.com/auth/login which returns a 404 error.

How can i change it so all of the routes will add the /folder so for example it will be mysite.com/folder/auth/login?

I have apache2 web server and the public folder is in webroot/folder and the rest of the files are on the same level as webroot in another folder

I followedthis to get to the stage im at currently :
https://medium.com/laravel-news/the-simple-guide-to-deploy-laravel-5-application-on-shared-hosting-1a8d0aee923e

答: Try to change your RewriteBase in the .htaccess file located in the public folder. If you currently have RewriteBase / you probably should write RewriteBase /folder/ instead.

Title: laravel in a subfolder - broken routes


问:
401 while creating customer in quickbooks using php api
I keep getting 401 in spite of using the test keys from the playground app, can someone help on how to resolve this, code works fine on a dev server, as soon as code moved to qa server i created a new QuickBooks account and a new app and now i keep getting a 401</p>

答:
Just moving code from one server to another is a guaranteed way to break anything OAuth related.

You would need to at least:

Move the code

Change the OAuth URLs in Intuit's control panel to point to the new server

Change the OAuth URLs in your code

Clear any stored OAuth access tokens from your database (if you moved the data in the database to the new server as well)

Reconnect to QuickBooks, via the [Connect to QuickBooks] button

Additional notes:

Why are you using test keys from Intuit's playground app? Create your own app, and use your own keys.

If you created a new app, you'll also need to swap our your OAuth consumer key, OAuth consumer secret, and App token in your code.

Be aware that if your app is in DEVELOPMENT mode, then you can only connect to DEVELOPMENT QuickBooks accounts. If you created a LIVE QuickBooks account, you can only connect to it with PRODUCTION/LIVE app credentials (e.g. you need to PUBLISH your app).

Since you didn't post:

Your code

Screenshots of the credentials from Intuit's control panel (assuming they are dev/sandbox and thus safe to post)

Any of the HTTP requests/responses you're sending/receiving

We won't be able to really help you much further.


问:
ASP .NET MVC multiple models in one view
I have this two classes:

```<code>public class Kolobezka : IEntity1
{
    public virtual int Id { get; set; }
    public virtual int VelikostKola { get; set; }
    public virtual string Znacka { get; set; }
    public virtual string Stav { get; set; }
    public virtual string Description { get; set; }
    public virtual Kategorie_kolobezek Kategorie { get; set; }
    public virtual int Dostupnost { get; set; }

}
public class Rezervace : IEntity1
    {
        public virtual int Id { get; set; }
        public virtual Kolobezka Rez_kolobezky { get; set; }
        [Required(ErrorMessage = "Jméno je požadováno!")]
        public virtual string Jmeno { get; set; }
        [Required(ErrorMessage = "Příjmení je požadováno!")]
        public virtual string Prijmeni { get; set; }
        [Required(ErrorMessage = "Datum začátku rezervace je požadováno!")]
        public virtual DateTime Datum_od { get; set; }
        [Required(ErrorMessage = "Datum konce rezervace je požadováno!")]
        public virtual DateTime Datum_do { get; set; }
        public virtual string Popis { get; set; }
    }
</code>```

So I need in one view called Index use two Ilists from those two clases because of this:

```<code>@foreach (Kolobezka k in Model)
        {

            foreach (Rezervace r1 in r)
            {
                if(k.Id == r1.Rez_kolobezky.Id && r1.Datum_od < DateTime.Now && r1.Datum_do > DateTime.Now)
                {
                    k.Dostupnost = 1;
                }
            }

            if (k.Dostupnost == 0)
            {
                <tr class="bg-danger">
                    <td>
                        @Ajax.ActionLink(k.Id.ToString(), "Detail", new { id = k.Id },
                       new AjaxOptions() { UpdateTargetId = "modalContent",
                           InsertionMode = InsertionMode.Replace, OnBegin = "openModalWindow" })
                    </td>
                    <td>@k.VelikostKola</td>
                    <td>@k.Znacka</td>
                    <td>@k.Kategorie.Nazev</td>
                    <td>@k.Stav</td>
                </tr>
            }
</code>```

Whot should I write instead r in the second foreach.
The beginning of index view looks like this:

```<code>@using ClassLibrary1.Model
@model IList<Kolobezka>

@{
    ViewBag.Title = "Index";
}
</code>```

Thank you a lot.

答:
Why don't you create a class view-model and on the controller you return the object(created on view model) and build in the view what is returned on the controller.</p>

```<code>@x.ViewModel.Name
</code>```

Body:
I have this two classes:

public class Kolobezka : IEntity1
{
    public virtual int Id { get; set; }
    public virtual int VelikostKola { get; set; }
    public virtual string Znacka { get; set; }
    public virtual string Stav { get; set; }
    public virtual string Description { get; set; }
    public virtual Kategorie_kolobezek Kategorie { get; set; }
    public virtual int Dostupnost { get; set; }

}
public class Rezervace : IEntity1
    {
        public virtual int Id { get; set; }
        public virtual Kolobezka Rez_kolobezky { get; set; }
        [Required(ErrorMessage = "Jméno je požadováno!")]
        public virtual string Jmeno { get; set; }
        [Required(ErrorMessage = "Příjmení je požadováno!")]
        public virtual string Prijmeni { get; set; }
        [Required(ErrorMessage = "Datum začátku rezervace je požadováno!")]
        public virtual DateTime Datum_od { get; set; }
        [Required(ErrorMessage = "Datum konce rezervace je požadováno!")]
        public virtual DateTime Datum_do { get; set; }
        public virtual string Popis { get; set; }
    }

So I need in one view called Index use two Ilists from those two clases because of this:

@foreach (Kolobezka k in Model)
        {

            foreach (Rezervace r1 in r)
            {
                if(k.Id == r1.Rez_kolobezky.Id && r1.Datum_od < DateTime.Now && r1.Datum_do > DateTime.Now)
                {
                    k.Dostupnost = 1;
                }
            }

            if (k.Dostupnost == 0)
            {

                        @Ajax.ActionLink(k.Id.ToString(), "Detail", new { id = k.Id },
                       new AjaxOptions() { UpdateTargetId = "modalContent",
                           InsertionMode = InsertionMode.Replace, OnBegin = "openModalWindow" })

                    @k.VelikostKola
                    @k.Znacka
                    @k.Kategorie.Nazev
                    @k.Stav

            }

Whot should I write instead r in the second foreach.
The beginning of index view looks like this:

@using ClassLibrary1.Model
@model IList<Kolobezka>

@{
    ViewBag.Title = "Index";
}

Thank you a lot.

Body:
Why don't you create a class view-model and on the controller you return the object(created on view model) and build in the view what is returned on the controller.

@x.ViewModel.Name


问:
Python: Conversion of a matrix to ordered form
I am new to Python. I have a matrix in Python as this:

```<code>4 4 4 4 1
4 4 4 4 1
1 1 1 1 7
</code>```

I want to convert it to a matrix as this:

```<code>    1   2   3   4   5   6   7
1   1   0   0   4   0   0   0
2   1   0   0   4   0   0   0
3   4   0   0   0   0   0   1
</code>```

The new matrix has number of columns as the maximum number in the original matrix. The number of rows are the same as number of rows in the actual matrix. The value in new matrix is the count of occurrence of each item.

For ex: 1 appears 4 times in third row of original matrix, so our new matrix has value 4 for [3][1], and so on.

How can I convert this? Thx in advance!

答:
```<code>import numpy as np

old_matrix = np.array([[4, 4, 4, 4, 1],
                       [4, 4, 4, 4, 1],
                       [1, 1, 1, 1, 7]])

new_matrix = np.vstack([np.bincount(row, minlength=old_matrix.max() + 1) for row in old_matrix])
</code>```

Body:
I am new to Python. I have a matrix in Python as this:

4 4 4 4 1
4 4 4 4 1
1 1 1 1 7

I want to convert it to a matrix as this:

    1   2   3   4   5   6   7
1   1   0   0   4   0   0   0
2   1   0   0   4   0   0   0
3   4   0   0   0   0   0   1

The new matrix has number of columns as the maximum number in the original matrix. The number of rows are the same as number of rows in the actual matrix. The value in new matrix is the count of occurrence of each item.

For ex: 1 appears 4 times in third row of original matrix, so our new matrix has value 4 for [3][1], and so on.

How can I convert this? Thx in advance!


问:
How to take screenshot of a uiview and drag in swift?
i got the code but its not working, let me know if im did anything wrong.
In the code i have a imageview which i created programmatically and adding the image into a uiview.Right now im unable to load the image in the "draggingView".

```<code>func longPressed(_ sender : UILongPressGestureRecognizer){

    let locationInView = sender.location(in: self.view)
    let cell = sender.view as? ParamterCollectionViewCell
    var tImageView: UIImageView!
    tImageView.frame = CGRect(x:0, y:0, width: 30 , height:30)
    tImageView.image = parameterImageArray[0]

    switch sender.state {
    case .began:
        // create an NSData object from myView
        let archive = NSKeyedArchiver.archivedData(withRootObject: tImageView!)

        // create a clone by unarchiving the NSData
       draggingView = NSKeyedUnarchiver.unarchiveObject(with: archive) as? UIView

        self.view.addSubview(draggingView!)
        draggingView!.center = locationInView;
        self.view.bringSubview(toFront: draggingView!)

        break

    case .changed:
        if (contentView.frame.contains(locationInView)) {
            draggingView?.center = locationInView;
        }
        break

    case .ended:
        break

    default:
        break

}
</code>```

}
}

答:
Give this a try... Very similar in idea to your code, but I think it might be a bit better of an approach:

```<code>func longPressed(_ sender : UILongPressGestureRecognizer) {

    let locationInView: CGPoint = sender.location(in: self.view)
    let locationInCollectionView: CGPoint = sender.location(in: self.collectionView)

    if sender.state == .began {
        if let indexPath: IndexPath = self.collectionView.indexPathForItem(at: locationInCollectionView) {
            if let cell = self.collectionView.cellForItem(at: indexPath) {

                UIGraphicsBeginImageContext(cell.bounds.size)
                cell.layer.render(in: UIGraphicsGetCurrentContext()!)
                let cellImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()

                self.movingCellImageView = UIImageView(image: cellImage)
                self.movingCellImageView?.alpha = 0.75

                self.view.addSubview(self.movingCellImageView!)
                self.movingCellImageView?.center = locationInView
            }
        }
    }
    // Move movingCellImageView following finger position
    if sender.state == .changed {
        self.movingCellImageView?.center = locationInView
    }
    // Remove movingCellImageView when ended
    if sender.state == .ended {
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: {
            self.movingCellImageView?.alpha = 0
        }, completion: { (success: Bool) in
            self.movingCellImageView?.removeFromSuperview()
            self.movingCellImageView = nil
        })
    }
}
</code>```

References:

Tim Puckett - https://adoptioncurve.net/archives/2014/07/creating-a-draggable-uicollectionviewcell/

Swift implementation by Chan Jing Hong
http://eatliftswift.weebly.com/technical/creating-a-draggable-uicollectionviewcell

Body:
i got the code but its not working, let me know if im did anything wrong.
In the code i have a imageview which i created programmatically and adding the image into a uiview.Right now im unable to load the image in the "draggingView".

func longPressed(_ sender : UILongPressGestureRecognizer){

    let locationInView = sender.location(in: self.view)
    let cell = sender.view as? ParamterCollectionViewCell
    var tImageView: UIImageView!
    tImageView.frame = CGRect(x:0, y:0, width: 30 , height:30)
    tImageView.image = parameterImageArray[0]

    switch sender.state {
    case .began:
        // create an NSData object from myView
        let archive = NSKeyedArchiver.archivedData(withRootObject: tImageView!)

        // create a clone by unarchiving the NSData
       draggingView = NSKeyedUnarchiver.unarchiveObject(with: archive) as? UIView

        self.view.addSubview(draggingView!)
        draggingView!.center = locationInView;
        self.view.bringSubview(toFront: draggingView!)

        break

    case .changed:
        if (contentView.frame.contains(locationInView)) {
            draggingView?.center = locationInView;
        }
        break

    case .ended:
        break

    default:
        break

}

}
}

Body:
Give this a try... Very similar in idea to your code, but I think it might be a bit better of an approach:

func longPressed(_ sender : UILongPressGestureRecognizer) {

    let locationInView: CGPoint = sender.location(in: self.view)
    let locationInCollectionView: CGPoint = sender.location(in: self.collectionView)

    if sender.state == .began {
        if let indexPath: IndexPath = self.collectionView.indexPathForItem(at: locationInCollectionView) {
            if let cell = self.collectionView.cellForItem(at: indexPath) {

                UIGraphicsBeginImageContext(cell.bounds.size)
                cell.layer.render(in: UIGraphicsGetCurrentContext()!)
                let cellImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()

                self.movingCellImageView = UIImageView(image: cellImage)
                self.movingCellImageView?.alpha = 0.75

                self.view.addSubview(self.movingCellImageView!)
                self.movingCellImageView?.center = locationInView
            }
        }
    }
    // Move movingCellImageView following finger position
    if sender.state == .changed {
        self.movingCellImageView?.center = locationInView
    }
    // Remove movingCellImageView when ended
    if sender.state == .ended {
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: {
            self.movingCellImageView?.alpha = 0
        }, completion: { (success: Bool) in
            self.movingCellImageView?.removeFromSuperview()
            self.movingCellImageView = nil
        })
    }
}

References:

Tim Puckett - https://adoptioncurve.net/archives/2014/07/creating-a-draggable-uicollectionviewcell/

Swift implementation by Chan Jing Hong
http://eatliftswift.weebly.com/technical/creating-a-draggable-uicollectionviewcell


问:
How to draw line between two nodes placed in different Panes / Regions
I am tryin to draw a genealogy tree. In my tree, I store information about ex partners. So the Panel (Region) for person shoud looking like this

```<code>Z * * * Z * * * Z * * * X --- Y
</code>```

Where Z represent exPartner,  X represent Persion and Y represent current Wife / Husband

And now I would like to draw line to connect current relation  with  children. And ec relations with children.  (graphicaly there will be a line beetwen Z and *)

But when the person is in the other region LayoutX and LayoutX property return  relative value.
 How Can I do that, and how dynamicaly resize this Panel ? I would like that Z should be allways at middle of line Horizontal line connecting children.

答:
Given any node, you can get its bounds in the coordinate system of any other node in the same scene graph with:

```<code>Node nodeOfInterest = ... ;
Node anotherNode = ... ;

// ...

Bounds boundsInScene = nodeOfInterest.localToScene(nodeOfInterest.getBoundsInLocal());
Bounds boundRelativeToAnotherNode = anotherNode.sceneToLocal(boundsInScene);
</code>```

So assuming you have some kind of pane which is a common ancestor to two nodes you want to connect, you can do this:

```<code>Pane commonAncestor = ... ;
Node n1 = ... ;
Node n2 = ... ;

Bounds n1InCommonAncestor = getRelativeBounds(n1, commonAncestor);
Bounds n2InCommonAncestor = getRelativeBounds(n2, commonAncestor);
Point2D n1Center = getCenter(n1InCommonAncestor);
Point2D n2Center = getCenter(n2InCommonAncestor);

Line connector = new Line(n1Center.getX(), n1Center.getY(), n2Center.getX(), n2Center.getY());
commonAncestor.getChildren().add(connector);

// ...

private Bounds getRelativeBounds(Node node, Node relativeTo) {
    Bounds nodeBoundsInScene = node.localToScene(node.getBoundsInLocal());
    return relativeTo.sceneToLocal(nodeBoundsInScene);
}

private Point2D getCenter(Bounds b) {
    return new Point2D(b.getMinX() + b.getWidth() / 2, b.getMinY() + b.getHeight() / 2);
}
</code>```

Body:
I am tryin to draw a genealogy tree. In my tree, I store information about ex partners. So the Panel (Region) for person shoud looking like this

Z * * * Z * * * Z * * * X --- Y

Where Z represent exPartner,  X represent Persion and Y represent current Wife / Husband

And now I would like to draw line to connect current relation  with  children. And ec relations with children.  (graphicaly there will be a line beetwen Z and *)

But when the person is in the other region LayoutX and LayoutX property return  relative value.
 How Can I do that, and how dynamicaly resize this Panel ? I would like that Z should be allways at middle of line Horizontal line connecting children.

Body:
Given any node, you can get its bounds in the coordinate system of any other node in the same scene graph with:

Node nodeOfInterest = ... ;
Node anotherNode = ... ;

// ...

Bounds boundsInScene = nodeOfInterest.localToScene(nodeOfInterest.getBoundsInLocal());
Bounds boundRelativeToAnotherNode = anotherNode.sceneToLocal(boundsInScene);

So assuming you have some kind of pane which is a common ancestor to two nodes you want to connect, you can do this:

Pane commonAncestor = ... ;
Node n1 = ... ;
Node n2 = ... ;

Bounds n1InCommonAncestor = getRelativeBounds(n1, commonAncestor);
Bounds n2InCommonAncestor = getRelativeBounds(n2, commonAncestor);
Point2D n1Center = getCenter(n1InCommonAncestor);
Point2D n2Center = getCenter(n2InCommonAncestor);

Line connector = new Line(n1Center.getX(), n1Center.getY(), n2Center.getX(), n2Center.getY());
commonAncestor.getChildren().add(connector);

// ...

private Bounds getRelativeBounds(Node node, Node relativeTo) {
    Bounds nodeBoundsInScene = node.localToScene(node.getBoundsInLocal());
    return relativeTo.sceneToLocal(nodeBoundsInScene);
}

private Point2D getCenter(Bounds b) {
    return new Point2D(b.getMinX() + b.getWidth() / 2, b.getMinY() + b.getHeight() / 2);
}


答:
hope this is what you are looking for.

angular.module("app", []).controller("myCtrl", function($scope) {
  $scope.parent = [{
    "SNO": "869",
    "Name": "ABC"
  }, {
    "SNO": "800",
    "Name": "CCC"
  }];

  $scope.Cost = [{
    "NO": "869",
    "Amnt": 100
  }, {
    "NO": "800",
    "Amnt": 200
  }, {
    "NO": "800",
    "Amnt": 560
  }];

  $scope.mergeArr = function(arr1, arr2) {
    var arrTmp = [];
    if (Array.isArray(arr1)) {
      arrTmp.push(...arr1);
    } else {
      arrTmp.push(arr1);
    }

    arrTmp.forEach(function(item) {
      var costArr = arr2.filter(function(item2) {
        return item2.NO === item.SNO;
      });

      if (costArr.length > 0) {
        if (!item.COST) {
          item["COST"] = [];
        }

        costArr.forEach(function(cost) {
          item.COST.push(cost);
        })
      }
    });
    console.log(arrTmp);
    return {
      "Parent": arrTmp
    };
  };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
  <div>
    <ui>
      <li ng-repeat="project in mergeArr(parent, Cost).Parent">
        {{project.SNO}} - {{project.Name}}
      </li>
    </ui>
  </div>
</div></code>```

Title: JSON object format/merge

Body:
I have these two variables below:

var parent: [{
  "SNO": "869",
  "Name": "ABC"
}, {
  "SNO": "800",
  "Name": "CCC"
}]
var Cost = [{
  "NO": "869",
  "Amnt": 100
}, {
  "NO": "800",
  "Amnt": 200
}, {
  "NO": "800",
  "Amnt": 560
}]

and the end updated result I want something like.
{
  "parent": [{
      "SNO": "869",
      "Name": "ABC",
      "Cost": [{
          "NO": "869",
          "Amnt": 100
        },
        {
          "NO": "869",
          "Amnt": 200
        },
        {
          "NO": "869",
          "Amnt": 560
        }
      ]
    },
    {
      "SNO": "800",
      "Name": "XYZ",
      "Cost": [{
          "NO": "800",
          "Amnt": 100
        },
        {
          "NO": "800",
          "Amnt": 200
        },
        {
          "NO": "800",
          "Amnt": 560
        }
      ]
    }
  ]
}

Can someone suggest me how to make it possible.

Body:
hope this is what you are looking for.

angular.module("app", []).controller("myCtrl", function($scope) {
  $scope.parent = [{
    "SNO": "869",
    "Name": "ABC"
  }, {
    "SNO": "800",
    "Name": "CCC"
  }];

  $scope.Cost = [{
    "NO": "869",
    "Amnt": 100
  }, {
    "NO": "800",
    "Amnt": 200
  }, {
    "NO": "800",
    "Amnt": 560
  }];

  $scope.mergeArr = function(arr1, arr2) {
    var arrTmp = [];
    if (Array.isArray(arr1)) {
      arrTmp.push(...arr1);
    } else {
      arrTmp.push(arr1);
    }

    arrTmp.forEach(function(item) {
      var costArr = arr2.filter(function(item2) {
        return item2.NO === item.SNO;
      });

      if (costArr.length > 0) {
        if (!item.COST) {
          item["COST"] = [];
        }

        costArr.forEach(function(cost) {
          item.COST.push(cost);
        })
      }
    });
    console.log(arrTmp);
    return {
      "Parent": arrTmp
    };
  };
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
  <div>
    <ui>
      <li ng-repeat="project in mergeArr(parent, Cost).Parent">
        {{project.SNO}} - {{project.Name}}
      </li>
    </ui>
  </div>
</div>


答:
I would do it a little different:
C#

```<code>public static class MyClass
{
        public static string Foo = "foo";
        public static string Barbaz = "bar baz";
}
</code>```

VIEW

```<code><div class="@MyClass.Foo"></div>
<div class="@MyClass.Barbaz"></div>
</code>```

reusing in action link:

```<code>@Html.ActionLink("mylink","@Url.Action("Index","Home")", new {@class=MyClass.Foo})
</code>```

Title: asp.net MVC adding Multiple classes not giving expected result

Body:
Code

C#

 public static class MyClass
    {
        public static object Foo = new { @class = "foo" };
        public static object Barbaz = new { @class = "bar baz" };
    }

cshtml

Desired HTML result

Actual HTML result

(works, but looks wrong)

(doesn't work, and looks even more wrong)

How should I declare Foo and Barbaz to achieve my desired result?

Body:
I would do it a little different:
C#

public static class MyClass
{
        public static string Foo = "foo";
        public static string Barbaz = "bar baz";
}

VIEW

<div class="@MyClass.Foo"></div>
<div class="@MyClass.Barbaz"></div>

reusing in action link:

@Html.ActionLink("mylink","@Url.Action("Index","Home")", new {@class=MyClass.Foo})


问:
how to setup the assets folder in CodeIgniter like in Laravel
like the public folder given by laravel default i tried to create something like that for easy make up of my css, js, picture and so on. I tried configuring it like this. In my application/helpers/utility_helpers.php

```<code>    <?php
    function asset_url()
    {
  return base_url().'assets/';
    }
     ?>
</code>```

I have my assests folder along with application, system, user_guide etc.
i confugured the autoload function of application/config as :

```<code>    $autoload['helper'] = array('url','utility');
</code>```

when i hit any url in browser now, it says

```<code>    An Error Was Encountered

    Unable to load the requested file: helpers/utility_helper.php
</code>```

how can i make it and can you explain me if i need to specify root for that helpers also.And if not can i simply access the assets like this:

```<code>    <img src="assets/base_components/build/banner.png">
</code>```

in my view

答:
Yo can do this instead: </p>

```<code><img src="<?= base_url('assets/base_components/build/banner.png') ?>">
</code>```

Body:
like the public folder given by laravel default i tried to create something like that for easy make up of my css, js, picture and so on. I tried configuring it like this. In my application/helpers/utility_helpers.php

    <?php
    function asset_url()
    {
  return base_url().'assets/';
    }
     ?>

I have my assests folder along with application, system, user_guide etc.
i confugured the autoload function of application/config as :

    $autoload['helper'] = array('url','utility');

when i hit any url in browser now, it says

    An Error Was Encountered

    Unable to load the requested file: helpers/utility_helper.php

how can i make it and can you explain me if i need to specify root for that helpers also.And if not can i simply access the assets like this:

in my view

Body:
Yo can do this instead:

<img src="<?= base_url('assets/base_components/build/banner.png') ?>">


问:
Drupal 8: Unwanted N/A option showing in radio button
I'm using Drupal 8. How to remove N/A option in radio button?

答:
Try this </p>

```<code>function MODULENAME_options_list_alter(array &$options, array $context) {
     unset($options['_none']);
}
</code>```

Body:
Try this

function MODULENAME_options_list_alter(array &$options, array $context) {
     unset($options['_none']);
}


问:
First few microsoft translator API requests succeed , then the calls fails and throws NoArgument exception with invalid appid
I am using Microsoft translator api, i have registered my app to datamarket and got the clientid and clientsecret. My api request succeed for few times . Now i am getting noArgument exceptio  with

NoArgumentException: Invalid appId
Parameter name: appId : ID=1116.V2_Json.Translate.4EEF7E6A - Row_IDArgumentException: Invalid appId

Please let me know in case i have missed something.

答: Sam, you are using the older DataMarket APIs which are being deprecated.  You should upgrade to use the Azure Cognitive Service APIs which use an authentication token instead of the client secret.  Step by step instructions are documented at http://docs.microsofttranslator.com/text-translate.html, or you can see https://azure.microsoft.com/en-us/services/cognitive-services/ for all of the APIs.</p>


问:
Mysql : Get relative complement from two tables that updated one day before
I have two tables which I will call A and B, and both has similar data but in different field. I'm trying to get data from A table and it should be does not exist in table B, but there is one condition. There is a field for timestamp indicates when does people updated this data, and I have to get data updated yesterday. I know how to get relative complement using subquery, but If I use subquery I can't put condition to filter timestamp. Is there any way to get relative complement while giving condition of time?

This is database A                      database B

```<code> ID  |   timestamp              |    ID  |   timestamp              |
 --------------------------------    --------------------------------
 1   |   2017-01-01 00:00:00    |    1   |   2017-01-01 00:00:00    |
 2   |   2017-01-04 00:00:00    |    8   |   2017-01-04 00:00:00    |
 3   |   2017-01-11 00:00:00    |    9   |   2017-01-11 00:00:00    |
 4   |   2017-01-14 00:00:00    |    4   |   2017-01-14 00:00:00    |
 5   |   2017-01-07 00:00:00    |    5   |   2017-01-07 00:00:00    |
</code>```

This is query I tried.

```<code>SELECT a.id FROM a as a
WHERE a.id not in (SELECT b.a_id FROM b as b) AND a.timestamp IS NOT NULL;
</code>```

This is condition that I would like to give

```<code>where timestamp >= date_add(now(), interval -1 day)
</code>```

答:
Your query should work fine, granted you actually have a date in your timestamp field whose value is today or greater.  Below are two different queries you can use.

```<code>select a.*
  from your_schema.your_table a
  left join your_schema.your_table_2 b
    on b.id = a.id
 where a.id > 0
   and b.id is null
   and a.checktime >= date_sub(now(), interval 1 day);
</code>```

OR

```<code>select *
  from your_schema.your_table
 where id not in (select id
                    from your_schema.your_table_2)
   and checktime >= date_sub(now(), interval 1 day);
</code>```

Body:
I have two tables which I will call A and B, and both has similar data but in different field. I'm trying to get data from A table and it should be does not exist in table B, but there is one condition. There is a field for timestamp indicates when does people updated this data, and I have to get data updated yesterday. I know how to get relative complement using subquery, but If I use subquery I can't put condition to filter timestamp. Is there any way to get relative complement while giving condition of time?

This is database A                      database B

 ID  |   timestamp              |    ID  |   timestamp              |
 --------------------------------    --------------------------------
 1   |   2017-01-01 00:00:00    |    1   |   2017-01-01 00:00:00    |
 2   |   2017-01-04 00:00:00    |    8   |   2017-01-04 00:00:00    |
 3   |   2017-01-11 00:00:00    |    9   |   2017-01-11 00:00:00    |
 4   |   2017-01-14 00:00:00    |    4   |   2017-01-14 00:00:00    |
 5   |   2017-01-07 00:00:00    |    5   |   2017-01-07 00:00:00    |

This is query I tried.

SELECT a.id FROM a as a
WHERE a.id not in (SELECT b.a_id FROM b as b) AND a.timestamp IS NOT NULL;

This is condition that I would like to give

where timestamp >= date_add(now(), interval -1 day)

Body:
Your query should work fine, granted you actually have a date in your timestamp field whose value is today or greater.  Below are two different queries you can use.

select a.*
  from your_schema.your_table a
  left join your_schema.your_table_2 b
    on b.id = a.id
 where a.id > 0
   and b.id is null
   and a.checktime >= date_sub(now(), interval 1 day);

OR

select *
  from your_schema.your_table
 where id not in (select id
                    from your_schema.your_table_2)
   and checktime >= date_sub(now(), interval 1 day);


问:
Eval Calculation-string: "2 * 3 + 4 * 5" in Postgresql
I would like to evaluate a pure-calculation string in Postgres.

For example: eval('234 + 65 * 3')

The function is NOT constant, so could also simply be 2 + 2

Expecting something like SELECT eval('2 + 2') AS result

I read about huge security issues regarding eval() functions, but those seem to incorporate SELECT statements. Here pure calculation requirements.

答:
You need PL/pgSQL:

```<code>create or replace function f(_s text)
returns numeric as $$
declare i numeric;
begin
    execute format('select %s', _s) into i;
    return i;
end;
$$ language plpgsql;

select f('1 + 1');
 f
---
 2
</code>```

Body:
You need PL/pgSQL:

create or replace function f(_s text)
returns numeric as $$
declare i numeric;
begin
    execute format('select %s', _s) into i;
    return i;
end;
$$ language plpgsql;

select f('1 + 1');
 f
---
 2


问:
Webpack indicate entry name from the CLI
I would like indicate my entry name from the CLI for compile many Sass theme.

My package.json :

```<code>./node_modules/.bin/webpack
  --config ./app/Resources/build/webpack.dev.js
  --progress
  --colors
   --watch THEME_NAME
</code>```

I recovers THEME_NAME in my webpack.config.js :

```<code>var processArguments = process.argv;
var theme = processArguments[7]; // Return theme name
</code>```

And add it in my entryApp :

```<code>entryApp: {
  app: './app/Resources/private/js/app.js',
  theme: './app/Resources/private/scss/themes/' + theme + '/' + theme + '.scss'
},
</code>```

But i've an error :

ERROR in Entry module not found

I am absolutely certain that the path is good :(

Anyone can help me ?

Thank you !

答:
Any argument to the webpack CLI is interpreted as an entry point (CLI Usage).

When you call:

```<code>webpack [options] myTheme
</code>```

it tries to find the module myTheme, just as if you had specified it as an entry point in the config.

You'll need to use another approach for this. One possibility is to use environment variables.

```<code>THEME=myTheme webpack [options]
</code>```

Then you can access it with process.env.THEME in your config.

Alternatively you can export a function as the webpack config, which returns the configuration object. The webpack CLI will pass any option specified with the --env CLI option to the function. See Exporting a function to use --env.

With an arrow function which implicitly returns the configuration object, it would look like this:

```<code>module.exports = env => ({
  entry: {
    entryApp: {
      app: './app/Resources/private/js/app.js',
      theme: './app/Resources/private/scss/themes/' + env.theme + '/' + env.theme + '.scss'
    },
  }
  // Rest of your config
});
</code>```

And you'd call webpack as follows:

```<code>webpack --env.theme=myTheme [other options]
</code>```

Body:
I would like indicate my entry name from the CLI for compile many Sass theme.

My package.json :

./node_modules/.bin/webpack
  --config ./app/Resources/build/webpack.dev.js
  --progress
  --colors
   --watch THEME_NAME

I recovers THEME_NAME in my webpack.config.js :

var processArguments = process.argv;
var theme = processArguments[7]; // Return theme name

And add it in my entryApp :

entryApp: {
  app: './app/Resources/private/js/app.js',
  theme: './app/Resources/private/scss/themes/' + theme + '/' + theme + '.scss'
},

But i've an error :

ERROR in Entry module not found

I am absolutely certain that the path is good :(

Anyone can help me ?

Thank you !

Body:
Any argument to the webpack CLI is interpreted as an entry point (CLI Usage).

When you call:

webpack [options] myTheme

it tries to find the module myTheme, just as if you had specified it as an entry point in the config.

You'll need to use another approach for this. One possibility is to use environment variables.

THEME=myTheme webpack [options]

Then you can access it with process.env.THEME in your config.

Alternatively you can export a function as the webpack config, which returns the configuration object. The webpack CLI will pass any option specified with the --env CLI option to the function. See Exporting a function to use --env.

With an arrow function which implicitly returns the configuration object, it would look like this:

module.exports = env => ({
  entry: {
    entryApp: {
      app: './app/Resources/private/js/app.js',
      theme: './app/Resources/private/scss/themes/' + env.theme + '/' + env.theme + '.scss'
    },
  }
  // Rest of your config
});

And you'd call webpack as follows:

webpack --env.theme=myTheme [other options]


问:
Thread interrupt not ending blocking call on input stream read
I'm using RXTX to read data from a serial port.  The reading is done within a thread spawned in the following manner:

```<code>CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(port);
CommPort comm = portIdentifier.open("Whatever", 2000);
SerialPort serial = (SerialPort)comm;
...settings
Thread t = new Thread(new SerialReader(serial.getInputStream()));
t.start();
</code>```

The SerialReader class implements Runnable and just loops indefinitely, reading from the port and constructing the data into useful packages before sending it off to other applications.  However, I've reduced it down to the following simplicity:

```<code>public void run() {
  ReadableByteChannel byteChan = Channels.newChannel(in); //in = InputStream passed to SerialReader
  ByteBuffer buffer = ByteBuffer.allocate(100);
  while (true) {
    try {
      byteChan.read(buffer);
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}
</code>```

When a user clicks a stop button, the following functionality fires that should in theory close the input stream and break out of the blocking byteChan.read(buffer) call.  The code is as follows:

```<code>public void stop() {
  t.interrupt();
  serial.close();
}
</code>```

However, when I run this code, I never get a ClosedByInterruptException, which SHOULD fire once the input stream closes.  Furthermore, the execution blocks on the call to serial.close() -- because the underlying input stream is still blocking on the read call.  I've tried replacing the interrupt call with byteChan.close(), which should then cause an AsynchronousCloseException, however, I'm getting the same results.

Any help on what I'm missing would be greatly appreciated.

答:
i am using the code below to shutdown rxtx. i run tests that start them up and shut them down and the seems to work ok. my reader looks like:

```<code>private void addPartsToQueue(final InputStream inputStream) {
    byte[] buffer = new byte[1024];
    int len = -1;
    boolean first = true;
    // the read can throw
    try {
        while ((len = inputStream.read(buffer)) > -1) {
            if (len > 0) {
                if (first) {
                    first = false;
                    t0 = System.currentTimeMillis();
                } else
                    t1 = System.currentTimeMillis();
                final String part = new String(new String(buffer, 0, len));
                queue.add(part);
                //System.out.println(part + " " + (t1 - t0));
            }
            try {
                Thread.sleep(sleep);
            } catch (InterruptedException e) {
                //System.out.println(Thread.currentThread().getName() + " interrupted " + e);
                break;
            }
        }
    } catch (IOException e) {
        System.err.println(Thread.currentThread().getName() + " " + e);
        //if(interruSystem.err.println(e);
        e.printStackTrace();
    }
    //System.out.println(Thread.currentThread().getName() + " is ending.");
}
</code>```

thanks

```<code>public void shutdown(final Device device) {
    shutdown(serialReaderThread);
    shutdown(messageAssemblerThread);
    serialPort.close();
    if (device != null)
        device.setSerialPort(null);
}

public static void shutdown(final Thread thread) {
    if (thread != null) {
        //System.out.println("before intterupt() on thread " + thread.getName() + ", it's state is " + thread.getState());
        thread.interrupt();
        //System.out.println("after intterupt() on thread " + thread.getName() + ", it's state is " + thread.getState());
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + " was interrupted trying to sleep after interrupting" + thread.getName() + " " + e);
        }
        //System.out.println("before join() on thread " + thread.getName() + ", it's state is " + thread.getState());
        try {
            thread.join();
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + " join interruped");
        }
        //System.out.println(Thread.currentThread().getName() + " after join() on thread " + thread.getName() + ", it's state is" + thread.getState());
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm using RXTX to read data from a serial port.  The reading is done within a thread spawned in the following manner:

CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(port);
CommPort comm = portIdentifier.open("Whatever", 2000);
SerialPort serial = (SerialPort)comm;
...settings
Thread t = new Thread(new SerialReader(serial.getInputStream()));
t.start();

The SerialReader class implements Runnable and just loops indefinitely, reading from the port and constructing the data into useful packages before sending it off to other applications.  However, I've reduced it down to the following simplicity:

public void run() {
  ReadableByteChannel byteChan = Channels.newChannel(in); //in = InputStream passed to SerialReader
  ByteBuffer buffer = ByteBuffer.allocate(100);
  while (true) {
    try {
      byteChan.read(buffer);
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}

When a user clicks a stop button, the following functionality fires that should in theory close the input stream and break out of the blocking byteChan.read(buffer) call.  The code is as follows:

public void stop() {
  t.interrupt();
  serial.close();
}

However, when I run this code, I never get a ClosedByInterruptException, which SHOULD fire once the input stream closes.  Furthermore, the execution blocks on the call to serial.close() -- because the underlying input stream is still blocking on the read call.  I've tried replacing the interrupt call with byteChan.close(), which should then cause an AsynchronousCloseException, however, I'm getting the same results.

Any help on what I'm missing would be greatly appreciated.

Body:
i am using the code below to shutdown rxtx. i run tests that start them up and shut them down and the seems to work ok. my reader looks like:

private void addPartsToQueue(final InputStream inputStream) {
    byte[] buffer = new byte[1024];
    int len = -1;
    boolean first = true;
    // the read can throw
    try {
        while ((len = inputStream.read(buffer)) > -1) {
            if (len > 0) {
                if (first) {
                    first = false;
                    t0 = System.currentTimeMillis();
                } else
                    t1 = System.currentTimeMillis();
                final String part = new String(new String(buffer, 0, len));
                queue.add(part);
                //System.out.println(part + " " + (t1 - t0));
            }
            try {
                Thread.sleep(sleep);
            } catch (InterruptedException e) {
                //System.out.println(Thread.currentThread().getName() + " interrupted " + e);
                break;
            }
        }
    } catch (IOException e) {
        System.err.println(Thread.currentThread().getName() + " " + e);
        //if(interruSystem.err.println(e);
        e.printStackTrace();
    }
    //System.out.println(Thread.currentThread().getName() + " is ending.");
}

thanks

public void shutdown(final Device device) {
    shutdown(serialReaderThread);
    shutdown(messageAssemblerThread);
    serialPort.close();
    if (device != null)
        device.setSerialPort(null);
}

public static void shutdown(final Thread thread) {
    if (thread != null) {
        //System.out.println("before intterupt() on thread " + thread.getName() + ", it's state is " + thread.getState());
        thread.interrupt();
        //System.out.println("after intterupt() on thread " + thread.getName() + ", it's state is " + thread.getState());
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + " was interrupted trying to sleep after interrupting" + thread.getName() + " " + e);
        }
        //System.out.println("before join() on thread " + thread.getName() + ", it's state is " + thread.getState());
        try {
            thread.join();
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + " join interruped");
        }
        //System.out.println(Thread.currentThread().getName() + " after join() on thread " + thread.getName() + ", it's state is" + thread.getState());
    }


问:
searching table and finding record
i am doing a self study on programming.  trying to develop a point of sale.
i am currently struggling with searching a table and finding an item from my inventory table and then throwing the item into my posinvoicedetails table with a default qty of 1

i cannot understand how to open connection on two different tables and search one and update the other at the same time.

can someone please expalin logic behind this.  i will try and figure out code thereafter.

i can open one table and search item in datagrid view and update records.

thanks

答:
Your question is quite vague so it's hard to guess what you want exactly. But this is what I think you're looking for.

Open the connection to the database .

Query it to search the specific table(the one you want to search) for what you're looking for.

Close the connection.

Open the connection again.

update the other table.

P.S. Through all of this, it should be the same database that you're connecting to but different tables within it.

Also, you need this code to connect to the database:

```<code>provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\file.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
</code>```

Title: searching table and finding record

Body:
Your question is quite vague so it's hard to guess what you want exactly. But this is what I think you're looking for.

Open the connection to the database .

Query it to search the specific table(the one you want to search) for what you're looking for.

Close the connection.

Open the connection again.

update the other table.

P.S. Through all of this, it should be the same database that you're connecting to but different tables within it.

Also, you need this code to connect to the database:

provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\file.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString


问:
Some wired behavior for display inline block
Update
it's a question of whether inline-block elements contains something or not, You can search for it and find a better solution.

The page contains three div(gray rectangle) and the first div(parent) contains three blue child-div. Parent divs are inline-block, child-divs are also the same. Why the first parent-div is moved downwards? I'm supposed that they should be aligned in a line.

```<code><body>
    <section>
        <div class = "container">
            <div class = "load_1"></div>
            <div class = "load_1"></div>
            <div class = "load_1"></div>
        </div>
        <div class = "container">

        </div>
        <div class = "container">

        </div>
    </section>
</body>
</code>```

css

```<code>           section{
                width:100%;
                height:100vh;
                background-color: rgba(236, 240, 241,1.0);
            }
            div.container{
                display: inline-block;
                width:150px;
                height:150px;
                margin:10px;
                background-color: rgba(189, 195, 199,1.0);
                border-radius: 5px;
            }
            div.container:first-child{
                margin-left: 20px;
            }
            div.container .load_1{
                width:20px;
                height:20px;
                display: inline-block;
                background-color: rgba(52, 152, 219,1.0);
            }
</code>```

Please check here in JSfiddle.

答:
Just add float: left which pushes everything up and left.</p>

```<code>    div.container:first-child{
        margin-left: 20px;
        float: left;
    }
</code>```

Body:
Update
it's a question of whether inline-block elements contains something or not, You can search for it and find a better solution.

The page contains three div(gray rectangle) and the first div(parent) contains three blue child-div. Parent divs are inline-block, child-divs are also the same. Why the first parent-div is moved downwards? I'm supposed that they should be aligned in a line.

css

           section{
                width:100%;
                height:100vh;
                background-color: rgba(236, 240, 241,1.0);
            }
            div.container{
                display: inline-block;
                width:150px;
                height:150px;
                margin:10px;
                background-color: rgba(189, 195, 199,1.0);
                border-radius: 5px;
            }
            div.container:first-child{
                margin-left: 20px;
            }
            div.container .load_1{
                width:20px;
                height:20px;
                display: inline-block;
                background-color: rgba(52, 152, 219,1.0);
            }

Please check here in JSfiddle.

Body:
Just add float: left which pushes everything up and left.

    div.container:first-child{
        margin-left: 20px;
        float: left;
    }


问:
Is there a shorter way to extract hour from timestamp stored as integer than EXTRACT(HOUR FROM TIMESTAMP_SECONDS(visitStartTime))?
As in topic. While using standard-sql is there a shorter way to extract hour (or other dateparts) from timestamp stored as integer than EXTRACT(HOUR FROM TIMESTAMP_SECONDS(visitStartTime))?</p>

答:
You can use User-Defined Functions in such cases when you feel something should have shorter way to be expressed

See example below

CREATE TEMPORARY FUNCTION HOUR(time INT64)
RETURNS INT64 AS (
  EXTRACT(HOUR FROM TIMESTAMP_SECONDS(time))
);

SELECT
  HOUR(visitStartTime) as `shorertWay`,
  EXTRACT(HOUR FROM TIMESTAMP_SECONDS(visitStartTime)) as `longerWay`
FROM `google.com:analytics-bigquery.LondonCycleHelmet.ga_sessions_20130910`
LIMIT 10
```

<p>So, now instead of  </p>

<pre class="lang-sql prettyprint-override"><code>EXTRACT(HOUR FROM TIMESTAMP_SECONDS(visitStartTime))
</code>```

you can use

HOUR(visitStartTime)
```

Body:
You can use User-Defined Functions in such cases when you feel something should have shorter way to be expressed

See example below

CREATE TEMPORARY FUNCTION HOUR(time INT64)
RETURNS INT64 AS (
  EXTRACT(HOUR FROM TIMESTAMP_SECONDS(time))
);

SELECT
  HOUR(visitStartTime) as `shorertWay`,
  EXTRACT(HOUR FROM TIMESTAMP_SECONDS(visitStartTime)) as `longerWay`
FROM `google.com:analytics-bigquery.LondonCycleHelmet.ga_sessions_20130910`
LIMIT 10

So, now instead of

EXTRACT(HOUR FROM TIMESTAMP_SECONDS(visitStartTime))

you can use

HOUR(visitStartTime)