问:
What is the best tips to improve the Application Performance in Asp.Net?
Can any help regarding the performance improvement in Asp.Net?The best practise tips for asp.net performance improvement?</p>

答:
What is the best drug to get healthier? It all depends on what is your health problem. The same thing is with ASP.NET performance. First, find what is your bottleneck, a single most slow down factor. Then fix it, retest performance and, if more speed is necessary, go to the previous step.

How to find a bottleneck?  If you really have no clue where to start, then start from analyzing your waterfall diagram. To create one from your client, use Fiddler or Firebug. To create it from different Internet geographies use WebPagetest. The waterfall will show whether the bottleneck is on the server or network, and also whether it is caused by main ASPX page or by resources (scripts, images, CSS). If the server and network are fast enough, then check slowness in the browser using Firebug or dynaTrace Ajax edition that can trace DOMContentLoaded/load events in browser. If the bottleneck is on the server, find out whether it is the database or application. Use database profiler and .NET profiler, for example from this question.

How to fix bottlenecks?  Check this Microsoft resource, but there are many others for each type of bottlenecks.

If you add the “performance“ tag to your question you may get more answers.


来源: stackexchange

问:
Python: join two bytearray objects
I would like to concatenate a bytearray to another bytearray. I thought this might work:

```<code>byt1 = bytearray(10)
byt2 = bytearray(10)
byt1.join(byt2)
print(repr(byt1))
</code>```

byt1.join(byt2)

TypeError: sequence item 0: expected a bytes-like object, int found

What is the most efficient way to achieve this?

答:
Create a new combined bytearray from two:

```<code>byt_combined = byt1 + byt2
</code>```

Extend one bytearray with another. This changes byt1:

```<code>byt1.extend(byt2)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Python: join two bytearray objects

Body:
I would like to concatenate a bytearray to another bytearray. I thought this might work:

byt1 = bytearray(10)
byt2 = bytearray(10)
byt1.join(byt2)
print(repr(byt1))

byt1.join(byt2)

TypeError: sequence item 0: expected a bytes-like object, int found

What is the most efficient way to achieve this?

Body:
Create a new combined bytearray from two:

byt_combined = byt1 + byt2

Extend one bytearray with another. This changes byt1:

byt1.extend(byt2)

ContentLicense: CC BY-SA 3.0


问:
AutocompleteInput: change format of query
Is it possible to, for example, change the "q" query key in the AutocompleteInput?

The default { "q": "foobar" } doesn't work with my API where "q" would be correspondent to a model key, e.g productName to make the filtering.

EDIT: (CLOSED)
Realizing this isn't really AoR's responsibility I've opted to instead modify my restClient to handle a "q" keyed request.

EDIT 2:
This can also be done in the view layer by using the filterToQuery prop on ReferenceInput/ReferenceArrayInput to modify the query sent to your restClient

答:
You can handle this at the client level as well. Just use a custom Rest Client or use a RestClient wrapper to intercept the call to your API and format the request URL depending on the value of the q filter.

https://marmelab.com/admin-on-rest/RestClients.html#decorating-your-rest-client-example-of-file-upload

https://marmelab.com/admin-on-rest/RestClients.html#writing-your-own-rest-client

Hope this helps.


问:
How to map between int and property c#
In the project I'm working on, (.net Core) we are using a range slider (noUiSlider)to represent quality in a product filter.

Slider

The slider returns an array of numbers as an example [2, 4] would be returned if the slider was set to Good and Excellent and I would need to retrieve all the products that match Good, Very Good, and Excellent in quality.

Here in lies some of the unique problems with this.
The products are pulled from a third party service, and I only receive the quality as the string value. So I need a way to assign a number value to the string value I receive so I can check for all products that have a quality >= to qualityArray[0] and <= to qualityArray[1]

What would be the best way to map between string to int so I can do the >= and <= check with the quality range and at the same time map the int to a string so when displaying the list of products that match the range I only have to display the string value? (Very Good)

I was imagining using an Enum or a Dictionary but I'm not sure what the advantages of either would be.

答:
Assuming your slider is a simple array you might try the follwing or something similar:</p>

```<code>       // This will be what is returned by your slider
int[] ar = [2,4];
 Dictionary<int, string> test = new Dictionary<int, string>()
            {
                {1,"OK" },
                {2,"Good"},
                {3,"Very Good"},
                {4,"Excellent"}

            };

            List<string> choosenquality = new List<string>();
            for(int x =ar[0];x<=ar[1];x++)
            {
                choosenquality.Add(test[x]);
            }
//The following will be all the products that meet good, very good, and excellent
            IEnumerable<Productclass> tested = from x in myapps join y in choosenquality where x.Quality== y select x;
</code>```

Title: How to map between int and property c#

Body:
Assuming your slider is a simple array you might try the follwing or something similar:

       // This will be what is returned by your slider
int[] ar = [2,4];
 Dictionary<int, string> test = new Dictionary<int, string>()
            {
                {1,"OK" },
                {2,"Good"},
                {3,"Very Good"},
                {4,"Excellent"}

            };

            List<string> choosenquality = new List<string>();
            for(int x =ar[0];x<=ar[1];x++)
            {
                choosenquality.Add(test[x]);
            }
//The following will be all the products that meet good, very good, and excellent
            IEnumerable<Productclass> tested = from x in myapps join y in choosenquality where x.Quality== y select x;


问:
angular component replacement feature
I am trying to use the angular component replacement feature.

```<code><ul>
  <li></li>
  <li class="com"></li>
  <li class="com"></li>
</ul>
</code>```

For complicated interface, if I want to make the middle .com "li" into a whole new component, and write this code like:

```<code><ul>
  <li></li>
  <com-component></com-component>
</ul>
</code>```

How can I make sure that the finally compiled html is exactly what the original html template looks like?

It is not possible as far as I have searched from angular docs.

In angularjs, there is replacement feature. For a "compiled" angular framework, this is bit of off-putting not to have this.

答:
You can use an attribute selector in the com-component.

```<code>@Component({
...
selector: '[com-component]'
})
</code>```

And then, in the template, simply add com-component as an attribute to the li element instead of adding it as a new tag.

```<code><ul>
  <li></li>
  <li com-component></li>
</ul>
</code>```

Title: angular component replacement feature

Body:
I am trying to use the angular component replacement feature.

For complicated interface, if I want to make the middle .com "li" into a whole new component, and write this code like:

  <com-component></com-component>

How can I make sure that the finally compiled html is exactly what the original html template looks like?

It is not possible as far as I have searched from angular docs.

In angularjs, there is replacement feature. For a "compiled" angular framework, this is bit of off-putting not to have this.

Body:
You can use an attribute selector in the com-component.

@Component({
...
selector: '[com-component]'
})

And then, in the template, simply add com-component as an attribute to the li element instead of adding it as a new tag.

<ul>
  <li></li>
  <li com-component></li>
</ul>


问:
Need a "yarn/npm link" workflow for dev and publishing for "multiple copies of react" module
I am building and publishing a module to npm. The module is dependent on React. I am currently using yarn and yarn link.

I have built this module in a parent project and now am trying to extract it to a standalone module. I want to continue developing the module locally as part of the parent project.

The package.json in the module looks like:

```<code>  "devDependencies": {
    "react": "^16.1.1",
    "react-reconciler": "^0.6.0",
    "react-dom": "^16.0.0",
    "regl": "^1.3.0",
}
</code>```

I include this module in a parent projection by running yarn link in the module directory and then yarn link module-name in the parent directory. When included in the parent project an error is then thrown

Element ref was specified as a string (canvas) but no owner was set.
  You may have multiple copies of React loaded. (details:
  https://reactjs.org/warnings/refs-must-have-owner.html).

I have previously tried this workflow using npm instead of yarn and had the same issues.

I'm hoping this is a solved problem with a boilerplate. I've looked at other projects and haven't seen a common solution. I"m looking for a high-level best practices answer. I'm open to configurations using webpack rollup or whatever.

答:
With Webpack you can use resolve.alias a long with npm/yarn link in order to have all dependencies use a single instance of React from your host app.

In your development Webpack config add the following:

```<code>resolve: {
   alias: {
      react: path.resolve('./node_modules/react'),
   },
},
</code>```

Body:
I am building and publishing a module to npm. The module is dependent on React. I am currently using yarn and yarn link.

I have built this module in a parent project and now am trying to extract it to a standalone module. I want to continue developing the module locally as part of the parent project.

The package.json in the module looks like:

  "devDependencies": {
    "react": "^16.1.1",
    "react-reconciler": "^0.6.0",
    "react-dom": "^16.0.0",
    "regl": "^1.3.0",
}

I include this module in a parent projection by running yarn link in the module directory and then yarn link module-name in the parent directory. When included in the parent project an error is then thrown

Element ref was specified as a string (canvas) but no owner was set.
  You may have multiple copies of React loaded. (details:
  https://reactjs.org/warnings/refs-must-have-owner.html).

I have previously tried this workflow using npm instead of yarn and had the same issues.

I'm hoping this is a solved problem with a boilerplate. I've looked at other projects and haven't seen a common solution. I"m looking for a high-level best practices answer. I'm open to configurations using webpack rollup or whatever.

Body:
With Webpack you can use resolve.alias a long with npm/yarn link in order to have all dependencies use a single instance of React from your host app.

In your development Webpack config add the following:

resolve: {
   alias: {
      react: path.resolve('./node_modules/react'),
   },
},


问:
how to make user interaction disable for tab bar in swift 3?
Here while adding item to cart at that time activity indicator will animate during this time while activity indicator animates during this time user should not able to access the tab bar items can anyone help me how to implement this ?

here is my code for this

```<code> var tabbarController = UITabBarController()
 loginCheck = UserDefaults.standard.integer(forKey: "CustomerLogin")
        print(loginCheck!)
        let storyBoard = UIStoryboard(name: "Main", bundle: nil)
        let vc1 = storyBoard.instantiateViewController(withIdentifier: "cartViewController") as! AddToCartViewController
        let vc2 = storyBoard.instantiateViewController(withIdentifier: "searchCategories") as! SearchCategoriesViewController
        let vc3 = storyBoard.instantiateViewController(withIdentifier: "myAccount") as! MyAccountViewController
        tabbarController.viewControllers = [vc1,vc2,vc3]
        let tabItems = self.tabBarController?.tabBar.items as NSArray!
        let tabItem = tabItems?[1] as! UITabBarItem
</code>```

答:
If you want to handle whole app user interaction then do the following-

To disable User interaction:

```<code> UIApplication.shared.beginIgnoringInteractionEvents()
</code>```

To enable User interaction:

```<code>if(UIApplication.shared.isIgnoringInteractionEvents){

        UIApplication.shared.endIgnoringInteractionEvents()

    }
</code>```

Body:
Here while adding item to cart at that time activity indicator will animate during this time while activity indicator animates during this time user should not able to access the tab bar items can anyone help me how to implement this ?

here is my code for this

 var tabbarController = UITabBarController()
 loginCheck = UserDefaults.standard.integer(forKey: "CustomerLogin")
        print(loginCheck!)
        let storyBoard = UIStoryboard(name: "Main", bundle: nil)
        let vc1 = storyBoard.instantiateViewController(withIdentifier: "cartViewController") as! AddToCartViewController
        let vc2 = storyBoard.instantiateViewController(withIdentifier: "searchCategories") as! SearchCategoriesViewController
        let vc3 = storyBoard.instantiateViewController(withIdentifier: "myAccount") as! MyAccountViewController
        tabbarController.viewControllers = [vc1,vc2,vc3]
        let tabItems = self.tabBarController?.tabBar.items as NSArray!
        let tabItem = tabItems?[1] as! UITabBarItem

Body:
If you want to handle whole app user interaction then do the following-

To disable User interaction:

 UIApplication.shared.beginIgnoringInteractionEvents()

To enable User interaction:

if(UIApplication.shared.isIgnoringInteractionEvents){

        UIApplication.shared.endIgnoringInteractionEvents()

    }


问:
How to setup test data for TestNG Java
There are some tests that need the data in the database in some state. For now I am using the @BeforeMethod Annotation to setup the data.  The problem that I face is duplication of the same setup in every test class.
What is the correct approach for the problem? Should I add an abstract class ?

Thanks.

答:
If you have N number of test classes that are dependent on each other, then use a @BeforeSuite method for setting up data. Use testNGxml to call this class (Which has @BeforeSuite method) firstly.

If you have independent test classes then use @BeforeClass method to setup data before each test class is executed.

Title: How to setup test data for TestNG Java


问:
What do you model and when? (Enterprise, Application and Database Design Modeling)
Imagine that you are designing a web application that could possibly grow to the scale of Amazon or Google. In the beginning you start with only one small aspect of the project knowing that, in the name of agile development, you have to start somewhere. For example, you might choose to create a simple directory of books hoping that your project takes off and some day you'll be not just a directory but a one-stop site for buying and selling books as well as all kinds of other merchandise. (This is all purely hypothetical.)

What are the different types of modeling you would employ? What are the different "entities" that you would model in the beginning? How important do you think modeling is and what information should you use to determine when and what to model?

In an answer on a previously asked question on SO there is reference made to the "data centric world view" versus the "process centric world view". Do you model the flow of information across an application or website(s) before you start to perform logical data modeling and physical data modeling? Or do these phrases refer to something different?

What tools might you use for modeling the different types of information?

答:
The future proofing of models is different from the future proofing of implementations.

Here are some models I have used.

```<code>Data models:
    Analysis model (conceptual):  Entity-Relationship modeling
    Design model (logical):  Relational Data Model
    Implementation model (physical):  DBMS specific model

Application models:
    Object Model:  governs messaging among component objects.
    Dynamic Model:  governs states, events, and transitions within an object.
    Functional Model:  governs transformations and computations.
</code>```

Models are important for what they leave out, as well as for what they leave in.  Don't try to anticipate everything, but don't paint yourself into a corner either.  Learn from the experience of others, then learn from your own experience.

Body:
The future proofing of models is different from the future proofing of implementations.

Here are some models I have used.

Data models:
    Analysis model (conceptual):  Entity-Relationship modeling
    Design model (logical):  Relational Data Model
    Implementation model (physical):  DBMS specific model

Application models:
    Object Model:  governs messaging among component objects.
    Dynamic Model:  governs states, events, and transitions within an object.
    Functional Model:  governs transformations and computations.

Models are important for what they leave out, as well as for what they leave in.  Don't try to anticipate everything, but don't paint yourself into a corner either.  Learn from the experience of others, then learn from your own experience.

ContentLicense: CC BY-SA 2.5


问:
Using Custom Authentication on Wowza Client Requests
Is it possible to use custom authentication, wherein each request for a stream is authenticated from my database and then a user is allowed to view a stream?

I've configured Wowza IDE for custom authentication using the following:

Integrating Wowza User Authentication with External Authentication

but I do not know exactly where this works? As in how do I make a request for a stream with authentication credentials that are eventually checked by this module's logic?

I am new to Wowza and Video Streaming as well.

Any help is appreciated.

答: take a look into documentation, perhaps there is something more convenient, like flussonic authentication mechanism that will just send HTTP request once per some time.</p>


问:
Excel Auto Customize Status Bar not summing up
All,

I am using MS Excel 2016. While highlighting a particular column MS Excel doesn't sum up values in the toolbar. I have checked the setting and sum and other values have been check marked. My column is Text format but changing it to any other format such as Number or General doesn't help.

Any hints/ideas ?

答: At the the lower left hand corner of the Green excel border there is a word "Ready". Point mouse-right click-check "Sum" (this is about 75% down the drop down menu</p>


问:
How do I stack bootstrap grid columns one below the other instead of one beside another?
I am just beginning to learn Bootstrap and I came across the grid system. I was playing around and noticed that the grid columns always start from the left and go towards the right, placing the divs one beside another. How do I make them appear one below the other?
Here's some sample code:

```<code><body>

<div class="container-fluid">
  <h2>Three Equal Columns</h2>
  <div class="row">
    <div class="col-4 bg-success">.col-1</div>
    <div class="col-4 bg-warning">.col-2</div>
    <div class="col-4 bg-success">.col-3</div>
  </div>
</div>

</body>
</code>```

Here's a fiddle.
https://jsfiddle.net/txdqjf8b/2/

How do I make col-1, col-2 and col-3 appear one below the other, so that later if I have a col-4, col-5 and col-6, I want them like this:

```<code>col-1    col-4    col-7
col-2    col-5    col-8
col-3    col-6    col-9
</code>```

答:
In bootstrap 4, there is a option of ordering your elements using order-lg/md/sm/xs-1 like below.

```<code><div class="col-md-4 order-md-1 bg-success">.col-1</div>
<div class="col-md-4 order-md-4 bg-warning">.col-2</div>
<div class="col-md-4 order-md-7 bg-success">.col-3</div>
<div class="col-md-4 order-md-2 bg-success">.col-4</div>
<div class="col-md-4 order-md-5 bg-warning">.col-5</div>
<div class="col-md-4 order-md-8 bg-success">.col-6</div>
<div class="col-md-4 order-md-3 bg-success">.col-7</div>
<div class="col-md-4 order-md-6 bg-warning">.col-8</div>
<div class="col-md-4 order-md-9 bg-success">.col-9</div>
</code>```

I have updated your fiddle. Here is the DEMO

You can get more clarity in docs https://v4-alpha.getbootstrap.com/utilities/flexbox/#order

The above code I have done it for applying only medium size screens. Like that way you can decide your order for large and small screen. Suppose if you want to apply commonly then use order-1 like below.

```<code><div class="col-4 order-1 bg-success">.col-1</div>
<div class="col-4 order-4 bg-warning">.col-2</div>
<div class="col-4 order-7 bg-success">.col-3</div>
<div class="col-4 order-2 bg-success">.col-4</div>
<div class="col-4 order-5 bg-warning">.col-5</div>
<div class="col-4 order-8 bg-success">.col-6</div>
<div class="col-4 order-3 bg-success">.col-7</div>
<div class="col-4 order-6 bg-warning">.col-8</div>
<div class="col-4 order-9 bg-success">.col-9</div>
</code>```

Here is the DEMO

Body:
I am just beginning to learn Bootstrap and I came across the grid system. I was playing around and noticed that the grid columns always start from the left and go towards the right, placing the divs one beside another. How do I make them appear one below the other?
Here's some sample code:

Three Equal Columns

.col-1

.col-2

.col-3

Here's a fiddle.
https://jsfiddle.net/txdqjf8b/2/

How do I make col-1, col-2 and col-3 appear one below the other, so that later if I have a col-4, col-5 and col-6, I want them like this:

col-1    col-4    col-7
col-2    col-5    col-8
col-3    col-6    col-9

Body:
In bootstrap 4, there is a option of ordering your elements using order-lg/md/sm/xs-1 like below.

<div class="col-md-4 order-md-1 bg-success">.col-1</div>
<div class="col-md-4 order-md-4 bg-warning">.col-2</div>
<div class="col-md-4 order-md-7 bg-success">.col-3</div>
<div class="col-md-4 order-md-2 bg-success">.col-4</div>
<div class="col-md-4 order-md-5 bg-warning">.col-5</div>
<div class="col-md-4 order-md-8 bg-success">.col-6</div>
<div class="col-md-4 order-md-3 bg-success">.col-7</div>
<div class="col-md-4 order-md-6 bg-warning">.col-8</div>
<div class="col-md-4 order-md-9 bg-success">.col-9</div>

I have updated your fiddle. Here is the DEMO

You can get more clarity in docs https://v4-alpha.getbootstrap.com/utilities/flexbox/#order

The above code I have done it for applying only medium size screens. Like that way you can decide your order for large and small screen. Suppose if you want to apply commonly then use order-1 like below.

<div class="col-4 order-1 bg-success">.col-1</div>
<div class="col-4 order-4 bg-warning">.col-2</div>
<div class="col-4 order-7 bg-success">.col-3</div>
<div class="col-4 order-2 bg-success">.col-4</div>
<div class="col-4 order-5 bg-warning">.col-5</div>
<div class="col-4 order-8 bg-success">.col-6</div>
<div class="col-4 order-3 bg-success">.col-7</div>
<div class="col-4 order-6 bg-warning">.col-8</div>
<div class="col-4 order-9 bg-success">.col-9</div>

Here is the DEMO


问:
Python regex: How to make a group of words/character optional?
I am trying to make regex that can match all of them:

word

word-hyphen

word-hyphen-again

that is -\w+could be many depends on words in a term. How can I make it optional

Thing I made so far is given here:- https://regex101.com/r/Atpwze/1

答:
Try using

\w+(-\w+)* for matching 0 or more hyphenated words after first word

\w+(-\w+){0,} same as first case

based on your exact requirement.

In order to eliminate some extreme cases like a-+-+---, you could use \w+(-\w+)*[^\W]

\W matches all non-word characters and ^\W negates the matching of non-word characters


问:
ReCall iframe after setInterval

I wish popup box (iframe colorbox) keep available even after setInterval running. But in fact, only the first iframe actually can pop up, the next after 2 seconds, bring me to my requested page. (sorry for bad english)

```<code>        <script type="text/javascript">
          $(document).ready(function(){

            $("#iframe").colorbox({iframe:true, width:"400px", height:"600px"});

            var refreshId = setInterval(function() {
             $('#chatting').load("<?php echo current_url() ?> #chatting") ;
             $("#iframe").colorbox({iframe:true, width:"400px", height:"600px"});
            }, 2000);

          });
        </script>

           <div id="chatting">
                <li class="chat-list">
                    <div class="chat-body">
                        <a id="iframe"href="intern/public_chat/test.php">XXX</a>
                    </div>
                </li>
            </div>
</code>```

I need every reload time (2 seconds as setinterval), updated value keep can using iframe colorbox.

But only it's always bring me to my requested page but not in pop up box.

答:
```<code> <script type="text/javascript">
  $(document).ready(function(){

    $("#iframe").colorbox({iframe:true, width:"500px", height:"600px"});

    var refreshId = setInterval(function() {
     $('#chatting').load("<?php echo current_url() ?> #chatting", function() {
         $("#iframe").colorbox({iframe:true, width:"500px", height:"600px"});
     }) ;
    }, 2000);

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

Title: ReCall iframe after setInterval

Body:
I wish popup box (iframe colorbox) keep available even after setInterval running. But in fact, only the first iframe actually can pop up, the next after 2 seconds, bring me to my requested page. (sorry for bad english)

                        XXX

I need every reload time (2 seconds as setinterval), updated value keep can using iframe colorbox.

But only it's always bring me to my requested page but not in pop up box.


问:
How to debug status ORA-28500 ("relation `X` does not exist") in Oracle?
```<code>select "gt.shiftkerja","i.jenis","i.konsinyasi","gp.group" from "tbl_ikhd gt"@PG
join "tbl_ikdt dt"@PG on "gt.notransaksi"="dt.notransaksi"
join "tbl_item i"@PG on "dt.kodeitem"="i.kodeitem"
LEFT JOIN "group_posting gp"@PG on "gp.kode_group"="i.jenis"and "gp.konsinyasi"="i.konsinyasi"
where to_char("gt.tanggal", 'YYYY-MM-DD')='2017-09-08' group by "gt.shiftkerja","i.jenis","i.konsinyasi","gp.group" order by "gt.shiftkerja","gp.group";
</code>```

this my error

status: ORA-28500: connection from ORACLE to a non-Oracle system
  returned this message: ERROR: relation "group_posting gp" does not
  exist; No query has been executed with that handle {42P01,NativeErr =
  1} ORA-02063: preceding 3 lines from PG

答:
You need to remove all the quotation marks from your query. Some of these are especially bad, e.g.

```<code>FROM "tbl_ikhd gt"
</code>```

What that is attempting to say is find a table with EXACTLY that name (including the space), that should read like this:

```<code>FROM tbl_ikhd gt
</code>```

Now the table name is tbl_ikhd and the alias for that table is gt.

So after removing all quotations and it should look like this:

```<code>SELECT
      gt.shiftkerja
    , i.jenis
    , i.konsinyasi
    , gp.group
FROM tbl_ikhd gt
JOIN tbl_ikdt dt ON gt.notransaksi = dt.notransaksi
JOIN tbl_item i ON dt.kodeitem = i.kodeitem
LEFT JOIN group_posting gp ON gp.kode_group = i.jenis AND gp.konsinyasi = i.konsinyasi
WHERE to_char(gt.tanggal, 'YYYY-MM-DD') = '2017-09-08'
GROUP BY
      gt.shiftkerja
    , i.jenis
    , i.konsinyasi
    , gp.group
ORDER BY
      gt.shiftkerja
    , gp.group;
</code>```

BUT please change the way you filter for the date. Currently you are changing every row of data by the function to_char. This removes access to an index on the date column. A better way is to just alter the way you filter the data so the data remains unaffected by functions, like this:

```<code>WHERE gt.tanggal >= to_date('2017-09-08', 'YYYY-MM-DD')
AND gt.tanggal < to_date('2017-09-09', 'YYYY-MM-DD')
</code>```

Body:
select "gt.shiftkerja","i.jenis","i.konsinyasi","gp.group" from "tbl_ikhd gt"@PG
join "tbl_ikdt dt"@PG on "gt.notransaksi"="dt.notransaksi"
join "tbl_item i"@PG on "dt.kodeitem"="i.kodeitem"
LEFT JOIN "group_posting gp"@PG on "gp.kode_group"="i.jenis"and "gp.konsinyasi"="i.konsinyasi"
where to_char("gt.tanggal", 'YYYY-MM-DD')='2017-09-08' group by "gt.shiftkerja","i.jenis","i.konsinyasi","gp.group" order by "gt.shiftkerja","gp.group";

this my error

status: ORA-28500: connection from ORACLE to a non-Oracle system
  returned this message: ERROR: relation "group_posting gp" does not
  exist; No query has been executed with that handle {42P01,NativeErr =
  1} ORA-02063: preceding 3 lines from PG

Body:
You need to remove all the quotation marks from your query. Some of these are especially bad, e.g.

FROM "tbl_ikhd gt"

What that is attempting to say is find a table with EXACTLY that name (including the space), that should read like this:

FROM tbl_ikhd gt

Now the table name is tbl_ikhd and the alias for that table is gt.

So after removing all quotations and it should look like this:

SELECT
      gt.shiftkerja
    , i.jenis
    , i.konsinyasi
    , gp.group
FROM tbl_ikhd gt
JOIN tbl_ikdt dt ON gt.notransaksi = dt.notransaksi
JOIN tbl_item i ON dt.kodeitem = i.kodeitem
LEFT JOIN group_posting gp ON gp.kode_group = i.jenis AND gp.konsinyasi = i.konsinyasi
WHERE to_char(gt.tanggal, 'YYYY-MM-DD') = '2017-09-08'
GROUP BY
      gt.shiftkerja
    , i.jenis
    , i.konsinyasi
    , gp.group
ORDER BY
      gt.shiftkerja
    , gp.group;

BUT please change the way you filter for the date. Currently you are changing every row of data by the function to_char. This removes access to an index on the date column. A better way is to just alter the way you filter the data so the data remains unaffected by functions, like this:

WHERE gt.tanggal >= to_date('2017-09-08', 'YYYY-MM-DD')
AND gt.tanggal < to_date('2017-09-09', 'YYYY-MM-DD')


问:
Changing .exe icon and get error message: python.exe has stopped working
Python.exe has stopped working during the compilation with py2exe. I used the following command to change the icon for my .exe python script, but python.exe hang and stopped working.

```<code>setup(
      console = [
      {
        "script": "CreateFile.py",
        "icon_resources": [(1, "Capture.ico")]
      }
     ]
)
</code>```

It hangs after this line in cmd prompt:
* copy extensions
 copy dlls *
copying C:\Python27\lib\site-packages\py2exe\run_w.exe -> C:\Users\PycharmProjects\exercise1\dist\CreateFile.exe

I have gone through many forum threads and tried many ways but still couldn't figure out why the hang is happening. Can anyone help? Thanks.

答:
why is there a "1" in
[(1, "Capture.ico")]</p>

Body:
Python.exe has stopped working during the compilation with py2exe. I used the following command to change the icon for my .exe python script, but python.exe hang and stopped working.

setup(
      console = [
      {
        "script": "CreateFile.py",
        "icon_resources": [(1, "Capture.ico")]
      }
     ]
)

It hangs after this line in cmd prompt:
* copy extensions
 copy dlls *
copying C:\Python27\lib\site-packages\py2exe\run_w.exe -> C:\Users\PycharmProjects\exercise1\dist\CreateFile.exe

I have gone through many forum threads and tried many ways but still couldn't figure out why the hang is happening. Can anyone help? Thanks.


问:
Time Complexity of Fibonacci Algorithm
So, i've got a recursive method in Java for getting the 'n'th fibonacci number - The only question i have, is: what's the time complexity? I think it's O(2^n), but i may be mistaken? (I know that iterative is way better, but it's an exercise)</p>

```<code>public int fibonacciRecursive(int n)
{
    if(n == 1 || n == 2) return 1;
    else return fibonacciRecursive(n-2) + fibonacciRecursive(n-1);
}
</code>```

答: It's easy to see (and to prove by induction) that the total number of calls to fibonacciRecursive is exactly equal to the final value returned. That is indeed exponential in the input number.</p>

Title: Time Complexity of Fibonacci Algorithm

Body:
So, i've got a recursive method in Java for getting the 'n'th fibonacci number - The only question i have, is: what's the time complexity? I think it's O(2^n), but i may be mistaken? (I know that iterative is way better, but it's an exercise)

public int fibonacciRecursive(int n)
{
    if(n == 1 || n == 2) return 1;
    else return fibonacciRecursive(n-2) + fibonacciRecursive(n-1);
}


问:
What is the difference between intermediate and terminal operations?
can someone tell me What is the difference between intermediate and terminal operations for Stream?

Stream operations are combined into pipelines to process streams. All operations are either intermediate or terminal ..means?.

答:
Terminal meaning ending the process, such as collecting a stream to a list, or aggregating a stream of values. </p>

<p>Intermediate as in transitioning to a new state, on the way to a terminal operation </p>

Body:
Terminal meaning ending the process, such as collecting a stream to a list, or aggregating a stream of values.

Intermediate as in transitioning to a new state, on the way to a terminal operation


问:
Getting rows from multiple table - PHP and loop
I'm trying to search for all the parent category of child category from 2 tables

Sample database

```<code>table1                            table2
+------------+-------------+      +------------+-------------+
|Categ_name  |Categ_parent |      |Temp_name   |Temp_parent  |
+------------+-------------+      +------------+-------------+
|Items       |0            |      |Cookware    |Kitchen      |
|House       |Item         |      |Utensils    |Cookware     |
|Car         |Item         |      +------------+-------------+
|Kitchen     |House        |
|Living Room |House        |
|Appliance   |Living Room  |
+------------+-------------+
</code>```

if I search for 'Utensils', hoping to get

Categories :

Cookware

Kitchen

House

Items

as a result but I'm a little confused with SQL.

```<code>$i='Utensils';

while($i!='0'){
  $sql="SELECT m.Categ_parent AS parent,t.Temp_parent AS parent, FROM table1 AS m,table2 AS t WHERE m.Categ_name='".$i."' OR t.Temp_name='".$i."' LIMIT 1";
  $result=mysqli_query($con,$sql);
  $row=mysqli_fetch_array($result);

  $i=$row['parent'];
  echo $i;
}
</code>```

I'm not getting any result or error from this code

答:
For repeatedly accessing the same table, you might be better off using a stored procedure.

```<code>## Create a view so that we can work more easily with the tables

create view items as select Categ_name as name, Categ_parent as parent from table1
  union (select Temp_name as name, Temp_parent as parent from table2);

name            parent
-------------------------
Item            0
House           Item
Car             Item
Kitchen         House
Living Room     House
Appliance       Living Room
Cookware        Kitchen
Utensils        Cookware

DROP PROCEDURE IF EXISTS selectName;
CREATE PROCEDURE selectName(IN currentName VARCHAR(100))
BEGIN
  drop temporary table if exists tmp_results;
  create temporary table tmp_results (
    name varchar(100)
  );

  while (exists(select parent from items where name = currentName)) DO
    select parent into currentName from items where name = currentName;
    insert into tmp_results select currentName;
  END WHILE;

  select * from tmp_results;
END;
</code>```

To use this procedure:

```<code>call selectName('Utensils');

Cookware
Kitchen
House
Item
0
</code>```

PHP code to initialize database (run the statements only ONCE to create the view and stored procedure):

```<code>// create view
$mysqli->query("
  drop view if exists viewItems;
  create view viewItems as select Categ_name as name, Categ_parent as parent from table1
    union (select Temp_name as name, Temp_parent as parent from table2)";
");

// create stored procedure
$mysqli->query("
  DROP PROCEDURE IF EXISTS selectParents;
  CREATE PROCEDURE selectParents(IN currentName VARCHAR(100))
  BEGIN
    drop temporary table if exists tmp_results;
    create temporary table tmp_results (
      name varchar(100)
    );

    while (exists(select parent from viewItems where name = currentName)) DO
      select parent into currentName from viewItems where name = currentName;
      insert into tmp_results select currentName;
    END WHILE;

    select * from tmp_results;
  END"
);
</code>```

PHP code to query

```<code>$name = mysqli_real_escape_string($name);
$results = $mysqli->query("CALL selectParents($name)");
</code>```

Body:
I'm trying to search for all the parent category of child category from 2 tables

Sample database

table1                            table2
+------------+-------------+      +------------+-------------+
|Categ_name  |Categ_parent |      |Temp_name   |Temp_parent  |
+------------+-------------+      +------------+-------------+
|Items       |0            |      |Cookware    |Kitchen      |
|House       |Item         |      |Utensils    |Cookware     |
|Car         |Item         |      +------------+-------------+
|Kitchen     |House        |
|Living Room |House        |
|Appliance   |Living Room  |
+------------+-------------+

if I search for 'Utensils', hoping to get

Categories :

Cookware

Kitchen

House

Items

as a result but I'm a little confused with SQL.

$i='Utensils';

while($i!='0'){
  $sql="SELECT m.Categ_parent AS parent,t.Temp_parent AS parent, FROM table1 AS m,table2 AS t WHERE m.Categ_name='".$i."' OR t.Temp_name='".$i."' LIMIT 1";
  $result=mysqli_query($con,$sql);
  $row=mysqli_fetch_array($result);

  $i=$row['parent'];
  echo $i;
}

I'm not getting any result or error from this code

Body:
For repeatedly accessing the same table, you might be better off using a stored procedure.

## Create a view so that we can work more easily with the tables

create view items as select Categ_name as name, Categ_parent as parent from table1
  union (select Temp_name as name, Temp_parent as parent from table2);

name            parent
-------------------------
Item            0
House           Item
Car             Item
Kitchen         House
Living Room     House
Appliance       Living Room
Cookware        Kitchen
Utensils        Cookware

DROP PROCEDURE IF EXISTS selectName;
CREATE PROCEDURE selectName(IN currentName VARCHAR(100))
BEGIN
  drop temporary table if exists tmp_results;
  create temporary table tmp_results (
    name varchar(100)
  );

  while (exists(select parent from items where name = currentName)) DO
    select parent into currentName from items where name = currentName;
    insert into tmp_results select currentName;
  END WHILE;

  select * from tmp_results;
END;

To use this procedure:

call selectName('Utensils');

Cookware
Kitchen
House
Item
0

PHP code to initialize database (run the statements only ONCE to create the view and stored procedure):

// create view
$mysqli->query("
  drop view if exists viewItems;
  create view viewItems as select Categ_name as name, Categ_parent as parent from table1
    union (select Temp_name as name, Temp_parent as parent from table2)";
");

// create stored procedure
$mysqli->query("
  DROP PROCEDURE IF EXISTS selectParents;
  CREATE PROCEDURE selectParents(IN currentName VARCHAR(100))
  BEGIN
    drop temporary table if exists tmp_results;
    create temporary table tmp_results (
      name varchar(100)
    );

    while (exists(select parent from viewItems where name = currentName)) DO
      select parent into currentName from viewItems where name = currentName;
      insert into tmp_results select currentName;
    END WHILE;

    select * from tmp_results;
  END"
);

PHP code to query

$name = mysqli_real_escape_string($name);
$results = $mysqli->query("CALL selectParents($name)");


问:
React-redux : listening to state changes to trigger action
I have my redux state like this:

```<code>{
  parks: [
    {
      _id:"ad1esdad",
      fullName : "Some Name"
    },
    {
      _id:"ad1es3s",
      fullName : "Some Name2"
    }
  ],
  parkInfo: {
    id : "search Id",
    start_time : "Some Time",
    end_time : "Some Time"
  }
}
</code>```

I have a parkSelector component from which a user selects parkId and start_time and end_time

```<code>import React, { Component } from 'react';
import { changeParkInfo } from '../../Actions';

class ParkSelector extends Component {

  constructor(props) {
    super(props);

    this.handleApply = this.handleApply.bind(this);
    this.rederOptions = this.rederOptions.bind(this);

    this.state = {
      startDate: moment().subtract(1, 'days'),
      endDate: moment(),
      parkId : this.props.parks[0]
    };
  }

  handleApply(event) {
    this.setState({
      parkId : event.target.parkId.value
      startDate: event.target.start_time.value,
      endDate: event.target.end_time.value,
    });
    this.props.changeParkInfo(this.state.parkId,this.state.startDate,this.state.endDate);
  }

  rederOptions(){
    return _.map(this.props.parks,(park,index)=>{
      return(
        <option value={park._id} key={park._id}>{park.profile.fullName}</option>
      );
    });
  }

  render() {

    return (
      <div className="row">
        <div className="pb-4 col-sm-3">
          <form onSubmit={this.handleApply}>
          <select name="parkId" value={this.state.parkId} className="form-control input-sm">
              {this.rederOptions()}
          </select>
          <input name="start_time" type="date" />
          <input name="end_time" type="date" />
          <button type="submit">Apply</button>
          </form>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    parks : state.parks
  };
}

export default connect(mapStateToProps,{ changeParkInfo })(ParkSelector);
</code>```

I have another component 'stats' which needs to displays information related with parkInfo which will be loaded my api request.

```<code>import React, { Component } from 'react';
import StatsCard from '../../components/StatsCard';
import { getDashboardStats } from '../../Actions';

class Dashboard extends Component {

  constructor(props) {
    super(props);
  }

  render() {

    return (
      <div className="animated fadeIn">
        <div className="row">
          <StatsCard text="Revenue Collected" value={9999} cardStyle="card-success" />
          <StatsCard text="Total Checkins" value={39} cardStyle="card-info" />
          <StatsCard text="Total Checkouts" value={29} cardStyle="card-danger" />
          <StatsCard text="Passes Issued" value={119} cardStyle="card-warning" />
        </div>

      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    parkInfo : state.parkInfo,
    dashboardStats : state.dashboardStats
  };
}

export default connect(mapStateToProps,{ getDashboardStats })(Dashboard);
</code>```

I need to call getDashboardStats action (which makes api call and stores in results in dashboardStats of the redux state) whenever the redux state of parkInfo changes.

What is the best way to call this action, I have tried componentWillUpdate but it keeps on updating infinitely. What is best practice for this scenario ?

答:
I think it should be this way:

Your component ParkSelector changes, you trigger the action via dispatch to changeParkInfo action.

This action does the AJAX and on it's success

1) you update the store state of parkInfo via another action.

2) you send getDashboardStats.

Now when point (2) is success, it will update the store state dashboardStats.

Next in your Dashboard you should not connect with parkInfo, reason: you are not using parkInfo in the dashboard.

Inside the dashboard component you should call action getDashboardStats  in componentDidMount() for loading up the dashboardStats for first time when component loads up.

The idea in nutshell is when data changes action should call the facade of actions and make the state change.

What you trying is trigger an action which changes state that goes into component via props that triggers another action so on.. thus there is a infinite loop as you have written the component action in componentWillUpdate.

Hope this clarifies your question.

Body:
I have my redux state like this:

{
  parks: [
    {
      _id:"ad1esdad",
      fullName : "Some Name"
    },
    {
      _id:"ad1es3s",
      fullName : "Some Name2"
    }
  ],
  parkInfo: {
    id : "search Id",
    start_time : "Some Time",
    end_time : "Some Time"
  }
}

I have a parkSelector component from which a user selects parkId and start_time and end_time

import React, { Component } from 'react';
import { changeParkInfo } from '../../Actions';

class ParkSelector extends Component {

  constructor(props) {
    super(props);

    this.handleApply = this.handleApply.bind(this);
    this.rederOptions = this.rederOptions.bind(this);

    this.state = {
      startDate: moment().subtract(1, 'days'),
      endDate: moment(),
      parkId : this.props.parks[0]
    };
  }

  handleApply(event) {
    this.setState({
      parkId : event.target.parkId.value
      startDate: event.target.start_time.value,
      endDate: event.target.end_time.value,
    });
    this.props.changeParkInfo(this.state.parkId,this.state.startDate,this.state.endDate);
  }

  rederOptions(){
    return _.map(this.props.parks,(park,index)=>{
      return(
        <option value={park._id} key={park._id}>{park.profile.fullName}</option>
      );
    });
  }

  render() {

    return (

          <form onSubmit={this.handleApply}>
          <select name="parkId" value={this.state.parkId} className="form-control input-sm">
              {this.rederOptions()}
          </select>
          <input name="start_time" type="date" />
          <input name="end_time" type="date" />
          <button type="submit">Apply</button>
          </form>

    )
  }
}

function mapStateToProps(state){
  return {
    parks : state.parks
  };
}

export default connect(mapStateToProps,{ changeParkInfo })(ParkSelector);

I have another component 'stats' which needs to displays information related with parkInfo which will be loaded my api request.

import React, { Component } from 'react';
import StatsCard from '../../components/StatsCard';
import { getDashboardStats } from '../../Actions';

class Dashboard extends Component {

  constructor(props) {
    super(props);
  }

  render() {

    return (

          <StatsCard text="Revenue Collected" value={9999} cardStyle="card-success" />
          <StatsCard text="Total Checkins" value={39} cardStyle="card-info" />
          <StatsCard text="Total Checkouts" value={29} cardStyle="card-danger" />
          <StatsCard text="Passes Issued" value={119} cardStyle="card-warning" />

    )
  }
}

function mapStateToProps(state){
  return {
    parkInfo : state.parkInfo,
    dashboardStats : state.dashboardStats
  };
}

export default connect(mapStateToProps,{ getDashboardStats })(Dashboard);

I need to call getDashboardStats action (which makes api call and stores in results in dashboardStats of the redux state) whenever the redux state of parkInfo changes.

What is the best way to call this action, I have tried componentWillUpdate but it keeps on updating infinitely. What is best practice for this scenario ?


问:
Ansible: copy a directory content to another directory
I am trying to copy the content of dist directory to nginx directory.

```<code>- name: copy html file
  copy: src=/home/vagrant/dist/ dest=/usr/share/nginx/html/
</code>```

But when I execute the playbook it throws an error:

```<code>TASK [NGINX : copy html file] **************************************************
fatal: [172.16.8.200]: FAILED! => {"changed": false, "failed": true, "msg": "attempted to take checksum of directory:/home/vagrant/dist/"}
</code>```

How can I copy a directory that has another directory and a file inside?

答:
This I found an ideal solution for copying file from Ansible server to remote.

copying  yaml file

```<code>- hosts: localhost
  user: {{ user }}
  connection: ssh
  become: yes
  gather_facts: no
  tasks:
   - name: Creation of directory on remote server
     file:
       path: /var/lib/jenkins/.aws
       state: directory
       mode: 0755
     register: result
   - debug:
       var: result

   - name: get file names to copy
     command: "find conf/.aws -type f"
     register: files_to_copy

   - name: copy files
     copy:
      src: "{{ item }}"
      dest: "/var/lib/jenkins/.aws"
      owner: {{ user }}
      group: {{ group }}
      remote_src: True
      mode: 0644
     with_items:
      - "{{ files_to_copy.stdout_lines }}"
</code>```

Body:
I am trying to copy the content of dist directory to nginx directory.

- name: copy html file
  copy: src=/home/vagrant/dist/ dest=/usr/share/nginx/html/

But when I execute the playbook it throws an error:

TASK [NGINX : copy html file] **************************************************
fatal: [172.16.8.200]: FAILED! => {"changed": false, "failed": true, "msg": "attempted to take checksum of directory:/home/vagrant/dist/"}

How can I copy a directory that has another directory and a file inside?

Body:
This I found an ideal solution for copying file from Ansible server to remote.

copying  yaml file

- hosts: localhost
  user: {{ user }}
  connection: ssh
  become: yes
  gather_facts: no
  tasks:
   - name: Creation of directory on remote server
     file:
       path: /var/lib/jenkins/.aws
       state: directory
       mode: 0755
     register: result
   - debug:
       var: result

   - name: get file names to copy
     command: "find conf/.aws -type f"
     register: files_to_copy

   - name: copy files
     copy:
      src: "{{ item }}"
      dest: "/var/lib/jenkins/.aws"
      owner: {{ user }}
      group: {{ group }}
      remote_src: True
      mode: 0644
     with_items:
      - "{{ files_to_copy.stdout_lines }}"


问:
UITextview edit mode in swift
I would like to edit some text in UITextview but whenever keyboard comes, it clear the previous text . I want to previous text on keyboard open as well.

Any one has idea how to do it in swift 3.0?

I am setting the string of UITextView in viewdidload

```<code>treatment.text = patient?.patientTreatment;
   func textViewDidBeginEditing(_ textView: UITextView)
{
    if textView.text != ""
    {
        textView.text = patient?.patientTreatment
    }
}
</code>```

I observed 1 thing here, My text is disappear once keyboard opens and comes back once keyboard closes.

答:
set placeholder in UITextView</p>

```<code>extension EditProfileVC:UITextViewDelegate{

    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.textColor == UIColor.lightGray {
            textView.text = nil
            textView.textColor = UIColor.black
        }
    }
    func textViewDidEndEditing(_ textView: UITextView) {
        if textView.text.isEmpty {
            textView.text = "Placeholder"
            textView.textColor = UIColor.lightGray
        }
    }
}
</code>```

Title: UITextview edit mode in swift

Body:
I would like to edit some text in UITextview but whenever keyboard comes, it clear the previous text . I want to previous text on keyboard open as well.

Any one has idea how to do it in swift 3.0?

I am setting the string of UITextView in viewdidload

treatment.text = patient?.patientTreatment;
   func textViewDidBeginEditing(_ textView: UITextView)
{
    if textView.text != ""
    {
        textView.text = patient?.patientTreatment
    }
}

I observed 1 thing here, My text is disappear once keyboard opens and comes back once keyboard closes.

Body:
set placeholder in UITextView

extension EditProfileVC:UITextViewDelegate{

    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.textColor == UIColor.lightGray {
            textView.text = nil
            textView.textColor = UIColor.black
        }
    }
    func textViewDidEndEditing(_ textView: UITextView) {
        if textView.text.isEmpty {
            textView.text = "Placeholder"
            textView.textColor = UIColor.lightGray
        }
    }
}


问:
MS BotFramework Temporary token issue in WebChat URL
I have developed a chatbot using Microsoft BotFramework and node.js and deployed it in webchat. As per this documentation, it is written that the bot's secret 's' can be replaced with a temporary token 't' which is valid for one conversation only.

But the problem is the life span of this token is 30 minutes and within this time window, if some intruder accesses the entire URL: "https://webchat.botframework.com/embed/YOUR_BOT_ID?t=YOUR_TOKEN_HERE&userid=some_user_id" then it is just a child’s play for him to get all of the user’s data because it mimics the chat of the actual user in the other machine.

Is there anything in the BotFramework (apart from DirectLine) that can be done that restricts the URL with the same token to be opened in another machine?

答:
There is an issue on GH which is facing the same event with you, and with the comments, we can found that this situation will not be changed currently.

However, we can get some hints from the comment:

Ultimately, you can't hide the secret/token from clients.

If you want to remove it from the URL, you can host the JS control on your own.

If you want to remove it from page source, you can pass the value in a cookie >and read it in JS in your webpage.

However, in all cases, the value will be available in memory.

I think you can build another simple web site yourself as the bridge from the iframe and yout bot application. You can restrict your user whether is unique in this website's session. And also you can verify your user before instantiate the Bot WebChat.


问:
Cannot access opened port in AWS from outside
I have developed an Angular 4 app inside my AWS instance. instance base image is windows. my Angular app runs on port 7000 inside the AWS instance. then I opened the port 7000 from security group using AWS Console and with the firewall using AWS instance. but I cannot access or see it from outside as publicly. it is running properly inside the instance on port 7000. What did I do wrong, or are there many more steps to achieve this. hope your help with this,

答:
Would be helpful if you posted most details. What does your security group look like? Are you also using a Load Blanceer?

Try setting your inbound to 0.0.0.0/0 (not recommended) or select "My IP" and try to access your instance via IP port ip-address:7000.

Cheers!


问:
Send array to function, multiply each variable by 2, return array c#
i am tryin to make a function that takes an array and multiples each of its values by 2, then returns each multiplied value in a new array, so I can write out the individual values of the original array and the new multiplied one.
IE, an array with 2, 4, and 6, I want to make a function that takes it, then multiplies each value by 2, then return a new array that has 4, 6, and 8.

Here is my function

```<code>public static int[] ArrayFunction(int[] array)
{
     int multiply = 0;
     foreach(int i in array)
     {
         multiply = i*2;
     }
    int[] multiArray = new int[] {multiply}
return multiArray;
}
</code>```

I'm just trying to return an array with each value of the original array multiplied by 2.

答:
Try this:

you can use ToArray.

ToArray(IEnumerable) method forces immediate query
  evaluation and returns an array that contains the query results. You
  can append this method to your query in order to obtain a cached copy
  of the query results.
  for more see Here

```<code>public static int[] ArrayFunction(int[] array)
{
    return array.Select(i=>i*2).ToArray();
}
</code>```

Body:
i am tryin to make a function that takes an array and multiples each of its values by 2, then returns each multiplied value in a new array, so I can write out the individual values of the original array and the new multiplied one.
IE, an array with 2, 4, and 6, I want to make a function that takes it, then multiplies each value by 2, then return a new array that has 4, 6, and 8.

Here is my function

public static int[] ArrayFunction(int[] array)
{
     int multiply = 0;
     foreach(int i in array)
     {
         multiply = i*2;
     }
    int[] multiArray = new int[] {multiply}
return multiArray;
}

I'm just trying to return an array with each value of the original array multiplied by 2.

Body:
Try this:

you can use ToArray.

ToArray(IEnumerable) method forces immediate query
  evaluation and returns an array that contains the query results. You
  can append this method to your query in order to obtain a cached copy
  of the query results.
  for more see Here

public static int[] ArrayFunction(int[] array)
{
    return array.Select(i=>i*2).ToArray();
}


问:
What is the difference between a Rule and a Policy
in the context of a database, we sometimes need to check values against some statements like "the customer name is non-empty" or "the customer number of purchases is positive"...

But do such statements constitute rules or policies ?

In general how would you define these concepts, their differences and relations ?

Thanks in advance.

答:
I think I know what you're talking about; I've run into such distinctions before (even though the English words are not all that different) and here is how I think it plays out in most business computing areas.

A rule in such a context is something that--whether it's a structural fact or a business-imposed statement--will not change, or at least stands only a very small chance of changing.  Most statements of the form "X cannot be null" represent rules.  "Null" typically doesn't make much sense to a business user; usually you arrive at these rules by examining the way that your model is constructed.  A change to a rule has far-reaching consequences to the way that your database and any supporting applications are built.

A policy is more like a business instruction.  Preferred customers get 10% off may be a policy, but as you know, things like this tend to change.  A change to a policy may impact the way your application works, but not its fundamental architecture or underpinnings.

Pragmatically speaking--and it sounds like you may already know this--you want to make policies relatively easy to change.  Rules, while they may change, are typically more involved: changing a rule often requires changing code, UIs, mental models, ways of thought, and so on.

I hope this helps.


问:
undefined reference to a pointer in c
I'm trying to run my program, but it keeps giving an error.

I have 3 files and will include the code from one of the 3 functions that are not working.

File: contacts.h

```<code>struct Name{
    char firstName[31];
    char middleInitial[7];
    char lastName[36];
};

struct Contact{
    struct Name name;
};

// function prototype:
void getName(struct Name *);
</code>```

File: contacts.c

```<code>#include <stdio.h>
#include “contacts.h”

void getName(struct Name *name)
{
    printf(“Please enter the contact’s first name: “);
    scanf(“%30[&\n]”, name->firstName);
}
</code>```

File:a1ms4.c

```<code>#include <stdio.h>
#include “contacts.h”

int main(void)
{
    struct Contact contact = { {0} };
    getName(&contect.name);
    printf(“Contact first name: %s\n”, contact.name.firstName);

    return 0;
}
</code>```

Any idea why I'm getting this error:

```<code>a1ms4.c:(.text+0x53): undefined reference to `getName'
</code>```

答:
I just hope

```<code>#include “contacts.h”
</code>```

is actually

```<code>#include "contacts.h"
</code>```

Remember, ” is not the same as "

The same goes for this one:

```<code>scanf(“%30[&\n]”, name->firstName);
</code>```

and these too:

```<code>printf(“Please enter the contact’s first name: “);
printf(“Contact first name: %s\n”, contact.name.firstName);
</code>```

Make sure that there is only one version of contacts.h in your include path and you have included the exact file you intend to.

Title: undefined reference to a pointer in c

Body:
I'm trying to run my program, but it keeps giving an error.

I have 3 files and will include the code from one of the 3 functions that are not working.

File: contacts.h

struct Name{
    char firstName[31];
    char middleInitial[7];
    char lastName[36];
};

struct Contact{
    struct Name name;
};

// function prototype:
void getName(struct Name *);

File: contacts.c

#include <stdio.h>
#include “contacts.h”

void getName(struct Name *name)
{
    printf(“Please enter the contact’s first name: “);
    scanf(“%30[&\n]”, name->firstName);
}

File:a1ms4.c

#include <stdio.h>
#include “contacts.h”

int main(void)
{
    struct Contact contact = { {0} };
    getName(&contect.name);
    printf(“Contact first name: %s\n”, contact.name.firstName);

    return 0;
}

Any idea why I'm getting this error:

a1ms4.c:(.text+0x53): undefined reference to `getName'

Body:
I just hope

#include “contacts.h”

is actually

#include "contacts.h"

Remember, ” is not the same as "

The same goes for this one:

scanf(“%30[&\n]”, name->firstName);

and these too:

printf(“Please enter the contact’s first name: “);
printf(“Contact first name: %s\n”, contact.name.firstName);

Make sure that there is only one version of contacts.h in your include path and you have included the exact file you intend to.


问:
Pass response of one http request to another Synchronously in Node.js
I want to Pass response of one http request to another Synchronously ,
Have three conditions to execute one by one  PreExecute(),OnExecute() and PostExecute() .

Each of the above will send http request to a URL and returns a json which should be the input to the next module .How to achieve this in Node.js

答:
Use waterfall from async library. You can work something like this

```<code>var request = require('request');
var async = require('async');

async.waterfall([
  function (callback) { //PreExecute
    request('http://www.google.com', function (error, response, body) {
      callback(null, 'one', 'two');
    });
  },
  function (arg1, arg2, callback) { //OnExecute
    request('http://www.google.com', function (error, response, body) {
      // arg1 now equals 'one' and arg2 now equals 'two'
      callback(null, 'three');
    });
  },
  function (arg1, callback) { // PostExecute
    request('http://www.google.com', function (error, response, body) {
      // arg1 now equals 'three'
      callback(null, 'done');
    });
  }
], function (err, result) { // Finally
  // result now equals 'done'
});
</code>```

Body:
Use waterfall from async library. You can work something like this

var request = require('request');
var async = require('async');

async.waterfall([
  function (callback) { //PreExecute
    request('http://www.google.com', function (error, response, body) {
      callback(null, 'one', 'two');
    });
  },
  function (arg1, arg2, callback) { //OnExecute
    request('http://www.google.com', function (error, response, body) {
      // arg1 now equals 'one' and arg2 now equals 'two'
      callback(null, 'three');
    });
  },
  function (arg1, callback) { // PostExecute
    request('http://www.google.com', function (error, response, body) {
      // arg1 now equals 'three'
      callback(null, 'done');
    });
  }
], function (err, result) { // Finally
  // result now equals 'done'
});


问:
qtWebengineProcess fails to start
I am deploying my app and getting some really cryptic messages.
I have read around and thought that it might be some issues with permissions, even apparmor. My other suspect is something missing but is unclear what, I run the application with strace and at first look nothing seems to be missing.

The build system is able to run the application but the destination machine where i am testing the install doesn't.

Here is the output:

```<code>LaunchProcess: failed to execvp:
/opt/Stremio/libexec/QtWebEngineProcess
[7511:7511:0131/125813:FATAL:zygote_host_impl_linux.cc(182)] Check failed: ReceiveFixedMessage(fds[0], kZygoteBootMessage, sizeof(kZygoteBootMessage), &boot_pid).
#0 0x7f1f9afa400e <unknown>
#1 0x7f1f9afb70ce <unknown>
#2 0x7f1f9b54ae33 <unknown>
#3 0x7f1f9b549b2b <unknown>
#4 0x7f1f9b54a0ce <unknown>
#5 0x7f1f9b5c1a69 <unknown>
#6 0x7f1f9b3cb373 <unknown>
#7 0x7f1f99e69d32 <unknown>
#8 0x7f1f99e6af45 <unknown>
#9 0x7f1f99e0cf31 QtWebEngineCore::BrowserContextAdapter::defaultContext()
#10 0x7f1f9f581938 QQuickWebEngineProfile::defaultProfile()
#11 0x7f1f9f58769a QQuickWebEngineViewPrivate::QQuickWebEngineViewPrivate()
#12 0x7f1f9f58842b QQuickWebEngineView::QQuickWebEngineView()
#13 0x7f1f7b138460 <unknown>
#14 0x7f1f97dce68a QQmlType::create()
#15 0x7f1f97e35680 <unknown>
#16 0x7f1f97e37dfe <unknown>
#17 0x7f1f97e382ae <unknown>
#18 0x7f1f97e34be2 <unknown>
#19 0x7f1f97e35959 <unknown>
#20 0x7f1f97e36502 <unknown>
#21 0x7f1f97dbbf24 QQmlComponentPrivate::beginCreate()
#22 0x7f1f97db9619 QQmlComponent::create()
#23 0x7f1f97e2a8bb QQmlApplicationEnginePrivate::_q_finishLoad()
#24 0x7f1f97e2aaa2 QQmlApplicationEnginePrivate::startLoad()
#25 0x7f1f97e2aadd QQmlApplicationEngine::load()
#26 0x00000040d969 main
#27 0x7f1f96789830 __libc_start_main
#28 0x00000040dbe9 _start

Aborted (core dumped)
</code>```

答:
As you had noted above, i tried giving permissions to the project folder and all its subfolders and files. Worked like magic.

```<code>chmod -R <permissionsettings> <dirname>
</code>```

For instance, i ran this:

```<code>chmod -R 755 <dirname>
</code>```

Then try testing the install again.

Title: qtWebengineProcess fails to start

Body:
I am deploying my app and getting some really cryptic messages.
I have read around and thought that it might be some issues with permissions, even apparmor. My other suspect is something missing but is unclear what, I run the application with strace and at first look nothing seems to be missing.

The build system is able to run the application but the destination machine where i am testing the install doesn't.

Here is the output:

LaunchProcess: failed to execvp:
/opt/Stremio/libexec/QtWebEngineProcess
[7511:7511:0131/125813:FATAL:zygote_host_impl_linux.cc(182)] Check failed: ReceiveFixedMessage(fds[0], kZygoteBootMessage, sizeof(kZygoteBootMessage), &boot_pid).
#0 0x7f1f9afa400e <unknown>
#1 0x7f1f9afb70ce <unknown>
#2 0x7f1f9b54ae33 <unknown>
#3 0x7f1f9b549b2b <unknown>
#4 0x7f1f9b54a0ce <unknown>
#5 0x7f1f9b5c1a69 <unknown>
#6 0x7f1f9b3cb373 <unknown>
#7 0x7f1f99e69d32 <unknown>
#8 0x7f1f99e6af45 <unknown>
#9 0x7f1f99e0cf31 QtWebEngineCore::BrowserContextAdapter::defaultContext()
#10 0x7f1f9f581938 QQuickWebEngineProfile::defaultProfile()
#11 0x7f1f9f58769a QQuickWebEngineViewPrivate::QQuickWebEngineViewPrivate()
#12 0x7f1f9f58842b QQuickWebEngineView::QQuickWebEngineView()
#13 0x7f1f7b138460 <unknown>
#14 0x7f1f97dce68a QQmlType::create()
#15 0x7f1f97e35680 <unknown>
#16 0x7f1f97e37dfe <unknown>
#17 0x7f1f97e382ae <unknown>
#18 0x7f1f97e34be2 <unknown>
#19 0x7f1f97e35959 <unknown>
#20 0x7f1f97e36502 <unknown>
#21 0x7f1f97dbbf24 QQmlComponentPrivate::beginCreate()
#22 0x7f1f97db9619 QQmlComponent::create()
#23 0x7f1f97e2a8bb QQmlApplicationEnginePrivate::_q_finishLoad()
#24 0x7f1f97e2aaa2 QQmlApplicationEnginePrivate::startLoad()
#25 0x7f1f97e2aadd QQmlApplicationEngine::load()
#26 0x00000040d969 main
#27 0x7f1f96789830 __libc_start_main
#28 0x00000040dbe9 _start

Aborted (core dumped)

Body:
As you had noted above, i tried giving permissions to the project folder and all its subfolders and files. Worked like magic.

chmod -R <permissionsettings> <dirname>

For instance, i ran this:

chmod -R 755 <dirname>

Then try testing the install again.


答:
at first the SQL you wrote has an error which is the "," before "from ...".

I suggest using UNION instead of the current SQL command. The current command will mix two parent values and one of which may not be right.

Try the following solution, which works good on my computer:

```<code>$i='Utensils';

while($i!='0'){

$sql="(SELECT Categ_parent as parent from table1 WHERE Categ_name='".$i."')
        UNION
        (SELECT  Temp_parent as parent from table2 where Temp_name='".$i."')";

$result = mysqli_query($con,$sql);
if($result && mysqli_num_rows($result)){
    $row = mysqli_fetch_array($result);
    $i = $row["parent"];
}
else{
    $i = '0';
}

echo $i."<br>";
}
</code>```

Title: Getting rows from multiple table - PHP and loop

Body:
at first the SQL you wrote has an error which is the "," before "from ...".

I suggest using UNION instead of the current SQL command. The current command will mix two parent values and one of which may not be right.

Try the following solution, which works good on my computer:

$i='Utensils';

while($i!='0'){

$sql="(SELECT Categ_parent as parent from table1 WHERE Categ_name='".$i."')
        UNION
        (SELECT  Temp_parent as parent from table2 where Temp_name='".$i."')";

$result = mysqli_query($con,$sql);
if($result && mysqli_num_rows($result)){
    $row = mysqli_fetch_array($result);
    $i = $row["parent"];
}
else{
    $i = '0';
}

echo $i."<br>";
}


问:
Which one to use: Java Swing or GTK+ for GNOME desktop application?
I am considering developing a GNOME desktop application with a graphical user interface. I know GTK+ is the first choice, especially when developing for the GNOME environment. End users also consider GTK+ as the first choice for applications they use. I am, however, considering future improvements: what if my application will need a port to another environments or OS like KDE or Mac or Windows? Which is the best way to go: Java Swing (because it's platform independent) or GTK+?</p>

答:
The answer depends on what you actually want.

GTK library is native in the Gnome environment: if you want to develop an application thought for Gnome, use GTK.

If you are not so much interested in giving a native feel to the Gnome users then use whatever you want (GTK, Swing, Qt, wx ...).

By the way if you want my personal opinion, I prefer GTK a lot. I personally don't like Swing, especially when it tries to emulate GTK look and feel.


问:
Android device not recognizing
I'm trying run android apk in Huawei tablet. In Android studio shows the connected device as none. In Hisuite also displays as Device not connected. But the device appears in device manager and I can access the data inside device through PC. adb not recognize.

Device - HUAWEI Mediapad T3 10(Android 7.0)

PC OS- Windows 7

Android Studio 2.3.3

HiSuite 5.0.1.300_OVE

答:
Enable Developer Options. In Developer Options enable USB Debugging.

Make Sure that Google USB Driver and ADB is installed

Change USB Mode to MTP

After Connecting to Allow Computer Enable USB Debugging on this Computer dialog will appear. Allow it .

After that Notification Window will show  USB Debbuging is Enabled  whenever you connect via USB on to the System. If it is not Shown Download the Phones Driver for the System. Because the System may Be Lacking the Corresponding device Driver.

If Debbuging Privellage is Revoked Then Go to Developer Options. Use Revoke all USB Permssions on Computer.

Also refer Android Studio doesn't see device

Title: Android device not recognizing


问:
How to create cropped scalable image containers in a flexbox?
I'm trying to have a 3 column flex-box layout on my website that has 3 images on top, and then 3 bodies of text. I want the images to be a fixed aspect ratio container that crops an image if it's too big for the container, the image needs to fill the entire container height-wise.

If the window is sized down, the images should scale down maintaining aspect ratio with the flexbox, instead right now it just scales the width in.

My problem is no matter what solutions i researched, i could not find one that gives cropped images with a fixed aspect ratio, that also scales maintaining that ratio. It always either has the entire image that will scale, or just scale in the width, further cropping the image.

Is there any solution out there I can use?

html {
  height: 100%;
}

body {
  text-wrap: normal;
  text-align: center;
  position: relative;
  padding-bottom: 5.5em;
  margin: 0;
  min-height: 100%;
}

.homeinfo-flex {
  margin: 0px;
  padding: 0px;
  float: left;
  width: 100%;
  position: absolute;
  transform: translateX(-50%);
  left: 50%;
  display: flex;
  max-width: 67em;
  justify-content: space-around;
  background: #CCC;
}

.homeinfo-flex .col {
  width: 30%;
  margin: 0 1%;
  text-align: left;
}

.homeinfo-flex .container {
  text-align: center;
  overflow: hidden;
  padding-bottom: 2em;
}

.homeinfo-flex img {
  position: relative;
  left: 100%;
  margin-left: -200%;
  height: 15.62em;
  max-width: 15.62em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="homeinfo-flex">
    <div class="col">
      <div class="container"><img src="images/street_ph.jpg" alt="Street" /></div>
      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
    </div>
    <div class="col">
      <div class="container"><img src="images/resturaunt_ph.jpg" alt="Street" /></div>
      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
    </div>
    <div class="col">
      <div class="container"><img src="images/event_ph.jpg" alt="Street" /></div>
      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
    </div>
  </div>
</body></code>```

答:
Option 1: Attach the image as a background image.
div class="container" style="background-image: url(images/resturaunt_ph.jpg);"   </p>

```<code>.container {
    background-image: url()
    background-size:cover;
    padding-bottom: 80%; // 5:4 ratio
}
</code>```

<p>Option 2: Pad the container with your aspect ratio and set image to object-fit:cover. </p>

```<code>.container {
    position:relative;
    padding-bottom: 80%; // 5:4 ratio
}
.container img {
    position:absolute;
    top:0;
    left:0;
    min-height: 100%;
    min-width:100%;
    object-fit: cover // check browser support
}
</code>```

Body:
I'm trying to have a 3 column flex-box layout on my website that has 3 images on top, and then 3 bodies of text. I want the images to be a fixed aspect ratio container that crops an image if it's too big for the container, the image needs to fill the entire container height-wise.

If the window is sized down, the images should scale down maintaining aspect ratio with the flexbox, instead right now it just scales the width in.

My problem is no matter what solutions i researched, i could not find one that gives cropped images with a fixed aspect ratio, that also scales maintaining that ratio. It always either has the entire image that will scale, or just scale in the width, further cropping the image.

Is there any solution out there I can use?

html {
  height: 100%;
}

body {
  text-wrap: normal;
  text-align: center;
  position: relative;
  padding-bottom: 5.5em;
  margin: 0;
  min-height: 100%;
}

.homeinfo-flex {
  margin: 0px;
  padding: 0px;
  float: left;
  width: 100%;
  position: absolute;
  transform: translateX(-50%);
  left: 50%;
  display: flex;
  max-width: 67em;
  justify-content: space-around;
  background: #CCC;
}

.homeinfo-flex .col {
  width: 30%;
  margin: 0 1%;
  text-align: left;
}

.homeinfo-flex .container {
  text-align: center;
  overflow: hidden;
  padding-bottom: 2em;
}

.homeinfo-flex img {
  position: relative;
  left: 100%;
  margin-left: -200%;
  height: 15.62em;
  max-width: 15.62em;
}

      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Body:
Option 1: Attach the image as a background image.
div class="container" style="background-image: url(images/resturaunt_ph.jpg);"

.container {
    background-image: url()
    background-size:cover;
    padding-bottom: 80%; // 5:4 ratio
}

Option 2: Pad the container with your aspect ratio and set image to object-fit:cover.

.container {
    position:relative;
    padding-bottom: 80%; // 5:4 ratio
}
.container img {
    position:absolute;
    top:0;
    left:0;
    min-height: 100%;
    min-width:100%;
    object-fit: cover // check browser support
}


问:
Undefined webrat methods in cucumber step_definitions
When i run my features i get this error:

```<code>undefined method `visit' for #<Cucumber::Rails::World:0x81b17ac0> (NoMethodError)
</code>```

This is the relevant part of my Gemfile.

```<code>group :development, :test do
  gem "rspec-rails", ">= 2.0.0.beta.19"
  gem "cucumber"
  gem "cucumber-rails", ">= 0.3.2"
  gem 'webrat', ">= 0.7.2.beta.1"
end
</code>```

The relating step_definition (though i don't think it's important)

```<code>When /^I create a movie Caddyshack in the Comendy genre$/ do
  visit movies_path
  click_link "Add Movie"
  fill_in "Title", :with => "Caddyshack"
  check "Comedy"
  click_button "Save"
end
</code>```

In the env.rb i have the following Webrat configuration:

```<code># […]
require 'webrat'
require 'webrat/core/matchers'

Webrat.configure do |config|
  config.mode = :rails
  config.open_error_files = false # Set to true if you want error pages to pop up in the browser
end
# […]
</code>```

Anything i am missing here?

答: I also encountered this error on two separate occasions: the first instance the adjustment to confg.mode solved the problem; the second time, however, after a lot of frustration I found a link that suggested a buggy version of bundler could be the culprit. Updating it solved the problem.</p>

Body:
When i run my features i get this error:

undefined method `visit' for #<Cucumber::Rails::World:0x81b17ac0> (NoMethodError)

This is the relevant part of my Gemfile.

group :development, :test do
  gem "rspec-rails", ">= 2.0.0.beta.19"
  gem "cucumber"
  gem "cucumber-rails", ">= 0.3.2"
  gem 'webrat', ">= 0.7.2.beta.1"
end

The relating step_definition (though i don't think it's important)

When /^I create a movie Caddyshack in the Comendy genre$/ do
  visit movies_path
  click_link "Add Movie"
  fill_in "Title", :with => "Caddyshack"
  check "Comedy"
  click_button "Save"
end

In the env.rb i have the following Webrat configuration:

# […]
require 'webrat'
require 'webrat/core/matchers'

Webrat.configure do |config|
  config.mode = :rails
  config.open_error_files = false # Set to true if you want error pages to pop up in the browser
end
# […]

Anything i am missing here?


问:
Extract Substring from string using Batch
I need to extract substring(numeric with underscore) from a string using batch file. For example :

I have AbC_d1344_454_78a.
or
 Deg_e23_74_67.

I want to extract substring 1344_454_78 and 23_74_67.

答:
You have a couple of solutions with a batch file.

If your data is always the same amount of characters before the numbers you can do a simple substring to extract part of the string. So this removes the first five characters from the string.

```<code>SET "VAR=AbC_d1344_454_78a"
SET "VAR=%VAR:~5%"
</code>```

But at this point you still have the alpha character at the end. So you can do a simple findstr command to see if there is an alpha character at the end and if so you can strip it again with another substring to remove the last character.

```<code>SET "var=AbC_d1344_454_78a"
SET "var=%var:~5%"
echo %var%|findstr /R /I /C:"[a-z]$">nul &&SET "var=%var:~0,-1%"
</code>```

Another option is to use the FOR /F command and take advantage of the DELIMS option to break up the string into separate variables by using the underscore as the separator.  You can get everything after the first underscore assigned to a variable like this.

```<code>FOR /F "TOKENS=1* DELIMS=_" %%G IN ("AbC_d1344_454_78a") DO SET "var=%%H"
</code>```

But yet again, you now have a leading and trailing alpha character.  So again, you can use the FINDSTR command to test for that and strip the leading and/or trailing alpha character.

```<code>FOR /F "TOKENS=1* DELIMS=_" %%G IN ("AbC_d1344_454_78a") DO SET "var=%%H"
echo %var%|findstr /R /I /C:"^[a-z]">nul &&SET "var=%var:~1%"
echo %var%|findstr /R /I /C:"[a-z]$">nul &&SET "var=%var:~0,-1%"
</code>```

If you have multiple leading and trailing alpha characters you can use a label and goto to keep iterating over the FINDSTR command.

```<code>FOR /F "TOKENS=1* DELIMS=_" %%G IN ("AbC_d1344_454_78a") DO SET "var=%%H"
:leading
echo %var%|findstr /R /I /C:"^[a-z]">nul &&(SET "var=%var:~1%" &GOTO leading)
:trailing
echo %var%|findstr /R /I /C:"[a-z]$">nul &&(SET "var=%var:~0,-1%" &GOTO trailing)
</code>```

Interchange any of the code examples as you desire.

Body:
You have a couple of solutions with a batch file.

If your data is always the same amount of characters before the numbers you can do a simple substring to extract part of the string. So this removes the first five characters from the string.

SET "VAR=AbC_d1344_454_78a"
SET "VAR=%VAR:~5%"

But at this point you still have the alpha character at the end. So you can do a simple findstr command to see if there is an alpha character at the end and if so you can strip it again with another substring to remove the last character.

SET "var=AbC_d1344_454_78a"
SET "var=%var:~5%"
echo %var%|findstr /R /I /C:"[a-z]$">nul &&SET "var=%var:~0,-1%"

Another option is to use the FOR /F command and take advantage of the DELIMS option to break up the string into separate variables by using the underscore as the separator.  You can get everything after the first underscore assigned to a variable like this.

FOR /F "TOKENS=1* DELIMS=_" %%G IN ("AbC_d1344_454_78a") DO SET "var=%%H"

But yet again, you now have a leading and trailing alpha character.  So again, you can use the FINDSTR command to test for that and strip the leading and/or trailing alpha character.

FOR /F "TOKENS=1* DELIMS=_" %%G IN ("AbC_d1344_454_78a") DO SET "var=%%H"
echo %var%|findstr /R /I /C:"^[a-z]">nul &&SET "var=%var:~1%"
echo %var%|findstr /R /I /C:"[a-z]$">nul &&SET "var=%var:~0,-1%"

If you have multiple leading and trailing alpha characters you can use a label and goto to keep iterating over the FINDSTR command.

FOR /F "TOKENS=1* DELIMS=_" %%G IN ("AbC_d1344_454_78a") DO SET "var=%%H"
:leading
echo %var%|findstr /R /I /C:"^[a-z]">nul &&(SET "var=%var:~1%" &GOTO leading)
:trailing
echo %var%|findstr /R /I /C:"[a-z]$">nul &&(SET "var=%var:~0,-1%" &GOTO trailing)

Interchange any of the code examples as you desire.


问:
java.io.FileNotFoundException: /storage/emulated/0/downloadedfilem.jpg (Permission denied)
i am trying to download and store image using Async task in android , when clicking download button getting following error.

```<code>    W/System.err: java.io.FileNotFoundException: /storage/emulated/0/downloadedfilem.jpg (Permission denied)
12-07 11:01:00.120 28478-28540/myoracle.com.quotes W/System.err:     at java.io.FileOutputStream.open(Native Method)
12-07 11:01:00.120 28478-28540/myoracle.com.quotes W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
12-07 11:01:00.120 28478-28540/myoracle.com.quotes W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:108)
12-07 11:01:00.120 28478-28540/myoracle.com.quotes W/System.err:     at myoracle.com.quotes.WallpaperDeatilsActivity$ImageDownload.doInBackground(WallpaperDeatilsActivity.java:113)
12-07 11:01:00.120 28478-28540/myoracle.com.quotes W/System.err:     at myoracle.com.quotes.WallpaperDeatilsActivity$ImageDownload.doInBackground(WallpaperDeatilsActivity.java:91)
</code>```

WallpaperActivity.java

```<code>class ImageDownload extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        int count;
        try {

            String root = Environment.getExternalStorageDirectory().toString();

            System.out.println("Downloading");
            URL url = new URL(params[0]);

            URLConnection conection = url.openConnection();
            conection.connect();
            // getting file length
            int lenghtOfFile = conection.getContentLength();

            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            // Output stream to write file
            System.out.println(root);
            OutputStream output = new FileOutputStream(root+"/downloadedfilem.jpg");
            byte data[] = new byte[1024];
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                // writing data to file
                output.write(data, 0, count);
                System.out.println(count);
            }
            // flushing output
            output.flush();
            // closing streams
            output.close();
           input.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
</code>```

Android Target Api 7.1.1

Permissions added in manifest

android.permission.READ_EXTERNAL_STORAGE

android.permission.WRITE_EXTERNAL_STORAGE

答:
You need to add runtime permission for OS Marshmallow or above.
Add this code for permission to allow run time operation in splash activity in onCreate or before download process of image.

```<code>if (!checkPermission()) {
    openActivity();
} else {
    if (checkPermission()) {
        requestPermissionAndContinue();
    } else {
        openActivity();
    }
}
</code>```

Add this method outside onCreate

```<code>private static final int PERMISSION_REQUEST_CODE = 200;
private boolean checkPermission() {

        return ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                ;
    }

private void requestPermissionAndContinue() {
    if (ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
            && ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this, WRITE_EXTERNAL_STORAGE)
                && ActivityCompat.shouldShowRequestPermissionRationale(this, READ_EXTERNAL_STORAGE)) {
            AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
            alertBuilder.setCancelable(true);
            alertBuilder.setTitle(getString(R.string.permission_necessary));
            alertBuilder.setMessage(R.string.storage_permission_is_encessary_to_wrote_event);
            alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCompat.requestPermissions(SplashActivity.this, new String[]{WRITE_EXTERNAL_STORAGE
                            , READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
                }
            });
            AlertDialog alert = alertBuilder.create();
            alert.show();
            Log.e("", "permission denied, show dialog");
        } else {
            ActivityCompat.requestPermissions(SplashActivity.this, new String[]{WRITE_EXTERNAL_STORAGE,
                    READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
        }
    } else {
        openActivity();
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    if (requestCode == PERMISSION_REQUEST_CODE) {
        if (permissions.length > 0 && grantResults.length > 0) {

            boolean flag = true;
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    flag = false;
                }
            }
            if (flag) {
                openActivity();
            } else {
                finish();
            }

        } else {
            finish();
        }
    } else {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

private void openActivity() {
  //add your further process after giving permission or to download images from remote server.
}
</code>```

Body:
i am trying to download and store image using Async task in android , when clicking download button getting following error.

    W/System.err: java.io.FileNotFoundException: /storage/emulated/0/downloadedfilem.jpg (Permission denied)
12-07 11:01:00.120 28478-28540/myoracle.com.quotes W/System.err:     at java.io.FileOutputStream.open(Native Method)
12-07 11:01:00.120 28478-28540/myoracle.com.quotes W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
12-07 11:01:00.120 28478-28540/myoracle.com.quotes W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:108)
12-07 11:01:00.120 28478-28540/myoracle.com.quotes W/System.err:     at myoracle.com.quotes.WallpaperDeatilsActivity$ImageDownload.doInBackground(WallpaperDeatilsActivity.java:113)
12-07 11:01:00.120 28478-28540/myoracle.com.quotes W/System.err:     at myoracle.com.quotes.WallpaperDeatilsActivity$ImageDownload.doInBackground(WallpaperDeatilsActivity.java:91)

WallpaperActivity.java

class ImageDownload extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        int count;
        try {

            String root = Environment.getExternalStorageDirectory().toString();

            System.out.println("Downloading");
            URL url = new URL(params[0]);

            URLConnection conection = url.openConnection();
            conection.connect();
            // getting file length
            int lenghtOfFile = conection.getContentLength();

            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            // Output stream to write file
            System.out.println(root);
            OutputStream output = new FileOutputStream(root+"/downloadedfilem.jpg");
            byte data[] = new byte[1024];
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                // writing data to file
                output.write(data, 0, count);
                System.out.println(count);
            }
            // flushing output
            output.flush();
            // closing streams
            output.close();
           input.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

Android Target Api 7.1.1

Permissions added in manifest

android.permission.READ_EXTERNAL_STORAGE

android.permission.WRITE_EXTERNAL_STORAGE

Body:
You need to add runtime permission for OS Marshmallow or above.
Add this code for permission to allow run time operation in splash activity in onCreate or before download process of image.

if (!checkPermission()) {
    openActivity();
} else {
    if (checkPermission()) {
        requestPermissionAndContinue();
    } else {
        openActivity();
    }
}

Add this method outside onCreate

private static final int PERMISSION_REQUEST_CODE = 200;
private boolean checkPermission() {

        return ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                ;
    }

private void requestPermissionAndContinue() {
    if (ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
            && ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this, WRITE_EXTERNAL_STORAGE)
                && ActivityCompat.shouldShowRequestPermissionRationale(this, READ_EXTERNAL_STORAGE)) {
            AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
            alertBuilder.setCancelable(true);
            alertBuilder.setTitle(getString(R.string.permission_necessary));
            alertBuilder.setMessage(R.string.storage_permission_is_encessary_to_wrote_event);
            alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCompat.requestPermissions(SplashActivity.this, new String[]{WRITE_EXTERNAL_STORAGE
                            , READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
                }
            });
            AlertDialog alert = alertBuilder.create();
            alert.show();
            Log.e("", "permission denied, show dialog");
        } else {
            ActivityCompat.requestPermissions(SplashActivity.this, new String[]{WRITE_EXTERNAL_STORAGE,
                    READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
        }
    } else {
        openActivity();
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    if (requestCode == PERMISSION_REQUEST_CODE) {
        if (permissions.length > 0 && grantResults.length > 0) {

            boolean flag = true;
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    flag = false;
                }
            }
            if (flag) {
                openActivity();
            } else {
                finish();
            }

        } else {
            finish();
        }
    } else {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

private void openActivity() {
  //add your further process after giving permission or to download images from remote server.
}