问:
c# and dynamic string scripting
I'd love some ideas about how I should implement a key part of a project I am working on.  Essentially it is data mapping, where I copy field x and put it into field y.  However, there needs to be some ability to dynamically change (using string manipulation) that value during the transition.

What I would like is a textbox where a user could enter script allowing them to modify that value using a scripting language, ideally VBScript.  That would then allow them to do simple manipulations such this example, which would take a substring:

```<code>Mid({input_value}, 2, 4)
</code>```

Where

```<code>{input_value}
</code>```

Would be replaced by the actual value at runtime.

So, for example, if the input from "field x" was "This is a test" and they used the above example of start = 2 and length = 4, the value saved into "field y" would be "his "

I know how I could run VBScript from C# as a scipt, that's not a problem.  However, Is it possible to run and evaluate srcipts such as above at runtime and record the output back into a C# variable?

Otherwise, does anyone have any suggestions about how I could approach this?

Many thanks

答:
You might want to look at a DLR-based language like IronPython or IronRuby. Both allow embedding and Michael Foord has a tutorial on how to embed these in an application.

If you use the standard DLR interfaces I believe you can embed any language including DLRBasic and the ASP Classic Compiler. Ben Hall has an article on IronRuby embedding in a production application for Red Gate.

I think you need to review the SetVariable() and GetVariable() methods shown below for an example of setting and return data from scripts:

```<code>public string evaluate(string x, string code)
{
    scope.SetVariable("x", x);
    scope.SetVariable("button", this.button);

    try
    {
        ScriptSource source = engine.CreateScriptSourceFromString(code,
            SourceCodeKind.Statements);

        source.Execute(scope);
    }
    catch (Exception ex)
    {
        return "Error executing code: " + ex.ToString();
    }

    if (!scope.VariableExists("x"))
    {
        return "x was deleted";
    }
    string result = scope.GetVariable<object>("x").ToString();
    return result;
}
</code>```

This example was taken from http://www.voidspace.org.uk/ironpython/dlr_hosting.shtml.

Title: c# and dynamic string scripting

Body:
I'd love some ideas about how I should implement a key part of a project I am working on.  Essentially it is data mapping, where I copy field x and put it into field y.  However, there needs to be some ability to dynamically change (using string manipulation) that value during the transition.

What I would like is a textbox where a user could enter script allowing them to modify that value using a scripting language, ideally VBScript.  That would then allow them to do simple manipulations such this example, which would take a substring:

Mid({input_value}, 2, 4)

Where

{input_value}

Would be replaced by the actual value at runtime.

So, for example, if the input from "field x" was "This is a test" and they used the above example of start = 2 and length = 4, the value saved into "field y" would be "his "

I know how I could run VBScript from C# as a scipt, that's not a problem.  However, Is it possible to run and evaluate srcipts such as above at runtime and record the output back into a C# variable?

Otherwise, does anyone have any suggestions about how I could approach this?

Many thanks

Body:
You might want to look at a DLR-based language like IronPython or IronRuby. Both allow embedding and Michael Foord has a tutorial on how to embed these in an application.

If you use the standard DLR interfaces I believe you can embed any language including DLRBasic and the ASP Classic Compiler. Ben Hall has an article on IronRuby embedding in a production application for Red Gate.

I think you need to review the SetVariable() and GetVariable() methods shown below for an example of setting and return data from scripts:

public string evaluate(string x, string code)
{
    scope.SetVariable("x", x);
    scope.SetVariable("button", this.button);

    try
    {
        ScriptSource source = engine.CreateScriptSourceFromString(code,
            SourceCodeKind.Statements);

        source.Execute(scope);
    }
    catch (Exception ex)
    {
        return "Error executing code: " + ex.ToString();
    }

    if (!scope.VariableExists("x"))
    {
        return "x was deleted";
    }
    string result = scope.GetVariable<object>("x").ToString();
    return result;
}

This example was taken from http://www.voidspace.org.uk/ironpython/dlr_hosting.shtml.


来源: stackexchange

问:
D3 JS stacked bar at top instead of bottom using path
I followed the following SA question to build a stacked bar chart using <path> instead of <rect>, so I can style the top bar part to have a rounded corner.

How to Make a bar chart with rounded corners with extended grid in d3.js?

Here is a code pen with my code showing my code and the wrong effect: https://codepen.io/Yeronimo/pen/jOPWBGL

The problem is that the stacked bars align at the top.

I have tried many changes to the bar function and the calling "attr d" function, but I seem to be only making things worse. Any help would be appreciated.

And here a poorly shopped image of what it should look like. So the idea is that the bars have the correct height and correct order in my current code, just that they should be aligning at the bottom. In the image the rounded corners got lost, but they are visible in the pen.

答:
Change the base y of the bars from yscale(d[1]) to yscale(0) like the following:

return bar((xscale(xlabels[i]) + (xscale.bandwidth() / num_groups) * gnum) + 5,
            yscale(0),
            14,
            yscale(d[1]), s);
```

<p>Now the bars will be upright. But don't be fooled. The stacks that appear on the graph are not correct, and do not reflect the data properly. That is because the <code>h</code> parameter in the <code>bar</code> function is the height of the bar, and <code>d[1]</code> is, in fact, <code>y - h</code>. So the <code>bar</code> function needs to be corrected.</p>

<pre class="lang-js prettyprint-override"><code>function bar(x, y, w, y1, r, f) {
    // Flag for sweep:
    if (f == undefined) f = 1;
    // x coordinates of top of arcs
    var x0 = x + r;
    var x1 = x + w - r;
    // y coordinates of bottom of arcs
    var y0 = y1 + r;
    // just for convenience (slightly different than above):
    var l = "L", a = "A";

    var parts = ["M", x, y, l, x, y0, a, r, r, 0, 0, f, x0, y1, l, x1, y1, a, r, r, 0, 0, f, x + w, y0, l, x + w, y, "Z"];
    return parts.join(" ");
}
</code>```

The same effect can be achieved by calling the original bar with yscale(0) - yscale(d[1]), but this will create unnecessary redundancy. Now the bars are in their correct sizes.

However, the shorter bars are now hidden behind the longer ones in each stacks. So the draw order of the bars need to be reversed. Alter the datasets as such, performing stack.reverse() for each stack.

var datasets = [
            d3.stack().keys(['LKV', 'SROI', 'NoRisk'])(data).reverse(),
            d3.stack().keys(['LKV1', 'SROI1', 'NoRisk1'])(data).reverse(),
            d3.stack().keys(['LKV2', 'SROI2', 'NoRisk2'])(data).reverse()
        ];
```

That's it. Here's my version.

ContentLicense: CC BY-SA 4.0

Body:
Change the base y of the bars from yscale(d[1]) to yscale(0) like the following:

return bar((xscale(xlabels[i]) + (xscale.bandwidth() / num_groups) * gnum) + 5,
            yscale(0),
            14,
            yscale(d[1]), s);

Now the bars will be upright. But don't be fooled. The stacks that appear on the graph are not correct, and do not reflect the data properly. That is because the h parameter in the bar function is the height of the bar, and d[1] is, in fact, y - h. So the bar function needs to be corrected.

function bar(x, y, w, y1, r, f) {
    // Flag for sweep:
    if (f == undefined) f = 1;
    // x coordinates of top of arcs
    var x0 = x + r;
    var x1 = x + w - r;
    // y coordinates of bottom of arcs
    var y0 = y1 + r;
    // just for convenience (slightly different than above):
    var l = "L", a = "A";

    var parts = ["M", x, y, l, x, y0, a, r, r, 0, 0, f, x0, y1, l, x1, y1, a, r, r, 0, 0, f, x + w, y0, l, x + w, y, "Z"];
    return parts.join(" ");
}

The same effect can be achieved by calling the original bar with yscale(0) - yscale(d[1]), but this will create unnecessary redundancy. Now the bars are in their correct sizes.

However, the shorter bars are now hidden behind the longer ones in each stacks. So the draw order of the bars need to be reversed. Alter the datasets as such, performing stack.reverse() for each stack.

var datasets = [
            d3.stack().keys(['LKV', 'SROI', 'NoRisk'])(data).reverse(),
            d3.stack().keys(['LKV1', 'SROI1', 'NoRisk1'])(data).reverse(),
            d3.stack().keys(['LKV2', 'SROI2', 'NoRisk2'])(data).reverse()
        ];

That's it. Here's my version.


问:
Redirect 403 forbidden error message to 404 in IIS
If we post the URL by appending the text "/../../../../ " at the end. IIS returns a "403 - Forbidden" error in the response header.

Is there any way to configure IIS to return a "404 - Not Found" error instead of a "403"?

This is an asp.net web application.

A security scan of our site noted that returning "403" could assist a malicious person mapping our site; had not thought of that before, but I have to admit it makes sense.

答:
Did you Post a  request like "http://mydomain/../../../../" and receive 403 error?

If so, you could probably notice that its RESPONSE SERVER is Server: Microsoft-HTTPAPI/2.0 instead of Server: Microsoft-IIS/7.5. It means the request get blocked in http.sys level. So I'm afraid we can't do anything in IIS.

We can only rewrite 403 to 404 with URL rewrite when the IIS module return 403 error executed after URL rewrite module.

Edit:

This rule works fine on my side.


问:
On Insert: Arithmetic overflow error converting expression to data type int
I tried creating my third table of phone numbers, I wrote the following commands:

```<code>CREATE TABLE MYPHONE (EMPLOYEE_ID INT, PHONE_NUMBER INT)

INSERT INTO MYPHONE
VALUES (1 , 7894561230)
</code>```

But when I tried executing this previous INSERT command, I got an error:

Msg 8115, Level 16, State 2, Line 46

  Arithmetic overflow error converting expression to data type int.

答:
Allowed range of INT datatype is -2,147,483,648 to 2,147,483,647

You can get more details on the allowed range here

You are trying to insert beyond that range. For phone number better choose VARCHAR data type. If you still want to go for number, in that case use BIGINT instead of INT.

Body:
I tried creating my third table of phone numbers, I wrote the following commands:

CREATE TABLE MYPHONE (EMPLOYEE_ID INT, PHONE_NUMBER INT)

INSERT INTO MYPHONE
VALUES (1 , 7894561230)

But when I tried executing this previous INSERT command, I got an error:

Msg 8115, Level 16, State 2, Line 46

  Arithmetic overflow error converting expression to data type int.


问:
Can't seem to find Opus engine even tough I have installed opusscript / @discordjs/opus
I can't install node-opus because it gives error code.

My code:

```<code>const Discord = require('discord.js');
const client = new Discord.Client();

client.login('my token :)');
client.on('message', message => {
  if (!message.guild) return;
  if (message.content === '/join') {
    if (message.member.voiceChannel) {
      message.member.voiceChannel.join()
      .then(connection => {
        const dispatcher = connection.playFile('./musik/taisonin.mp3');
        dispatcher.resume()
        dispatcher.on("end", end => {message.memver.voiceChannel.leave()});
      });
    } else {
      message.reply('-');
    }
  }
});
</code>```

everything seems to work fine until it tries to start playing my mp3 file. -> " Error: Couldn't find an Opus engine."

Depencies:

```<code>"@discordjs/opus": "^0.1.0",
"discord.js": "github:discordjs/discord.js#master",
"discord.js-commando": "github:discordjs/Commando",
"ffmpeg-static": "^4.0.1",
"opusscript": "0.0.7"
</code>```

答:
Given that they have many overlapping functions, you might be receiving an error for trying to install node-opus on top of opusscript.

to decode and encode the mp3 file you want to play you must install a codec to do that for you:

So try uninstalling opusscript then install npm install discord.js node-opus and you should be fine.

Body:
I can't install node-opus because it gives error code.

My code:

const Discord = require('discord.js');
const client = new Discord.Client();

client.login('my token :)');
client.on('message', message => {
  if (!message.guild) return;
  if (message.content === '/join') {
    if (message.member.voiceChannel) {
      message.member.voiceChannel.join()
      .then(connection => {
        const dispatcher = connection.playFile('./musik/taisonin.mp3');
        dispatcher.resume()
        dispatcher.on("end", end => {message.memver.voiceChannel.leave()});
      });
    } else {
      message.reply('-');
    }
  }
});

everything seems to work fine until it tries to start playing my mp3 file. -> " Error: Couldn't find an Opus engine."

Depencies:

"@discordjs/opus": "^0.1.0",
"discord.js": "github:discordjs/discord.js#master",
"discord.js-commando": "github:discordjs/Commando",
"ffmpeg-static": "^4.0.1",
"opusscript": "0.0.7"


问:
How to dom-repeat slot content
I'm trying create a reusable list that gets it's row template passed in as a slot but the slot content only get repeated once. Example here: https://codepen.io/chris-gunawardena/project/editor/XkPYQw

```<code><script src="https://polygit.org/components/webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import" href="https://polygit.org/components/paper-button/paper-button.html">
<dom-module id="list-repeater">
  <template>
      <template is="dom-repeat" items="{{items}}" as="item">
        <li>
          # [[index]]:  [[item]] <slot name="row-template"></slot>
        </li>
    </template>
  </template>
  <script>
    class ListRepeater extends Polymer.Element {
      static get is() {
        return 'list-repeater';
      }
      static get properties() {
        return {
          items: Array,
        };
      }
    }
    customElements.define(ListRepeater.is, ListRepeater);
  </script>
</dom-module>
</code>```

This gets used like this:

```<code>  <list-repeater items='["a","b"]'>
    <div slot="row-template">--slot content--</div>
  </list-repeater>
</code>```

The functionality is similar to iron-list which takes in a template but having a hard time following what iron-list is doing.

答:
I was also stuck with the same issue and i got one solution for this, you may try this and lemme know if this works for you or not. This approach used a templatizer.

HTML:

```<code><div id="you-component-list"><your-component></you-component><div>
</code>```

JS:

In attached method add this line:

```<code>attached() {
this.templatize(/** @type {!HTMLTemplateElement} **/ (
    this.$.'your-component-list'.querySelector('template')));},

const /** !Array */ flattenedNodes = Polymer.FlattenedNodesObserver.getFlattenedNodes(this); const distributedNodeToAppend = /** !Node */ flattenedNodes.find( (/** !Node */ node) => (node.nodeType === Node.ELEMENT_NODE && node.hasAttribute('slot'))); const clone = this.stamp({item: item}); if (distributedNodeToAppend) { const childNode = distributedNodeToAppend.cloneNode(true); childNode.removeAttribute('slot'); clone.root.querySelector('Your-component').appendChild(childNode); } Polymer.dom(this.$.'you-component-list').appendChild(clone.root);
</code>```

Title: How to dom-repeat slot content

Body:
I'm trying create a reusable list that gets it's row template passed in as a slot but the slot content only get repeated once. Example here: https://codepen.io/chris-gunawardena/project/editor/XkPYQw

<link rel="import" href="https://polygit.org/components/paper-button/paper-button.html">
<dom-module id="list-repeater">
  <template>
      <template is="dom-repeat" items="{{items}}" as="item">

          # [[index]]:  [[item]] <slot name="row-template"></slot>

    </template>
  </template>

</dom-module>

This gets used like this:

  <list-repeater items='["a","b"]'>

--slot content--

  </list-repeater>

The functionality is similar to iron-list which takes in a template but having a hard time following what iron-list is doing.

Body:
I was also stuck with the same issue and i got one solution for this, you may try this and lemme know if this works for you or not. This approach used a templatizer.

HTML:

<div id="you-component-list"><your-component></you-component><div>

JS:

In attached method add this line:

attached() {
this.templatize(/** @type {!HTMLTemplateElement} **/ (
    this.$.'your-component-list'.querySelector('template')));},

const /** !Array */ flattenedNodes = Polymer.FlattenedNodesObserver.getFlattenedNodes(this); const distributedNodeToAppend = /** !Node */ flattenedNodes.find( (/** !Node */ node) => (node.nodeType === Node.ELEMENT_NODE && node.hasAttribute('slot'))); const clone = this.stamp({item: item}); if (distributedNodeToAppend) { const childNode = distributedNodeToAppend.cloneNode(true); childNode.removeAttribute('slot'); clone.root.querySelector('Your-component').appendChild(childNode); } Polymer.dom(this.$.'you-component-list').appendChild(clone.root);


问:
How do I write an eloquent query which joins, merges or unions these 2 queries into 1?
// 2 eloqent collections merged

```<code>$publicCategories = Category::where('menu', '=', 1)
    ->where('display_scope', 1)
    ->orderBy('parent_id')
    ->get();
$privateCategories = Category::where('menu', '=', 1)
    ->whereIn('id', $ids)
    ->orderBy('parent_id')
    ->get();
$categories = $publicCategories->merge($privateCategories);
</code>```

// This query above does these 2 MySQL queries which are duplicated.

The result from this is correct, however, requires 2 queries.

How do I write an eloquent query which joins, merges or unions these 2 queries into 1?

答:
Why you're getting it separately? You can use Orwhere for this.

```<code>$publicprivateCategories = Category::where('menu', '=', 1)
                        ->whereIn('id', $ids)
                        ->orWhere('display_scope', 1)
                        ->orderBy('parent_id')
                        ->get();
</code>```

Update

```<code>$publicprivateCategories = Category::where('menu', '=', 1)
                        ->where(function($q) use($ids){
                             $q->whereIn('id', $ids)->orWhere('display_scope', 1);
                        })
                        ->where('id', '!=', 2)
                        ->orderBy('parent_id')
                        ->get();
</code>```

By this, you'll get both(Public or private) categories.

Body:
// 2 eloqent collections merged

$publicCategories = Category::where('menu', '=', 1)
    ->where('display_scope', 1)
    ->orderBy('parent_id')
    ->get();
$privateCategories = Category::where('menu', '=', 1)
    ->whereIn('id', $ids)
    ->orderBy('parent_id')
    ->get();
$categories = $publicCategories->merge($privateCategories);

// This query above does these 2 MySQL queries which are duplicated.

The result from this is correct, however, requires 2 queries.

How do I write an eloquent query which joins, merges or unions these 2 queries into 1?

Body:
Why you're getting it separately? You can use Orwhere for this.

$publicprivateCategories = Category::where('menu', '=', 1)
                        ->whereIn('id', $ids)
                        ->orWhere('display_scope', 1)
                        ->orderBy('parent_id')
                        ->get();

Update

$publicprivateCategories = Category::where('menu', '=', 1)
                        ->where(function($q) use($ids){
                             $q->whereIn('id', $ids)->orWhere('display_scope', 1);
                        })
                        ->where('id', '!=', 2)
                        ->orderBy('parent_id')
                        ->get();

By this, you'll get both(Public or private) categories.


问:
Android: Activity that displays a map image with zoom and drag?
I need to display an image(a map), and allow users to drag and zoom(two finger pinch, or is multitouch control not support on some earlier versions?), also, when user clicks on an area on the map, information of that area is displayed. I wonder is there any standard way(such like imageview wrapped in an activity) of doing this, or do I have to create an activity that has imageview in it? I searched and read some of others questions/answers, found that WebView is a good way to display image, but I need to do some operations on the image(map) like I said, is it possible for WebView?

Thanks!

edit:
Is there anyway to do this, apart from femi's answer? Also, the 3rd party package in femi's answer has a bug report that pinch image view does not zoom, so it is actually no an answer.

答: Try looking at http://code.google.com/p/android-pinch/ for ImageViews that offer some of what you need. Let me know if that works for you.</p>

ContentLicense: CC BY-SA 3.0


问:
Python Input Function duplicating
Is there a reason why my input is being asked twice? I need to use three separate functions to calculate the formula using user input.</p>

```<code>def values():
    initInv=input("Enter initial investment ")
    rate=input("Enter the interest rate in the form of a decimal ")
    freq=input("Enter the frequency that the interest is paid out per year ")
    years=input("Enter the number of years the interest is compounded for ")
    return initInv, rate, freq, years

w, x, y, z=values()

def typecast():
    invest=int(w)
    RATE=float(x)
    FREQ=int(y)
    time=int(z)
    return invest, RATE, FREQ, time

first, second, third, fourth=typecast()

def formula():
    P=first
    r=second
    n=third
    t=fourth
    A=(P*(1+(r/n))**(n*t))
    return A

values()
typecast()
formula()
</code>```

答:
You call values twice. Once after defining it: w, x, y, z=values() Then again at the end: values()

Edit: the same with typecast. You call it twice too.

Here's the code with duplicates removed.

def values():
    initInv=input("Enter initial investment ")
    rate=input("Enter the interest rate in the form of a decimal ")
    freq=input("Enter the frequency that the interest is paid out per year ")
    years=input("Enter the number of years the interest is compounded for ")
    return initInv, rate, freq, years

def typecast():
    invest=int(w)
    RATE=float(x)
    FREQ=int(y)
    time=int(z)
    return invest, RATE, FREQ, time

def formula():
    P=first
    r=second
    n=third
    t=fourth
    A=(P*(1+(r/n))**(n*t))
    return A

w, x, y, z=values()
first, second, third, fourth=typecast()
A = formula()
```

Title: Python Input Function duplicating

Body:
Is there a reason why my input is being asked twice? I need to use three separate functions to calculate the formula using user input.

def values():
    initInv=input("Enter initial investment ")
    rate=input("Enter the interest rate in the form of a decimal ")
    freq=input("Enter the frequency that the interest is paid out per year ")
    years=input("Enter the number of years the interest is compounded for ")
    return initInv, rate, freq, years

w, x, y, z=values()

def typecast():
    invest=int(w)
    RATE=float(x)
    FREQ=int(y)
    time=int(z)
    return invest, RATE, FREQ, time

first, second, third, fourth=typecast()

def formula():
    P=first
    r=second
    n=third
    t=fourth
    A=(P*(1+(r/n))**(n*t))
    return A

values()
typecast()
formula()


问:
Suppress Error Message Box when file not available
I have a code that open another workbook based on today date. I plan to use task scheduler to auto run but in the case of the external workbook not found, I want my workbook to auto close so it wouldnt stuck there opened. But i encounter error message `Sorry we couldn't open 'D:\Users......."'. Anyway to suppress this error message?</p>

```<code>Sub DataGrab()
    On Error GoTo ErrorHandler

    Dim extwbk As Workbook, twb As Workbook

    Set twb = ThisWorkbook
    Set extwbk = Workbooks.Open("D:\Users\Desktop\Report " & Format(Now, "DD-MMM-YYYY") & ".xls*", UpdateLinks:=0)
    '
    'my code
    '
    Exit Sub

ErrorHandler:
    Application.DisplayAlerts = False
    Application.Quit
    Application.DisplayAlerts = True

End Sub
</code>```

答:
You have to first check if the workbook extwbk exists

you can do so with fso.fileexists function

if the file does not exists you can go to errorhandler

please check this image with references I used.

Body:
I have a code that open another workbook based on today date. I plan to use task scheduler to auto run but in the case of the external workbook not found, I want my workbook to auto close so it wouldnt stuck there opened. But i encounter error message `Sorry we couldn't open 'D:\Users......."'. Anyway to suppress this error message?

Sub DataGrab()
    On Error GoTo ErrorHandler

    Dim extwbk As Workbook, twb As Workbook

    Set twb = ThisWorkbook
    Set extwbk = Workbooks.Open("D:\Users\Desktop\Report " & Format(Now, "DD-MMM-YYYY") & ".xls*", UpdateLinks:=0)
    '
    'my code
    '
    Exit Sub

ErrorHandler:
    Application.DisplayAlerts = False
    Application.Quit
    Application.DisplayAlerts = True

End Sub


问:
append string to each element in string array in typescript
How can I append a string to each element from a string array in typescript
I have an array like const original = ['a', 'b', 'c'] I want to make it as const original_string = ['i am key a', 'i am key b', 'i am key c'] how can I do that? maybe something like const original_string = original.map(() => ${'i am key'})?
I have following but it does not work

```<code>const original_string = original.forEach((item)=> (`i am key ${item}`));
</code>```

答:
You can use map function to create a new array out of existing array, in this case you want to create original_string out of original array.

For eg. You can do this.

```<code>const original = ['a', 'b', 'c'];
const original_string: string[] = original.map((key: string) => {
   return `I'm key ${key}`;
});

console.log(original_string);
</code>```

Body:
How can I append a string to each element from a string array in typescript
I have an array like const original = ['a', 'b', 'c'] I want to make it as const original_string = ['i am key a', 'i am key b', 'i am key c'] how can I do that? maybe something like const original_string = original.map(() => ${'i am key'})?
I have following but it does not work

const original_string = original.forEach((item)=> (`i am key ${item}`));

Body:
You can use map function to create a new array out of existing array, in this case you want to create original_string out of original array.

For eg. You can do this.

const original = ['a', 'b', 'c'];
const original_string: string[] = original.map((key: string) => {
   return `I'm key ${key}`;
});

console.log(original_string);


问:
CSS error source-map information is not available at URL() declaration (found orphan CR, try removeCR option)
I am having a problem when I execute NPM start in my project.
I get this error message:

```<code>./src/assets/base.scss (./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-5-1!./node_modules/postcss-loader/src??postcss!./node_modules/react-scripts/node_modules/resolve-url-loader??ref--6-oneOf-5-3!./node_modules/sass-loader/dist/cjs.js??ref--6-oneOf-5-4!./src/assets/base.scss)
Error: resolve-url-loader: CSS error
  source-map information is not available at url() declaration (found orphan CR, try removeCR option)
</code>```

答: Open the file *.css and select end of line sequense to LF (in my case I have change from CRLF to LF) in IDE.</p>

Body:
I am having a problem when I execute NPM start in my project.
I get this error message:

./src/assets/base.scss (./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-5-1!./node_modules/postcss-loader/src??postcss!./node_modules/react-scripts/node_modules/resolve-url-loader??ref--6-oneOf-5-3!./node_modules/sass-loader/dist/cjs.js??ref--6-oneOf-5-4!./src/assets/base.scss)
Error: resolve-url-loader: CSS error
  source-map information is not available at url() declaration (found orphan CR, try removeCR option)


答:
An int probably isn't the best data type for a phone number - you don't need to do any arithmetic on phone numbers, so why use a numerical data type? Store it as a string (or varchar in SQL).

Also, if you did need to store a value as an int, 2,147,483,647 is the maximum - anything higher would "overflow", hence the error you're getting. A long (or bigint in SQL) would allow values up to 9,223,372,036,854,775,808.

Title: On Insert: Arithmetic overflow error converting expression to data type int


问:
Unix/C command line arguments: Every single function has the same error what am I doing wrong?
I am supposed to take in arguments from the command line, to build a sample Unix-style 'ls' style program that lists the directory contents.

I have pre-built functions given to me and I have to separate the code down into modularized header and c files for each individual function and create a makefile.

The makefile will run and gives these warnings:

```<code>-bash-3.2$ make run
gcc -c main.c
main.c: In function ‘main’:
main.c:18: warning: passing argument 1 of ‘do_ls’ from incompatible pointer type
</code>```

Here is do_ls.h:

'''

```<code>#ifndef DO_LS
#define DO_LS
                void do_ls( char*[] );

#endif
</code>```

'''

Errors:

```<code>-bash-3.2$ gcc main.c
main.c: In function ‘main’:
main.c:18: warning: passing argument 1 of ‘do_ls’ from incompatible pointer type
main.c:23: warning: passing argument 1 of ‘do_ls’ from incompatible pointer type
/tmp/cc8Q7153.o: In function `main':
main.c:(.text+0x1b): undefined reference to `do_ls'
main.c:(.text+0x47): undefined reference to `do_ls'
collect2: ld returned 1 exit status
</code>```

main:

```<code>#include        <stdio.h>
#include        <sys/types.h>
#include        <dirent.h>
#include        "do_ls.h"

    int main(int ac, char *av[])
    {
     if ( ac == 1 )
            do_ls(".");

     else
            while ( --ac ){
                    printf("%s:\n", *++av );
                    do_ls( *av );
            }
    }
</code>```

答:
The do_ls function expects an array of char *, but when you call it you only pass in a single char *.  This is what the warning in the initial call to make is complaining about.  This argument mismatch invokes undefined behavior.

Try calling it like this:

```<code>if ( ac == 1 ) {
    char *args[] = { ".", NULL };
    do_ls(args);
} else {
    do_ls(av+1);
}
</code>```

Body:
I am supposed to take in arguments from the command line, to build a sample Unix-style 'ls' style program that lists the directory contents.

I have pre-built functions given to me and I have to separate the code down into modularized header and c files for each individual function and create a makefile.

The makefile will run and gives these warnings:

-bash-3.2$ make run
gcc -c main.c
main.c: In function ‘main’:
main.c:18: warning: passing argument 1 of ‘do_ls’ from incompatible pointer type

Here is do_ls.h:

'''

#ifndef DO_LS
#define DO_LS
                void do_ls( char*[] );

#endif

'''

Errors:

-bash-3.2$ gcc main.c
main.c: In function ‘main’:
main.c:18: warning: passing argument 1 of ‘do_ls’ from incompatible pointer type
main.c:23: warning: passing argument 1 of ‘do_ls’ from incompatible pointer type
/tmp/cc8Q7153.o: In function `main':
main.c:(.text+0x1b): undefined reference to `do_ls'
main.c:(.text+0x47): undefined reference to `do_ls'
collect2: ld returned 1 exit status

main:

#include        <stdio.h>
#include        <sys/types.h>
#include        <dirent.h>
#include        "do_ls.h"

    int main(int ac, char *av[])
    {
     if ( ac == 1 )
            do_ls(".");

     else
            while ( --ac ){
                    printf("%s:\n", *++av );
                    do_ls( *av );
            }
    }

Body:
The do_ls function expects an array of char *, but when you call it you only pass in a single char *.  This is what the warning in the initial call to make is complaining about.  This argument mismatch invokes undefined behavior.

Try calling it like this:

if ( ac == 1 ) {
    char *args[] = { ".", NULL };
    do_ls(args);
} else {
    do_ls(av+1);
}


答:
const original = ['a', 'b', 'c'];
const original_string = original.map(item => `i am key ${item}`)
console.log({original, original_string});```

You want to use map which will put the value in the array for you.

Title: append string to each element in string array in typescript

Body:
const original = ['a', 'b', 'c'];
const original_string = original.map(item => `i am key ${item}`)
console.log({original, original_string});

You want to use map which will put the value in the array for you.


问:
Pass express server instance to other node files
I have a project set up where in my bin/www file I have my node server set up with the following line which works:

const server = http.createServer(app);

I am working on setting up socket.io so I would like to make another file called socket.js and in there do all the socket.io set up but I need to be able to get access to my server variable. I tried to export my server variable like this:

module.exports = server;

and then use it in my new file like this:

```<code>const server = require("./bin/www");
const io = require('socket.io')(server); //server doesn't seem to be working here

io.on("connection", socket => {
    socket.on('sendMessage', data => {
        socket.join(socket.id, () => {
            console.log('Joined group');
            io.sockets.in(socket.id).emit('sendMessage', data)
        });
    });
});
</code>```

But it doesn't look like this is setting up the socket on the server as I am getting the following error:

GET /socket.io/?EIO=3&transport=polling&t=N1HOkXK which happens when it isn't set up correctly.

答:
Instead of exports your server you can send server reference from bin/www to start your socket server.

Your bin/www

```<code>const express = require('express');
const socket = require('./socket');
const app = express();

const server = https.createServer(app);

sockets.startSocketServer(server);
</code>```

Your socket.js file

```<code>const socketio = require('socket.io');
var io;

module.exports = {
    startSocketServer: function (server) {
        io = socketio.listen(server);
        io.sockets.on('connection', function (socket) {
            socket.on('sendMessage', data => {
                socket.join(socket.id, () => {
                    console.log('Joined group');
                    io.sockets.in(socket.id).emit('sendMessage', data)
                });
            });
        })
    }
}
</code>```

Body:
I have a project set up where in my bin/www file I have my node server set up with the following line which works:

const server = http.createServer(app);

I am working on setting up socket.io so I would like to make another file called socket.js and in there do all the socket.io set up but I need to be able to get access to my server variable. I tried to export my server variable like this:

module.exports = server;

and then use it in my new file like this:

const server = require("./bin/www");
const io = require('socket.io')(server); //server doesn't seem to be working here

io.on("connection", socket => {
    socket.on('sendMessage', data => {
        socket.join(socket.id, () => {
            console.log('Joined group');
            io.sockets.in(socket.id).emit('sendMessage', data)
        });
    });
});

But it doesn't look like this is setting up the socket on the server as I am getting the following error:

GET /socket.io/?EIO=3&transport=polling&t=N1HOkXK which happens when it isn't set up correctly.

Body:
Instead of exports your server you can send server reference from bin/www to start your socket server.

Your bin/www

const express = require('express');
const socket = require('./socket');
const app = express();

const server = https.createServer(app);

sockets.startSocketServer(server);

Your socket.js file

const socketio = require('socket.io');
var io;

module.exports = {
    startSocketServer: function (server) {
        io = socketio.listen(server);
        io.sockets.on('connection', function (socket) {
            socket.on('sendMessage', data => {
                socket.join(socket.id, () => {
                    console.log('Joined group');
                    io.sockets.in(socket.id).emit('sendMessage', data)
                });
            });
        })
    }
}


问:
How do I show an uploaded image in Jquery?
```<code><html>
<head><script src = "/jquery.js"></script></head>

Test Image Upload
    <input type = "file" id = "chooseimage" name = "chooseimage" accept = ".jpg, .jpeg, .png" multiple><br>
    <input type = "button" id = "submitimages" value = "Send Image">
    <br>
<div id = "test"></div>

<script>
    $("#submitimages").click(function(){
        var imageinput = $("#chooseimage")[0].files[0];
        var reader = new FileReader();
        var a = reader.readAsDataURL(imageinput);
        reader.onload = function(e)(){};  // what do i do with this?
        $("#test").html(a);
    });
</script>
</html>
</code>```

For the Jquery, let me quickly run down my thought process.

1) I get the input id "chooseimage" and grab the files using .files command. I assume .files[0] means to select the first file from the HTML element (but it only selects it, not actually reading it)?

2) create a new FileReader(). I'm not quite sure what this does, I think it allows me to... read the file?

3) But to first read the file using FileReader, we need to convert the file to a base64 encoded string, so we use readAsDataURL to convert.

4) And then I do somrthing with reader.onload(), but I am not sure what this does. I was reading other tutorials on this and they all had it but no explanation what it does. I read the Mozilla Documentation but didn.t quite understand it. I've done nothing with it so far.

5) I want to show the base64 string in the div element with id "test". I think the browser will automatically interpret the string into an image. Either way, it's not showing anything.

Can someone walk me through what I do or do not understand correctly and what I'm doing wrong?

答:
Check this out, and let me know how it goes. :)

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      $('#imageShow').attr('src', e.target.result);
    }

    reader.readAsDataURL(input.files[0]);
  }
}

$("#imgPreview").change(function() {
  readURL(this);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form runat="server">
  <input type='file' id="imgPreview" />
  <img id="imageShow" src="#" alt="your image" />
</form></code>```

Body:
Test Image Upload
    <input type = "file" id = "chooseimage" name = "chooseimage" accept = ".jpg, .jpeg, .png" multiple>

    <input type = "button" id = "submitimages" value = "Send Image">

For the Jquery, let me quickly run down my thought process.

1) I get the input id "chooseimage" and grab the files using .files command. I assume .files[0] means to select the first file from the HTML element (but it only selects it, not actually reading it)?

2) create a new FileReader(). I'm not quite sure what this does, I think it allows me to... read the file?

3) But to first read the file using FileReader, we need to convert the file to a base64 encoded string, so we use readAsDataURL to convert.

4) And then I do somrthing with reader.onload(), but I am not sure what this does. I was reading other tutorials on this and they all had it but no explanation what it does. I read the Mozilla Documentation but didn.t quite understand it. I've done nothing with it so far.

5) I want to show the base64 string in the div element with id "test". I think the browser will automatically interpret the string into an image. Either way, it's not showing anything.

Can someone walk me through what I do or do not understand correctly and what I'm doing wrong?

Body:
Check this out, and let me know how it goes. :)

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      $('#imageShow').attr('src', e.target.result);
    }

    reader.readAsDataURL(input.files[0]);
  }
}

$("#imgPreview").change(function() {
  readURL(this);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form runat="server">
  <input type='file' id="imgPreview" />
  <img id="imageShow" src="#" alt="your image" />
</form>


问:
How to print and display all results of web scraper?
```<code>import requests
from bs4 import BeautifulSoup

URL = ""
page = requests.get(URL)

soup = BeautifulSoup(page.content, 'html.parser')
results = soup.find(id='simple-view')

events_elems = results.find_all('ul', class_='searchResults')

for event_elem in events_elems:

    date_elem = event_elem.find('li', class_='date-indicator')
    location_elem = event_elem.find('div', class_='text--labelSecondary')
    e_elem = event_elem.find('a', class_='event')
    if None in (date_elem,location_elem, e_elem):
        continue
    print(date_elem.text)
    print(location_elem.text)
    print(e_elem.text)
</code>```

I just start to play with python web scraping function, trying to scrape on meetup.com with the above code, but only one set of results are shown, is there something wrong I did in the iteration section?

答:
The .find_all you used in

events_elems = results.find_all('ul', class_='searchResults')
```

<p>did not capture each individual rows from the website, i.e., you need to tighten the search criteria.</p>

<p>The <code>event_elem.find('li', class_='date-indicator')</code> you used are also insufficient, as it did not capture each individual event's date.</p>

<hr>

<p>See the following working code, which capture the set of results by event-listing's container:</p>

<pre class="lang-py prettyprint-override"><code>import requests
from bs4 import BeautifulSoup

URL = "https://www.meetup.com/find/events/"
page = requests.get(URL)

soup = BeautifulSoup(page.content, 'html.parser')
results = soup.find(id='simple-view')

event_container = results.find_all('ul', class_='event-listing-container')[0]
events_elems = event_container.find_all(class_= 'event-listing')

for event_elem in events_elems:

    location_elem = event_elem.find('div', class_='text--labelSecondary')
    e_elem = event_elem.find('a', class_='event')
    date = "{}-{}-{} {}".format(
        event_elem.attrs['data-year'],
        event_elem.attrs['data-month'],
        event_elem.attrs['data-day'],
        event_elem.find('time').text.replace('\n', ''),
    )

    print(date)
    print(location_elem.text)
    print(e_elem.text)
    print('-----')
</code>```

with sample output of

2020-2-17 9:00AM

Architecting for Innovation

Australasian Enterprise Architecture Summer School 2020

-----
2020-2-17 5:00PM

Sydney Indoor Rock Climbers

Monday and Thursday Night Climbing @ St Peters (Beginners Welcome)

-----
2020-2-17 5:30PM

......
......

```

Body:
import requests
from bs4 import BeautifulSoup

URL = ""
page = requests.get(URL)

soup = BeautifulSoup(page.content, 'html.parser')
results = soup.find(id='simple-view')

events_elems = results.find_all('ul', class_='searchResults')

for event_elem in events_elems:

    date_elem = event_elem.find('li', class_='date-indicator')
    location_elem = event_elem.find('div', class_='text--labelSecondary')
    e_elem = event_elem.find('a', class_='event')
    if None in (date_elem,location_elem, e_elem):
        continue
    print(date_elem.text)
    print(location_elem.text)
    print(e_elem.text)

I just start to play with python web scraping function, trying to scrape on meetup.com with the above code, but only one set of results are shown, is there something wrong I did in the iteration section?

Body:
The .find_all you used in

events_elems = results.find_all('ul', class_='searchResults')

did not capture each individual rows from the website, i.e., you need to tighten the search criteria.

The event_elem.find('li', class_='date-indicator') you used are also insufficient, as it did not capture each individual event's date.

See the following working code, which capture the set of results by event-listing's container:

import requests
from bs4 import BeautifulSoup

URL = "https://www.meetup.com/find/events/"
page = requests.get(URL)

soup = BeautifulSoup(page.content, 'html.parser')
results = soup.find(id='simple-view')

event_container = results.find_all('ul', class_='event-listing-container')[0]
events_elems = event_container.find_all(class_= 'event-listing')

for event_elem in events_elems:

    location_elem = event_elem.find('div', class_='text--labelSecondary')
    e_elem = event_elem.find('a', class_='event')
    date = "{}-{}-{} {}".format(
        event_elem.attrs['data-year'],
        event_elem.attrs['data-month'],
        event_elem.attrs['data-day'],
        event_elem.find('time').text.replace('\n', ''),
    )

    print(date)
    print(location_elem.text)
    print(e_elem.text)
    print('-----')

with sample output of

2020-2-17 9:00AM

Architecting for Innovation

Australasian Enterprise Architecture Summer School 2020

-----
2020-2-17 5:00PM

Sydney Indoor Rock Climbers

Monday and Thursday Night Climbing @ St Peters (Beginners Welcome)

-----
2020-2-17 5:30PM

......
......


问:
Using a Method to update a 2D Array by finding a matching value and then updating with a different input variable
Lets say I have a public class called GameBoard that will be a two dimensional array with 4 rows and 5 columns.  The spaces in the array are filed with String values from 1 to 20.  A card will be drawn that has a name (King of Spades for example) . If the user inputs 15 I will store it in a String variable called userLocation. What would be the most efficient way to create a method that takes the input location and updates the array with the name of the Card?  Would a for loop be most efficient?

```<code>public GameBoard() {
    square  = new String[4][5];
    square[0][0] = new String("1");
    square[0][1] = new String("2");
    square[0][2] = new String("3");
    square[0][3] = new String("4");
    square[0][4] = new String("5");
    square[1][0] = new String("6");
    square[1][1] = new String("7");
    square[1][2] = new String("8");
    square[1][3] = new String("9");
    square[1][4] = new String("10");
    square[2][1] = new String("11");
    square[2][2] = new String("12");
    square[2][3] = new String("13");
    square[3][1] = new String("14");
    square[3][2] = new String("15");
    square[3][3] = new String("16");
    square[2][0] = new String(17);
    square[3][0] = new String(18);
    square[2][4] = new String(19);
    square[3][4] = new String(20);

}
</code>```

My preferred method as of now would look something like this but it gives me the error code "type mismatch:cannot convert string to boolean" under userLocation = board[i][j]

```<code>public String[][] updateBoard(String userLocation, Card card, String[][] board) {

    for (int i = 0; i <4; i++)
        {
           for (int j = 0; j < 5; j++)
           {
             if(userLocation = board[i][j]) {

                 board[i][j] = card.name;

             }
           }
        }

    return board;

}
</code>```

答:
So the reason it will not compile is your = does not return a boolean expression. == would, but it's still not what you want, since you want to check if the String contents are the same, not if they're the same object, so use .equals.

But, no, I think you don't want to depend on strings to identify locations. What if you want to replace a card? And why look through everything when you need not?

Rather if i is some number between 1 and 20, identify the corresponding spot in the array by square[(i-1)/5][(i-1)%5]

That should bypass the issue you are having with matching strings.

So for example, your constructor becomes:

```<code>public GameBoard() {
square  = new String[4][5];
for (int i=1; i<=20;i++){
    square[(i-1)/5][(i-1)%5]=""+i;//initialize with 1 to 20 if you like
}
</code>```

and userLocation is an int.

Body:
Lets say I have a public class called GameBoard that will be a two dimensional array with 4 rows and 5 columns.  The spaces in the array are filed with String values from 1 to 20.  A card will be drawn that has a name (King of Spades for example) . If the user inputs 15 I will store it in a String variable called userLocation. What would be the most efficient way to create a method that takes the input location and updates the array with the name of the Card?  Would a for loop be most efficient?

public GameBoard() {
    square  = new String[4][5];
    square[0][0] = new String("1");
    square[0][1] = new String("2");
    square[0][2] = new String("3");
    square[0][3] = new String("4");
    square[0][4] = new String("5");
    square[1][0] = new String("6");
    square[1][1] = new String("7");
    square[1][2] = new String("8");
    square[1][3] = new String("9");
    square[1][4] = new String("10");
    square[2][1] = new String("11");
    square[2][2] = new String("12");
    square[2][3] = new String("13");
    square[3][1] = new String("14");
    square[3][2] = new String("15");
    square[3][3] = new String("16");
    square[2][0] = new String(17);
    square[3][0] = new String(18);
    square[2][4] = new String(19);
    square[3][4] = new String(20);

}

My preferred method as of now would look something like this but it gives me the error code "type mismatch:cannot convert string to boolean" under userLocation = board[i][j]

public String[][] updateBoard(String userLocation, Card card, String[][] board) {

    for (int i = 0; i <4; i++)
        {
           for (int j = 0; j < 5; j++)
           {
             if(userLocation = board[i][j]) {

                 board[i][j] = card.name;

             }
           }
        }

    return board;

}

Body:
So the reason it will not compile is your = does not return a boolean expression. == would, but it's still not what you want, since you want to check if the String contents are the same, not if they're the same object, so use .equals.

But, no, I think you don't want to depend on strings to identify locations. What if you want to replace a card? And why look through everything when you need not?

Rather if i is some number between 1 and 20, identify the corresponding spot in the array by square[(i-1)/5][(i-1)%5]

That should bypass the issue you are having with matching strings.

So for example, your constructor becomes:

public GameBoard() {
square  = new String[4][5];
for (int i=1; i<=20;i++){
    square[(i-1)/5][(i-1)%5]=""+i;//initialize with 1 to 20 if you like
}

and userLocation is an int.


答:
You'll need regular expressions to extract the betas and the Cs. Then use bquote with variables .() to plot them. This is similar to expression() but more flexible. And the mtext can go outside the loop.

```<code>op <- par(mfrow=c(2,3))
for(b in loop.vector) {
  x.beta <- keep.beta[,b]
  beta <- substr(sub("^beta_", '', names(keep.beta)[b]),1,2)
  Cn <- sub("^\\S+\\s+", '', names(keep.beta)[b] )
  plot(x.beta, type = "l", main=bquote(beta[.(beta)]~.(Cn)), ylab="")
}
mtext("beta plot",line=-1.5, cex=1.5, outer = TRUE)
par(op)
</code>```

Data:

```<code>keep.beta <- data.frame(1:5, 2:6, 3:7, 4:8, 5:9, 6:10)
names(keep.beta) <- c("beta_0 C1","beta_1 C1","beta_2 C1",
                      "beta_0 C2","beta_1 C2","beta_2 C2")
</code>```

Title: How to add the math expression title in multiple plots according to the column name of data set in R?

Body:
keep.beta
  beta_0 C1   beta_1 C1     beta_2 C1 beta_0 C2 beta_1 C2    beta_2 C2 beta_0 C3  beta_1 C3    beta_2 C3
1  6.118431  0.14186598 -8.898830e-04  6.022789 0.2284664 -0.008715484  6.362422  0.1623198 -0.007603638
2  6.063539  0.13401758  5.027927e-06  5.986915 0.2469357 -0.009225261  6.150559  0.2002901 -0.007515155
3  6.193407  0.05483201  6.126576e-03  5.841100 0.3347416 -0.016506298  7.146271 -0.3979893  0.041127363
4  6.078092  0.05110730  6.354140e-03  5.562972 0.4690519 -0.027162758  8.179671 -1.0250484  0.089065099
5  6.256228 -0.09785900  1.856215e-02  5.644385 0.4701571 -0.027528102  8.394842 -1.2646359  0.106934875
  beta_0 C4   beta_1 C4    beta_2 C4
1  6.097189  0.16624813 -0.004341827
2  6.164902  0.09360776  0.002282821
3  6.211754  0.03602315  0.007230330
4  6.505551 -0.10780312  0.016602683
5  6.692843 -0.24754950  0.028275593

To plot each column separately, I am using the following loop,

loop.vector=1:ncol(keep.beta)
  #plot for betas
  for(b in loop.vector) {
    x.beta<-keep.beta[,b]
    plot(x.beta, type = "l", main=colnames(keep.beta)[b], ylab="")
    mtext("beta plot",line=-1.5, cex=1.5, outer = TRUE)
    }

All the title comes as beta_0 C1 , beta_1 C1 and so on. How can I replace all the betas in the title by math notation beta?

Body:
You'll need regular expressions to extract the betas and the Cs. Then use bquote with variables .() to plot them. This is similar to expression() but more flexible. And the mtext can go outside the loop.

op <- par(mfrow=c(2,3))
for(b in loop.vector) {
  x.beta <- keep.beta[,b]
  beta <- substr(sub("^beta_", '', names(keep.beta)[b]),1,2)
  Cn <- sub("^\\S+\\s+", '', names(keep.beta)[b] )
  plot(x.beta, type = "l", main=bquote(beta[.(beta)]~.(Cn)), ylab="")
}
mtext("beta plot",line=-1.5, cex=1.5, outer = TRUE)
par(op)

Data:

keep.beta <- data.frame(1:5, 2:6, 3:7, 4:8, 5:9, 6:10)
names(keep.beta) <- c("beta_0 C1","beta_1 C1","beta_2 C1",
                      "beta_0 C2","beta_1 C2","beta_2 C2")


问:
RMI (JDK 1.6): ClassNotFoundException for <server>_Stub in client-app
After 2 days of googling, stackoverflow-ing and looking for answers in other forums, I finally gave up and hope to find an answer here!

I have an annoying problem in getting a simple RMI client-server application to run although it seems (or maybe I'm simply missing a tiny bit) to be a well-known issue with RMI.

I'm using Eclipse and m2eclipse (Maven integration) for dependency management. My project structure is as follows:
 - client: the client code, dependency to shared
 - server: server code, dependency to shared
 - shared: remote interfaces and shared classes between server and client
 - integrationtest: test project, having both dependencies on client and server

Shared:

The remote interface clients can call is:

```<code>public interface IServerReceiver extends Remote, Serializable {
  void connect(long clientId) throws RemoteException;
}
</code>```

This interface is in the shared project where both client and server have dependencies on so it is in the client's classpath.

Server-side:

The Server class is responsible for creating a registry and exporting the remote object (ServerReceiver implements IServerReceiver):

```<code>registry = LocateRegistry.createRegistry(rmiRegistryPort);
serverReceiver = new ServerReceiver(rmiRegistryPort);

registry.rebind(IConstants.RMI_SERVER_RECEIVER_ID, UnicastRemoteObject.exportObject(serverReceiver, 0));
</code>```

When starting the server, a security policy file is provided to the server's JVM by defining -Djava.security.policy (although I don't think that this has to do with the issue described here).

Client-side

The class responsible for connecting the client to the server is the ServerConnector class:

```<code>...
public ServerConnector() {
 ...
 registry = LocateRegistry.getRegistry(serverRMIHost, serverRMIPort);
 serverReceiver = (IServerReceiver) registry.lookup(IConstants.RMI_SERVER_RECEIVER_ID);
 serverReceiver.connect(client.getId());
 ...
}
</code>```

The Client class' constructor looks like this (some lines omitted):

```<code>public Client(..) {
 ....
 serverConnector = new ServerConnector(serverRMIHost, serverRMIPort, this);
 ....
}
</code>```

As well as the server, the client also gets a security policy file.

Testing

When I fire up an integration test creating a server and then a client: all works fine as expected and the connect()-method returns the expected result.

However, when I try to normally start a Server instance, then starting the client instance which tries to connect() to the server, the following exception gets throws:

```<code>Caused by: java.rmi.UnmarshalException: error unmarshalling return; nested exception is:
java.lang.ClassNotFoundException: assign2.comm.ServerReceiver_Stub
at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
at assign2.comm.ServerConnector.<init>(ServerConnector.java:65)
</code>```

While looking for answers, the most prominent was: the client must have access to the servers interface definition (IServerReceiver). However, to me it seems like that's the case here as proper dependencies are in place (client->shared, server->shared, IServerReceiver place in shared).
Another aspect of the exception I don't quite understand is: since JDK 1.5, stub generation through rmic is no longer necessary and is achieved through dynamic proxyies. The client therefore only needs access to the interface IServerReceiver in order to create the dynamic proxy. Why would he be complaining about not finding the ServerReceiver_Stub class at all then?

Since the integration test runs successfully and within that test the client also has access to the implementation of the IServerReceiver interface, am I right in assuming that the client needs not only access to the remote interface but also it's implementation?

I'm pretty confused by now so maybe you can help me shed some light on this matter? Thanks for having read that long post! ;-)

Cheers,
Chris

答:
I agree, you don't need a stub, as you are providing a port number when exporting the object. The only explanation is that a generated stub got bound instead of a dynamic stub. I would delete any stub files that exist and re-test. If the server needs a stub and doesn't have one it should fail at export time, not when someone looks it up.

Am I right in assuming that the client
  needs not only access to the remote
  interface but also its
  implementation?

No. It only needs the stub. The implementation is remote. That's the whole idea. But it also needs whatever classes the stub depends on, i.e. the remote interface and any classes it depends on, and so on until closure.

I have some further questions:

Why is the registry port being provided to the new ServerReceiver(rmiRegistryPort)?

I assume ServerReceiver doesn't extend UnicastRemoteObject?

Are you sure this is the real server code that is executing?

Body:
After 2 days of googling, stackoverflow-ing and looking for answers in other forums, I finally gave up and hope to find an answer here!

I have an annoying problem in getting a simple RMI client-server application to run although it seems (or maybe I'm simply missing a tiny bit) to be a well-known issue with RMI.

I'm using Eclipse and m2eclipse (Maven integration) for dependency management. My project structure is as follows:
 - client: the client code, dependency to shared
 - server: server code, dependency to shared
 - shared: remote interfaces and shared classes between server and client
 - integrationtest: test project, having both dependencies on client and server

Shared:

The remote interface clients can call is:

public interface IServerReceiver extends Remote, Serializable {
  void connect(long clientId) throws RemoteException;
}

This interface is in the shared project where both client and server have dependencies on so it is in the client's classpath.

Server-side:

The Server class is responsible for creating a registry and exporting the remote object (ServerReceiver implements IServerReceiver):

registry = LocateRegistry.createRegistry(rmiRegistryPort);
serverReceiver = new ServerReceiver(rmiRegistryPort);

registry.rebind(IConstants.RMI_SERVER_RECEIVER_ID, UnicastRemoteObject.exportObject(serverReceiver, 0));

When starting the server, a security policy file is provided to the server's JVM by defining -Djava.security.policy (although I don't think that this has to do with the issue described here).

Client-side

The class responsible for connecting the client to the server is the ServerConnector class:

...
public ServerConnector() {
 ...
 registry = LocateRegistry.getRegistry(serverRMIHost, serverRMIPort);
 serverReceiver = (IServerReceiver) registry.lookup(IConstants.RMI_SERVER_RECEIVER_ID);
 serverReceiver.connect(client.getId());
 ...
}

The Client class' constructor looks like this (some lines omitted):

public Client(..) {
 ....
 serverConnector = new ServerConnector(serverRMIHost, serverRMIPort, this);
 ....
}

As well as the server, the client also gets a security policy file.

Testing

When I fire up an integration test creating a server and then a client: all works fine as expected and the connect()-method returns the expected result.

However, when I try to normally start a Server instance, then starting the client instance which tries to connect() to the server, the following exception gets throws:

Caused by: java.rmi.UnmarshalException: error unmarshalling return; nested exception is:
java.lang.ClassNotFoundException: assign2.comm.ServerReceiver_Stub
at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
at assign2.comm.ServerConnector.<init>(ServerConnector.java:65)

While looking for answers, the most prominent was: the client must have access to the servers interface definition (IServerReceiver). However, to me it seems like that's the case here as proper dependencies are in place (client->shared, server->shared, IServerReceiver place in shared).
Another aspect of the exception I don't quite understand is: since JDK 1.5, stub generation through rmic is no longer necessary and is achieved through dynamic proxyies. The client therefore only needs access to the interface IServerReceiver in order to create the dynamic proxy. Why would he be complaining about not finding the ServerReceiver_Stub class at all then?

Since the integration test runs successfully and within that test the client also has access to the implementation of the IServerReceiver interface, am I right in assuming that the client needs not only access to the remote interface but also it's implementation?

I'm pretty confused by now so maybe you can help me shed some light on this matter? Thanks for having read that long post! ;-)

Cheers,
Chris


问:
Changing the span of CollectionView while rotating phone isn't working
I'm trying to change the span of CollectionView while rotating my iPhone. To make it easy, just show 2 columns in portrait, and 4 columns in landscape.
It works when rotating from portrait to landscape mode, but when rotating back to portrait mode, it always shows 1 column. My code likes,

```<code>    VideoCollectionView = new CollectionView()
        {
            ItemsLayout = new GridItemsLayout(2, ItemsLayoutOrientation.Vertical),
        };
    ...

    private static double screen_width = 1280.0;
    private static double screen_height = 720.0;

    protected override void OnSizeAllocated(double width, double height)
    {
        base.OnSizeAllocated(width, height);

        if ((Math.Abs(screen_width - width) > minimum_double) || (Math.Abs(screen_height - height) > minimum_double))
        {
            screen_width = width;
            screen_height = height;

            int split;
            if (screen_width > screen_height)
            {   // landscape mode
                split = 4;
            }
            else
            {   // portrait mode
                split = 2;
            }

            VideoCollectionView.ItemsLayout = new GridItemsLayout(split, ItemsLayoutOrientation.Vertical);
        }
    }
</code>```

Is this a bug? Or I should use other ways? Thanks for help.

答:
You could use a Singleton for storing the current orientation.Because it is unwise to set the screen size as s static value . It maybe will cause issue on different size of device .

```<code>public class CurrentDevice
{
    protected static CurrentDevice Instance;
    double width;
    double height;

    static CurrentDevice()
    {
        Instance = new CurrentDevice();
    }
    protected CurrentDevice()
    {
    }

    public static bool IsOrientationPortrait()
    {
        return Instance.height > Instance.width;
    }

    public static void SetSize(double width, double height)
    {
        Instance.width = width;
        Instance.height = height;
    }
}
</code>```

And in the method

```<code>protected override void OnSizeAllocated(double width, double height)
{
   base.OnSizeAllocated(width, height);

   if (CurrentDevice.IsOrientationPortrait() && width > height || !CurrentDevice.IsOrientationPortrait() && width < height)
   {
      int split;
      CurrentDevice.SetSize(width, height);

      // Orientation got changed! Do your changes here
      if (CurrentDevice.IsOrientationPortrait())
      {
         // portrait mode
         split = 2;
      }

      else
      {
         // landscape mode
         split = 4;
      }

      VideoCollectionView.ItemsLayout = new GridItemsLayout(split, ItemsLayoutOrientation.Vertical);
   }

}
</code>```

Body:
I'm trying to change the span of CollectionView while rotating my iPhone. To make it easy, just show 2 columns in portrait, and 4 columns in landscape.
It works when rotating from portrait to landscape mode, but when rotating back to portrait mode, it always shows 1 column. My code likes,

    VideoCollectionView = new CollectionView()
        {
            ItemsLayout = new GridItemsLayout(2, ItemsLayoutOrientation.Vertical),
        };
    ...

    private static double screen_width = 1280.0;
    private static double screen_height = 720.0;

    protected override void OnSizeAllocated(double width, double height)
    {
        base.OnSizeAllocated(width, height);

        if ((Math.Abs(screen_width - width) > minimum_double) || (Math.Abs(screen_height - height) > minimum_double))
        {
            screen_width = width;
            screen_height = height;

            int split;
            if (screen_width > screen_height)
            {   // landscape mode
                split = 4;
            }
            else
            {   // portrait mode
                split = 2;
            }

            VideoCollectionView.ItemsLayout = new GridItemsLayout(split, ItemsLayoutOrientation.Vertical);
        }
    }

Is this a bug? Or I should use other ways? Thanks for help.

Body:
You could use a Singleton for storing the current orientation.Because it is unwise to set the screen size as s static value . It maybe will cause issue on different size of device .

public class CurrentDevice
{
    protected static CurrentDevice Instance;
    double width;
    double height;

    static CurrentDevice()
    {
        Instance = new CurrentDevice();
    }
    protected CurrentDevice()
    {
    }

    public static bool IsOrientationPortrait()
    {
        return Instance.height > Instance.width;
    }

    public static void SetSize(double width, double height)
    {
        Instance.width = width;
        Instance.height = height;
    }
}

And in the method

protected override void OnSizeAllocated(double width, double height)
{
   base.OnSizeAllocated(width, height);

   if (CurrentDevice.IsOrientationPortrait() && width > height || !CurrentDevice.IsOrientationPortrait() && width < height)
   {
      int split;
      CurrentDevice.SetSize(width, height);

      // Orientation got changed! Do your changes here
      if (CurrentDevice.IsOrientationPortrait())
      {
         // portrait mode
         split = 2;
      }

      else
      {
         // landscape mode
         split = 4;
      }

      VideoCollectionView.ItemsLayout = new GridItemsLayout(split, ItemsLayoutOrientation.Vertical);
   }

}


问:
Add for loop inside a django view
this is my django view.What it basically does is, it gets the checked data from Html view.But I have to loop through each data in the view, or in template so that I can get not only the name of subtest but also it's fields.Subtest is the name of my model,and name is it's field</p>

```<code>def create_test_bills(request):
    if request.method == 'GET':
        selected = request.GET.getlist('selected')
        for i in range(0,len(selected)):
            a = selected [i]
            print(selected)
            print(a)
            sub_test = Subtest.objects.filter(name=a)
    return render(request,'report.html',{'sub_test':sub_test})
</code>```

答:
you can use django filter __in
https://docs.djangoproject.com/en/3.0/ref/models/querysets/#in

instead of looping through it:

```<code>def create_test_bills(request):
    if request.method == 'GET':
        selected = request.GET.getlist('selected')
        if len(selected) > 0:
           sub_test = Subtest.objects.filter(name__in=selected)
    return render(request,'report.html',{'sub_test':sub_test})
</code>```

Title: Add for loop inside a django view

Body:
this is my django view.What it basically does is, it gets the checked data from Html view.But I have to loop through each data in the view, or in template so that I can get not only the name of subtest but also it's fields.Subtest is the name of my model,and name is it's field

def create_test_bills(request):
    if request.method == 'GET':
        selected = request.GET.getlist('selected')
        for i in range(0,len(selected)):
            a = selected [i]
            print(selected)
            print(a)
            sub_test = Subtest.objects.filter(name=a)
    return render(request,'report.html',{'sub_test':sub_test})

Body:
you can use django filter __in
https://docs.djangoproject.com/en/3.0/ref/models/querysets/#in

instead of looping through it:

def create_test_bills(request):
    if request.method == 'GET':
        selected = request.GET.getlist('selected')
        if len(selected) > 0:
           sub_test = Subtest.objects.filter(name__in=selected)
    return render(request,'report.html',{'sub_test':sub_test})


问:
Python how to get a value from a complex dictionary?
In dict1 below, how do I assign from_port to the value of 'FromPort' if I am unsure what index it will be in the 'IpPermissions'?

For the example below, I can use an index, but it is not always index 0.

from_port = dict1['IpPermissions'][0]['FromPort']

dict1 = {'Description': 'Some AWS security group', 'IpPermissions': [{'Cidr': '0.0.0.0/0', 'FromPort': '80', 'IpProtocol': 'TCP'}]}

答:
This approach will pull out any dictionary from the array that contains a 'FromPort' key.

```<code>tmp = [d for d in dict1['IpPermissions'] if 'FromPort' in d]
from_port = tmp[0]['FromPort']
</code>```

Keep in mind this will fail if FromPort is not present (tmp will be empty) and similar to the other answer doesn't address multiple entries if you don't have that guarantee.

Body:
This approach will pull out any dictionary from the array that contains a 'FromPort' key.

tmp = [d for d in dict1['IpPermissions'] if 'FromPort' in d]
from_port = tmp[0]['FromPort']

Keep in mind this will fail if FromPort is not present (tmp will be empty) and similar to the other answer doesn't address multiple entries if you don't have that guarantee.


问:
How do you use force adb to backup without user confirmation?
Running adb backup -apk -shared -all on an Android device yields Now unlock your device and confirm the backup operation. on the Terminal and a prompt on the device screen that requires user intervention. I was hoping to automate backup and restore from adb. is there a way to force and proceed with backup without user confirmation?

答:
My solution for this case is to use dd (it's available in vanilla Android, and custom recoveries, like TWRP, as well):

```<code>sudo adb shell dd if=/dev/block/bootdevice/by-name/boot > boot.bin
sudo adb shell dd if=/dev/block/bootdevice/by-name/modem > modem.bin
sudo adb shell dd if=/dev/block/bootdevice/by-name/system > system.bin
</code>```

...Or with compression:

```<code>sudo adb shell dd if=/dev/block/bootdevice/by-name/system | xz -9 -T0 - > system.bin.xz
</code>```

Later the binary image can be transformed to any desired backup format.

Body:
My solution for this case is to use dd (it's available in vanilla Android, and custom recoveries, like TWRP, as well):

sudo adb shell dd if=/dev/block/bootdevice/by-name/boot > boot.bin
sudo adb shell dd if=/dev/block/bootdevice/by-name/modem > modem.bin
sudo adb shell dd if=/dev/block/bootdevice/by-name/system > system.bin

...Or with compression:

sudo adb shell dd if=/dev/block/bootdevice/by-name/system | xz -9 -T0 - > system.bin.xz

Later the binary image can be transformed to any desired backup format.


问:
cPanel / WHM restore from backup tar archive (from another cPanel server)
I am quite new to server migrations, but fairly familiar with cPanel though. My current task is to migrate an entire website from a server with cPanel to another one.

What I did so far:

Use the Backup Wizard on the old server to create a full backup archive, and FTP it to the new server.

The full archive (about 6 GB because there are a lot of images) is now in my new server's public_html directory.

Now, what I need is a way to make the server take this tar archive, which is a full backup, and restore from it.

What I tried:

I tried simply extracting the archive, but it is taking forever to finish (again the archive is 6 GB), and for some reason my browser tab has to stay open until the end of the process, otherwise the extracting halts.

Also, as I have WHM access, I tried the "Restore a Full Backup/cpmove File" option, but for some reason, under the "Username for the account that you wish to restore:" textbox, WHM does not find my cPanel username.

If anyone can either tell me what I am doing wrong, or propose another option, I would really appreciate it.

P.S.: I only have WHM access to the new server, not the old one.

Edit: I got the WHM method working now. My mistake was that my tar archive was not stored in the /home directory, but in the home directory of the cPanel user (which is /home/username)!

答:
Move your cpanel full backup file to /home directory and if you root have access of the server use below command as  /scripts/restorepkg  (cpanel username )

OR

Login to WHM with root user and go through the steps mentioned on below URL.

http://documentation.cpanel.net:8090/display/68Docs/Restore+a+Full+Backup+cpmove+File


问:
How to convert a nested json string into accessible structure in C# for printing select items?
Which procedure and data-structure should I use that will give me access all the key-value pairs in a nested JSON string in C#?

Pictured below is a portion of the JSON string I am working with. As you can see it is nested. I am seeking to retrieve the "date" and "message" from each block with their respective keys using C-Sharp C#.

I have tried putting my JSON string into a Dictionary.

```<code>private static async Task<String> ProcessRepo()
{

   var stringTask = APIclient.GetStringAsync("https://a.RESTapi.fakecom");
   var x = await stringTask;
   Dictionary<string, object> data = JsonConvert.DeserializeObject<Dictionary<string, object>>(x);

   return data;
}
</code>```

This gives me 2 key-values pairs. One is "pagelen" with a value of 30, and the other is "values" with a value of everything that followed in one long string. Not very useful.

This is my first time using C#.  Please point me in the right direction. I have spent many hours searching for something that will work.

答:
Issue with the deserialization is that you are trying to deserialize the complete JSON as Dictionary of key value pairs but that was not how the JSON is, that is the reason why you could not access the values as expected/

Two ways to solve this case

Method 1:

```<code>var data = JsonConvert.DeserializeObject(x);
</code>```

This will deserialize the complete json in an unstructured way, and you will get keys and values for each and every nested JSON.

Method 2:
Create a class with the same structure as your JSON.

```<code>    public class MyJson
    {
        [JsonProperty("pageLen")]
        public int PageLen { get; set; }

        [JsonProperty("values")]
        public Values Values { get; set; }

    }

    public class Values
    {
        [JsonProperty("rendered")]
        public Rendered Rendered { get; set; }

        [JsonProperty("hash")]
        public string Hash { get; set; }
    }

    public class Rendered
    {

    }
</code>```

And then pass this as deserializing class as below.

```<code>    private static async Task<String> ProcessRepo()
    {
         MyJson data = JsonConvert.DeserializeObject<MyJson>(x);
    }
</code>```

Body:
Which procedure and data-structure should I use that will give me access all the key-value pairs in a nested JSON string in C#?

Pictured below is a portion of the JSON string I am working with. As you can see it is nested. I am seeking to retrieve the "date" and "message" from each block with their respective keys using C-Sharp C#.

I have tried putting my JSON string into a Dictionary.

private static async Task<String> ProcessRepo()
{

   var stringTask = APIclient.GetStringAsync("https://a.RESTapi.fakecom");
   var x = await stringTask;
   Dictionary<string, object> data = JsonConvert.DeserializeObject<Dictionary<string, object>>(x);

   return data;
}

This gives me 2 key-values pairs. One is "pagelen" with a value of 30, and the other is "values" with a value of everything that followed in one long string. Not very useful.

This is my first time using C#.  Please point me in the right direction. I have spent many hours searching for something that will work.

Body:
Issue with the deserialization is that you are trying to deserialize the complete JSON as Dictionary of key value pairs but that was not how the JSON is, that is the reason why you could not access the values as expected/

Two ways to solve this case

Method 1:

var data = JsonConvert.DeserializeObject(x);

This will deserialize the complete json in an unstructured way, and you will get keys and values for each and every nested JSON.

Method 2:
Create a class with the same structure as your JSON.

    public class MyJson
    {
        [JsonProperty("pageLen")]
        public int PageLen { get; set; }

        [JsonProperty("values")]
        public Values Values { get; set; }

    }

    public class Values
    {
        [JsonProperty("rendered")]
        public Rendered Rendered { get; set; }

        [JsonProperty("hash")]
        public string Hash { get; set; }
    }

    public class Rendered
    {

    }

And then pass this as deserializing class as below.

    private static async Task<String> ProcessRepo()
    {
         MyJson data = JsonConvert.DeserializeObject<MyJson>(x);
    }


问:
How would I include the output from a project in msbuild deployment from a project built afterward
I am working with NopCommerce.  The framework is built in such a way that allows the creation of plugins as additional projects in the solution.  These projects have to reference the "Core" which is essentially the MVC website that gets deployed.

Due to the nature of msbuild, I cannot think of any way (without hacks) to get the output of the plugin projects build (dll files) to be included in the Core build deployment because the plugins are required to build the core first.

I understand this is a circular dependency, and I also understand that in a normal situation, one would not require the plugins to even know the web project exists...  But this is how it is when using NopCommerce.

I have tried to do the following with msbuild in the website csproj file:

```<code><Target Name="NopTarget" AfterTargets="Build">
    <ItemGroup>
      <BuildPlugins Include="..\..\Plugins\**\*.csproj" />
    </ItemGroup>

    <Message Text="directory: @(BuildPlugins)" Importance="HIGH" />

    <MSBuild Projects="@(BuildPlugins)" />

    <ItemGroup>
      <NopPlugins Include="$(MSBuildProjectDirectory)\Plugins\**\*.*" />
    </ItemGroup>

    <Message Text="@(BuildPlugins)" Importance="HIGH" />
    <Message Text="After Build Plugin Copy - @(NopPlugins) - $(TargetDir)\%(RecursiveDir)" Importance="HIGH" />

    <Copy SourceFiles="@(NopPlugins)" DestinationFolder="$(TargetDir)\Plugins\%(RecursiveDir)" />
</code>```

... but I think its a giant mess.  Also, it only seems to work properly on my dev machine.  When I try it in devops, I get a bunch of nuget package errors related to failed restore.  Again, it's an issue with circular dependencies, or build order.

(FYI, I'm working on a parameterized deployment to use with Azure Devops)

答:
... but I think its a giant mess. Also, it only seems to work properly
  on my dev machine. When I try it in devops, I get a bunch of nuget
  package errors related to failed restore. Again, it's an issue with
  circular dependencies, or build order.

Since it works in your local machine, I assume it's just something wrong with your restore step. And it caused next build error.

According to your script, your core project and plugins project are not in same directory level. So your nuget/dotnet restore task should run twice to restore packages for both two project separately if the plugins project is not defined in xx.sln file.

If your project targets .net framework, use nuget restore task, or use the restore command in use .net core task if your projects target .net core/standard. Just make sure you've restored packages for all the projects.

Body:
I am working with NopCommerce.  The framework is built in such a way that allows the creation of plugins as additional projects in the solution.  These projects have to reference the "Core" which is essentially the MVC website that gets deployed.

Due to the nature of msbuild, I cannot think of any way (without hacks) to get the output of the plugin projects build (dll files) to be included in the Core build deployment because the plugins are required to build the core first.

I understand this is a circular dependency, and I also understand that in a normal situation, one would not require the plugins to even know the web project exists...  But this is how it is when using NopCommerce.

I have tried to do the following with msbuild in the website csproj file:

<Target Name="NopTarget" AfterTargets="Build">
    <ItemGroup>
      <BuildPlugins Include="..\..\Plugins\**\*.csproj" />
    </ItemGroup>

    <Message Text="directory: @(BuildPlugins)" Importance="HIGH" />

    <MSBuild Projects="@(BuildPlugins)" />

    <ItemGroup>
      <NopPlugins Include="$(MSBuildProjectDirectory)\Plugins\**\*.*" />
    </ItemGroup>

    <Message Text="@(BuildPlugins)" Importance="HIGH" />
    <Message Text="After Build Plugin Copy - @(NopPlugins) - $(TargetDir)\%(RecursiveDir)" Importance="HIGH" />

    <Copy SourceFiles="@(NopPlugins)" DestinationFolder="$(TargetDir)\Plugins\%(RecursiveDir)" />

... but I think its a giant mess.  Also, it only seems to work properly on my dev machine.  When I try it in devops, I get a bunch of nuget package errors related to failed restore.  Again, it's an issue with circular dependencies, or build order.

(FYI, I'm working on a parameterized deployment to use with Azure Devops)


问:
How do you fix the "element not interactable" exception?
I know this has been asked lots of times before but how do you get around the "element not interactable" exception?

Here is my code:

```<code>button = driver.find_element_by_class_name(u"infoDismiss")
type(button)
button.click()
driver.implicitly_wait(10)
</code>```

Here is the HTML:

```<code><button class="dismiss infoDismiss">
    <string for="inplay_button_dismiss">Dismiss</string>
</button>
</code>```

And here is the error message:

```<code>selenium.common.exceptions.ElementNotInteractableException: Message:
</code>```

After is says message there is literally nothing.

I have spent lots of time searching the web, not finding anything that solves my issue. I would really appreciate an answer.

Edit: Changed "w" to driver so it is easier to read

Update: I have just realized that I've found the HTML of the wrong button! The real button HTML is below:

```<code><button class="dismiss">
    <string for="exit">Dismiss</string>
</button>
</code>```

Also, I've used the answers and comments and edited my code to look like this:

```<code>button = driver.find_element_by_css_selector("button.dismiss")
w.implicitly_wait(10)
ActionChains(w).move_to_element(button).click(button)
</code>```

And now I get a new error:

```<code>selenium.common.exceptions.WebDriverException: Message: Tried to run command without establishing a connection
</code>```

The error happens in line 1: button = driver.find_element_by_css_selector("button.dismiss")

答: use id of the element except x_path.It will work 100%

Body:
I know this has been asked lots of times before but how do you get around the "element not interactable" exception?

Here is my code:

button = driver.find_element_by_class_name(u"infoDismiss")
type(button)
button.click()
driver.implicitly_wait(10)

Here is the HTML:

<button class="dismiss infoDismiss">
    <string for="inplay_button_dismiss">Dismiss</string>
</button>

And here is the error message:

selenium.common.exceptions.ElementNotInteractableException: Message:

After is says message there is literally nothing.

I have spent lots of time searching the web, not finding anything that solves my issue. I would really appreciate an answer.

Edit: Changed "w" to driver so it is easier to read

Update: I have just realized that I've found the HTML of the wrong button! The real button HTML is below:

<button class="dismiss">
    <string for="exit">Dismiss</string>
</button>

Also, I've used the answers and comments and edited my code to look like this:

button = driver.find_element_by_css_selector("button.dismiss")
w.implicitly_wait(10)
ActionChains(w).move_to_element(button).click(button)

And now I get a new error:

selenium.common.exceptions.WebDriverException: Message: Tried to run command without establishing a connection

The error happens in line 1: button = driver.find_element_by_css_selector("button.dismiss")


问:
Earning the event argument from a non-callback function (normal function calling)
I want to get the event argument from a normal function calling.
in callback functions we do something like this:

```<code>document.addEventListener('something', function(e){e.target.parentNode...etc});
</code>```

Here is my code

```<code><div class="options">
    <div onclick="controller.question_type('circleTheCorrectAnswer')">Circle The Correct Answer</div>
</div>

<script type="text/javascript">
 const controller = (()=>{

  const question_type = (x)=>{
    console.log(x.target.parentNode);
    console.log(x.target);
  }

  return {
    question_type: question_type
  }

 })();
</script>
</code>```

答:
In your code,

```<code><div onclick="controller.question_type('circleTheCorrectAnswer')">
</code>```

is a rough equivalent of

```<code>document.addEventListener('click', controller.question_type('circleTheCorrectAnswer'));
</code>```

The problem with the above is that you're not returning a function from controller.question_type(), hence the event has nowhere to be passed.

You can change the question_type to something like

```<code>const question_type = (type) => {
  console.log(`type is ${type}`)
  return (event) => {
    console.log(event.target.parentNode);
    console.log(event.target);
  }
}
</code>```

Body:
I want to get the event argument from a normal function calling.
in callback functions we do something like this:

document.addEventListener('something', function(e){e.target.parentNode...etc});

Here is my code

Circle The Correct Answer

Body:
In your code,

<div onclick="controller.question_type('circleTheCorrectAnswer')">

is a rough equivalent of

document.addEventListener('click', controller.question_type('circleTheCorrectAnswer'));

The problem with the above is that you're not returning a function from controller.question_type(), hence the event has nowhere to be passed.

You can change the question_type to something like

const question_type = (type) => {
  console.log(`type is ${type}`)
  return (event) => {
    console.log(event.target.parentNode);
    console.log(event.target);
  }
}


问:
How to access source code from within Docker build?
I'm trying to build a Github Action that's going to take a screenshot of the Github Pages website (built with Jekyll) and allow the user to upload it as an artifact. For my convienience and since installing Pyppeteer is non-trivial, I wrapped the thing around in Docker. Here's the source code for the action at the time of writing the question:

https://github.com/hakierspejs/jekyll-screenshot-github-action/tree/8569f1370c5decf5ecfb4bc17a977cad5aa3d2aa

The problem is in accessing the source code of the Github Pages website. I noticed that Github Actions is mapping a couple of directories as a volume, but neither /github/workflow nor /github/workspace seems to contain the source code. Is there a path I could mount to somehow access it?

答:
/github/workflow is the right path, but I was missing a actions/checkout@master step. Adding this line to the list of steps made it work:

```<code>- uses: actions/checkout@master
</code>```

Body:
/github/workflow is the right path, but I was missing a actions/checkout@master step. Adding this line to the list of steps made it work:

- uses: actions/checkout@master


问:
Scope 'session' is not active for the current thread - multi-threading
I have a java-spring web application and I use some external libraries which I don't have access to.
At one of the flows, I create a new thread and use this external library. I get an exception:

Is there any possible way to overcome this exception?

Thanks!

答:
Encountered the same problem as this, and came across with: https://bekce.github.io/replacing-session-scope-with-thread-scope-in-spring-framework/

"here is a problem with session scoped beans when your application also needs other integration points other than web servlets".

I then used the custom scope = "thread" from sping's SimpleThredScope.

In bean config, something like this:

```<code><bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
      <property name="scopes">
          <map>
              <entry key="thread">
                  <bean class="org.springframework.context.support.SimpleThreadScope"/>
              </entry>
          </map>
      </property>
    </bean>
    <bean id="testA" class="com.concretepage.A"  scope="thread" />
</code>```

Body:
Encountered the same problem as this, and came across with: https://bekce.github.io/replacing-session-scope-with-thread-scope-in-spring-framework/

"here is a problem with session scoped beans when your application also needs other integration points other than web servlets".

I then used the custom scope = "thread" from sping's SimpleThredScope.

In bean config, something like this:

<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
      <property name="scopes">
          <map>
              <entry key="thread">
                  <bean class="org.springframework.context.support.SimpleThreadScope"/>
              </entry>
          </map>
      </property>
    </bean>
    <bean id="testA" class="com.concretepage.A"  scope="thread" />


问:
ionic 4 Form control problem not showing value in input
Ionic 4 not showing the value in input. I have 4 fields in my form. 2 is disabled. But i need to show some value in fix input. here is my code

```<code><form [formGroup]="ionicForm" (ngSubmit)="submitForm()" novalidate>

    <ion-item>
      <ion-input  type="text" formControlName="username"></ion-input>
    </ion-item>

    <ion-item>
      <ion-input  type="text" formControlName="email"></ion-input>

    </ion-item>

    <ion-item>
      <ion-input placeholder="Phone" type="number" formControlName="number"></ion-input>
      <ion-icon name="call" slot="end" color="primary"></ion-icon>
    </ion-item>
     <span class="error ion-padding" *ngIf="isSubmitted && errorControl.number.errors?.required">
      Please enter your 11 digit number
    </span>

  <ion-item>
    <ion-label style="color: #1d808c">Select Operator</ion-label>
    <ion-select formControlName="operator">
      <ion-select-option value="Telenor">Telenor</ion-select-option>
      <ion-select-option value="Jazz">Jazz</ion-select-option>
      <ion-select-option value="Warid">Warid</ion-select-option>
      <ion-select-option value="Ufone">Ufone</ion-select-option>
      <ion-select-option value="Zong">Zong</ion-select-option>
    </ion-select>
  </ion-item>
     <span class="error ion-padding" *ngIf="isSubmitted && errorControl.operator.errors?.required">
      Please select operator
    </span>
</form>
</ion-card>

<div style="display: flex; justify-content: center;">
  <ion-button expand="block" class="btn" fill="outline" type="submit" (click)="submitForm()">Save</ion-button>
</div>
</code>```

As in form first 2 value i have disable it and showing some values but its showing error of Cannot read property 'get' of undefined

Here my .ts code

```<code>ngOnInit() {

    //Get user
  this.auth.getUserData().subscribe((data:any) => {
      console.log('home');
      console.log(data);
      this.data = data;

    this.ionicForm = this.formBuilder.group({
      number: ['', [Validators.required, Validators.minLength(11)]],
      operator: ['', [Validators.required]],
      username: [{value: this.data.username, disabled: true}], //here is problem
      email: [{value: this.data.email, disabled: true}],

    })

  });

}
</code>```

Its working fine if i am hardcoding value like username: [{value: 'abc, disabled: true}]

Its showing abc if i am hardcoding this but when i am passing value its not working

答:
You need To use ngModel to Bind Data in HTML

in .html file

```<code><form [formGroup]="ionicForm" (ngSubmit)="submitForm()" novalidate>

    <ion-item>
      <ion-input  type="text" name="username" [(ngModel)]="data.username" formControlName="username" disabled></ion-input>
    </ion-item>

    <ion-item>
      <ion-input  type="text"  name="email" [(ngModel)]="data.email" formControlName="email" disabled></ion-input>

    </ion-item>
  </form>
</code>```

in .ts file

```<code> data:any={
    username:'username',
    email:"email"
  }
</code>```

Body:
Ionic 4 not showing the value in input. I have 4 fields in my form. 2 is disabled. But i need to show some value in fix input. here is my code

<form [formGroup]="ionicForm" (ngSubmit)="submitForm()" novalidate>

    <ion-item>
      <ion-input  type="text" formControlName="username"></ion-input>
    </ion-item>

    <ion-item>
      <ion-input  type="text" formControlName="email"></ion-input>

    </ion-item>

    <ion-item>
      <ion-input placeholder="Phone" type="number" formControlName="number"></ion-input>
      <ion-icon name="call" slot="end" color="primary"></ion-icon>
    </ion-item>

      Please enter your 11 digit number

  <ion-item>
    <ion-label style="color: #1d808c">Select Operator</ion-label>
    <ion-select formControlName="operator">
      <ion-select-option value="Telenor">Telenor</ion-select-option>
      <ion-select-option value="Jazz">Jazz</ion-select-option>
      <ion-select-option value="Warid">Warid</ion-select-option>
      <ion-select-option value="Ufone">Ufone</ion-select-option>
      <ion-select-option value="Zong">Zong</ion-select-option>
    </ion-select>
  </ion-item>

      Please select operator

</form>
</ion-card>

  <ion-button expand="block" class="btn" fill="outline" type="submit" (click)="submitForm()">Save</ion-button>

As in form first 2 value i have disable it and showing some values but its showing error of Cannot read property 'get' of undefined

Here my .ts code

ngOnInit() {

    //Get user
  this.auth.getUserData().subscribe((data:any) => {
      console.log('home');
      console.log(data);
      this.data = data;

    this.ionicForm = this.formBuilder.group({
      number: ['', [Validators.required, Validators.minLength(11)]],
      operator: ['', [Validators.required]],
      username: [{value: this.data.username, disabled: true}], //here is problem
      email: [{value: this.data.email, disabled: true}],

    })

  });

}

Its working fine if i am hardcoding value like username: [{value: 'abc, disabled: true}]

Its showing abc if i am hardcoding this but when i am passing value its not working

Body:
You need To use ngModel to Bind Data in HTML

in .html file

<form [formGroup]="ionicForm" (ngSubmit)="submitForm()" novalidate>

    <ion-item>
      <ion-input  type="text" name="username" [(ngModel)]="data.username" formControlName="username" disabled></ion-input>
    </ion-item>

    <ion-item>
      <ion-input  type="text"  name="email" [(ngModel)]="data.email" formControlName="email" disabled></ion-input>

    </ion-item>
  </form>

in .ts file

 data:any={
    username:'username',
    email:"email"
  }


问:
Search for “whole word match” with SQL Server LIKE pattern
Does anyone have a LIKE pattern that matches whole words only?

It needs to account for spaces, punctuation, and start/end of string as word boundaries.

I am not using SQL Full Text Search as that is not available. I don't think it would be necessary for a simple keyword search when LIKE should be able to do the trick.  However if anyone has tested performance of Full Text Search against LIKE patterns, I would be interested to hear.

Edit:

I got it to this stage, but it does not match start/end of string as a word boundary.

```<code>where DealTitle like '%[^a-zA-Z]pit[^a-zA-Z]%'
</code>```

I want this to match "pit" but not "spit" in a sentence or as a single word.

E.g. DealTitle might contain "a pit of despair" or "pit your wits" or "a pit" or "a pit." or "pit!" or just "pit".

答:
If you can use regexp operator in your SQL query..

For finding any combination of spaces, punctuation and start/end of string as word boundaries:

```<code>where DealTitle regexp '(^|[[:punct:]]|[[:space:]])pit([[:space:]]|[[:punct:]]|$)'
</code>```

Body:
Does anyone have a LIKE pattern that matches whole words only?

It needs to account for spaces, punctuation, and start/end of string as word boundaries.

I am not using SQL Full Text Search as that is not available. I don't think it would be necessary for a simple keyword search when LIKE should be able to do the trick.  However if anyone has tested performance of Full Text Search against LIKE patterns, I would be interested to hear.

Edit:

I got it to this stage, but it does not match start/end of string as a word boundary.

where DealTitle like '%[^a-zA-Z]pit[^a-zA-Z]%'

I want this to match "pit" but not "spit" in a sentence or as a single word.

E.g. DealTitle might contain "a pit of despair" or "pit your wits" or "a pit" or "a pit." or "pit!" or just "pit".

Body:
If you can use regexp operator in your SQL query..

For finding any combination of spaces, punctuation and start/end of string as word boundaries:

where DealTitle regexp '(^|[[:punct:]]|[[:space:]])pit([[:space:]]|[[:punct:]]|$)'