问:
Android Kotlin : java.lang.NoClassDefFoundError: Failed resolution of: <KotlinObject>
Every second run of our android app, we get a crash that says

```<code>java.lang.NoClassDefFoundError: Failed resolution of: Lin/blahapp/xxx/BlahUtil
</code>```

BlahUtil is a kotlin object with @JvmStatic annotations in it. I call these static methods from the rest of the android app(All in java) .

We use multidex 1.0.1.

I am on android studio 2.1.2, using JDK 7.

Relevant gradle configs:

```<code>compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
        minSdkVersion 16
        targetSdkVersion 23
}
dexOptions {
        incremental true
        dexInProcess true
        javaMaxHeapSize "10g"
        preDexLibraries true
}
buildscript {
    ext.kotlin_version = '1.0.3'

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
apply plugin: 'kotlin-android'
dependencies {
  compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
  compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
}
</code>```

Trace:

```<code>at in.blahapp.xxx.OurActivity
at android.app.Activity.performCreate(Activity.java:6251)
at ndroid.app.Instrumentation.callActivityOnCreate
at android.app.ActivityThread.performLaunchActivity
at android.app.ActivityThread.handleLaunchActivity
at android.app.ActivityThread.-wrap11
at android.app.ActivityThread$H.handleMessage
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Caused by: java.lang.ClassNotFoundException: Didn't find class "in.blahapp.xxx.BlahUtil" on path: DexPathList[[dex file ....
</code>```

logcat output

答:
The only workaround I've found is to set android.compileOptions.incremental = false

See this issue for details.

Body:
Every second run of our android app, we get a crash that says

java.lang.NoClassDefFoundError: Failed resolution of: Lin/blahapp/xxx/BlahUtil

BlahUtil is a kotlin object with @JvmStatic annotations in it. I call these static methods from the rest of the android app(All in java) .

We use multidex 1.0.1.

I am on android studio 2.1.2, using JDK 7.

Relevant gradle configs:

compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
        minSdkVersion 16
        targetSdkVersion 23
}
dexOptions {
        incremental true
        dexInProcess true
        javaMaxHeapSize "10g"
        preDexLibraries true
}
buildscript {
    ext.kotlin_version = '1.0.3'

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
apply plugin: 'kotlin-android'
dependencies {
  compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
  compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
}

Trace:

at in.blahapp.xxx.OurActivity
at android.app.Activity.performCreate(Activity.java:6251)
at ndroid.app.Instrumentation.callActivityOnCreate
at android.app.ActivityThread.performLaunchActivity
at android.app.ActivityThread.handleLaunchActivity
at android.app.ActivityThread.-wrap11
at android.app.ActivityThread$H.handleMessage
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Caused by: java.lang.ClassNotFoundException: Didn't find class "in.blahapp.xxx.BlahUtil" on path: DexPathList[[dex file ....

logcat output


来源: stackexchange

问:
Splitting strings into text and number?
Let’s say I have this string 'foo1bar2xyz'

I know the indexes for the digits in it {'1': 3, '2': 7}

I want to form substrings of the parent string which don’t have the numbers. How would I get substrings of a string removing particular indexes?

Which in the above case which would be ['foo', 'bar', 'xyz']

Have tried this so far

```<code>def iterate_string(og_string, start, stop):
    if start == 0:
        return og_string[:stop]
    else:
        return og_string[start+1:stop]

def ret_string(S):
    digit_dict = {c:i for i,c in enumerate(S) if c.isdigit()}
    digit_positions = list(digit_dict.values())
    # return digit_positions
    substrings = []
    start_index = 0
    for position in digit_positions:
        p = iterate_string(S, start_index, position)
        substrings.append(p)
        start_index = position

    return substrings

print ret_string('foo1bar2xyz')
</code>```

But this returns ['foo', 'bar']

Relevant SO questions

答:
You can do it using RE

```<code>import re
h = "foo1bar2xyz"
l = re.compile("\d").split(h)
</code>```

Output:

```<code>['foo', 'bar', 'xyz']
</code>```

ContentLicense: CC BY-SA 3.0

Title: Splitting strings into text and number?

Body:
Let’s say I have this string 'foo1bar2xyz'

I know the indexes for the digits in it {'1': 3, '2': 7}

I want to form substrings of the parent string which don’t have the numbers. How would I get substrings of a string removing particular indexes?

Which in the above case which would be ['foo', 'bar', 'xyz']

Have tried this so far

def iterate_string(og_string, start, stop):
    if start == 0:
        return og_string[:stop]
    else:
        return og_string[start+1:stop]

def ret_string(S):
    digit_dict = {c:i for i,c in enumerate(S) if c.isdigit()}
    digit_positions = list(digit_dict.values())
    # return digit_positions
    substrings = []
    start_index = 0
    for position in digit_positions:
        p = iterate_string(S, start_index, position)
        substrings.append(p)
        start_index = position

    return substrings

print ret_string('foo1bar2xyz')

But this returns ['foo', 'bar']

Relevant SO questions

Body:
You can do it using RE

import re
h = "foo1bar2xyz"
l = re.compile("\d").split(h)

Output:

['foo', 'bar', 'xyz']


问:
How to work with detached object in CF9?
If User is an entity, and I need to store User in Session, it will be detached on next request.

AFAIK there're only 2 methods to handle these detached objects

EntityMerge(session.user) - update DB with session's object (unsafe)

session.userID - entityLoadByPK() again on next request (more load)

Are these the only 2 workarounds?  Any other ways?

According to Advanced Techniques with ColdFusion 9 ORM Integration Slide Deck Concurrency with method #1 will throw error if entity has been changed on merge, but how is this useful? catch the exception and use method #2?

When to use EntityReload()?  I thought it works the same way as EntityMerge(entity) but it doesn't.

Thanks!

答:
I tend to only store the ID of the user that is logged in in the session.

Then I have a UserService.getCurrentUser() facade method that returns that user if I need it.

That way the user is always current, and never detached.

ContentLicense: CC BY-SA 2.5


问:
DropoutWrapper being non-deterministic across runs?
In the beginning of my code, (outside the scope of a Session), I've set my random seed -

```<code>np.random.seed(1)
tf.set_random_seed(1)
</code>```

This is what my dropout definition looks like -

```<code>cell = tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=args.keep_prob, seed=1)
</code>```

In my first experiment, I kept keep_prob=1. All results obtained were deterministic. I'm running this on a multicore CPU.

In my second experiment, I set keep_prob=0.8 and I ran the same code two times. Each code had these statements,

```<code>sess.run(model.cost, feed)
sess.run(model.cost, feed)
</code>```

Results for first code run -

```<code>(Pdb) sess.run(model.cost, feed)
4.9555049
(Pdb) sess.run(model.cost, feed)
4.9548969
</code>```

Expected behaviour, since DropoutWrapper uses random_uniform.

Results for second code run -

```<code>(Pdb) sess.run(model.cost, feed)
4.9551616
(Pdb) sess.run(model.cost, feed)
4.9552417
</code>```

Why is this sequence not identical to the first output despite defining an operation and graph seed?

答:
The answer was already provided in the comments, but no-one has written it explicitly yet, so here it is:

dynamic_rnn will internally use tf.while_loop, which can actually evaluate multiple iterations in parallel (see documentation on parallel_iterations). In practice, if everything inside the loop-body or loop-cond depends on the previous values, it cannot run anything in parallel but there could be computations which don't depend on the previous values. These will be evaluated in parallel. In your case, inside the DropoutWrapper, you have at some point sth like this:

```<code>random_ops.random_uniform(noise_shape, ...)
</code>```

This operation is independent from the previous values of the loop, so it can be calculated in parallel for all time-steps. If you do such parallel execution, it will be non-deterministic which time-frame gets which dropout mask.

Body:
In the beginning of my code, (outside the scope of a Session), I've set my random seed -

np.random.seed(1)
tf.set_random_seed(1)

This is what my dropout definition looks like -

cell = tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=args.keep_prob, seed=1)

In my first experiment, I kept keep_prob=1. All results obtained were deterministic. I'm running this on a multicore CPU.

In my second experiment, I set keep_prob=0.8 and I ran the same code two times. Each code had these statements,

sess.run(model.cost, feed)
sess.run(model.cost, feed)

Results for first code run -

(Pdb) sess.run(model.cost, feed)
4.9555049
(Pdb) sess.run(model.cost, feed)
4.9548969

Expected behaviour, since DropoutWrapper uses random_uniform.

Results for second code run -

(Pdb) sess.run(model.cost, feed)
4.9551616
(Pdb) sess.run(model.cost, feed)
4.9552417

Why is this sequence not identical to the first output despite defining an operation and graph seed?

Body:
The answer was already provided in the comments, but no-one has written it explicitly yet, so here it is:

dynamic_rnn will internally use tf.while_loop, which can actually evaluate multiple iterations in parallel (see documentation on parallel_iterations). In practice, if everything inside the loop-body or loop-cond depends on the previous values, it cannot run anything in parallel but there could be computations which don't depend on the previous values. These will be evaluated in parallel. In your case, inside the DropoutWrapper, you have at some point sth like this:

random_ops.random_uniform(noise_shape, ...)

This operation is independent from the previous values of the loop, so it can be calculated in parallel for all time-steps. If you do such parallel execution, it will be non-deterministic which time-frame gets which dropout mask.


问:
Hide UIBarButtonItem but not make is nil
Is it possible to hide UIBarButtonItem (rightButton of navigationBar) but not making it nil? In my application I have a condition  </p>

```<code>if(self.navigationItem.rightBarButtonItem == nil)
</code>```

<p>which is really important. But hiding the barButton is equally important.  </p>

答:
Please check my answer here to similar question. It's applicable here too.

It adds isHidden property to UIBarButtonItem.

Body:
Is it possible to hide UIBarButtonItem (rightButton of navigationBar) but not making it nil? In my application I have a condition

if(self.navigationItem.rightBarButtonItem == nil)

which is really important. But hiding the barButton is equally important.


问:
How to disable "do not use ids in selectors" in sublime text
In sublime text 3 with the sublimelinter plugin (linter / css) how to disable these warnings IDs and padding specifically
warnings</p>

答:
.csslintrc

CSSLint allows you to disable its rules using the .csslintrc in your project root.

Example:

```<code>{
    "ids": false
}
</code>```

.sublimelinterrc

The same thing can be achieved using Sublime Linter's own configuration file, which is basically making use of CSSLint's --ignore command-line parameter.

Example:

```<code>{
    "linters": {
        "csslint": {
          "ignore": ["ids]
        }
      }
}
</code>```

Body:
.csslintrc

CSSLint allows you to disable its rules using the .csslintrc in your project root.

Example:

{
    "ids": false
}

.sublimelinterrc

The same thing can be achieved using Sublime Linter's own configuration file, which is basically making use of CSSLint's --ignore command-line parameter.

Example:

{
    "linters": {
        "csslint": {
          "ignore": ["ids]
        }
      }
}


问:
j-query and javascript form using multiple submits not submitting all data from form
I'm not hugely good with javascript or jQuery, mainly dealing with databases, but I've been having a little trouble getting a rather complex form to submit all its data.

Basically it amounts to three different submit buttons which are meant to post the data in the form with a different privacy setting sent to the table. The table in the database is being updated with the correct privacy setting for each button, but it isn't sending a value for the thought part of the form to the php file it is meant to.

The form is implemented in the HTML as follows:

```<code><FORM action="thought_post.php" method="post" name="thought">

<INPUT onfocus="this.select(); this.value=''"
       type="text" value="Thought..."
       size="72" />
<div class="megamenu" style="position: absolute; ;left: 478px; top: 11px;">
    <ul>
        <li class="downservices"><a href="#">Publish...</a></li>
        <div class="servicesdropped">
            <ul class="right">
                <input type="hidden" name="privacy">
                <li><a href="javascript:poststyle('private')">Private</a></li>
                <li><a href="javascript:poststyle('friends')">Friends only</a></li>
                <li><a href="javascript:poststyle('public')">Public</a></li>
            </ul>
        </div>
    </ul>
</div>

</FORM>
</code>```

and the javascript in the header of the same page is as follows:

```<code><link rel="stylesheet" href="dropdown.css" type="text/css" media="screen" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>

<script type="text/javascript">
    $(document).ready(function(){
        $(".downservices").click(function(){
            $(".servicesdropped").toggle("fast");
        });
    });
</script>

<script language="JavaScript" type="text/javascript">
<!--
   function poststyle(selectedtype)
    {
       document.thought.privacy.value = selectedtype ;
       document.thought.submit() ;
    }
-->
</script>
</code>```

If anyone could explain why the thought value entered by the user isn't being passed to thought_post.php that would be wonderful!

答:
Try assigning a name to your "thought" input.  name is required for a form control to be valid for submission:

```<code><INPUT onfocus="this.select(); this.value=''" type="text" value="Thought..." size="72" name="thought" />
</code>```

As a side note, make sure your other input is valid markup as well, input tags should be self closing:

```<code><input type="hidden" name="privacy" />
</code>```

After making these changes and inspecting the form post with FireBug, I could see the correct value for "thought" go through.

Additionally, as the other answer mentions, you should separate your JavaScript and HTML and maybe accomplish this completely with jQuery.

Hope that helps!

Body:
I'm not hugely good with javascript or jQuery, mainly dealing with databases, but I've been having a little trouble getting a rather complex form to submit all its data.

Basically it amounts to three different submit buttons which are meant to post the data in the form with a different privacy setting sent to the table. The table in the database is being updated with the correct privacy setting for each button, but it isn't sending a value for the thought part of the form to the php file it is meant to.

The form is implemented in the HTML as follows:

<FORM action="thought_post.php" method="post" name="thought">

<INPUT onfocus="this.select(); this.value=''"
       type="text" value="Thought..."
       size="72" />

Publish...

                <input type="hidden" name="privacy">

Private

Friends only

Public

</FORM>

and the javascript in the header of the same page is as follows:

<link rel="stylesheet" href="dropdown.css" type="text/css" media="screen" />

If anyone could explain why the thought value entered by the user isn't being passed to thought_post.php that would be wonderful!

Body:
Try assigning a name to your "thought" input.  name is required for a form control to be valid for submission:

<INPUT onfocus="this.select(); this.value=''" type="text" value="Thought..." size="72" name="thought" />

As a side note, make sure your other input is valid markup as well, input tags should be self closing:

<input type="hidden" name="privacy" />

After making these changes and inspecting the form post with FireBug, I could see the correct value for "thought" go through.

Additionally, as the other answer mentions, you should separate your JavaScript and HTML and maybe accomplish this completely with jQuery.

Hope that helps!


问:
Values printing in pairs issue? Lua
For some reason the countries that seem to be returned are all returning in pairs? How can you change the code so it only returns the countries in 'Europe' once?</p>

```<code>function newcountry(continent,country)
  local object = {}
  object.continent = continent
  object.country = country

  local list = {}

  for i in pairs( object ) do
   if object.continent == "Europe" then
     table.insert(list, object.country)
     print(object.country)

  end
end

  return object
end

a = newcountry("Africa","Algeria")
b = newcountry("Europe","England")
c = newcountry("Europe","France")
d = newcountry("Europe","Spain")
e = newcountry("Asia","China")
</code>```

答:
I'm not sure what you are trying to accomplish with this code, but to answer your question:

```<code>function newcountry(continent,country)
    local object = {}
    object.continent = continent
    object.country = country
    local list = {}
    if object.continent == "Europe" then
        table.insert(list, object.country)
        print(object.country)
    end
    return object
end
</code>```

This code will print countries in Europe just once. When there was loop in there, it printed name of the country twice, because it did it for each element of object table (continent and country, hence two times).

Generic for loops in Programming in Lua (first edition).

I would also like to point out that list is quite useless at the moment. It is not being returned and stays local. On top of that, every time you call newcountry there is new list created. They are all unique - country objects are not added to single list. But again - I don't know what you are trying to accomplish.

Title: Values printing in pairs issue? Lua

Body:
For some reason the countries that seem to be returned are all returning in pairs? How can you change the code so it only returns the countries in 'Europe' once?

function newcountry(continent,country)
  local object = {}
  object.continent = continent
  object.country = country

  local list = {}

  for i in pairs( object ) do
   if object.continent == "Europe" then
     table.insert(list, object.country)
     print(object.country)

  end
end

  return object
end

a = newcountry("Africa","Algeria")
b = newcountry("Europe","England")
c = newcountry("Europe","France")
d = newcountry("Europe","Spain")
e = newcountry("Asia","China")

Body:
I'm not sure what you are trying to accomplish with this code, but to answer your question:

function newcountry(continent,country)
    local object = {}
    object.continent = continent
    object.country = country
    local list = {}
    if object.continent == "Europe" then
        table.insert(list, object.country)
        print(object.country)
    end
    return object
end

This code will print countries in Europe just once. When there was loop in there, it printed name of the country twice, because it did it for each element of object table (continent and country, hence two times).

Generic for loops in Programming in Lua (first edition).

I would also like to point out that list is quite useless at the moment. It is not being returned and stays local. On top of that, every time you call newcountry there is new list created. They are all unique - country objects are not added to single list. But again - I don't know what you are trying to accomplish.


问:
BroadcastBlock missing items
I have a list of project numbers that I need to process. A project could have about 8000 items and I need to get the data for each item in the project and then push this data into a list of servers. Can anybody please tell me the following..

1) I have 1000 items in iR but only 998 were written to the servers.  Did I loose items by using broadCastBlock?
2) Am I doing the await on all actionBlocks correctly?
3) How do I make the database call async?

Here is the database code

```<code>    public  MemcachedDTO GetIR(MemcachedDTO dtoItem)
    {

        string[] Tables = new string[] { "iowa", "la" };
        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["test"].ConnectionString))
        {
            using (SqlCommand command = new SqlCommand("test", connection))
            {
                DataSet Result = new DataSet();
                command.CommandType = CommandType.StoredProcedure;

                command.Parameters.Add("@ProjectId", SqlDbType.VarChar);
                command.Parameters["@ProjectId"].Value = dtoItem.ProjectId;

                connection.Open();
                Result.EnforceConstraints = false;
                Result.Load(command.ExecuteReader(CommandBehavior.CloseConnection), LoadOption.OverwriteChanges, Tables);
                dtoItem.test = Result;
            }
        }
        return dtoItem;
    }
</code>```

Update:
I have updated the code to the below. It just hangs when I run it and only writes 1/4 of the data to the server?  Can you please let me know what I am doing wrong?

```<code>      public static ITargetBlock<T> CreateGuaranteedBroadcastBlock<T>(IEnumerable<ITargetBlock<T>> targets, DataflowBlockOptions options)
    {
        var targetsList = targets.ToList();

        var block = new ActionBlock<T>(
            async item =>
            {
                foreach (var target in targetsList)
                {
                    await target.SendAsync(item);
                }
            }, new ExecutionDataflowBlockOptions
            {
                CancellationToken = options.CancellationToken
            });

        block.Completion.ContinueWith(task =>
        {
            foreach (var target in targetsList)
            {
                if (task.Exception != null)
                    target.Fault(task.Exception);
                else
                    target.Complete();
            }
        });

        return block;
    }

    [HttpGet]
    public async Task< HttpResponseMessage> ReloadItem(string projectQuery)
    {
        try
        {

            var linkCompletion = new ExecutionDataflowBlockOptions
            {
                 MaxDegreeOfParallelism = 2
            };
             var cts = new CancellationTokenSource();
            var dbOptions = new DataflowBlockOptions { CancellationToken = cts.Token };

            IList<string> projectIds = projectQuery.Split(',').ToList();
            IEnumerable<string> serverList = ConfigurationManager.AppSettings["ServerList"].Split(',').Cast<string>();

            var iR = new TransformBlock<MemcachedDTO, MemcachedDTO>(
                dto => dto.GetIR(dto), new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 3 });

            List<ActionBlock<MemcachedDTO>> actionList = new List<ActionBlock<MemcachedDTO>>();

            List<MemcachedDTO> dtoList = new List<MemcachedDTO>();

            foreach (string pid in projectIds)
            {
                IList<MemcachedDTO> dtoTemp = new List<MemcachedDTO>();
                dtoTemp = MemcachedDTO.GetItemIdsByProject(pid);
                dtoList.AddRange(dtoTemp);
            }
            foreach (string s in serverList)
            {
                var action = new ActionBlock<MemcachedDTO>(
                async dto => await PostEachServerAsync(dto, s, "setitemcache"));
                actionList.Add(action);
            }
            var bBlock = CreateGuaranteedBroadcastBlock(actionList, dbOptions);

            foreach (MemcachedDTO d in dtoList)
            {
                await iR.SendAsync(d);
            }

            iR.Complete();
            iR.LinkTo(bBlock);
            await Task.WhenAll(actionList.Select(action => action.Completion).ToList());

            return Request.CreateResponse(HttpStatusCode.OK, new { message = projectIds.ToString() + " reload success" });
        }
        catch (Exception ex)
        {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, new { message = ex.Message.ToString() });
        }
    }
</code>```

答:
1) I have 1000 items in iR but only 998 were written to the servers. Did I loose items by using broadCastBlock?

Yes in the code below you set BoundedCapacity to one, if at anytime your BroadcastBlock cannot pass along an item it will drop it. Additionally a BroadcastBlock will only propagate Completion to one TargetBlock, do not use PropagateCompletion=true here. If you want all blocks to complete you need to handle Completion manually. This can be done by setting the ContinueWith on the BroadcastBlock to pass Completion to all of the connected targets.

```<code>var action = new ActionBlock<MemcachedDTO>(dto => PostEachServerAsync(dto, s, "set"), new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 3, BoundedCapacity = 1 });
broadcast.LinkTo(action, linkCompletion);
actionList.Add(action);
</code>```

Option: Instead of the BroadcastBlock use a properly bounded BufferBlock. When your downstream blocks are bound to one item they cannot receive additional items until they finish processing what they have. That will allow the BufferBlock to offer its items to another, possibly idle, ActionBlock.

When you add items into a throttled flow, i.e. a flow with a BoundedCapacity less than Unbounded. You need to be using the  SendAsync method or at least handling the return of Post. I'd recommend simply using SendAsync:

```<code>foreach (MemcachedDTO d in dtoList)
{
    await iR.SendAsync(d);
}
</code>```

That will force your method signature to become:

```<code>public async Task<HttpResponseMessage> ReloadItem(string projectQuery)
</code>```

2) Am I doing the await on all actionBlocks correctly?

The previous change will permit you to loose the blocking Wait call in favor of a await Task.WhenAlll

```<code>iR.Complete();
actionList.ForEach(x => x.Completion.Wait());

To:

iR.Complete();
await bufferBlock.Completion.ContinueWith(tsk => actionList.ForEach(x => x.Complete());
await Task.WhenAll(actionList.Select(action => action.Completion).ToList());
</code>```

3) How do I make the database call async?

I'm going to leave this open because it should be a separate question unrelated to TPL-Dataflow, but in short use an async Api to access your Db and async will naturally grow through your code base. This should get you started.

BufferBlock vs BroadcastBlock

After re-reading your previous question and the answer from @VMAtm. It seems you want each item sent to All five servers, in that case you will need a BroadcastBlock. You would use a BufferBlock to distribute the messages relatively evenly to a flexible pool of servers that each could handle a message. None the less, you will still need to take control of propagating completion and faults to all the connected ActionBlocks by awaiting the completion of the BroadcastBlock.

To Prevent BroadcastBlock Dropped Messages

In general you two options, set your ActionBlocks to be unbound, which is their default value:

```<code>new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 3, BoundedCapacity = Unbounded });
</code>```

Or broadcast messages your self from any variety of your own construction. Here is an example implementation from @i3arnon. And another from @svick

Title: BroadcastBlock missing items

Body:
I have a list of project numbers that I need to process. A project could have about 8000 items and I need to get the data for each item in the project and then push this data into a list of servers. Can anybody please tell me the following..

1) I have 1000 items in iR but only 998 were written to the servers.  Did I loose items by using broadCastBlock?
2) Am I doing the await on all actionBlocks correctly?
3) How do I make the database call async?

Here is the database code

    public  MemcachedDTO GetIR(MemcachedDTO dtoItem)
    {

        string[] Tables = new string[] { "iowa", "la" };
        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["test"].ConnectionString))
        {
            using (SqlCommand command = new SqlCommand("test", connection))
            {
                DataSet Result = new DataSet();
                command.CommandType = CommandType.StoredProcedure;

                command.Parameters.Add("@ProjectId", SqlDbType.VarChar);
                command.Parameters["@ProjectId"].Value = dtoItem.ProjectId;

                connection.Open();
                Result.EnforceConstraints = false;
                Result.Load(command.ExecuteReader(CommandBehavior.CloseConnection), LoadOption.OverwriteChanges, Tables);
                dtoItem.test = Result;
            }
        }
        return dtoItem;
    }

Update:
I have updated the code to the below. It just hangs when I run it and only writes 1/4 of the data to the server?  Can you please let me know what I am doing wrong?

      public static ITargetBlock<T> CreateGuaranteedBroadcastBlock<T>(IEnumerable<ITargetBlock<T>> targets, DataflowBlockOptions options)
    {
        var targetsList = targets.ToList();

        var block = new ActionBlock<T>(
            async item =>
            {
                foreach (var target in targetsList)
                {
                    await target.SendAsync(item);
                }
            }, new ExecutionDataflowBlockOptions
            {
                CancellationToken = options.CancellationToken
            });

        block.Completion.ContinueWith(task =>
        {
            foreach (var target in targetsList)
            {
                if (task.Exception != null)
                    target.Fault(task.Exception);
                else
                    target.Complete();
            }
        });

        return block;
    }

    [HttpGet]
    public async Task< HttpResponseMessage> ReloadItem(string projectQuery)
    {
        try
        {

            var linkCompletion = new ExecutionDataflowBlockOptions
            {
                 MaxDegreeOfParallelism = 2
            };
             var cts = new CancellationTokenSource();
            var dbOptions = new DataflowBlockOptions { CancellationToken = cts.Token };

            IList<string> projectIds = projectQuery.Split(',').ToList();
            IEnumerable<string> serverList = ConfigurationManager.AppSettings["ServerList"].Split(',').Cast<string>();

            var iR = new TransformBlock<MemcachedDTO, MemcachedDTO>(
                dto => dto.GetIR(dto), new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 3 });

            List<ActionBlock<MemcachedDTO>> actionList = new List<ActionBlock<MemcachedDTO>>();

            List<MemcachedDTO> dtoList = new List<MemcachedDTO>();

            foreach (string pid in projectIds)
            {
                IList<MemcachedDTO> dtoTemp = new List<MemcachedDTO>();
                dtoTemp = MemcachedDTO.GetItemIdsByProject(pid);
                dtoList.AddRange(dtoTemp);
            }
            foreach (string s in serverList)
            {
                var action = new ActionBlock<MemcachedDTO>(
                async dto => await PostEachServerAsync(dto, s, "setitemcache"));
                actionList.Add(action);
            }
            var bBlock = CreateGuaranteedBroadcastBlock(actionList, dbOptions);

            foreach (MemcachedDTO d in dtoList)
            {
                await iR.SendAsync(d);
            }

            iR.Complete();
            iR.LinkTo(bBlock);
            await Task.WhenAll(actionList.Select(action => action.Completion).ToList());

            return Request.CreateResponse(HttpStatusCode.OK, new { message = projectIds.ToString() + " reload success" });
        }
        catch (Exception ex)
        {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, new { message = ex.Message.ToString() });
        }
    }

Body:
1) I have 1000 items in iR but only 998 were written to the servers. Did I loose items by using broadCastBlock?

Yes in the code below you set BoundedCapacity to one, if at anytime your BroadcastBlock cannot pass along an item it will drop it. Additionally a BroadcastBlock will only propagate Completion to one TargetBlock, do not use PropagateCompletion=true here. If you want all blocks to complete you need to handle Completion manually. This can be done by setting the ContinueWith on the BroadcastBlock to pass Completion to all of the connected targets.

var action = new ActionBlock<MemcachedDTO>(dto => PostEachServerAsync(dto, s, "set"), new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 3, BoundedCapacity = 1 });
broadcast.LinkTo(action, linkCompletion);
actionList.Add(action);

Option: Instead of the BroadcastBlock use a properly bounded BufferBlock. When your downstream blocks are bound to one item they cannot receive additional items until they finish processing what they have. That will allow the BufferBlock to offer its items to another, possibly idle, ActionBlock.

When you add items into a throttled flow, i.e. a flow with a BoundedCapacity less than Unbounded. You need to be using the  SendAsync method or at least handling the return of Post. I'd recommend simply using SendAsync:

foreach (MemcachedDTO d in dtoList)
{
    await iR.SendAsync(d);
}

That will force your method signature to become:

public async Task<HttpResponseMessage> ReloadItem(string projectQuery)

2) Am I doing the await on all actionBlocks correctly?

The previous change will permit you to loose the blocking Wait call in favor of a await Task.WhenAlll

iR.Complete();
actionList.ForEach(x => x.Completion.Wait());

To:

iR.Complete();
await bufferBlock.Completion.ContinueWith(tsk => actionList.ForEach(x => x.Complete());
await Task.WhenAll(actionList.Select(action => action.Completion).ToList());

3) How do I make the database call async?

I'm going to leave this open because it should be a separate question unrelated to TPL-Dataflow, but in short use an async Api to access your Db and async will naturally grow through your code base. This should get you started.

BufferBlock vs BroadcastBlock

After re-reading your previous question and the answer from @VMAtm. It seems you want each item sent to All five servers, in that case you will need a BroadcastBlock. You would use a BufferBlock to distribute the messages relatively evenly to a flexible pool of servers that each could handle a message. None the less, you will still need to take control of propagating completion and faults to all the connected ActionBlocks by awaiting the completion of the BroadcastBlock.

To Prevent BroadcastBlock Dropped Messages

In general you two options, set your ActionBlocks to be unbound, which is their default value:

new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 3, BoundedCapacity = Unbounded });

Or broadcast messages your self from any variety of your own construction. Here is an example implementation from @i3arnon. And another from @svick


问:
Set boolean for a function inside a variable
```<code>//     openMNav.isDropDown = false;
       var openMNav = function () {
              if (!this.isDropDown) {
              this.isDropDown = true;
              console.log(1);
            } else {
              this.isDropDown = false;
              console.log(0);
        }
</code>```

My question is how to do something like this: var openMNav.isDropDown = false;.
I want to set openMNav -> isDropDown outside the function to false

答:
You mean to set on the function itself, you should just use openMNav in the function not this.</p>

```<code>function openMNav () {

    if (!openMNav.isDropDown) {
        console.log('do open');
        openMNav.isDropDown = true;
    }
    else {
        console.log('already opened');
        openMNav.isDropDown = false;
    }
}

openMNav();
openMNav();
</code>```

Body:
//     openMNav.isDropDown = false;
       var openMNav = function () {
              if (!this.isDropDown) {
              this.isDropDown = true;
              console.log(1);
            } else {
              this.isDropDown = false;
              console.log(0);
        }

My question is how to do something like this: var openMNav.isDropDown = false;.
I want to set openMNav -> isDropDown outside the function to false

Body:
You mean to set on the function itself, you should just use openMNav in the function not this.

function openMNav () {

    if (!openMNav.isDropDown) {
        console.log('do open');
        openMNav.isDropDown = true;
    }
    else {
        console.log('already opened');
        openMNav.isDropDown = false;
    }
}

openMNav();
openMNav();


问:
Bash replace character into = separated values
I have the following script:

```<code>#!/bin/bash

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done

SCRIPT_PATH="$( cd -P "$( dirname "$SOURCE" )" && pwd )"/..

grep -o -P "(\w*_?)*=(\"|\').*(\"|\')" ${SCRIPT_PATH}/start.sh  > ${SCRIPT_PATH}/run.env
</code>```

That generates a file with the contents:

```<code>SOME_VAR="13434"
ANOTHER_VAR="BlAH BLAH BLAH"
</code>```

From a file that has contents:

```<code>asdf SOME_VAR="13434"\
     ANOTHER_VAR= "BlAH BLAH BLAH" some other strings
</code>```

But now I want to remove (trim) ONLY the STARTING and TAILING " characters from the generated result. In my case the result I want it to be:

```<code>SOME_VAR=13434
ANOTHER_VAR=BlAH BLAH BLAH
</code>```

Do you have any ideas how I can do that?

答:
A single sed call will do the trick:

```<code>sed -e 's/\([^=]*=\)"/\1/g' -e 's/"$//' file1 > file2
</code>```

The first regex only matches a quotation mark immediately after the first =, while the second regex only matches a quotation mark at the end of the line.

It should be noted that the resulting file will throw errors if you try to source or execute it in Bash because Bash won't allow something like ANOTHER_VAR=BlAH BLAH.

Body:
I have the following script:

#!/bin/bash

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done

SCRIPT_PATH="$( cd -P "$( dirname "$SOURCE" )" && pwd )"/..

grep -o -P "(\w*_?)*=(\"|\').*(\"|\')" ${SCRIPT_PATH}/start.sh  > ${SCRIPT_PATH}/run.env

That generates a file with the contents:

SOME_VAR="13434"
ANOTHER_VAR="BlAH BLAH BLAH"

From a file that has contents:

asdf SOME_VAR="13434"\
     ANOTHER_VAR= "BlAH BLAH BLAH" some other strings

But now I want to remove (trim) ONLY the STARTING and TAILING " characters from the generated result. In my case the result I want it to be:

SOME_VAR=13434
ANOTHER_VAR=BlAH BLAH BLAH

Do you have any ideas how I can do that?

Body:
A single sed call will do the trick:

sed -e 's/\([^=]*=\)"/\1/g' -e 's/"$//' file1 > file2

The first regex only matches a quotation mark immediately after the first =, while the second regex only matches a quotation mark at the end of the line.

It should be noted that the resulting file will throw errors if you try to source or execute it in Bash because Bash won't allow something like ANOTHER_VAR=BlAH BLAH.


问:
MPMoviePlayerViewController playing only audio no video on simulator?
i am using the following code to play a video from a url but when the video loads only audio is played and no video is shown on simulator..right now i cant test it on iphone 4.0 device...is there a problem with the simulator or is MPMoviePlayerViewController  is not the right way??

```<code>NSString *videoFilepath = @"http://www.migital.com/Hemant/1.3gp";
NSURL *videoURL = [NSURL URLWithString:videoFilepath ];

MPMoviePlayerViewController *movie = [[MPMoviePlayerViewController alloc] initWithContentURL:videoURL];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(playbackFinishedCallback:)
                                             name:MPMoviePlayerPlaybackDidFinishNotification
                                           object:movie];

[self presentMoviePlayerViewControllerAnimated:movie];
</code>```

答:
try this</p>

```<code>NSString *videoFilepath = @"http://www.migital.com/Hemant/1.3gp";
NSURL *videoURL = [NSURL URLWithString:videoFilepath ];

MPMoviePlayerViewController *movie = [[MPMoviePlayerViewController alloc] initWithContentURL:videoURL];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(playbackFinishedCallback:)
                                             name:MPMoviePlayerPlaybackDidFinishNotification
                                           object:[movie moviePlayer]];

[self presentMoviePlayerViewControllerAnimated:movie];
movie.moviePlayer.movieSourceType = MPMovieSourceTypeStreaming;
[movie.moviePlayer play];
</code>```

Body:
i am using the following code to play a video from a url but when the video loads only audio is played and no video is shown on simulator..right now i cant test it on iphone 4.0 device...is there a problem with the simulator or is MPMoviePlayerViewController  is not the right way??

NSString *videoFilepath = @"http://www.migital.com/Hemant/1.3gp";
NSURL *videoURL = [NSURL URLWithString:videoFilepath ];

MPMoviePlayerViewController *movie = [[MPMoviePlayerViewController alloc] initWithContentURL:videoURL];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(playbackFinishedCallback:)
                                             name:MPMoviePlayerPlaybackDidFinishNotification
                                           object:movie];

[self presentMoviePlayerViewControllerAnimated:movie];

Body:
try this

NSString *videoFilepath = @"http://www.migital.com/Hemant/1.3gp";
NSURL *videoURL = [NSURL URLWithString:videoFilepath ];

MPMoviePlayerViewController *movie = [[MPMoviePlayerViewController alloc] initWithContentURL:videoURL];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(playbackFinishedCallback:)
                                             name:MPMoviePlayerPlaybackDidFinishNotification
                                           object:[movie moviePlayer]];

[self presentMoviePlayerViewControllerAnimated:movie];
movie.moviePlayer.movieSourceType = MPMovieSourceTypeStreaming;
[movie.moviePlayer play];


问:
seaborn pairplot seperate bins in diagonal
```<code>sns.pairplot(iris, hue='class', palette='husl',kind='reg')
plt.show()
</code>```

That is the code I used to generate the plot(picture below).
There is also a picture of how I want it to look.

This is how it looks now:

This is how I want it to look:

答:
The main difference is that compared to the example you show on the bottom, you use a different palette and a regression line.

Once you leave out palette='husl',kind='reg' you get the plot on the bottom.

The remaining difference is due to a different style in different matplotlib versions. The picture on the bottom has been produced with a version of matplotlib prior to version 2. To get the old style back in matplotlib 2 you can use

```<code>import matplotlib.pyplot as plt
plt.style.use('classic')
</code>```

Complete code:

```<code>import matplotlib.pyplot as plt
plt.style.use('classic')
import seaborn as sns; sns.set(style="ticks", color_codes=True)
iris = sns.load_dataset("iris")
g = sns.pairplot(iris, hue="species")

plt.show()
</code>```

produces

Body:
sns.pairplot(iris, hue='class', palette='husl',kind='reg')
plt.show()

That is the code I used to generate the plot(picture below).
There is also a picture of how I want it to look.

This is how it looks now:

This is how I want it to look:

Body:
The main difference is that compared to the example you show on the bottom, you use a different palette and a regression line.

Once you leave out palette='husl',kind='reg' you get the plot on the bottom.

The remaining difference is due to a different style in different matplotlib versions. The picture on the bottom has been produced with a version of matplotlib prior to version 2. To get the old style back in matplotlib 2 you can use

import matplotlib.pyplot as plt
plt.style.use('classic')

Complete code:

import matplotlib.pyplot as plt
plt.style.use('classic')
import seaborn as sns; sns.set(style="ticks", color_codes=True)
iris = sns.load_dataset("iris")
g = sns.pairplot(iris, hue="species")

plt.show()

produces


答:
```<code>grep -oP '[^\s]+\s*=\s*"[^"]+"' file |sed 's/=\s*"\([^"]*\)"/=\1/'
</code>```

-o matches only what's in single quotes

-P perl-like regexp

[^\s]+ non-space characters

sed deletes quotes

Title: Bash replace character into = separated values

Body:
grep -oP '[^\s]+\s*=\s*"[^"]+"' file |sed 's/=\s*"\([^"]*\)"/=\1/'

-o matches only what's in single quotes

-P perl-like regexp

[^\s]+ non-space characters

sed deletes quotes


问:
C# Access Database Update Syntax Error
Is there something wrong with this query?

```<code>"UPDATE tb_EmployeeMasterList SET [EmployeeID] = " + txt_EmpId.Text +", [LastName] = '" + txt_LN.Text + "', [FirstName] = '" + txt_FN.Text + "', [MiddleName] = '" + txt_MN.Text + "', [PositionOrSkill] = '" + txt_PorS.Text + "', [BasicSalary] = " + txt_Basic.Text + ", [Allowance] = " + txt_Allow.Text + ", [Total] = " + total + ", [EPAproposedBonus] = " + txt_Bonus.Text + ", [Remarks] = '" + txt_Remarks.Text + "' WHERE ([LastName] = '" + LN + "' AND [FirstName] = '" + FN + "');"
</code>```

I keep on Getting syntax error on that query alone.

答: If total, LN and FN values come from variables not Textboxes then the syntax is OK but Textbox then add .Text after them otherwise it gives the Syntax error.

Title: C# Access Database Update Syntax Error

Body:
Is there something wrong with this query?

"UPDATE tb_EmployeeMasterList SET [EmployeeID] = " + txt_EmpId.Text +", [LastName] = '" + txt_LN.Text + "', [FirstName] = '" + txt_FN.Text + "', [MiddleName] = '" + txt_MN.Text + "', [PositionOrSkill] = '" + txt_PorS.Text + "', [BasicSalary] = " + txt_Basic.Text + ", [Allowance] = " + txt_Allow.Text + ", [Total] = " + total + ", [EPAproposedBonus] = " + txt_Bonus.Text + ", [Remarks] = '" + txt_Remarks.Text + "' WHERE ([LastName] = '" + LN + "' AND [FirstName] = '" + FN + "');"

I keep on Getting syntax error on that query alone.


问:
Adding Data to multiple tables with a single form Laravel
I am trying to insert a blog post on db, I do have two tables posts and tags tables. When I insert the create the post I want to be able to insert the data from the form in those two different tables.

create.blade.php;

```<code><div class="account_grid">

<div class="col-md-6 login-right wow fadeInRight col-md-offset-3" data-wow-delay="0.4s">
    <h3>CREATE A BLOG POST</h3>
    <p>Please fill out the required fields *</p>
    <form method="post" action="/posts"  enctype="multipart/form-data">
         {{csrf_field()}}
        <div>
            <span>Title:<label>*</label></span>
            <input type="text" id="title" name="title"  >
        </div>
        <div>
            <span>Body<label>*</label></span>
            <textarea id="body" name="body" rows="14"  ></textarea>
        </div>
        <div>
            <span>Tags:<label>*</label></span>
            <input type="text" id="tags" name="tags">
        </div>
        <div>
            <span>Image<label>*</label></span>
            <input type="file" name="image" id="image"  >
        </div>
        <input type="submit" value="Publish">

    </form>

@include('layouts.errors')
</div>
<div class="clearfix"> </div>
</div>
</code>```

On my route file I have the path that leads to PostsController.php which has a store method like below:

PostsController.php

```<code>    public function store(Request $request){

        $this->validate($request, [

            'title' =>'required|max:48',
            'body'=>'required',
            'image'=>'required',
            'tags' =>'required|max:200'
        ]);

        $post = new Post;

        $destination ='uploads';
        $image = $request->file('image');
        $filename = $image->getClientOriginalName();
        $image->move($destination, $filename);
        $location=$destination.'/'.$filename;
        $tags = request('tags');

           Post::create([
            'title'=>request('title'),
            'body' =>request('body'),
            'user_id'=>auth()->id(),
            'image' =>$destination.'/'.$filename

        ]);

        $tag = new Tag;

        Tag::create([

            'name' => $tags
        ]);

        return redirect('/blog');
    }
}
</code>```

The thing is that when I call the method I want the form data to be saved on two different tables, I have tried like below but I am getting ERROR:

MassAssignmentException in Model.php line 232:
name

I did research the issue but no luck; and yes I do have the 'name' listed in the protected $fillable array. Any suggestion on how to store data in two different tables or what type of relationship should i use.

On post.php model i do have a relationship specified. Tags belongsToMany as well as on my tag.php model Post belongsToMany

p.s New to Laravel.

tag.php model:

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model
{
    //

        public function posts(){

        return $this->belongsToMany(Post::class);
    }

    public function getRouteKeyName(){

        return 'name';

    }
}
</code>```

Post.php model:

```<code><?php

namespace App;
use Carbon\Carbon;
class Post extends Model
{

    public function comments(){

        return $this->hasMany(Comment::class);
    }

    public function addComment($body, $name, $email, $user_id){

        $this->comments()->create(compact('body','name','email', 'user_id'));
    }

    public function user(){ // $comment->user->name

        return $this->belongsTo(User::class);
    }

    public function scopeFilter($query, $filters){

        if($month =$filters['month']){
//
            $query->whereMonth('created_at', Carbon::parse($month)->month);
        }

        if($year = $filters['year']){

            $query->whereYear('created_at',$year );
        }
    }

    public static function archives(){
        return static:: selectRaw('year(created_at)year, monthname(created_at)month, count(*) published')
       ->groupBy('year','month')
       ->orderByRaw('min(created_at) desc')
       ->get()
       ->toArray();
    }

    public function tags(){

        return $this->belongsToMany(Tag::class);
    }

}
</code>```

答:
Based on the comments and discussion you have a couple of issues. The original MassAssignmentException was due to the fact that you have a custom base model in which you define a single $fillable property for all the models. But you still referenced the default Eloquent model when extending your Tag model.

Then the next issue would be attaching the tags to the post. You're passing a space delimited tag value and you're planning to separate them when accessing. That's not how tags work when you use many-to-many relationship. You need to split the tags up before storing them and attach each one to the post.

```<code>public function store(Request $request)
{
    $this->validate($request, [
        'title' => 'required|max:48',
        'body' => 'required',
        'image' => 'required',
        'tags' => 'required|max:200'
    ]);

    $destination = 'uploads';
    $image = $request->file('image');
    $filename = $image->getClientOriginalName();
    $image->move($destination, $filename);
    $location = $destination . '/' . $filename;

    $post = Post::create([
        'title' => request('title'),
        'body' => request('body'),
        'user_id' => auth()->id(),
        'image' => $location
    ]);

    $tags = explode(' ', request('tags'));

    $tagInstances = [];

    foreach($tags as $tag) {
        $tagInstances[] = new Tag(['name' => $tag]);
    }

    $post->tags()->saveMany($tagInstances);

    return redirect('/blog');
}
</code>```

Body:
I am trying to insert a blog post on db, I do have two tables posts and tags tables. When I insert the create the post I want to be able to insert the data from the form in those two different tables.

create.blade.php;

CREATE A BLOG POST

Please fill out the required fields *

    <form method="post" action="/posts"  enctype="multipart/form-data">
         {{csrf_field()}}

            Title:*
            <input type="text" id="title" name="title"  >

            Body*
            <textarea id="body" name="body" rows="14"  ></textarea>

            Tags:*
            <input type="text" id="tags" name="tags">

            Image*
            <input type="file" name="image" id="image"  >

        <input type="submit" value="Publish">

    </form>

@include('layouts.errors')

On my route file I have the path that leads to PostsController.php which has a store method like below:

PostsController.php

    public function store(Request $request){

        $this->validate($request, [

            'title' =>'required|max:48',
            'body'=>'required',
            'image'=>'required',
            'tags' =>'required|max:200'
        ]);

        $post = new Post;

        $destination ='uploads';
        $image = $request->file('image');
        $filename = $image->getClientOriginalName();
        $image->move($destination, $filename);
        $location=$destination.'/'.$filename;
        $tags = request('tags');

           Post::create([
            'title'=>request('title'),
            'body' =>request('body'),
            'user_id'=>auth()->id(),
            'image' =>$destination.'/'.$filename

        ]);

        $tag = new Tag;

        Tag::create([

            'name' => $tags
        ]);

        return redirect('/blog');
    }
}

The thing is that when I call the method I want the form data to be saved on two different tables, I have tried like below but I am getting ERROR:

MassAssignmentException in Model.php line 232:
name

I did research the issue but no luck; and yes I do have the 'name' listed in the protected $fillable array. Any suggestion on how to store data in two different tables or what type of relationship should i use.

On post.php model i do have a relationship specified. Tags belongsToMany as well as on my tag.php model Post belongsToMany

p.s New to Laravel.

tag.php model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model
{
    //

        public function posts(){

        return $this->belongsToMany(Post::class);
    }

    public function getRouteKeyName(){

        return 'name';

    }
}

Post.php model:

<?php

namespace App;
use Carbon\Carbon;
class Post extends Model
{

    public function comments(){

        return $this->hasMany(Comment::class);
    }

    public function addComment($body, $name, $email, $user_id){

        $this->comments()->create(compact('body','name','email', 'user_id'));
    }

    public function user(){ // $comment->user->name

        return $this->belongsTo(User::class);
    }

    public function scopeFilter($query, $filters){

        if($month =$filters['month']){
//
            $query->whereMonth('created_at', Carbon::parse($month)->month);
        }

        if($year = $filters['year']){

            $query->whereYear('created_at',$year );
        }
    }

    public static function archives(){
        return static:: selectRaw('year(created_at)year, monthname(created_at)month, count(*) published')
       ->groupBy('year','month')
       ->orderByRaw('min(created_at) desc')
       ->get()
       ->toArray();
    }

    public function tags(){

        return $this->belongsToMany(Tag::class);
    }

}

Body:
Based on the comments and discussion you have a couple of issues. The original MassAssignmentException was due to the fact that you have a custom base model in which you define a single $fillable property for all the models. But you still referenced the default Eloquent model when extending your Tag model.

Then the next issue would be attaching the tags to the post. You're passing a space delimited tag value and you're planning to separate them when accessing. That's not how tags work when you use many-to-many relationship. You need to split the tags up before storing them and attach each one to the post.

public function store(Request $request)
{
    $this->validate($request, [
        'title' => 'required|max:48',
        'body' => 'required',
        'image' => 'required',
        'tags' => 'required|max:200'
    ]);

    $destination = 'uploads';
    $image = $request->file('image');
    $filename = $image->getClientOriginalName();
    $image->move($destination, $filename);
    $location = $destination . '/' . $filename;

    $post = Post::create([
        'title' => request('title'),
        'body' => request('body'),
        'user_id' => auth()->id(),
        'image' => $location
    ]);

    $tags = explode(' ', request('tags'));

    $tagInstances = [];

    foreach($tags as $tag) {
        $tagInstances[] = new Tag(['name' => $tag]);
    }

    $post->tags()->saveMany($tagInstances);

    return redirect('/blog');
}


问:
mod_rewrite: redirect `x -> /legacy/x` if file _does not exist_ in `/` but _does exist_ in `/legacy/`
For over 10 years I uploaded all sorts of files to the root of my webserver.

```<code>/
  oldphoto.jpg
  oldjunk.txt
  oldfolder/
    oldfile.txt
  newpage.html
  newimg.png
</code>```

There's now ~1800 files in the root. My FTP client is slow to retrieve directory listing, so managing the website is difficult.

I'd like to tidy this up. I know which files I want to be stored at root-level (new stuff). Everything else, I've moved into a legacy/ folder.

```<code>/
  legacy/
    oldphoto.jpg
    oldjunk.txt
    oldfolder/
      oldfile.txt
  newpage.html
  newimg.png
</code>```

Problematically: some of those old files are still accessed today, from various external websites.

I want to make a cunning mod_rewrite rule that works like this:

file didn't exist?

  okay, does it exist in the legacy/ folder?

  then, I'll redirect you to the appropriate file in the legacy/ folder

So the following cases need to work:

```<code>#[A] file does not exist in /, exists in legacy folder: redirect
http://example.com/oldphoto.jpg -> http://example.com/legacy/oldphoto.jpg

#[B] file does not exist in /, exists in legacy folder: redirect
http://example.com/oldfolder/oldfile.txt -> http://example.com/legacy/oldfolder/oldfile.txt

#[C] file does not exist in /, does not exist in legacy folder: 404 as usual
http://example.com/not-exist.txt -> 404

#[D] file exists in /: serve page as usual
http://example.com/newpage.html -> http://example.com/newpage.html
</code>```

I got pretty close to getting this working:

```<code>RewriteEngine on

# No such file exists:
RewriteCond %{SCRIPT_FILENAME} !-f
# No such directory exists:
RewriteCond %{SCRIPT_FILENAME} !-d

# Capture the head of REQUEST_URI into %2 backreference; this tells us the absolute path to our web root
RewriteCond %{REQUEST_URI}::%{SCRIPT_FILENAME} ^(.*?)::(.*)\1$

# File exists web_root/legacy/REQUEST_URI OR
RewriteCond %2/legacy/%{REQUEST_URI} -f [OR]
# Directory exists web_root/legacy/REQUEST_URI OR
RewriteCond %2/legacy/%{REQUEST_URI} -d

# Redirect to /legacy/REQUEST_URI
RewriteRule .* /legacy/%{REQUEST_URI} [L,R=301]
</code>```

But this only solves cases A,C, and D. The nested case (B) fails, because %{SCRIPT_FILENAME} is not what I thought it was.

I am testing the redirect like so:

```<code>curl -sI 'http://example.com/oldphoto.jpg' | grep Location | sed 's/^Location: //'
http://example.com/legacy//oldphoto.jpg
</code>```

Here is what the macros expand to:

```<code># when requesting 'http://example.com/oldphoto.jpg':
SCRIPT_FILENAME:  /customer/homepages/13/c12345678/htdocs/user/oldphoto.jpg
REQUEST_FILENAME: /customer/homepages/13/c12345678/htdocs/user/oldphoto.jpg
DOCUMENT_ROOT:    /var/www/html
REQUEST_URI:      /oldphoto.jpg
THE_REQUEST: HEAD /oldphoto.jpg HTTP/1.1

# when requesting 'http://example.com/oldfolder/oldfile.txt':
SCRIPT_FILENAME:  /customer/homepages/13/c12345678/htdocs/user/oldfolder
REQUEST_FILENAME: /customer/homepages/13/c12345678/htdocs/user/oldfolder
DOCUMENT_ROOT:    /var/www/html
REQUEST_URI:      /oldfolder/oldfile.txt
THE_REQUEST: HEAD /oldfolder/oldfile.txt HTTP/1.1
</code>```

We can see that %{SCRIPT_FILENAME} does not give the full path to my file.

We can also see that %{DOCUMENT_ROOT} cannot be relied upon to give us the absolute path to my web root.

If somebody requests http://example.com/oldfolder/oldfile.txt:

how do I check for the existence of /customer/homepages/13/c12345678/htdocs/user/legacy/oldfolder/oldfile.txt?

how do I redirect the user to http://example.com/legacy/oldfolder/oldfile.txt?

I assume that /customer/homepages/13/c12345678/htdocs/user/ is likely to change (I have managed web hosting), so I would prefer not to hard-code it.

I am surprised that %{DOCUMENT_ROOT} does not give me this. Maybe it gives logical web root instead of physical web root.

I am also surprised that %{SCRIPT_FILENAME} gives me …/oldfolder rather than the path suggested in %{REQUEST_URI}: …/oldfolder/oldfile.txt.

答:
I think you might be over complicating the process. The process is simply:

If the requested file does not exist, but does exist in the /legacy subdirectory then redirect.

This would seem to handle situations A, B, C and D. For C and D you don't actually need to do anything.

So, try something like the following instead:

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/legacy/$1 -f
RewriteRule (.*) /legacy/$1 [R=302,L]
</code>```

This naturally only checks that a file exists in the /legacy subdirectory. Is there really a need to check for directories as well? I thought you were only moving "files"?

Change the 302 (temporary) redirect to a 301 (permanent) only when you are sure it's working OK. Make sure you clear your browser cache before testing.

We can also see that %{DOCUMENT_ROOT} cannot be relied upon to give us the absolute path to my web root.

  :

  I am surprised that %{DOCUMENT_ROOT} does not give me this.

Me too, something is a bit off here... this is precisely what the DOCUMENT_ROOT server variable should be returning: the absolute filesystem path to your web root (ie. the document root). In your output, /var/www/html, looks "normal". (If this isn't returning the expected value then many web applications will fail to work? Unless your environment is mashing something together before the server-side script gets to have a go?)

In order to get /customer/homepages/13/c12345678/htdocs/user it looks like your server is maybe using some kind of Alias to map files from a different area of the filesystem?!

If you do need to grab the filesystem path from REQUEST_FILENAME (same as SCRIPT_FILENAME) then you could perhaps do something like:

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} ^((/[^/]+){6})
RewriteCond %1/legacy%{REQUEST_URI} -f
RewriteRule .* /legacy/$0 [R=302,L]
</code>```

This grabs the first 6 path segments from the REQUEST_FILENAME server variable.

Body:
For over 10 years I uploaded all sorts of files to the root of my webserver.

/
  oldphoto.jpg
  oldjunk.txt
  oldfolder/
    oldfile.txt
  newpage.html
  newimg.png

There's now ~1800 files in the root. My FTP client is slow to retrieve directory listing, so managing the website is difficult.

I'd like to tidy this up. I know which files I want to be stored at root-level (new stuff). Everything else, I've moved into a legacy/ folder.

/
  legacy/
    oldphoto.jpg
    oldjunk.txt
    oldfolder/
      oldfile.txt
  newpage.html
  newimg.png

Problematically: some of those old files are still accessed today, from various external websites.

I want to make a cunning mod_rewrite rule that works like this:

file didn't exist?

  okay, does it exist in the legacy/ folder?

  then, I'll redirect you to the appropriate file in the legacy/ folder

So the following cases need to work:

#[A] file does not exist in /, exists in legacy folder: redirect
http://example.com/oldphoto.jpg -> http://example.com/legacy/oldphoto.jpg

#[B] file does not exist in /, exists in legacy folder: redirect
http://example.com/oldfolder/oldfile.txt -> http://example.com/legacy/oldfolder/oldfile.txt

#[C] file does not exist in /, does not exist in legacy folder: 404 as usual
http://example.com/not-exist.txt -> 404

#[D] file exists in /: serve page as usual
http://example.com/newpage.html -> http://example.com/newpage.html

I got pretty close to getting this working:

RewriteEngine on

# No such file exists:
RewriteCond %{SCRIPT_FILENAME} !-f
# No such directory exists:
RewriteCond %{SCRIPT_FILENAME} !-d

# Capture the head of REQUEST_URI into %2 backreference; this tells us the absolute path to our web root
RewriteCond %{REQUEST_URI}::%{SCRIPT_FILENAME} ^(.*?)::(.*)\1$

# File exists web_root/legacy/REQUEST_URI OR
RewriteCond %2/legacy/%{REQUEST_URI} -f [OR]
# Directory exists web_root/legacy/REQUEST_URI OR
RewriteCond %2/legacy/%{REQUEST_URI} -d

# Redirect to /legacy/REQUEST_URI
RewriteRule .* /legacy/%{REQUEST_URI} [L,R=301]

But this only solves cases A,C, and D. The nested case (B) fails, because %{SCRIPT_FILENAME} is not what I thought it was.

I am testing the redirect like so:

curl -sI 'http://example.com/oldphoto.jpg' | grep Location | sed 's/^Location: //'
http://example.com/legacy//oldphoto.jpg

Here is what the macros expand to:

# when requesting 'http://example.com/oldphoto.jpg':
SCRIPT_FILENAME:  /customer/homepages/13/c12345678/htdocs/user/oldphoto.jpg
REQUEST_FILENAME: /customer/homepages/13/c12345678/htdocs/user/oldphoto.jpg
DOCUMENT_ROOT:    /var/www/html
REQUEST_URI:      /oldphoto.jpg
THE_REQUEST: HEAD /oldphoto.jpg HTTP/1.1

# when requesting 'http://example.com/oldfolder/oldfile.txt':
SCRIPT_FILENAME:  /customer/homepages/13/c12345678/htdocs/user/oldfolder
REQUEST_FILENAME: /customer/homepages/13/c12345678/htdocs/user/oldfolder
DOCUMENT_ROOT:    /var/www/html
REQUEST_URI:      /oldfolder/oldfile.txt
THE_REQUEST: HEAD /oldfolder/oldfile.txt HTTP/1.1

We can see that %{SCRIPT_FILENAME} does not give the full path to my file.

We can also see that %{DOCUMENT_ROOT} cannot be relied upon to give us the absolute path to my web root.

If somebody requests http://example.com/oldfolder/oldfile.txt:

how do I check for the existence of /customer/homepages/13/c12345678/htdocs/user/legacy/oldfolder/oldfile.txt?

how do I redirect the user to http://example.com/legacy/oldfolder/oldfile.txt?

I assume that /customer/homepages/13/c12345678/htdocs/user/ is likely to change (I have managed web hosting), so I would prefer not to hard-code it.

I am surprised that %{DOCUMENT_ROOT} does not give me this. Maybe it gives logical web root instead of physical web root.

I am also surprised that %{SCRIPT_FILENAME} gives me …/oldfolder rather than the path suggested in %{REQUEST_URI}: …/oldfolder/oldfile.txt.

Body:
I think you might be over complicating the process. The process is simply:

If the requested file does not exist, but does exist in the /legacy subdirectory then redirect.

This would seem to handle situations A, B, C and D. For C and D you don't actually need to do anything.

So, try something like the following instead:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/legacy/$1 -f
RewriteRule (.*) /legacy/$1 [R=302,L]

This naturally only checks that a file exists in the /legacy subdirectory. Is there really a need to check for directories as well? I thought you were only moving "files"?

Change the 302 (temporary) redirect to a 301 (permanent) only when you are sure it's working OK. Make sure you clear your browser cache before testing.

We can also see that %{DOCUMENT_ROOT} cannot be relied upon to give us the absolute path to my web root.

  :

  I am surprised that %{DOCUMENT_ROOT} does not give me this.

Me too, something is a bit off here... this is precisely what the DOCUMENT_ROOT server variable should be returning: the absolute filesystem path to your web root (ie. the document root). In your output, /var/www/html, looks "normal". (If this isn't returning the expected value then many web applications will fail to work? Unless your environment is mashing something together before the server-side script gets to have a go?)

In order to get /customer/homepages/13/c12345678/htdocs/user it looks like your server is maybe using some kind of Alias to map files from a different area of the filesystem?!

If you do need to grab the filesystem path from REQUEST_FILENAME (same as SCRIPT_FILENAME) then you could perhaps do something like:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} ^((/[^/]+){6})
RewriteCond %1/legacy%{REQUEST_URI} -f
RewriteRule .* /legacy/$0 [R=302,L]

This grabs the first 6 path segments from the REQUEST_FILENAME server variable.


问:
Getting Json exception for a string
I am calling an async task which returns a json object which has result,message as a string and result as cost.

Though it shows result,message string in the response object it shows json exception as no value for result.

Asynctask

```<code>public class SearchPostsAsyncTask extends AsyncTask<String, Void, JSONObject> {
    String api;
    JSONObject jsonParams;
    Context mContext;
    private SearchPostsCallBack searchPostsCallBack;
    private ProgressDialog loadingDialog;
    private Snackbar snackbar;
    private LinearLayout parentLayout;
    private ArrayList<PostDelivery> list;
    private JSONArray listsArray;
    private JSONObject jsonObject;

    public SearchPostsAsyncTask(Context context, LinearLayout linearLayout,SearchPostsCallBack searchPostsCallBack) {

        this.mContext = context;
        this.searchPostsCallBack = searchPostsCallBack;
        this.parentLayout = linearLayout;

    }

    public interface SearchPostsCallBack {
        void doPostExecute(ArrayList<PostDelivery> list);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        loadingDialog = new ProgressDialog(mContext);

        if (!isOnline()) {

            snackbar = Snackbar.make(parentLayout, R.string.check_network, Snackbar.LENGTH_LONG);
            snackbar.show();
        } else {
            loadingDialog.show(mContext, null,mContext.getString(R.string.wait));
        }

    }

    @Override
    protected JSONObject doInBackground(String... params) {
        try {
            api = mContext.getResources().getString(R.string.url) + "requestlist";

            jsonParams = new JSONObject();
            jsonParams.put("st_lati", params[0]);
            jsonParams.put("st_longi", params[1]);
            jsonParams.put("ed_lati", params[2]);
            jsonParams.put("ed_longi", params[3]);
            jsonParams.put("pt_date", params[4]);

            ServerRequest request = new ServerRequest(api, jsonParams);
            return request.sendPostRequest(params[5]);

        } catch (JSONException je) {
            Log.e("exception",je.toString());
            return Excpetion2JSON.getJSON(je);
        } catch (Exception ue) {
            return Excpetion2JSON.getJSON(ue);
        }
    }

    @Override
    protected void onPostExecute(JSONObject response) {
        super.onPostExecute(response);
        if (loadingDialog.isShowing())
            loadingDialog.dismiss();
        try {
            list = new ArrayList<>();

                    String result = response.getString("result");
                    String message = response.getString("message");
                    if (result.equals("1")) {

                        listsArray = response.getJSONArray("cost");

                        for (int j = 0; j < listsArray.length(); j++) {

                            jsonObject = listsArray.getJSONObject(j);

                    PostDelivery postDelivery = new PostDelivery();

                    postDelivery.setmPt_id(jsonObject.getString("pt_id"));
                    postDelivery.setmPt_name(jsonObject.getString("pt_name"));
                    postDelivery.setmPtDetail(jsonObject.getString("pt_detail"));
                    postDelivery.setmPtStartLoc(jsonObject.getString("pt_start_loc"));
                    postDelivery.setmPtEndLoc(jsonObject.getString("pt_end_loc"));
                    postDelivery.setmPtDate(jsonObject.getString("pt_date"));

                    list.add(postDelivery);

                    searchPostsCallBack.doPostExecute(list);

                }
            }

                snackbar = Snackbar.make(parentLayout, "sorry", Snackbar.LENGTH_LONG);

                snackbar.show();

    }catch (JSONException je) {
            je.printStackTrace();
            //  Toast.makeText(getApplicationContext(), je.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

}
</code>```

Exception and response :

```<code>D/ServerResponse: {"result":1,"message":"Success","cost":[{"pt_id":"5","ur_id":"2","pt_name":"mobile","pt_detail":"samsung mobile ","pt_size":"0","pt_weight":"150","pt_start_loc":"nashik"}]}
06-04 19:26:06.284 7129-7129/com.carryapp W/System.err: org.json.JSONException: No value for result
</code>```

What is going wrong here? Please help.Thank you..

答:
{"result":1,"message":"Success","cost":[{"pt_id":"5","ur_id":"2","pt_name":"mobile","pt_detail":"samsung
  mobile ","pt_size":"0","pt_weight":"150","pt_start_loc":"nashik"}]}

Form your attached response, it seems that the value of result is an int value and you are trying to get this value using:

```<code>String result = response.getString("result"); // WRONG
</code>```

Try using:

```<code>int result = response.getInt("result");
</code>```

Title: Getting Json exception for a string

Body:
I am calling an async task which returns a json object which has result,message as a string and result as cost.

Though it shows result,message string in the response object it shows json exception as no value for result.

Asynctask

public class SearchPostsAsyncTask extends AsyncTask<String, Void, JSONObject> {
    String api;
    JSONObject jsonParams;
    Context mContext;
    private SearchPostsCallBack searchPostsCallBack;
    private ProgressDialog loadingDialog;
    private Snackbar snackbar;
    private LinearLayout parentLayout;
    private ArrayList<PostDelivery> list;
    private JSONArray listsArray;
    private JSONObject jsonObject;

    public SearchPostsAsyncTask(Context context, LinearLayout linearLayout,SearchPostsCallBack searchPostsCallBack) {

        this.mContext = context;
        this.searchPostsCallBack = searchPostsCallBack;
        this.parentLayout = linearLayout;

    }

    public interface SearchPostsCallBack {
        void doPostExecute(ArrayList<PostDelivery> list);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        loadingDialog = new ProgressDialog(mContext);

        if (!isOnline()) {

            snackbar = Snackbar.make(parentLayout, R.string.check_network, Snackbar.LENGTH_LONG);
            snackbar.show();
        } else {
            loadingDialog.show(mContext, null,mContext.getString(R.string.wait));
        }

    }

    @Override
    protected JSONObject doInBackground(String... params) {
        try {
            api = mContext.getResources().getString(R.string.url) + "requestlist";

            jsonParams = new JSONObject();
            jsonParams.put("st_lati", params[0]);
            jsonParams.put("st_longi", params[1]);
            jsonParams.put("ed_lati", params[2]);
            jsonParams.put("ed_longi", params[3]);
            jsonParams.put("pt_date", params[4]);

            ServerRequest request = new ServerRequest(api, jsonParams);
            return request.sendPostRequest(params[5]);

        } catch (JSONException je) {
            Log.e("exception",je.toString());
            return Excpetion2JSON.getJSON(je);
        } catch (Exception ue) {
            return Excpetion2JSON.getJSON(ue);
        }
    }

    @Override
    protected void onPostExecute(JSONObject response) {
        super.onPostExecute(response);
        if (loadingDialog.isShowing())
            loadingDialog.dismiss();
        try {
            list = new ArrayList<>();

                    String result = response.getString("result");
                    String message = response.getString("message");
                    if (result.equals("1")) {

                        listsArray = response.getJSONArray("cost");

                        for (int j = 0; j < listsArray.length(); j++) {

                            jsonObject = listsArray.getJSONObject(j);

                    PostDelivery postDelivery = new PostDelivery();

                    postDelivery.setmPt_id(jsonObject.getString("pt_id"));
                    postDelivery.setmPt_name(jsonObject.getString("pt_name"));
                    postDelivery.setmPtDetail(jsonObject.getString("pt_detail"));
                    postDelivery.setmPtStartLoc(jsonObject.getString("pt_start_loc"));
                    postDelivery.setmPtEndLoc(jsonObject.getString("pt_end_loc"));
                    postDelivery.setmPtDate(jsonObject.getString("pt_date"));

                    list.add(postDelivery);

                    searchPostsCallBack.doPostExecute(list);

                }
            }

                snackbar = Snackbar.make(parentLayout, "sorry", Snackbar.LENGTH_LONG);

                snackbar.show();

    }catch (JSONException je) {
            je.printStackTrace();
            //  Toast.makeText(getApplicationContext(), je.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

}

Exception and response :

D/ServerResponse: {"result":1,"message":"Success","cost":[{"pt_id":"5","ur_id":"2","pt_name":"mobile","pt_detail":"samsung mobile ","pt_size":"0","pt_weight":"150","pt_start_loc":"nashik"}]}
06-04 19:26:06.284 7129-7129/com.carryapp W/System.err: org.json.JSONException: No value for result

What is going wrong here? Please help.Thank you..

Body:
{"result":1,"message":"Success","cost":[{"pt_id":"5","ur_id":"2","pt_name":"mobile","pt_detail":"samsung
  mobile ","pt_size":"0","pt_weight":"150","pt_start_loc":"nashik"}]}

Form your attached response, it seems that the value of result is an int value and you are trying to get this value using:

String result = response.getString("result"); // WRONG

Try using:

int result = response.getInt("result");


问:
Filtering in PartialView
I have a PartialView, that displays items in table. And I want to filter them with some criteria. My view:

```<code>@model Bike_Store.Models.PartsViewModel

<form method="get">
    <div>
        <label>Category: </label>
        @Html.DropDownList("categorie", Model.Categories as SelectList,
        htmlAttributes: new { @class="form-control"})

        <label>Brand: </label>
        @Html.DropDownList("brand", Model.Brands as SelectList,
        htmlAttributes: new { @class="form-control" })
        <input type="submit" value="Filter" />
    </div>
</form>

 <table>...</table>
</code>```

My controller:

```<code>[HttpGet]
    public ActionResult PartsPartial(int? categorie, int? brand)
    {
        IQueryable<bs_parts> parts = _db.bs_parts.Include(p => p.bs_categories);
        if (categorie != null && categorie != 0)
        {
            parts = parts.Where(p => p.parts_category_id == categorie);
        }
        if (brand != null && brand != 0)
        {
            parts = parts.Where(p => p.parts_brand_id == brand);
        }

        List<bs_categories> categoriesList = _db.bs_categories.ToList();
        List<bs_brands> brandsList = _db.bs_brands.ToList();

        PartsViewModel pvm = new PartsViewModel
        {
            Parts = parts.ToList(),
            Categories = new SelectList(categoriesList, "categories_id", "categories_name"),
            Brands = new SelectList(brandsList, "brands_id", "brands_name")
        };
        return PartialView(pvm);
    }
</code>```

This way of filtering works fine with normal View. But when I try to do the same with Partial View it doesn't work, the page just reloads. I put break point to check, if my Get method works when I press Filter button, and I noticed that it doesn't. What is the problem?

I am calling Partial View from menu with:

```<code>@Ajax.ActionLink(
"Parts",
"PartsPartial",
new
{
    value1 = 1
},
new AjaxOptions
{
    HttpMethod = "GET",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "content"
}, new { @class = "button" }
)
<div class="content" id="content">

</div>
</code>```

答:
@Html.Partial() or @Html.RenderPartial do not make any controller call and just render html with the model of yours.

Consider using Html.RenderAction instead

UPDATE:
It looks like there is a number of answers to similar questions already:

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction. can any one please describe the difference

Controller for partial view in layout page MVC

Title: Filtering in PartialView

Body:
I have a PartialView, that displays items in table. And I want to filter them with some criteria. My view:

@model Bike_Store.Models.PartsViewModel

<form method="get">

        Category:
        @Html.DropDownList("categorie", Model.Categories as SelectList,
        htmlAttributes: new { @class="form-control"})

        Brand:
        @Html.DropDownList("brand", Model.Brands as SelectList,
        htmlAttributes: new { @class="form-control" })
        <input type="submit" value="Filter" />

</form>

...

My controller:

[HttpGet]
    public ActionResult PartsPartial(int? categorie, int? brand)
    {
        IQueryable<bs_parts> parts = _db.bs_parts.Include(p => p.bs_categories);
        if (categorie != null && categorie != 0)
        {
            parts = parts.Where(p => p.parts_category_id == categorie);
        }
        if (brand != null && brand != 0)
        {
            parts = parts.Where(p => p.parts_brand_id == brand);
        }

        List<bs_categories> categoriesList = _db.bs_categories.ToList();
        List<bs_brands> brandsList = _db.bs_brands.ToList();

        PartsViewModel pvm = new PartsViewModel
        {
            Parts = parts.ToList(),
            Categories = new SelectList(categoriesList, "categories_id", "categories_name"),
            Brands = new SelectList(brandsList, "brands_id", "brands_name")
        };
        return PartialView(pvm);
    }

This way of filtering works fine with normal View. But when I try to do the same with Partial View it doesn't work, the page just reloads. I put break point to check, if my Get method works when I press Filter button, and I noticed that it doesn't. What is the problem?

I am calling Partial View from menu with:

@Ajax.ActionLink(
"Parts",
"PartsPartial",
new
{
    value1 = 1
},
new AjaxOptions
{
    HttpMethod = "GET",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "content"
}, new { @class = "button" }
)


问:
PHP/HTML - Trying to make image appear using localhost
I am using XAMPP for APACHE server on localhost:8080 (I had to change the default port for it to work). Assume that I have the rest of the html needed to run.
Here is the current code:

home.html

```<code><body>
<script src="main/profile.php"></script>
</body>
</code>```

profile.php

```<code><?php
$imagepath ="omj/logo.jpg";
$image = imagecreatefromjpeg( $imagepath);
header('Content-Type: image/jpeg');
imagejpeg($image);
?>
</code>```

I tried referencing the following articles to no avail:

http://www.configure-all.com/howto_display_image.php

How to display images from a folder using php - PHP

Edit
I got the image to work using HTML by simply moving the image folder inside the html folder. Now the question remains, why isn't the php code running to show the image?

The image path is within the directory of the html file. Like this: /htmlfolder/imagefolder/image.jpg while html file is /htmlfolder/file.html

答:
Try this </p>

```<code><?php $input = '<img src="/image/your.jpg" title="you are title " alt="any"/>'; $sx = simplexml_load_string($input); var_dump($sx); ?>
</code>```

Body:
I am using XAMPP for APACHE server on localhost:8080 (I had to change the default port for it to work). Assume that I have the rest of the html needed to run.
Here is the current code:

home.html

profile.php

<?php
$imagepath ="omj/logo.jpg";
$image = imagecreatefromjpeg( $imagepath);
header('Content-Type: image/jpeg');
imagejpeg($image);
?>

I tried referencing the following articles to no avail:

http://www.configure-all.com/howto_display_image.php

How to display images from a folder using php - PHP

Edit
I got the image to work using HTML by simply moving the image folder inside the html folder. Now the question remains, why isn't the php code running to show the image?

The image path is within the directory of the html file. Like this: /htmlfolder/imagefolder/image.jpg while html file is /htmlfolder/file.html

Body:
Try this

<?php $input = '<img src="/image/your.jpg" title="you are title " alt="any"/>'; $sx = simplexml_load_string($input); var_dump($sx); ?>


问:
Send File as a parameter to a REST Service, from a client?
My Requirement is to send the file to the REST Service through one client. That service is going to process the file. I am using Jersey API for implementing this. But I have searched in many articles, there is no any information of how to pass the file from client side and how the REST service will retrieve the file... How to achieve this?

And I am not using the Servlets for Creating REST Service.

答:
Am I right by assuming, since its a MimeMultipart type, that I could not just send one, but multiple files or additional information maybe as String or whatever, on doing only one simple post, just by adding multiple MimeBodyParts containing the different files or whatever? for example like:

```<code>final MimeMultipart request = new MimeMultipart();
request.addBodyPart(new MimeBodyPart(new FileInputStream(new File(
    fileOne))), 0);
request.addBodyPart(new MimeBodyPart(new FileInputStream(new File(
    fileTwo))), 1);
</code>```

etc.

Body:
Am I right by assuming, since its a MimeMultipart type, that I could not just send one, but multiple files or additional information maybe as String or whatever, on doing only one simple post, just by adding multiple MimeBodyParts containing the different files or whatever? for example like:

final MimeMultipart request = new MimeMultipart();
request.addBodyPart(new MimeBodyPart(new FileInputStream(new File(
    fileOne))), 0);
request.addBodyPart(new MimeBodyPart(new FileInputStream(new File(
    fileTwo))), 1);

etc.


问:
tkinter canvas stays minimized
how do I get a canvas to actually have a size?

```<code>root = Tk()
canv = Canvas(root, width=600, height=600)
canv.pack(fill = BOTH, expand = True)

root.after(1, draw)
mainloop()
</code>```

just creates a window with a 1px canvas in the top left corner

edit: I omitted draw, because it didn’t throw anything, thus didn’t seem relevant. But since it runs perfectly if I n through it via pdb, here’s the full code:

```<code>from tkinter import *
from pdb import set_trace

class Field: #abstact
    def __init__(self, size):
        super().__init__()
        self.tiles = [[(None, 0) for i in range(size[1])] for j in     range(size[0])] #list of columns

    def get_tile(self, x,y):
        return tiles[x][y]

    def inc_tile(self, x,y,player):
        t = self.tiles[x][y]
        tiles[x][y] = (player, t[1])

class RectField(Field):
    def __init__(self, size):
        super().__init__(size)

    def select_tile(self, x, y):
        lx = len(self.tiles)
        rx = floor(x*lx)
        ly = len(self.tiles[rx])
        ry = floor(x*ly)
        return (rx, ry)

    def draw(self, canvas):
        canvas.delete(ALL)
        w = canvas.winfo_width()
        h = canvas.winfo_height()
        canvas.create_rectangle(0, 0, w, h, fill='#f0f')
        sx = w/len(self.tiles)
        for i in range(len(self.tiles)):
            sy = h/len(self.tiles[i])
            for j in range(len(self.tiles[i])):
                pl = self.tiles[i][j][0]
                cl = '#888' if not pl else ('#f20' if pl == 1 else '#02f')
                canvas.create_rectangle(i*sx, j*sy, (i+1)*sx, (j+1)*sy,     fill=cl, outline='#000')

    ##############################################################################    #####################
# MAIN
##############################################################################    #####################

root = Tk()
canv = Canvas(root, width=600, height=600)
canv.pack(fill = BOTH, expand = True)

#set_trace()
field = RectField((4,4))

def init():
    canv.create_rectangle(0, 0, 600, 600, fill='#f0f')
    set_trace()
    field.draw(canv)
    root.update()

root.after(1, init)
mainloop()
</code>```

OS is ubuntu 16.04,
python version is the preinstalled python3, run via terminal

答:
I was able to get your canvas to show up and work fine. It looks like your init function was the problem. You don't need to define a time to wait when calling your init() function just call it directly and the program will do the rest.

Also I have looked over the tkinter documentation for canvas and I do not see anything like .draw() I do not think a function like that exist for tkinter. I could be wrong but if it does exist the documentation is not obvious.

use this instead:

```<code>def init():
    canv.create_rectangle(0, 0, 600, 600, fill='blue')
    # I only changed the color to make sure it was working
    #set_trace() # not needed.
    #field.draw(canv) # does nothing?
    #root.update()  # not needed in this case.

init()
</code>```

Title: tkinter canvas stays minimized

Body:
how do I get a canvas to actually have a size?

root = Tk()
canv = Canvas(root, width=600, height=600)
canv.pack(fill = BOTH, expand = True)

root.after(1, draw)
mainloop()

just creates a window with a 1px canvas in the top left corner

edit: I omitted draw, because it didn’t throw anything, thus didn’t seem relevant. But since it runs perfectly if I n through it via pdb, here’s the full code:

from tkinter import *
from pdb import set_trace

class Field: #abstact
    def __init__(self, size):
        super().__init__()
        self.tiles = [[(None, 0) for i in range(size[1])] for j in     range(size[0])] #list of columns

    def get_tile(self, x,y):
        return tiles[x][y]

    def inc_tile(self, x,y,player):
        t = self.tiles[x][y]
        tiles[x][y] = (player, t[1])

class RectField(Field):
    def __init__(self, size):
        super().__init__(size)

    def select_tile(self, x, y):
        lx = len(self.tiles)
        rx = floor(x*lx)
        ly = len(self.tiles[rx])
        ry = floor(x*ly)
        return (rx, ry)

    def draw(self, canvas):
        canvas.delete(ALL)
        w = canvas.winfo_width()
        h = canvas.winfo_height()
        canvas.create_rectangle(0, 0, w, h, fill='#f0f')
        sx = w/len(self.tiles)
        for i in range(len(self.tiles)):
            sy = h/len(self.tiles[i])
            for j in range(len(self.tiles[i])):
                pl = self.tiles[i][j][0]
                cl = '#888' if not pl else ('#f20' if pl == 1 else '#02f')
                canvas.create_rectangle(i*sx, j*sy, (i+1)*sx, (j+1)*sy,     fill=cl, outline='#000')

    ##############################################################################    #####################
# MAIN
##############################################################################    #####################

root = Tk()
canv = Canvas(root, width=600, height=600)
canv.pack(fill = BOTH, expand = True)

#set_trace()
field = RectField((4,4))

def init():
    canv.create_rectangle(0, 0, 600, 600, fill='#f0f')
    set_trace()
    field.draw(canv)
    root.update()

root.after(1, init)
mainloop()

OS is ubuntu 16.04,
python version is the preinstalled python3, run via terminal

Body:
I was able to get your canvas to show up and work fine. It looks like your init function was the problem. You don't need to define a time to wait when calling your init() function just call it directly and the program will do the rest.

Also I have looked over the tkinter documentation for canvas and I do not see anything like .draw() I do not think a function like that exist for tkinter. I could be wrong but if it does exist the documentation is not obvious.

use this instead:

def init():
    canv.create_rectangle(0, 0, 600, 600, fill='blue')
    # I only changed the color to make sure it was working
    #set_trace() # not needed.
    #field.draw(canv) # does nothing?
    #root.update()  # not needed in this case.

init()


问:
D3 how to call functions on event when inside a class?
This is an abstract of my code

```<code>class X {
    constructor() {
        ...
    }

    function1(...) {
        ...
        self = this;
        this.xyz.append('g')
            .attr("id", this.id)
            .data([{
                        "x": this.x,
                        "y": this.y
                    }
                ])
            .attr("transform", "translate(" + this.x + "," + this.y + ")")
            .on("click", self.function2(this.id));
    }

    function2(...){
        ...
    }
}
</code>```

So when the function 1 is called I've kept a listener onclick to run function2, but the function2 is never called during onclick but during first instance function1 is called. Could you please let me know my mistake

答:
The second argument to .on is a function, you are instead invoking the function and passing it's return value to .on.  Further, since this.id is in scope of function2, I'm not sure you need to pass it.

If you do need to pass a variable, wrapper it in an anon function:

So it just becomes:

```<code>class X {
    constructor() {
        ...
    }

    function1(...) {
        ...
        self = this;

        var someValue = 6;

        this.xyz.append('g')
            .attr("id", this.id)
            .data([{
                        "x": this.x,
                        "y": this.y
                    }
                ])
            .attr("transform", "translate(" + this.x + "," + this.y + ")")
            .on("click", function(){
               self.function2(someValue)
             });
    }

    function2(theValue){
        console.log(theValue); // 6
    }
}
</code>```

Running code:

<!DOCTYPE html>

    <svg></svg>

```

Body:
This is an abstract of my code

class X {
    constructor() {
        ...
    }

    function1(...) {
        ...
        self = this;
        this.xyz.append('g')
            .attr("id", this.id)
            .data([{
                        "x": this.x,
                        "y": this.y
                    }
                ])
            .attr("transform", "translate(" + this.x + "," + this.y + ")")
            .on("click", self.function2(this.id));
    }

    function2(...){
        ...
    }
}

So when the function 1 is called I've kept a listener onclick to run function2, but the function2 is never called during onclick but during first instance function1 is called. Could you please let me know my mistake

Body:
The second argument to .on is a function, you are instead invoking the function and passing it's return value to .on.  Further, since this.id is in scope of function2, I'm not sure you need to pass it.

If you do need to pass a variable, wrapper it in an anon function:

So it just becomes:

class X {
    constructor() {
        ...
    }

    function1(...) {
        ...
        self = this;

        var someValue = 6;

        this.xyz.append('g')
            .attr("id", this.id)
            .data([{
                        "x": this.x,
                        "y": this.y
                    }
                ])
            .attr("transform", "translate(" + this.x + "," + this.y + ")")
            .on("click", function(){
               self.function2(someValue)
             });
    }

    function2(theValue){
        console.log(theValue); // 6
    }
}

Running code:

<!DOCTYPE html>
<html>

  <head>
    <script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
  </head>

  <body>
    <svg></svg>
    <script>
    class X {

      constructor() {
      }

      function1() {

        var self = this,
            someValue = 6;

        d3.select('svg').append('rect')
          .attr("width", 500)
          .attr("height", 500)
          .attr("fill", "steelblue")
          .on("click", function() {
            self.function2(someValue)
          });
      }

      function2(theValue) {
        console.log(theValue); // 6
      }
    }

    var y = new X();
    y.function1();

  </script>
  </body>

</html>


问:
Releasing Windows file share locks
This problem crops up every now and then at work. Our build machine can have it's files accessed via a normal windows file share. If someone browses a folder remotely on the machine, and leaves the window open overnight, then the build fails (as it has done now). The explorer window left opened points at one of the sub folders in the source tree. The build deletes the source, and does a clean checkout before building. The delete is failing.

Right now, I'd like to get the build to work. I'm logged in from home, and I'd rather not reboot the build machine. I'm unable to get hold of the person whose machine is looking and the files, and I can't remotely reboot their machine.

When a windows share has a lock, the locking process is System, so I don't think I can kill it, as with normal locks.

Does anyone know a way to release the lock on a shared folder without having to reboot the machine?

答:
Another option is, starting from Windows Vista, to use the Windows tool built into the system:

monitor resources: perfmon.exe /res

Extracted from: Http://www.sysadmit.com/2017/06/windows-how-to-know-that-process-has-open-a-file.html

OwnerDisplayName: Jonathan Wright

Title: Releasing Windows file share locks