问:
JSON with Dynamic Keys while using Retrofit in Android
I'm new in using Retrofit with Android. I'm stuck at a point where I make a request to the REST Api and the response has a dynamic keys. Can anyone tell me what is the best way to parse the JSON something like this.

```<code>{
  "Meta Data": {
    "1. Information": "Intraday (1min) prices and volumes",
    "2. Symbol": "MSFT",
    "3. Last Refreshed": "2017-12-01 16:00:00",
    "4. Interval": "1min",
    "5. Output Size": "Compact",
    "6. Time Zone": "US/Eastern"
  },
  "Time Series (1min)": {
    "2017-12-01 16:00:00": {
      "1. open": "84.2000",
      "2. high": "84.2600",
      "3. low": "84.1800",
      "4. close": "84.2000",
      "5. volume": "3311341"
    },
    "2017-12-01 15:59:00": {
      "1. open": "84.2500",
      "2. high": "84.2600",
      "3. low": "84.2000",
      "4. close": "84.2000",
      "5. volume": "175169"
    },
    "2017-12-01 15:58:00": {
      "1. open": "84.2800",
      "2. high": "84.3000",
      "3. low": "84.2400",
      "4. close": "84.2550",
      "5. volume": "139520"
    }

  }
}
</code>```

答:
If you want to manually parse JsonString, follow below code:

```<code>        JSONObject object = new JSONObject(jsonString);
        Map<String, Object> metaDataMap = toMap(object.getJSONObject("Meta Data"));
        displayMap(metaDataMap);

        Map<String, Object> timeSeriesMap = toMap(object.getJSONObject("Time Series (1min)"));
        displayMap(timeSeriesMap);
</code>```

toMap method:

```<code>public Map<String, Object> toMap(JSONObject object) throws JSONException {
        Map<String, Object> map = new TreeMap<String, Object>();  // TreeMap(for getting data in sorted order[Ascending])

        Iterator<String> keysItr = object.keys();
        while(keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = object.get(key);

            if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            map.put(key, value);
        }
        return map;
    }
</code>```

displayMap method:

```<code>public void displayMap(Map<String, Object> myMap) {
        Iterator iterator = myMap.entrySet().iterator();
        while(iterator.hasNext()) {
            Map.Entry mentry = (Map.Entry)iterator.next();
             System.out.println("key is: "+ mentry.getKey() + " & Value is: " + mentry.getValue());
        }
    }
</code>```

OUTPUT:

```<code>key is: 1. Information & Value is: Intraday (1min) prices and volumes
key is: 2. Symbol & Value is: MSFT
key is: 3. Last Refreshed & Value is: 2017-12-01 16:00:00
key is: 4. Interval & Value is: 1min
key is: 5. Output Size & Value is: Compact
key is: 6. Time Zone & Value is: US/Eastern

key is: 2017-12-01 15:58:00 & Value is: {1. open=84.2800, 2. high=84.3000, 3. low=84.2400, 4. close=84.2550, 5. volume=139520}
key is: 2017-12-01 15:59:00 & Value is: {1. open=84.2500, 2. high=84.2600, 3. low=84.2000, 4. close=84.2000, 5. volume=175169}
key is: 2017-12-01 16:00:00 & Value is: {1. open=84.2000, 2. high=84.2600, 3. low=84.1800, 4. close=84.2000, 5. volume=3311341}
</code>```

Body:
I'm new in using Retrofit with Android. I'm stuck at a point where I make a request to the REST Api and the response has a dynamic keys. Can anyone tell me what is the best way to parse the JSON something like this.

{
  "Meta Data": {
    "1. Information": "Intraday (1min) prices and volumes",
    "2. Symbol": "MSFT",
    "3. Last Refreshed": "2017-12-01 16:00:00",
    "4. Interval": "1min",
    "5. Output Size": "Compact",
    "6. Time Zone": "US/Eastern"
  },
  "Time Series (1min)": {
    "2017-12-01 16:00:00": {
      "1. open": "84.2000",
      "2. high": "84.2600",
      "3. low": "84.1800",
      "4. close": "84.2000",
      "5. volume": "3311341"
    },
    "2017-12-01 15:59:00": {
      "1. open": "84.2500",
      "2. high": "84.2600",
      "3. low": "84.2000",
      "4. close": "84.2000",
      "5. volume": "175169"
    },
    "2017-12-01 15:58:00": {
      "1. open": "84.2800",
      "2. high": "84.3000",
      "3. low": "84.2400",
      "4. close": "84.2550",
      "5. volume": "139520"
    }

  }
}

Body:
If you want to manually parse JsonString, follow below code:

        JSONObject object = new JSONObject(jsonString);
        Map<String, Object> metaDataMap = toMap(object.getJSONObject("Meta Data"));
        displayMap(metaDataMap);

        Map<String, Object> timeSeriesMap = toMap(object.getJSONObject("Time Series (1min)"));
        displayMap(timeSeriesMap);

toMap method:

public Map<String, Object> toMap(JSONObject object) throws JSONException {
        Map<String, Object> map = new TreeMap<String, Object>();  // TreeMap(for getting data in sorted order[Ascending])

        Iterator<String> keysItr = object.keys();
        while(keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = object.get(key);

            if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            map.put(key, value);
        }
        return map;
    }

displayMap method:

public void displayMap(Map<String, Object> myMap) {
        Iterator iterator = myMap.entrySet().iterator();
        while(iterator.hasNext()) {
            Map.Entry mentry = (Map.Entry)iterator.next();
             System.out.println("key is: "+ mentry.getKey() + " & Value is: " + mentry.getValue());
        }
    }

OUTPUT:

key is: 1. Information & Value is: Intraday (1min) prices and volumes
key is: 2. Symbol & Value is: MSFT
key is: 3. Last Refreshed & Value is: 2017-12-01 16:00:00
key is: 4. Interval & Value is: 1min
key is: 5. Output Size & Value is: Compact
key is: 6. Time Zone & Value is: US/Eastern

key is: 2017-12-01 15:58:00 & Value is: {1. open=84.2800, 2. high=84.3000, 3. low=84.2400, 4. close=84.2550, 5. volume=139520}
key is: 2017-12-01 15:59:00 & Value is: {1. open=84.2500, 2. high=84.2600, 3. low=84.2000, 4. close=84.2000, 5. volume=175169}
key is: 2017-12-01 16:00:00 & Value is: {1. open=84.2000, 2. high=84.2600, 3. low=84.1800, 4. close=84.2000, 5. volume=3311341}


来源: stackexchange

问:
Serializable[] attribute in Object not stored in db4o
I ran in a strange behavior of db4o. When I persist an Object (implementing Serializable) with an attribute of Serializable[], the Array is only returned once from the store correctly then ever after only an Array with null elements.

I use db4o 7.12.

Edit

This is the POJO:

```<code>public class ResponseRowWrapper implements Serializable {

/**
 *
 */
private static final long serialVersionUID = 1L;

private long uuid;
private long responseUuid;
private Serializable[] row;
private long timestamp;
</code>```

And this the config in spring:

```<code>        <property name="transparentActivation" value="true" />
    <property name="transparentPersistence" value="true" />
    <property name="configurationCreationMode" value="NEW" />
    <property name="lockDatabaseFile" value="false" />
    <property name="callConstructors" value="true" />
    <property name="exceptionsOnNotStorable" value="true" />
</code>```

and in in the db4o Config Object:

```<code>configuration.common().objectClass(ResponseRowWrapper.class).cascadeOnUpdate(true);
</code>```

答: Try passing the db4o configuration object a cascadeOnActivate(true) (that causes a cascaded load) or set a higher activation depth in db4o.</p>

ContentLicense: CC BY-SA 2.5

Body:
I ran in a strange behavior of db4o. When I persist an Object (implementing Serializable) with an attribute of Serializable[], the Array is only returned once from the store correctly then ever after only an Array with null elements.

I use db4o 7.12.

Edit

This is the POJO:

public class ResponseRowWrapper implements Serializable {

/**
 *
 */
private static final long serialVersionUID = 1L;

private long uuid;
private long responseUuid;
private Serializable[] row;
private long timestamp;

And this the config in spring:

        <property name="transparentActivation" value="true" />
    <property name="transparentPersistence" value="true" />
    <property name="configurationCreationMode" value="NEW" />
    <property name="lockDatabaseFile" value="false" />
    <property name="callConstructors" value="true" />
    <property name="exceptionsOnNotStorable" value="true" />

and in in the db4o Config Object:

configuration.common().objectClass(ResponseRowWrapper.class).cascadeOnUpdate(true);


问:
possible ways of splitting a string into n substrings
I'm trying to write a method that would take 'abcd' as an input, and return:

```<code>["a b c d", "a b cd", "a bc d", "a bcd", "ab c d", "ab cd", "abc d", "abcd"]
</code>```

so, all possible ways of splitting a string into n substrings that when you concatenage s1 + s2 + s3 + ... you get back the original string.

I have solved it like this, but I feel like there should be a faster and more straightforward way to do it.

```<code>def sequence(n)
  [true, false].repeated_permutation(n).to_a
end

def breakdown4(string)
  guide = sequence(string.length-1)
  arr = []
  guide.each do |i|
    s = string.dup
    counter = 0
    i.each do |j|
      if j
        s.insert(counter+1, " ")
        p counter
        counter += 2
      else
        counter += 1
      end
    end
    arr.push(s)
  end
  arr
end
</code>```

any suggestions?

答:
```<code>s = 'abcd'

s[1..-1].each_char.reduce([s[0]]) do |arr, c|
  space_c = " #{c}"
  arr.flat_map { |str| [str + c, str + space_c] }
end
  # => ["abcd", "abc d", "ab cd", "ab c d", "a bcd", "a bc d", "a b cd", "a b c d"]
</code>```

Here's another way (stuffing spaces into the string).

```<code>arr = (1..s.size-1).to_a
  #=> [1, 2, 3]
s.size.times.flat_map do |n|
  arr.combination(n).map do |locs|
    scopy = s.dup
    locs.reverse_each { |idx| scopy.insert(idx, ' ') }
    scopy
  end
end
  #=> ["abcd", "a bcd", "ab cd", "abc d", "a b cd", "a bc d", "ab c d", "a b c d"]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to write a method that would take 'abcd' as an input, and return:

["a b c d", "a b cd", "a bc d", "a bcd", "ab c d", "ab cd", "abc d", "abcd"]

so, all possible ways of splitting a string into n substrings that when you concatenage s1 + s2 + s3 + ... you get back the original string.

I have solved it like this, but I feel like there should be a faster and more straightforward way to do it.

def sequence(n)
  [true, false].repeated_permutation(n).to_a
end

def breakdown4(string)
  guide = sequence(string.length-1)
  arr = []
  guide.each do |i|
    s = string.dup
    counter = 0
    i.each do |j|
      if j
        s.insert(counter+1, " ")
        p counter
        counter += 2
      else
        counter += 1
      end
    end
    arr.push(s)
  end
  arr
end

any suggestions?

Body:
s = 'abcd'

s[1..-1].each_char.reduce([s[0]]) do |arr, c|
  space_c = " #{c}"
  arr.flat_map { |str| [str + c, str + space_c] }
end
  # => ["abcd", "abc d", "ab cd", "ab c d", "a bcd", "a bc d", "a b cd", "a b c d"]

Here's another way (stuffing spaces into the string).

arr = (1..s.size-1).to_a
  #=> [1, 2, 3]
s.size.times.flat_map do |n|
  arr.combination(n).map do |locs|
    scopy = s.dup
    locs.reverse_each { |idx| scopy.insert(idx, ' ') }
    scopy
  end
end
  #=> ["abcd", "a bcd", "ab cd", "abc d", "a b cd", "a bc d", "ab c d", "a b c d"]


问:
angular-datatables Error: Metadata version mismatch for module
now Iam use

```<code>@angular/cli: 1.4.4
node: 8.6.0
os: win32 x64
@angular/animations: 4.4.4
@angular/common: 4.4.4
@angular/compiler: 4.4.4
@angular/core: 4.4.4
@angular/forms: 4.4.4
@angular/http: 4.4.4
@angular/platform-browser: 4.4.4
@angular/platform-browser-dynamic: 4.4.4
@angular/router: 4.4.4
@angular/cli: 1.4.4
@angular/compiler-cli: 4.4.4
@angular/language-service: 4.4.4
typescript: 2.3.4
</code>```

when Iam add a new pakage use npm then get my 'ERROR in Error: Metadata version mismatch for module....
How  posiable to slove In my current pakage.json seating or some change ?

答:
If the error is for specific module run :
    npm install @angular/"module name" --save
else you will need to get latest version of all the npm modules</p>

Body:
now Iam use

@angular/cli: 1.4.4
node: 8.6.0
os: win32 x64
@angular/animations: 4.4.4
@angular/common: 4.4.4
@angular/compiler: 4.4.4
@angular/core: 4.4.4
@angular/forms: 4.4.4
@angular/http: 4.4.4
@angular/platform-browser: 4.4.4
@angular/platform-browser-dynamic: 4.4.4
@angular/router: 4.4.4
@angular/cli: 1.4.4
@angular/compiler-cli: 4.4.4
@angular/language-service: 4.4.4
typescript: 2.3.4

when Iam add a new pakage use npm then get my 'ERROR in Error: Metadata version mismatch for module....
How  posiable to slove In my current pakage.json seating or some change ?


问:
Kodi initial set up for Xcode and running git code on system
I am just beginning with the set up of Kodi so I need help on this to start. Here is GitHub link on which I am working:

https://github.com/xbmc/xbmc/tree/master

Please help me on this to implement.

Thanks,
Ratneshwar

答:
It would be helpful to know what platform you are attempting to set up kodi on so we can help you however i have dropped a easy to follow guide on how to perform the intial setup.

http://www.wirelesshack.org/new-kodi-17-krypton-setup-and-how-to-install-exodus.html

EDIT: After reading your question more i notice you mention Xcode which implies IOS device. Below will describe how to install kodi with both Xcode and Cydia Impactor.

Below instructions come from https://www.macworld.co.uk/how-to/iosapps/how-install-kodi-on-iphone-or-ipad-without-jailbreaking-3634908/ I have tested both methods and can confirm they work.

Cydia Impactor

you'll require the latest kodi .ipa file (these are easily found on the internet) e.g. https://mega.nz/#!ojghwCDI!HnQx6lhzxoeRRxchyLlrrINGW8ISZodDbg20uOIgegE

Connect your iPhone or iPad to your PC or Mac. If iTunes opens automatically when you plug in your iOS device, make sure you close it before you go any further.

Open Cydia Impactor and drag-and-drop the Kodi IPA file you downloaded earlier on to the app. (download Cydia Impactor here: http://www.cydiaimpactor.com/)

Make sure your iOS device is selected in the drop-down menu, and click Start.

Cydia Impactor will ask for an Apple ID login. It's verified with Apple, and is only used to sign the IPA file, but you can use an alternative Apple ID if privacy is a concern.

Once the app has been installed, head to Settings > General > Profiles & Device Management (this may vary slightly depending on your version of iOS), find the profile with your Apple ID and open it.

Tap the Trust button to 'trust' the new Kodi app on your iPhone or iPad.

Open the app and enjoy the many benefits available to users of Kodi!

Xcode

You'll require 3 things before beginning

Kodi deb file available here (https://kodi.tv/download)

IOS app signer available here (http://dantheman827.github.io/ios-app-signer/)

Xcode available here (https://itunes.apple.com/us/app/xcode/id497799835?mt=12)

Once this is done follow the steps below

Plug your iPad or iPhone into your Mac and open Xcode.

Select 'Create a new Xcode project'. Make sure Application is highlighted in the iOS section on the left, and then click on Single View Application. Hit Next.

In the next dialogue box you need to identify the application you're creating. Fill in Product Name (we'd suggest Kodi) and Organisation Identifier (which should be something unique - I went with com.DavidPrice). The other fields should be filled in already, and you can leave the options as they are. You could choose to make the app specifically iPad or iPhone at this point but we might as well leave it as Universal. Hit Next.

On the next box, choose a location for your Git repository. We just saved it on the desktop

Don't allow Xcode to access your contacts. Or do, if you want. We said no, but we don't think it makes a difference.

In the middle of the Xcode screen you'll see an unobtrusive error message: 'No code signing identities found'. Click Fix Issue underneath this message, then Add… on the next dialogue box. Enter your Apple ID and sign in.

Go back to the main screen and you'll see a message: "To fix this issue, select a Development Team to use for provisioning". There should only be one 'Development Team' to choose from, so go ahead and click Choose. Xcode will say it's resolving the issues, and after a short wait everything should be fixed.

Open App Signer - just double-click the icon that you saved to your desktop when you unzipped the download. Where it says Input File, you want the Kodi deb file we downloaded earlier: click Browse, find the file on your desktop (or wherever else you saved it) and click Open.
Signing Certificate should be filled in already (this should contain your Apple ID); for Provisioning Profile, select the profile with the identifier we set in step 3. New Application ID will be filled in, but we added Kodi as an App Display Name (this is what will appear on your Home screen). Click Start.

Choose a file name for the Save As field - again, you can just go with the suggestion, provided you'll be able to remember it - and a location. Click Save. App Signer will unpack the data and save the file; it'll say Done (at the bottom of the tab - you don't get a separate message) when it's finished.

We're nearly there. Go back into Xcode and select Window > Devices. Click on your iOS device in the lefthand pane. At the bottom of the righthand pane containing your iPhone or iPad's details - you may have to scroll down to see it - is a small plus sign. Click this. (There's a plus sign at the bottom of the lefthand pane too, and this is more easily visible. But you want the one on the right.)
Find and select the .ipa file that iOS App Signer generated in step 9, and click Open. After a short pause while it installs the app (maybe 10-15 seconds in our experience) you'll see the Kodi app listed under Installed Apps.

Unplug your iOS device and unlock it. You'll see the Kodi icon in the first available space on your device. Depending on your settings, there's a good chance that you'll get an 'Untrusted Developer' error message when you first tap the icon, and you'll only be able to tap Cancel.
So tap Cancel (or just don't try to start the app yet), and instead go to Settings > General, and scroll down to, and tap, Device Management (it's near the bottom of the list). Under DEVELOPER APP, tap on the account you used earlier in the process, then on the next screen, tap Trust "[name of account]". Then tap Trust again.

That's it! Go back to the your Home screen

You can use whatever of the above methods to install Kodi then follow the directions I included in the original post to set up the app once its installed. You can also jailbreak your iOS device for an easier time at installing but i would'nt recommend this.

Due to iOS 11 being a 64x OS Kodi did not work on newer version of iOS for awhile i'm not sure if this has changed but it may still be an issue you should look up


问:
Chrome/Safari supported way of IMG height/width by percent?
In Firefox, using  seems to be fine, but any other browser doesn't recognize this the way I want it to. Is there a better way of styling this using CSS? Thanks!

答:
You should avoid using the height and width attributes of an element.  If your styling absolutely must be inline, you could do this:

```<code><img src="derp.jpg" style="width:50%;height:50%" />
</code>```

However, sizing using percents is relative to the parent element: If your img's parent element has no prescribed size, your results will vary wildly.

Body:
You should avoid using the height and width attributes of an element.  If your styling absolutely must be inline, you could do this:

<img src="derp.jpg" style="width:50%;height:50%" />

However, sizing using percents is relative to the parent element: If your img's parent element has no prescribed size, your results will vary wildly.


问:
Javascript showing number with leading zero
I am new to javascript, while i was trying to test an example with below code,
Code:

function sayHello(name, age) {
  document.write (name + " is " + age + " years old.");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Click the following button to call the function</p>
<form>
   <input type="button" onclick="sayHello('abc', 010)" value="Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p></code>```

i am sending parameter as 'abc' and 010. But  in output I am getting like below,

Output:
abc is 8 years old

答:
When JavaScript encounters a number preceeded by a 0, it assumes an octal is being used, hence the 8. As Eddie stated in the comments, the best way to avoid this would be by converting the number to a string by encasing it in quotations. Hope this example below helps!

Try

```<code>onclick="sayHello('abc', '010')"
</code>```

and use + sign to convert the string to the number explicitly.

```<code>console.log('age: ' , +age); //print age: 10
</code>```

Body:
I am new to javascript, while i was trying to test an example with below code,
Code:

function sayHello(name, age) {
  document.write (name + " is " + age + " years old.");
}

Click the following button to call the function

<form>
   <input type="button" onclick="sayHello('abc', 010)" value="Say Hello">
</form>

Use different parameters inside the function and then try...

i am sending parameter as 'abc' and 010. But  in output I am getting like below,

Output:
abc is 8 years old

Body:
When JavaScript encounters a number preceeded by a 0, it assumes an octal is being used, hence the 8. As Eddie stated in the comments, the best way to avoid this would be by converting the number to a string by encasing it in quotations. Hope this example below helps!

Try

onclick="sayHello('abc', '010')"

and use + sign to convert the string to the number explicitly.

console.log('age: ' , +age); //print age: 10


问:
Getting the date/time of the last change to a MySQL database
I'm working with MySQL and I would like to get the date/time of the very last change to any table within a database.  Each of my tables has an auto updating '*_modified' timestamp so I could use this (* is a prefix).

The purpose of this is to work out if the data has changed at all since the date/time of the last database backup.

I was wondering is there an simpler way to do this using DESCRIBE or SHOW?  I've searched and experimented, but found nothing yet.

Thanks for the help.

答:
Simply,
to get all tables under one database use this query

```<code>SELECT TABLE_NAME,CREATE_TIME,UPDATE_TIME
FROM   information_schema.tables
WHERE  table_schema = 'database_name'
</code>```

That's all

Body:
Simply,
to get all tables under one database use this query

SELECT TABLE_NAME,CREATE_TIME,UPDATE_TIME
FROM   information_schema.tables
WHERE  table_schema = 'database_name'

That's all


问:
Roslyn Scripting API throws Insufficient memory to continue the execution of the program
I'm using roslyn ScriptingAPI throws an exception says:

Insufficient memory to continue the execution of the program

When compiling multiple string scripts, one by one, like this:

```<code>foreach (string script in scripts)
{
  var evalFunc = CSharpScript.Create(script, roslynOptions, typeof(ParamsVM));
  evalFunc.Compile();
  cachedScripts.Add(rule.Formula,evalFunc);
}
</code>```

I thought I can save all compiled scripts to use them later on thousands of data items, but the memory reach ~4GB because of this saving.

If I used each script on time of need (later when I iterate over the data items) then each script will be compiled again and again.

What's the solution for such a use case ?

答:
I got rid of the idea of using Roslyn Scripting API for evaluating my scripts.

I went toward using Microsoft.CSharp.CSharpCodeProvider, I iterated over all the scripts and formed (as string) a complete class (with all its using parts and namespace) then I compiled it (consider it as caching) so after that I can call the methods dynamically by reflecting the assembly I already compiled and pass to it the arguments it needed.

Body:
I'm using roslyn ScriptingAPI throws an exception says:

Insufficient memory to continue the execution of the program

When compiling multiple string scripts, one by one, like this:

foreach (string script in scripts)
{
  var evalFunc = CSharpScript.Create(script, roslynOptions, typeof(ParamsVM));
  evalFunc.Compile();
  cachedScripts.Add(rule.Formula,evalFunc);
}

I thought I can save all compiled scripts to use them later on thousands of data items, but the memory reach ~4GB because of this saving.

If I used each script on time of need (later when I iterate over the data items) then each script will be compiled again and again.

What's the solution for such a use case ?


问:
wp-admin - ERR_EMPTY_RESPONSE
When I try to access my wp-admin I'm getting on some specific sites ERR_EMPTY_RESPONSE.

This includes - plugins, themes, general settings and more. Some areas are still accessible, like Pages or Posts.

I tried basically everything. I renamed the plugins folder and themes folder, it didn't work. Then I removed the whole WP install (I kept wp-content, it contains a lot of stuff), and reinstalled everything (wp-admin, wp-includes etc). And it still didn't work. I changed all permissions to 755 with chmod -R 755 ... and still no effect.

The thing is - it was totally random. I actually didn't install anything or change anything in the last week. I suspect that it is a problem with my host, AWS. It might be firewall settings or something like that?

I'm completely lost and a hint or some kind of help would be greatly appreciated.

答:
I had this problem and this link helped me a lot,Method 10 worked for me.

right-click on the network icon located in the notification area of the taskbar and then click on "Open Network and Sharing Center".

Click on "Change adapter settings" (top left).

Right click on your network and choose "Properties".

Select "Internet Protocol Version 4 (TCP/IPv4)" and click on "Properties".

Select "Use the following DNS server addresses".

Type the DNS server numbers.
208.67.222.222
208.67.220.220

Change DNS Server Addresses to OpenDNS
7. Check "Validate settings upon exit".

Click on "OK".

Click on "Close".

Windows will now check for problems and if there are problems try to resolve it.

Now it's time to clear (flush) Google Chrome's DNS cache. To do this, open Google Chrome.

Type chrome://net-internals/#dns in the address bar and press Enter.

Click on the ▼ icon located at the top right.

Click on "Clear cache".

Click on "Flush sockets".

Clear Cache & Flush Sockets in Google Chrome
15. Restart Google Chrome.

ContentLicense: CC BY-SA 4.0

Title: wp-admin - ERR_EMPTY_RESPONSE


问:
Set default shipping method if multiple shipping methods are available - Magento 2
How to set default shipping method if multiple shipping methods are available in checkout page.</p>

答:
Override the Magento 2 file Magento_Checkout/js/model/checkout-data-resolver.js

Add this condition in resolveShippingRates method.

```<code>if (ratesData.length >= 1) {
//set shipping rate if we have only one available shipping rate
    if(!selectedShippingRate) {
        selectShippingMethodAction(ratesData[0]);
    }
}
</code>```

Body:
Override the Magento 2 file Magento_Checkout/js/model/checkout-data-resolver.js

Add this condition in resolveShippingRates method.

if (ratesData.length >= 1) {
//set shipping rate if we have only one available shipping rate
    if(!selectedShippingRate) {
        selectShippingMethodAction(ratesData[0]);
    }
}


问:
Error Deploying Artifact to Github from VSTS
I am trying to build maven project in VSTS using hosted agent.
I want to deploy my artifact to github. task i am using is Powershell. i am getting error "There is no tracking information for the current branch".
but artifcat are deploying to github, But Build Defination is failing.

答:
If the github repo is not empty and you want to keep the commit histories, you can use the script as below:

```<code>cd $(Build.ArtifactStagingDirectory)
git init
git config --global user.name name
git config --global user.email ***@gmail.com
git add .
git commit -m "update"
git remote add origin https://username:password@github.com/username/reponame -f
git checkout -b temp
git checkout master
git reset --hard origin/master
git merge temp -X theirs --allow-unrelated-histories
git push -u origin master
</code>```

If the github repo is empty or you don’t need to keep the commit histories, you can use the script as below:

```<code>cd $(Build.ArtifactStagingDirectory)
git init
git config --global user.name name
git config --global user.email ***@gmail.com
git add .
git commit -m "update"
git remote add origin  https://username:password@github.com/username/reponame -f
git push -f origin master
</code>```

And deselect Fail on Standard Error option:

Body:
If the github repo is not empty and you want to keep the commit histories, you can use the script as below:

cd $(Build.ArtifactStagingDirectory)
git init
git config --global user.name name
git config --global user.email ***@gmail.com
git add .
git commit -m "update"
git remote add origin https://username:password@github.com/username/reponame -f
git checkout -b temp
git checkout master
git reset --hard origin/master
git merge temp -X theirs --allow-unrelated-histories
git push -u origin master

If the github repo is empty or you don’t need to keep the commit histories, you can use the script as below:

cd $(Build.ArtifactStagingDirectory)
git init
git config --global user.name name
git config --global user.email ***@gmail.com
git add .
git commit -m "update"
git remote add origin  https://username:password@github.com/username/reponame -f
git push -f origin master

And deselect Fail on Standard Error option:


问:
Adding support:preference-v7 or -v14 library causes Gradle build to fail
My project builds fine, until I attempt to include the Support Preference library.

When I do, build fails with this error:

```<code>C:\Users\user\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.0.0.aar\e8afe3ff4b4dc10495266439a3695e57\res\values\values.xml:252:5-69: AAPT: error: duplicate value for resource 'attr/min' with config ''.

C:\Users\user\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.0.0.aar\e8afe3ff4b4dc10495266439a3695e57\res\values\values.xml:252:5-69: AAPT: error: resource previously defined here.

C:\Users\user\StudioProjects\project\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:627: error: duplicate value for resource 'attr/min' with config ''.

C:\Users\user\StudioProjects\project\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:483: error: resource previously defined here.

* What went wrong:
Execution failed for task ':app:mergeDebugResources'.
> Error: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
</code>```

I really don't know why this error is occuring...

EDIT: Full build.gradle:

```<code>apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

android {
    compileSdkVersion 27

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.myapp"
        minSdkVersion 16
        targetSdkVersion 27
        multiDexEnabled true
        versionCode 1
        versionName "myVersion"
        resConfigs "en"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
            ext.enableCrashlytics = false
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')

    def firebaseVersion = '11.4.2'
    def supportVersion = '27.0.0'

    //Firebase Crashlytics
    compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
        transitive = true
    }

    //Firebase
    implementation 'com.google.firebase:firebase-auth:' + firebaseVersion
    implementation 'com.google.firebase:firebase-core:' + firebaseVersion
    implementation 'com.google.firebase:firebase-firestore:' + firebaseVersion

    //FirebaseUI
    implementation 'com.firebaseui:firebase-ui-auth:3.1.0'

    //Android Support
    implementation 'com.android.support:support-v4:' + supportVersion

    implementation 'com.android.support:appcompat-v7:' + supportVersion
    implementation 'com.android.support:cardview-v7:' + supportVersion
    implementation 'com.android.support:gridlayout-v7:' + supportVersion
    implementation 'com.android.support:recyclerview-v7:' + supportVersion
    implementation 'com.android.support:preference-v7:' + supportVersion

    implementation 'com.android.support:preference-v14:' + supportVersion

    implementation 'com.android.support:support-vector-drawable:' + supportVersion

    implementation 'com.android.support:design:' + supportVersion

    implementation 'com.android.support.constraint:constraint-layout:1.0.2'

    implementation 'com.android.support:multidex:1.0.2'

    //Material About
    implementation 'com.github.daniel-stoneuk:material-about-library:2.2.3-support26.1.0' //Weird version system

    //OpenCSV
    implementation('com.opencsv:opencsv:4.0') {
        //Transitively requires Apache Commons, which necessitates multidex...
        exclude group: 'commons-beanutils'
    }

    //Gson
    implementation 'com.google.code.gson:gson:2.8.2'
}

apply plugin: 'com.google.gms.google-services'
</code>```

It wants some more details, so I'll elaborate on the problem.
I want to use the AppCompat Preference library, but the error at the beginning pops up whenever I try to add it to my build.gradle.

答: You may go to file->Invalidate caches /restart . This will invalidate any things wrong to you project.. Lets me know if it helps !</p>

Body:
My project builds fine, until I attempt to include the Support Preference library.

When I do, build fails with this error:

C:\Users\user\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.0.0.aar\e8afe3ff4b4dc10495266439a3695e57\res\values\values.xml:252:5-69: AAPT: error: duplicate value for resource 'attr/min' with config ''.

C:\Users\user\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.0.0.aar\e8afe3ff4b4dc10495266439a3695e57\res\values\values.xml:252:5-69: AAPT: error: resource previously defined here.

C:\Users\user\StudioProjects\project\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:627: error: duplicate value for resource 'attr/min' with config ''.

C:\Users\user\StudioProjects\project\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:483: error: resource previously defined here.

* What went wrong:
Execution failed for task ':app:mergeDebugResources'.
> Error: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

I really don't know why this error is occuring...

EDIT: Full build.gradle:

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

android {
    compileSdkVersion 27

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.myapp"
        minSdkVersion 16
        targetSdkVersion 27
        multiDexEnabled true
        versionCode 1
        versionName "myVersion"
        resConfigs "en"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
            ext.enableCrashlytics = false
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')

    def firebaseVersion = '11.4.2'
    def supportVersion = '27.0.0'

    //Firebase Crashlytics
    compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
        transitive = true
    }

    //Firebase
    implementation 'com.google.firebase:firebase-auth:' + firebaseVersion
    implementation 'com.google.firebase:firebase-core:' + firebaseVersion
    implementation 'com.google.firebase:firebase-firestore:' + firebaseVersion

    //FirebaseUI
    implementation 'com.firebaseui:firebase-ui-auth:3.1.0'

    //Android Support
    implementation 'com.android.support:support-v4:' + supportVersion

    implementation 'com.android.support:appcompat-v7:' + supportVersion
    implementation 'com.android.support:cardview-v7:' + supportVersion
    implementation 'com.android.support:gridlayout-v7:' + supportVersion
    implementation 'com.android.support:recyclerview-v7:' + supportVersion
    implementation 'com.android.support:preference-v7:' + supportVersion

    implementation 'com.android.support:preference-v14:' + supportVersion

    implementation 'com.android.support:support-vector-drawable:' + supportVersion

    implementation 'com.android.support:design:' + supportVersion

    implementation 'com.android.support.constraint:constraint-layout:1.0.2'

    implementation 'com.android.support:multidex:1.0.2'

    //Material About
    implementation 'com.github.daniel-stoneuk:material-about-library:2.2.3-support26.1.0' //Weird version system

    //OpenCSV
    implementation('com.opencsv:opencsv:4.0') {
        //Transitively requires Apache Commons, which necessitates multidex...
        exclude group: 'commons-beanutils'
    }

    //Gson
    implementation 'com.google.code.gson:gson:2.8.2'
}

apply plugin: 'com.google.gms.google-services'

It wants some more details, so I'll elaborate on the problem.
I want to use the AppCompat Preference library, but the error at the beginning pops up whenever I try to add it to my build.gradle.


问:
Python one-liner to print text converted from ASCII numbers?
The following command print text from it's ASCII representative.

```<code>python -c "print unichr(72)"
</code>```

E.g.

```<code>[user@linux ~]$ python -c "print unichr(72)"
H
[user@linux ~]$
</code>```

But this is only for a single character. If I have an ASCII string, let say 72 101 108 108 111 32 87 111 114 108 100 for Hello World, is it possible to convert it in Python in one line?

I've been trying the following commands but it didn't work.

```<code>[user@linux ~]$ python -c "print unichr(72)" "unichr(72)"
H
[user@linux ~]$
</code>```

...

```<code>[user@linux ~]$ python -c "print unichr(72) unichr(72)"
  File "<string>", line 1
    print unichr(72) unichr(72)
                          ^
SyntaxError: invalid syntax
[user@linux ~]$
</code>```

...

```<code>[user@linux ~]$ python -c "print unichr(72)(72)"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: 'unicode' object is not callable
[user@linux ~]$
</code>```

答:
```<code>$ python -c 'print "".join(unichr(i) for i in (72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100))'
Hello World
</code>```

How it works

This generates a list of unicode characters:

```<code>>>> [unichr(i) for i in (72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100)]
[u'H', u'e', u'l', u'l', u'o', u' ', u'W', u'o', u'r', u'l', u'd']
</code>```

This combines the list of characters into a string:

```<code>>>> ''.join(unichr(i) for i in (72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100))
u'Hello World'
</code>```

Python3 Version

unichr no longer exists in python3.  Instead, use:

```<code>>>> print("".join(chr(i) for i in (72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100)))
Hello World
</code>```

Body:
The following command print text from it's ASCII representative.

python -c "print unichr(72)"

E.g.

[user@linux ~]$ python -c "print unichr(72)"
H
[user@linux ~]$

But this is only for a single character. If I have an ASCII string, let say 72 101 108 108 111 32 87 111 114 108 100 for Hello World, is it possible to convert it in Python in one line?

I've been trying the following commands but it didn't work.

[user@linux ~]$ python -c "print unichr(72)" "unichr(72)"
H
[user@linux ~]$

...

[user@linux ~]$ python -c "print unichr(72) unichr(72)"
  File "<string>", line 1
    print unichr(72) unichr(72)
                          ^
SyntaxError: invalid syntax
[user@linux ~]$

...

[user@linux ~]$ python -c "print unichr(72)(72)"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: 'unicode' object is not callable
[user@linux ~]$

Body:
$ python -c 'print "".join(unichr(i) for i in (72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100))'
Hello World

How it works

This generates a list of unicode characters:

>>> [unichr(i) for i in (72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100)]
[u'H', u'e', u'l', u'l', u'o', u' ', u'W', u'o', u'r', u'l', u'd']

This combines the list of characters into a string:

>>> ''.join(unichr(i) for i in (72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100))
u'Hello World'

Python3 Version

unichr no longer exists in python3.  Instead, use:

>>> print("".join(chr(i) for i in (72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100)))
Hello World


问:
Displaying html div class elements repeatedly based on dropdown selection
Im having trouble using the value of of a dropdown selection to display elements within a page. Im trying to use the number given by a user in a dropdown to repeatedly display a 1 of 8 random "penguin" images. Here I can initially get the first value of the dropdown however I want the page to change once a new value is selected. I also cant seem to get my 2nd for loop here to display each image. Only my html yeti class appears.

```<code>$(document).ready( function() {

    //This code will run after the page loads
    $(function() {
        var maxPenguin = 64;
        var penguinCount = 8;

      for (var i = 2; i < maxPenguin; i++) {
        $('select').append('<option value="' + i + '">' + i + '</option>');
      }

    penguinCount = document.getElementById("penguinsSelected").value;
      alert(penguinCount);
    });

    $(function displayPenguins(penguinCount){
        for(var i = 0; i < penguinCount; i++) {
            var penguin = document.createElement("penguin" + Math.ceil(Math.random() * 8));
            document.body.appendChild(penguin);
        }
    })

    $(".yeti").mousedown(function() {
        alert("Yaaaarrrr!");
        yetiClicked();
    });

});
</code>```

It may be easier if I ran it without JQuery

答:
https://jsfiddle.net/sudarpochong/f1n0190a/1/

You should practically handle dropdown change event and/or have another button to create those penguins.

Step 1

On document ready, create dropdown penguins. Your code is already working for this.

```<code>    // dropdown 2-64 possible elements
      for (var i = 2; i < maxPenguin; i++) {
        $("#penguinsSelected").append('<option value="' + i + '">' + i + '</option>');
      }
</code>```

Step 2

Handle dropdown change event or button click event

$("#create-penguin").on("click", function()

OR

$("#penguinsSelected").on("change", function() {

Hope you get the ideas.

```<code>$("#create-penguin").on("click", function() {

  $(".penguin-list").empty();

  // create penguin
  var numberSelected = $("#penguinsSelected").val();
  for(var i = 0; i < numberSelected; i++) {
    var penguinNo = Math.ceil(Math.random() * 8);
    var penguin = $("<div>").addClass("penguin" + penguinNo).html("penguin" + penguinNo);
    $(".penguin-list").append(penguin);
  }

});
</code>```

EDIT

https://jsfiddle.net/sudarpochong/q4zqa6cd/2/

If your yeti div is inside #gameholder, you can use this event handler to be able to add handler for dynamically created yeti

```<code>$("#gameholder").on("mousedown", ".yeti", function() {
    alert("AAAAAAAAAAAAAAA");
});
</code>```

Body:
Im having trouble using the value of of a dropdown selection to display elements within a page. Im trying to use the number given by a user in a dropdown to repeatedly display a 1 of 8 random "penguin" images. Here I can initially get the first value of the dropdown however I want the page to change once a new value is selected. I also cant seem to get my 2nd for loop here to display each image. Only my html yeti class appears.

$(document).ready( function() {

    //This code will run after the page loads
    $(function() {
        var maxPenguin = 64;
        var penguinCount = 8;

      for (var i = 2; i < maxPenguin; i++) {
        $('select').append('<option value="' + i + '">' + i + '</option>');
      }

    penguinCount = document.getElementById("penguinsSelected").value;
      alert(penguinCount);
    });

    $(function displayPenguins(penguinCount){
        for(var i = 0; i < penguinCount; i++) {
            var penguin = document.createElement("penguin" + Math.ceil(Math.random() * 8));
            document.body.appendChild(penguin);
        }
    })

    $(".yeti").mousedown(function() {
        alert("Yaaaarrrr!");
        yetiClicked();
    });

});

It may be easier if I ran it without JQuery

Body:
https://jsfiddle.net/sudarpochong/f1n0190a/1/

You should practically handle dropdown change event and/or have another button to create those penguins.

Step 1

On document ready, create dropdown penguins. Your code is already working for this.

    // dropdown 2-64 possible elements
      for (var i = 2; i < maxPenguin; i++) {
        $("#penguinsSelected").append('<option value="' + i + '">' + i + '</option>');
      }

Step 2

Handle dropdown change event or button click event

$("#create-penguin").on("click", function()

OR

$("#penguinsSelected").on("change", function() {

Hope you get the ideas.

$("#create-penguin").on("click", function() {

  $(".penguin-list").empty();

  // create penguin
  var numberSelected = $("#penguinsSelected").val();
  for(var i = 0; i < numberSelected; i++) {
    var penguinNo = Math.ceil(Math.random() * 8);
    var penguin = $("<div>").addClass("penguin" + penguinNo).html("penguin" + penguinNo);
    $(".penguin-list").append(penguin);
  }

});

EDIT

https://jsfiddle.net/sudarpochong/q4zqa6cd/2/

If your yeti div is inside #gameholder, you can use this event handler to be able to add handler for dynamically created yeti

$("#gameholder").on("mousedown", ".yeti", function() {
    alert("AAAAAAAAAAAAAAA");
});


问:
Laravel Validation custom message does not work
I create a custom validation in AppServiceProvider:

```<code>class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Validator::extend('greaterEqual', function($attribute, $value, $parameters, $validator) {
            $min_field = $parameters[0];
            $data = $validator->getData();
            $min_value = $data[$min_field];
            return $value >= $min_value;
        });

        Validator::replacer('greaterEqual', function($message, $attribute, $rule, $parameters) {

            return str_replace(':field', $parameters[0], $message);
        });
    }

    public function register()
    {
        //
    }
}
</code>```

I want to pass custom validation message but not worked and after submit form i receive this message: validation.greater_equal.

This is my validation in controller:

```<code>$this->validate($request,[
  'quantity' => 'required|min:1|integer|greaterEqual:sale_quantity',
  'sale_quantity' => 'required|min:0|integer',
],[
  'quantity.greaterEqual' => 'The :attribute number is invalid'
]);
</code>```

What is my mistake?!

答:
I was having a simple mistake. :-)

1- I added the sale_quantity translation in:

```<code>/resources
    /lang
        /en
            validation.php
</code>```

2- I edited code as following:

```<code>class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Validator::extend('greater_equal', function($attribute, $value, $parameters, $validator) {
            $min_field = $parameters[0];
            $data = $validator->getData();
            $min_value = $data[$min_field];
            return $value >= $min_value;
        });

        Validator::replacer('greater_equal', function($message, $attribute, $rule, $parameters) {

            return str_replace(':field', trans('validation.attributes.'.$parameters[0]), $message);
        });
    }

    public function register()
    {
        //
    }
}
</code>```

Validation in controller:

```<code>$this->validate($request,[
  'quantity' => 'required|min:1|integer|greaterqual:sale_quantity',
  'sale_quantity' => 'required|min:0|integer',
],[
  'quantity.greater_equal' => 'The :attribute number is invalid. The value of :attribute must be greater than :field'
]);
</code>```

Body:
I create a custom validation in AppServiceProvider:

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Validator::extend('greaterEqual', function($attribute, $value, $parameters, $validator) {
            $min_field = $parameters[0];
            $data = $validator->getData();
            $min_value = $data[$min_field];
            return $value >= $min_value;
        });

        Validator::replacer('greaterEqual', function($message, $attribute, $rule, $parameters) {

            return str_replace(':field', $parameters[0], $message);
        });
    }

    public function register()
    {
        //
    }
}

I want to pass custom validation message but not worked and after submit form i receive this message: validation.greater_equal.

This is my validation in controller:

$this->validate($request,[
  'quantity' => 'required|min:1|integer|greaterEqual:sale_quantity',
  'sale_quantity' => 'required|min:0|integer',
],[
  'quantity.greaterEqual' => 'The :attribute number is invalid'
]);

What is my mistake?!

Body:
I was having a simple mistake. :-)

1- I added the sale_quantity translation in:

/resources
    /lang
        /en
            validation.php

2- I edited code as following:

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Validator::extend('greater_equal', function($attribute, $value, $parameters, $validator) {
            $min_field = $parameters[0];
            $data = $validator->getData();
            $min_value = $data[$min_field];
            return $value >= $min_value;
        });

        Validator::replacer('greater_equal', function($message, $attribute, $rule, $parameters) {

            return str_replace(':field', trans('validation.attributes.'.$parameters[0]), $message);
        });
    }

    public function register()
    {
        //
    }
}

Validation in controller:

$this->validate($request,[
  'quantity' => 'required|min:1|integer|greaterqual:sale_quantity',
  'sale_quantity' => 'required|min:0|integer',
],[
  'quantity.greater_equal' => 'The :attribute number is invalid. The value of :attribute must be greater than :field'
]);


问:
dynamically include a layout to another layout file inside a fragment
I have a fragment layout to which i want to add another sub layout dynamically ,

I tried this https://stackoverflow.com/a/22592269/8476022

sub-layout xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="20dp"
    android:hint="Question"
    android:textColor="@color/colorTextBlack"
    android:textSize="16dp" />
</android.support.constraint.ConstraintLayout>
</code>```

this is my main layout

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f2f2f2"
android:orientation="vertical">
<FrameLayout
    android:id="@+id/flContainer"
    android:layout_width="match_parent"
    android:layout_margin="20dp"
    android:layout_height="wrap_content"/>
</LinearLayout>
</code>```

inside my fragment i included the sublayout

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_start_question, container, false);
     flContainer = (FrameLayout) v.findViewById(R.id.flContainer);
     flContainer.addView(R.layout.sub_layout);
    return v;
}
</code>```

but i am getting error near addView the screenshot is below

can anyone please help to find the error

答:
You are getting Error because
addView(View child) need parameter a view and you are adding FrameLayout which is ViewGroup

Try this way

```<code>LayoutInflater inflater = (LayoutInflater)   getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View myView = inflater.inflate(R.layout.sub_layout, null);;
flContainer = (FrameLayout) v.findViewById(R.id.flContainer);
flContainer.addView(myView);
</code>```

Body:
I have a fragment layout to which i want to add another sub layout dynamically ,

I tried this https://stackoverflow.com/a/22592269/8476022

sub-layout xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="20dp"
    android:hint="Question"
    android:textColor="@color/colorTextBlack"
    android:textSize="16dp" />
</android.support.constraint.ConstraintLayout>

this is my main layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f2f2f2"
android:orientation="vertical">
<FrameLayout
    android:id="@+id/flContainer"
    android:layout_width="match_parent"
    android:layout_margin="20dp"
    android:layout_height="wrap_content"/>
</LinearLayout>

inside my fragment i included the sublayout

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_start_question, container, false);
     flContainer = (FrameLayout) v.findViewById(R.id.flContainer);
     flContainer.addView(R.layout.sub_layout);
    return v;
}

but i am getting error near addView the screenshot is below

can anyone please help to find the error

Body:
You are getting Error because
addView(View child) need parameter a view and you are adding FrameLayout which is ViewGroup

Try this way

LayoutInflater inflater = (LayoutInflater)   getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View myView = inflater.inflate(R.layout.sub_layout, null);;
flContainer = (FrameLayout) v.findViewById(R.id.flContainer);
flContainer.addView(myView);


问:
Script to build the LAST commit in a Gerrit topic branch
We're using Gerrit.  We thought we could do the following:

create some commits on a topic branch:
     - a
     - b
     - c

Push those commits to gerrit.

Get some reviews.

Have Jenkins build only the last commit of the bunch.

Unfortunately, it looks like gerrit internally creates three different branches for those three commits, and when we have Jenkins run the script to build the topic,  it winds up picking a different commit than the one we intended.  Is there someway to get the behavior we desire?

答:
You can change the project configuration to only create one review for your series of changes. This can be done by setting the Create a new change for every commit not in the target branch to false

Biggest disadvantage is that you can't review what has been changed in the changesets leading up to the latest change.

See the Gerrit Documentation


Title: Python one-liner to print text converted from ASCII numbers?

Body:
How about

 python -c 'print "".join(unichr(int(c)) for c in "72 101 108 108 111 32 87 111 114 108 100".split(" "))'


问:
TensorFlow Trained Model Predicts Always Zero
I have one simple TensorFlow model and accuracy for that is 1. But when I try to predict some new inputs it always returns Zero(0).

```<code>import numpy as np
import tensorflow as tf

sess = tf.InteractiveSession()

# generate data

np.random.seed(10)

#inputs = np.random.uniform(low=1.2, high=1.5, size=[5000, 150]).astype('float32')

inputs = np.random.randint(low=50, high=500, size=[5000, 150])

label = np.random.uniform(low=1.3, high=1.4, size=[5000, 1])
# reverse_label = 1 - label
reverse_label = np.random.uniform(
    low=1.3, high=1.4, size=[5000, 1])
reverse_label1 = np.random.randint(
    low=80, high=140, size=[5000, 1])
#labels = np.append(label, reverse_label, 1)
#labels = np.append(labels, reverse_label1, 1)
labels = reverse_label1
print(inputs)
print(labels)
# parameters

learn_rate = 0.001
epochs = 100
n_input = 150
n_hidden = 15
n_output = 1

# set weights/biases

x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_output])

b0 = tf.Variable(tf.truncated_normal([n_hidden], stddev=0.2, seed=0))
b1 = tf.Variable(tf.truncated_normal([n_output], stddev=0.2, seed=0))

w0 = tf.Variable(tf.truncated_normal([n_input, n_hidden], stddev=0.2, seed=0))
w1 = tf.Variable(tf.truncated_normal([n_hidden, n_output], stddev=0.2, seed=0))

# step function

def returnPred(x, w0, w1, b0, b1):

    z1 = tf.add(tf.matmul(x, w0), b0)
    a2 = tf.nn.relu(z1)

    z2 = tf.add(tf.matmul(a2, w1), b1)
    h = tf.nn.relu(z2)

    return h  # return the first response vector from the

y_ = returnPred(x, w0, w1, b0, b1)  # predict operation

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
    logits=y_, labels=y))  # calculate loss between prediction and actual
model = tf.train.AdamOptimizer(learning_rate=learn_rate).minimize(
    loss)  # apply gradient descent based on loss

init = tf.global_variables_initializer()
tf.Session = sess
sess.run(init)  # initialize graph

for step in range(0, epochs):
    sess.run([model, loss], feed_dict={x: inputs, y: labels})  # train model

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: inputs, y: labels}))  # print accuracy

inp = np.random.randint(low=50, high=500, size=[5, 150])

print(sess.run(tf.argmax(y_, 1), feed_dict={x: inp})) # predict some new inputs
</code>```

All functions are working properly and my problem is with the latest line of code. I tried only "y_" instead "tf.argmax(y_, 1)" but not worked too.
How can I fix that?
Regards,

答:
There are multiple mistakes in your code.

Starting with this lines of code:

```<code>correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: inputs, y: labels}))  # print accuracy
</code>```

You are performing linear regression but you are checking accuracy with that of logistic regression methodology. If you want to see how your linear regression network is performing, print the loss. Ensure that your loss is decreasing after each epoch of training.

If you look into that accuracy code, run the following code:

```<code>print(y_.get_shape())    # Outputs (?, 1)
</code>```

There is only one input and both of your function tf.argmax(y,1) and tf.argmax(y_,1) will always return [0,0,..]. So as a result your accuracy will be always 1.0.  Delete those three lines of code.

Next, to get the outputs, just run the following code:

```<code>print(sess.run(y_, feed_dict={x: inp}))
</code>```

But since your data is random, don't expect good set of outputs.

Body:
I have one simple TensorFlow model and accuracy for that is 1. But when I try to predict some new inputs it always returns Zero(0).

import numpy as np
import tensorflow as tf

sess = tf.InteractiveSession()

# generate data

np.random.seed(10)

#inputs = np.random.uniform(low=1.2, high=1.5, size=[5000, 150]).astype('float32')

inputs = np.random.randint(low=50, high=500, size=[5000, 150])

label = np.random.uniform(low=1.3, high=1.4, size=[5000, 1])
# reverse_label = 1 - label
reverse_label = np.random.uniform(
    low=1.3, high=1.4, size=[5000, 1])
reverse_label1 = np.random.randint(
    low=80, high=140, size=[5000, 1])
#labels = np.append(label, reverse_label, 1)
#labels = np.append(labels, reverse_label1, 1)
labels = reverse_label1
print(inputs)
print(labels)
# parameters

learn_rate = 0.001
epochs = 100
n_input = 150
n_hidden = 15
n_output = 1

# set weights/biases

x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_output])

b0 = tf.Variable(tf.truncated_normal([n_hidden], stddev=0.2, seed=0))
b1 = tf.Variable(tf.truncated_normal([n_output], stddev=0.2, seed=0))

w0 = tf.Variable(tf.truncated_normal([n_input, n_hidden], stddev=0.2, seed=0))
w1 = tf.Variable(tf.truncated_normal([n_hidden, n_output], stddev=0.2, seed=0))

# step function

def returnPred(x, w0, w1, b0, b1):

    z1 = tf.add(tf.matmul(x, w0), b0)
    a2 = tf.nn.relu(z1)

    z2 = tf.add(tf.matmul(a2, w1), b1)
    h = tf.nn.relu(z2)

    return h  # return the first response vector from the

y_ = returnPred(x, w0, w1, b0, b1)  # predict operation

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
    logits=y_, labels=y))  # calculate loss between prediction and actual
model = tf.train.AdamOptimizer(learning_rate=learn_rate).minimize(
    loss)  # apply gradient descent based on loss

init = tf.global_variables_initializer()
tf.Session = sess
sess.run(init)  # initialize graph

for step in range(0, epochs):
    sess.run([model, loss], feed_dict={x: inputs, y: labels})  # train model

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: inputs, y: labels}))  # print accuracy

inp = np.random.randint(low=50, high=500, size=[5, 150])

print(sess.run(tf.argmax(y_, 1), feed_dict={x: inp})) # predict some new inputs

All functions are working properly and my problem is with the latest line of code. I tried only "y_" instead "tf.argmax(y_, 1)" but not worked too.
How can I fix that?
Regards,

Body:
There are multiple mistakes in your code.

Starting with this lines of code:

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: inputs, y: labels}))  # print accuracy

You are performing linear regression but you are checking accuracy with that of logistic regression methodology. If you want to see how your linear regression network is performing, print the loss. Ensure that your loss is decreasing after each epoch of training.

If you look into that accuracy code, run the following code:

print(y_.get_shape())    # Outputs (?, 1)

There is only one input and both of your function tf.argmax(y,1) and tf.argmax(y_,1) will always return [0,0,..]. So as a result your accuracy will be always 1.0.  Delete those three lines of code.

Next, to get the outputs, just run the following code:

print(sess.run(y_, feed_dict={x: inp}))

But since your data is random, don't expect good set of outputs.


问:
Spring MongoTemplate upsert entire list
I have a list of objects which I want to insert into a collection. The mongoTemplate.insert(list); works fine but now I want to modify it to upsert(); as my list can contain duplicate objects which are already inserted into a collection. So what I want is insert entire list and on the go check if the item is already present in the collection then skip it else insert it.

答:
You can try out continueOnError or ordered flag like this:

```<code>db.collection.insert(myArray, {continueOnError: true})
</code>```

OR,

```<code>db.collection.insert(myArray, {ordered: false})
</code>```

Title: Spring MongoTemplate upsert entire list

Body:
You can try out continueOnError or ordered flag like this:

db.collection.insert(myArray, {continueOnError: true})

OR,

db.collection.insert(myArray, {ordered: false})


问:
How to Read KeyStore File Path From standalone.xml wildfly
First of all i am sorry if my question is not valid because i don't have any idea on the SSL implementation and validating the request from a trusted certificate authority.

Basically we are using .jks file to validate the request and we are using JAX-RS deployed on wildfly.

In the standalone.xml we have done the configuration like this:

```<code><management>
 <security-realms>
**<security-realm name="SslRealm">
  <server-identities>
    <ssl>
      <keystore path="../../../ssl/keystore.jks" relative-to="jboss.server.config.dir" keystore-password="changeme"/>
    </ssl>
  </server-identities>
</security-realm>**
</security-realms>
</code>```

Now in the java code we need to read the .jks file , username and password:

```<code> public static Response getArtifactsHttps(String authInfo, String area) {
        String username = "username";
        String password1 = "password";
        StringBuilder authorization = new StringBuilder();
        authorization.append(username).append(":").append(password1);

        // String authHeader = "Basic " + Base64.getEncoder().encodeToString(authorization.toString().getBytes());
        Response response = RestAssured
                .given()
                .keyStore("pathOffile\\DemoTrust.jks", "DemoTrustKeyStorePassPhrase")
                .when()
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .header(Constant.HTTP_HEADERS.AUTHORIZATION, "Basic " + authInfo)
                .header(Constant.HTTP_HEADERS.MODULETYPE, Constant.AC_MODULETYPE.CLIENT)
                .get("login").thenReturn();

        System.out.println("RESPONSE" + response);
        return response;
    }
</code>```

In the above you can see i have hardcoded the path of the .jks file
  pathoffile\DemoTrust.jks also username and password i have hardcoded.

Now i want to read all these value from the standalone.xml file. Can anybody suggest me how i can do this using java?

答: Use System.getProperty("jboss.server.config.dir") to get the root of the configuration path. </p>

Body:
First of all i am sorry if my question is not valid because i don't have any idea on the SSL implementation and validating the request from a trusted certificate authority.

Basically we are using .jks file to validate the request and we are using JAX-RS deployed on wildfly.

In the standalone.xml we have done the configuration like this:

<management>
 <security-realms>
**<security-realm name="SslRealm">
  <server-identities>
    <ssl>
      <keystore path="../../../ssl/keystore.jks" relative-to="jboss.server.config.dir" keystore-password="changeme"/>
    </ssl>
  </server-identities>
</security-realm>**
</security-realms>

Now in the java code we need to read the .jks file , username and password:

 public static Response getArtifactsHttps(String authInfo, String area) {
        String username = "username";
        String password1 = "password";
        StringBuilder authorization = new StringBuilder();
        authorization.append(username).append(":").append(password1);

        // String authHeader = "Basic " + Base64.getEncoder().encodeToString(authorization.toString().getBytes());
        Response response = RestAssured
                .given()
                .keyStore("pathOffile\\DemoTrust.jks", "DemoTrustKeyStorePassPhrase")
                .when()
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .header(Constant.HTTP_HEADERS.AUTHORIZATION, "Basic " + authInfo)
                .header(Constant.HTTP_HEADERS.MODULETYPE, Constant.AC_MODULETYPE.CLIENT)
                .get("login").thenReturn();

        System.out.println("RESPONSE" + response);
        return response;
    }

In the above you can see i have hardcoded the path of the .jks file
  pathoffile\DemoTrust.jks also username and password i have hardcoded.

Now i want to read all these value from the standalone.xml file. Can anybody suggest me how i can do this using java?


问:
Protecting my website content from being downloaded through cURL
I heard about external access of a website using curl by the following code:

```<code>$curl_handle=curl_init();
curl_setopt($curl_handle,CURLOPT_URL,'http://example.com');
$buffer=curl_exec($curl_handle);
curl_close($curl_handle);
</code>```

I want to protect my website from this external access. I am using PHP. How can I protect my web site?

答:
Another thing you can do is protect your site with a Captcha. This will prevent access via curl but will allow your users access. </p>

<p>Be aware that doing this will stop search engines from visiting your site. </p>

Body:
I heard about external access of a website using curl by the following code:

$curl_handle=curl_init();
curl_setopt($curl_handle,CURLOPT_URL,'http://example.com');
$buffer=curl_exec($curl_handle);
curl_close($curl_handle);

I want to protect my website from this external access. I am using PHP. How can I protect my web site?

Body:
Another thing you can do is protect your site with a Captcha. This will prevent access via curl but will allow your users access.

Be aware that doing this will stop search engines from visiting your site.


问:
JMeter - Benefits of master-slaves configuration over all masters when doing a load test
About JMeter Distributed configuration for load testing (not in cloud),

I can setup X JMeter masters in different machines and execute them with shared files using shared folder(s).

The benefits are:

Each master is oblivious to other and can be shutdown and start when needed with dynamic/different properties.

Each master have its own logs and results that can be explored separately.

I don't need network connection between JMeter masters' machines.

What are the benefits for using master-slave configuration in such case? It seems like an unnecessary overhead when focusing on load test.

答:
The benefits are:

centralization of results on 1 node (master), you can follow results in Summarizer from the master node, you have the CSV/XML file generated there and you can generate the web report at end of test using this

centralization of jmx plan on 1 node (master)

synchronization of the test from master, ie the master will start/stop the test from master

Besides the drawbacks you describe there are:
- network configuration complexity
- need to deploy csv on each node (although there are options with plugins (redis, simple table server)
- network traffic between nodes and master

It was created at time deployment automation was not available through things like vagrant, ansible, cloud ...


问:
ForEach inside API does not work properly
I am using angualr 4.

i have an array.

Here is my array;

```<code>this.bookings = [
    {
     'id':'dsjdsfhkdsjhfjkds01'
    },
    {
     'id':'dsjdsfhkdsjhfjkds01'
    }
]
</code>```

I need retrieve data from database based on id.

Here is my script.

```<code>let scope = this;
scope.bookings.forEach(function(BookingItem){
  var bId = BookingItem.id;
  console.log("BId",bId);
  scope.Bservice.getbooking(scope.at,bId).subscribe(booking => {
    var responseVal = booking;
  })
})
</code>```

I need  like forEach Take on firstvalue then get retrive data from database.After going to second value of booking then get data from database.

But i consoled value of  bId.

ForEach taken on id values one by one After retreive data from database.

How can i fix this pblm.

Kindly advice me,

Thanks.

答:
I am not understading you code at full but you have to do like this

You have to loop throught bookings array and than in argument of foreach you need vriable name not name of you class ,

Another thing is if you go in loop, you last returned value from ajax request will override vlaue of your variable , so better to store response in array thats why below code use array to store you response for each id.

```<code>let responseFromServer = new Array<any>();

this.bookings.forEach((bookingItem) => {
   var bId=bookingItem.id;
   console.log("BId",bId);
   scope.Bservice.getbooking(scope.at,bId).subscribe(booking=>{
      let response = new ResponseFromServer();
      responseFromServer.Add(booking);
   });
});
</code>```

Body:
I am using angualr 4.

i have an array.

Here is my array;

this.bookings = [
    {
     'id':'dsjdsfhkdsjhfjkds01'
    },
    {
     'id':'dsjdsfhkdsjhfjkds01'
    }
]

I need retrieve data from database based on id.

Here is my script.

let scope = this;
scope.bookings.forEach(function(BookingItem){
  var bId = BookingItem.id;
  console.log("BId",bId);
  scope.Bservice.getbooking(scope.at,bId).subscribe(booking => {
    var responseVal = booking;
  })
})

I need  like forEach Take on firstvalue then get retrive data from database.After going to second value of booking then get data from database.

But i consoled value of  bId.

ForEach taken on id values one by one After retreive data from database.

How can i fix this pblm.

Kindly advice me,

Thanks.

Body:
I am not understading you code at full but you have to do like this

You have to loop throught bookings array and than in argument of foreach you need vriable name not name of you class ,

Another thing is if you go in loop, you last returned value from ajax request will override vlaue of your variable , so better to store response in array thats why below code use array to store you response for each id.

let responseFromServer = new Array<any>();

this.bookings.forEach((bookingItem) => {
   var bId=bookingItem.id;
   console.log("BId",bId);
   scope.Bservice.getbooking(scope.at,bId).subscribe(booking=>{
      let response = new ResponseFromServer();
      responseFromServer.Add(booking);
   });
});


问:
Trying to update Pivot Table using Excel Visual, but get error 438. Why?
Sub TestingMacros()
'
' TestingMacros Macro
'

```<code>Dim sht As Worksheet
Dim SrcData As String
Dim pvtCache As PivotCache

Sheets("Sheet1").Select

'Determine the data range you want to pivot
    Set sht = ThisWorkbook.Worksheets("Sheet1")
    SrcData = sht.Name & "!" & Range("A1:R23").Address(ReferenceStyle:=xlR1C1)

'Create New Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
    SourceType:=xlDatabase, _
    SourceData:=SrcData)

'Change which Pivot Cache the Pivot Table is referring to
    ActiveSheet.PivotTables("PivotTable1").ChangePivotCache (pvtCache)
End Sub
</code>```

This last sentence (ActiveSheet.PivotTables("PivotTable1").ChangePivotCache (pvtCache)) has error 438. Cannot figure why.

答:
This worked for me:</p>

```<code>Sub TestingMacros()

    Dim sht As Worksheet
    Dim SrcData As Range

    Set sht = ThisWorkbook.Worksheets("Sheet1")
    Set SrcData = sht.Range("A1:R23")

    sht.PivotTables("PivotTable1").ChangePivotCache _
        sht.Parent.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=SrcData)

End Sub
</code>```

Body:
Sub TestingMacros()
'
' TestingMacros Macro
'

Dim sht As Worksheet
Dim SrcData As String
Dim pvtCache As PivotCache

Sheets("Sheet1").Select

'Determine the data range you want to pivot
    Set sht = ThisWorkbook.Worksheets("Sheet1")
    SrcData = sht.Name & "!" & Range("A1:R23").Address(ReferenceStyle:=xlR1C1)

'Create New Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
    SourceType:=xlDatabase, _
    SourceData:=SrcData)

'Change which Pivot Cache the Pivot Table is referring to
    ActiveSheet.PivotTables("PivotTable1").ChangePivotCache (pvtCache)
End Sub

This last sentence (ActiveSheet.PivotTables("PivotTable1").ChangePivotCache (pvtCache)) has error 438. Cannot figure why.

Body:
This worked for me:

Sub TestingMacros()

    Dim sht As Worksheet
    Dim SrcData As Range

    Set sht = ThisWorkbook.Worksheets("Sheet1")
    Set SrcData = sht.Range("A1:R23")

    sht.PivotTables("PivotTable1").ChangePivotCache _
        sht.Parent.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=SrcData)

End Sub


答:
You need to inflate layout to add the view refer this</p>

```<code>View child = getLayoutInflater().inflate(R.layout.sub_layout, null);
flContainer = (FrameLayout) v.findViewById(R.id.flContainer);
flContainer.addView(child);
</code>```

Title: dynamically include a layout to another layout file inside a fragment

Body:
You need to inflate layout to add the view refer this

View child = getLayoutInflater().inflate(R.layout.sub_layout, null);
flContainer = (FrameLayout) v.findViewById(R.id.flContainer);
flContainer.addView(child);


问:
spacing between UITableViewCells swift3
I am creating a IOS app in swift and want to add spacing between cells like this

I would like to give space of each table view cell same like my attach image.
How I can do that? and Right now all cells are coming without any space.
swift3

答:
If you are using UITableViewCell to achieve this kind of layout, there is no provision to provide spacing between UITableViewCells.

Here are the options you can choose:

Create a custom UIView within UITableViewCell with clear background, so that it appears like the spacing between cells.

You need to set the background as clear of: cell, content view.

You can use UICollectionView instead of UITableView. It is much more flexible and you can design it the way you want.

Let me know if you want any more details regarding this.

Title: spacing between UITableViewCells swift3


问:
Chrome/Safari supported way of IMG height/width by percent?
In Firefox, using  seems to be fine, but any other browser doesn't recognize this the way I want it to. Is there a better way of styling this using CSS? Thanks!

答: you could try css, using the max-height and max-width styles</p>


答:
Separate the unichr() calls with a + or , will work.

Example:python -c "print unichr(72)+unichr(73),unichr(65)" prints HI A

You can see + concatenates and , adds a space in between.

So, you can use the + operator between the unichr() function calls

Body:
The following command print text from it's ASCII representative.

python -c "print unichr(72)"

E.g.

[user@linux ~]$ python -c "print unichr(72)"
H
[user@linux ~]$

But this is only for a single character. If I have an ASCII string, let say 72 101 108 108 111 32 87 111 114 108 100 for Hello World, is it possible to convert it in Python in one line?

I've been trying the following commands but it didn't work.

[user@linux ~]$ python -c "print unichr(72)" "unichr(72)"
H
[user@linux ~]$

...

[user@linux ~]$ python -c "print unichr(72) unichr(72)"
  File "<string>", line 1
    print unichr(72) unichr(72)
                          ^
SyntaxError: invalid syntax
[user@linux ~]$

...

[user@linux ~]$ python -c "print unichr(72)(72)"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: 'unicode' object is not callable
[user@linux ~]$


问:
How to retrieve a value from JSON Object Swift 4
I am trying to decode JSON object using Codable with Swift 4:

```<code>{
USD: {
"15m": 9977.49,
last: 9977.49,
buy: 9979.36,
sell: 9975.62,
symbol: "$"
    },
AUD: {
"15m": 13181.69,
last: 13181.69,
buy: 13184.16,
sell: 13179.22,
symbol: "$"
    },
TBD: {
"15m": 13181.69,
last: 13181.69,
buy: 13184.16,
sell: 13179.22,
symbol: "$"
    }
}
</code>```

This is what I've done so far with a model of an object:

```<code>struct Currency: Codable {

    let fifteenMin: Double?
    let last: Double?
    let buy: Double
    let sell: Double
    let symbol: String

    enum CodingKeys: String, CodingKey {
        case fifteenMin = "15m"
        case last
        case buy
        case sell
        case symbol
    }
}
</code>```

And this is how I decode that:

```<code>var currencyName = [String]()
var currenciesArray = [Currency]()

func fetchCurrencyData() {
    guard let urlString = API.RateURL.absoluteString else { return }
    guard let url = URL(string: urlString) else { return }
    let jsonData = try! Data(contentsOf: url)
    let decoder = JSONDecoder()
    do {
        let currenciesData = try decoder.decode([String: Currency].self, from: jsonData)
        for currency in currenciesData {
            self.currencyName.append(currency.key)
            self.currenciesArray.append(currency.value)
        }
    } catch let err {
        print(err.localizedDescription)
    }
}
</code>```

So when I want to populate rows in tableView with that Data I use "for loop" and append "USD", "AUD" and so on in one array and Currency object in another array.

What is the better way of fetching data and populating Currency object. Cuz I am pretty sure that fetching and appending the same object of JSON into two separate arrays isn't good practice I assume.

If my question isn't clear I can explain in more details what I would like to achieve.

Thank you.

答:
Shouldn't the currency name be inside the Currency object? That would be much easier to manipulate.

But if you must use that format, you can create an array of tuples or dictionaries.

```<code>var currenciesArray = [(String, Currency)]()
</code>```

and then append like this:

```<code>for currency in currenciesData {
    currenciesArray.append((currency.key, currency.value))
}
</code>```

p.s. : You need to add quotes(") on the string values inside the JSON, or it will be invalid.

****Added*****

The code below will encode and decode a JSON similar to the one you mentioned:

```<code>struct Price: Codable {

    let fifteenMin: Double?
    let last: Double?
    let buy: Double
    let sell: Double
    let symbol: String

    enum CodingKeys: String, CodingKey {
        case fifteenMin = "15m"
        case last
        case buy
        case sell
        case symbol
    }
}

struct Currencies: Codable {
    var USD: Price?
    var JPY: Price?
    var EUR: Price?
    var AUD: Price?
}

let usdPrice = Price(fifteenMin: 10, last: 11, buy: 12, sell: 13, symbol: "$")
let jpyPrice = Price(fifteenMin: 10, last: 11, buy: 12, sell: 13, symbol: "¥")
var currencies = Currencies()
currencies.USD = usdPrice

// Encode data
let jsonEncoder = JSONEncoder()
do {
    let jsonData = try jsonEncoder.encode(currencies)
    let jsonString = String(data: jsonData, encoding: .utf8)
    print("JSON String : " + jsonString!)
    do {
        // Decode data to object
        let jsonDecoder = JSONDecoder()
        let currencies = try jsonDecoder.decode(Currencies.self, from: jsonData)

        print("USD: \(currencies.USD)")
        print("JPY: \(currencies.JPY)")
    }
    catch {
    }

}
catch {
}
</code>```

Body:
I am trying to decode JSON object using Codable with Swift 4:

{
USD: {
"15m": 9977.49,
last: 9977.49,
buy: 9979.36,
sell: 9975.62,
symbol: "$"
    },
AUD: {
"15m": 13181.69,
last: 13181.69,
buy: 13184.16,
sell: 13179.22,
symbol: "$"
    },
TBD: {
"15m": 13181.69,
last: 13181.69,
buy: 13184.16,
sell: 13179.22,
symbol: "$"
    }
}

This is what I've done so far with a model of an object:

struct Currency: Codable {

    let fifteenMin: Double?
    let last: Double?
    let buy: Double
    let sell: Double
    let symbol: String

    enum CodingKeys: String, CodingKey {
        case fifteenMin = "15m"
        case last
        case buy
        case sell
        case symbol
    }
}

And this is how I decode that:

var currencyName = [String]()
var currenciesArray = [Currency]()

func fetchCurrencyData() {
    guard let urlString = API.RateURL.absoluteString else { return }
    guard let url = URL(string: urlString) else { return }
    let jsonData = try! Data(contentsOf: url)
    let decoder = JSONDecoder()
    do {
        let currenciesData = try decoder.decode([String: Currency].self, from: jsonData)
        for currency in currenciesData {
            self.currencyName.append(currency.key)
            self.currenciesArray.append(currency.value)
        }
    } catch let err {
        print(err.localizedDescription)
    }
}

So when I want to populate rows in tableView with that Data I use "for loop" and append "USD", "AUD" and so on in one array and Currency object in another array.

What is the better way of fetching data and populating Currency object. Cuz I am pretty sure that fetching and appending the same object of JSON into two separate arrays isn't good practice I assume.

If my question isn't clear I can explain in more details what I would like to achieve.

Thank you.

Body:
Shouldn't the currency name be inside the Currency object? That would be much easier to manipulate.

But if you must use that format, you can create an array of tuples or dictionaries.

var currenciesArray = [(String, Currency)]()

and then append like this:

for currency in currenciesData {
    currenciesArray.append((currency.key, currency.value))
}

p.s. : You need to add quotes(") on the string values inside the JSON, or it will be invalid.

****Added*****

The code below will encode and decode a JSON similar to the one you mentioned:

struct Price: Codable {

    let fifteenMin: Double?
    let last: Double?
    let buy: Double
    let sell: Double
    let symbol: String

    enum CodingKeys: String, CodingKey {
        case fifteenMin = "15m"
        case last
        case buy
        case sell
        case symbol
    }
}

struct Currencies: Codable {
    var USD: Price?
    var JPY: Price?
    var EUR: Price?
    var AUD: Price?
}

let usdPrice = Price(fifteenMin: 10, last: 11, buy: 12, sell: 13, symbol: "$")
let jpyPrice = Price(fifteenMin: 10, last: 11, buy: 12, sell: 13, symbol: "¥")
var currencies = Currencies()
currencies.USD = usdPrice

// Encode data
let jsonEncoder = JSONEncoder()
do {
    let jsonData = try jsonEncoder.encode(currencies)
    let jsonString = String(data: jsonData, encoding: .utf8)
    print("JSON String : " + jsonString!)
    do {
        // Decode data to object
        let jsonDecoder = JSONDecoder()
        let currencies = try jsonDecoder.decode(Currencies.self, from: jsonData)

        print("USD: \(currencies.USD)")
        print("JPY: \(currencies.JPY)")
    }
    catch {
    }

}
catch {
}


问:
Python: How can I get the current page’s title as a variable in Flask?
Say I have this HTML page;

```<code><html>
    <head>
        <title>I want this as a variable</title>
    </head>
    <body>
        <h1>Hello World</h1>
    </body>
</html>
</code>```

And a Python variable in my app called x, how could I make x = 'I want this as a variable'?

答:
BeautifulSoup is great for this:
https://www.crummy.com/software/BeautifulSoup/bs4/doc/</p>

```<code>from bs4 import BeautifulSoup
html_doc = """
<html>
    <head>
        <title>I want this as a variable</title>
    </head>
    <body>
        <h1>Hello World</h1>
    </body>
</html>
"""

soup = BeautifulSoup(html_doc, 'html.parser')

x = soup.title.text
</code>```

Body:
Say I have this HTML page;

        <title>I want this as a variable</title>

Hello World

And a Python variable in my app called x, how could I make x = 'I want this as a variable'?

Body:
BeautifulSoup is great for this:
https://www.crummy.com/software/BeautifulSoup/bs4/doc/

from bs4 import BeautifulSoup
html_doc = """
<html>
    <head>
        <title>I want this as a variable</title>
    </head>
    <body>
        <h1>Hello World</h1>
    </body>
</html>
"""

soup = BeautifulSoup(html_doc, 'html.parser')

x = soup.title.text


问:
Define the queue condition for Heapq Python
I have lists :

```<code>mylist = [[3, "A", "X", "xyz", 0.93243],[43, "C", "X", "zyx", 0.23243],[13, "B", "X", "xyz", 0.43243]]

heapq.heapify(mylist)
mylist
[[3, 'A', 'X', 'xyz', 0.93243],
 [43, 'C', 'X', 'zyx', 0.23243],
 [13, 'B', 'X', 'xyz', 0.43243]]
</code>```

When I want to pop list by using heapq.heappop(mylist).
First item that will be popped is [3, 'A', 'X', 'xyz', 0.93243]. I guess, it is because the first value (3) in the item list is the lowest.

Is it possible If I want to use the last value, index[4] as the basis. So the popping item is based on the last element in the list?

Expected output when I want to pop item, the first item will be popped is [43, 'C', 'X', 'zyx', 0.23243] because the index[4] has lowest value which is 0.23243

答:
Your lists need to be objects that implement a custom cmp function like so:</p>

```<code>class MyObject():
...
...     def __cmp__(self, other):
...         return cmp(self.val, other.val)
...
</code>```

Body:
I have lists :

mylist = [[3, "A", "X", "xyz", 0.93243],[43, "C", "X", "zyx", 0.23243],[13, "B", "X", "xyz", 0.43243]]

heapq.heapify(mylist)
mylist
[[3, 'A', 'X', 'xyz', 0.93243],
 [43, 'C', 'X', 'zyx', 0.23243],
 [13, 'B', 'X', 'xyz', 0.43243]]

When I want to pop list by using heapq.heappop(mylist).
First item that will be popped is [3, 'A', 'X', 'xyz', 0.93243]. I guess, it is because the first value (3) in the item list is the lowest.

Is it possible If I want to use the last value, index[4] as the basis. So the popping item is based on the last element in the list?

Expected output when I want to pop item, the first item will be popped is [43, 'C', 'X', 'zyx', 0.23243] because the index[4] has lowest value which is 0.23243

Body:
Your lists need to be objects that implement a custom cmp function like so:

class MyObject():
...
...     def __cmp__(self, other):
...         return cmp(self.val, other.val)
...


答:
Add view takes View object. You are passing the layout Id.

addView(View view)

you do not pass the layout Id

flContainer.addView(R.layout.sub_layout);// Wrong

First inflate a view using inflater then add it to container.

```<code> View view=LayoutInflater.from(getContext()).inflate(R.layout.yourView,null);
  yourContainer.addView(view);
</code>```

Body:
I have a fragment layout to which i want to add another sub layout dynamically ,

I tried this https://stackoverflow.com/a/22592269/8476022

sub-layout xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="20dp"
    android:hint="Question"
    android:textColor="@color/colorTextBlack"
    android:textSize="16dp" />
</android.support.constraint.ConstraintLayout>

this is my main layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f2f2f2"
android:orientation="vertical">
<FrameLayout
    android:id="@+id/flContainer"
    android:layout_width="match_parent"
    android:layout_margin="20dp"
    android:layout_height="wrap_content"/>
</LinearLayout>

inside my fragment i included the sublayout

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_start_question, container, false);
     flContainer = (FrameLayout) v.findViewById(R.id.flContainer);
     flContainer.addView(R.layout.sub_layout);
    return v;
}

but i am getting error near addView the screenshot is below

can anyone please help to find the error

Body:
Add view takes View object. You are passing the layout Id.

addView(View view)

you do not pass the layout Id

flContainer.addView(R.layout.sub_layout);// Wrong

First inflate a view using inflater then add it to container.

 View view=LayoutInflater.from(getContext()).inflate(R.layout.yourView,null);
  yourContainer.addView(view);


问:
MDX TopPrice (max) for each group
I have a query like

```<code>SELECT
 NON EMPTY
{
[Measures].[ItemPrice]
}
 ON COLUMNS ,
 NON EMPTY
[DimItemView].[ItemName].[ItemName]
*[DimDateView].[MonthOfYear].[MonthOfYear]
*[DimCustomerView].[CustomerName].[CustomerName]
on rows

FROM [Model]
WHERE (
[DimCompanyView].[CompanyKey].&[smr],
[DimDateView].[Year].&[2017],
[DimCurrencyParam].[CurrencyCode].&[TL],
[DimItemView].[ItemKey].&[03001],--Filtered for single item, just for simplicity. Will be all ItemKey s
[DimDateView].[MonthName].[All])
</code>```

And the output is

Another query

```<code>WITH
  SET [AllItems] AS [DimItemView].[ItemName].[ItemName]
  SET [AllMonths] AS [DimDateView].[MonthOfYear].[MonthOfYear]

  SET [A] AS
    Generate
    (
    {[AllItems]*[AllMonths] } AS s
     ,
       s.current*
        TopCount
        (
            [DimCustomerView].[CustomerName].[CustomerName]
            ,1
            ,[Measures].[ItemPrice]
        )
    )
SELECT
  [Measures].[ItemPrice]
ON 0
 ,
[A] ON 1

FROM [Model]
WHERE (
[DimCompanyView].[CompanyKey].&[smr],
[DimDateView].[Year].&[2017],
[DimCurrencyParam].[CurrencyCode].&[TL],
[DimItemView].[ItemKey].&[03001], --Filtered for single item, just for simplicity. Will be all ItemKey s
[DimDateView].[MonthName].[All])
</code>```

And the output is

What I would like to achieve is Left join two result in a single query, but containing TopPrice for each row for the left result for corresponding group (ItemName and MonthOfYear). Desired output is like

Any help appreciated.

答:
ItemPrice=ExwAmount/QtyKg

Actually below code is gives me expected results, but too slow. Any improvments?

```<code>WITH
MEMBER [Measures].[GroupPrice] AS
max([DimCustomerView].[CustomerName].Members,[Measures].[ItemPrice])

SELECT
NON EMPTY
{
[Measures].[ItemPrice],
[Measures].[GroupPrice]
}
 ON COLUMNS ,
 NON EMPTY
[DimItemView].[ItemName].[ItemName]
*[DimDateView].[MonthOfYear].[MonthOfYear]
*[DimCustomerView].[CustomerName].[CustomerName]
having [Measures].[Fiili_Fiyat]<>0
on rows
</code>```

Title: MDX TopPrice (max) for each group

Body:
I have a query like

SELECT
 NON EMPTY
{
[Measures].[ItemPrice]
}
 ON COLUMNS ,
 NON EMPTY
[DimItemView].[ItemName].[ItemName]
*[DimDateView].[MonthOfYear].[MonthOfYear]
*[DimCustomerView].[CustomerName].[CustomerName]
on rows

FROM [Model]
WHERE (
[DimCompanyView].[CompanyKey].&[smr],
[DimDateView].[Year].&[2017],
[DimCurrencyParam].[CurrencyCode].&[TL],
[DimItemView].[ItemKey].&[03001],--Filtered for single item, just for simplicity. Will be all ItemKey s
[DimDateView].[MonthName].[All])

And the output is

Another query

WITH
  SET [AllItems] AS [DimItemView].[ItemName].[ItemName]
  SET [AllMonths] AS [DimDateView].[MonthOfYear].[MonthOfYear]

  SET [A] AS
    Generate
    (
    {[AllItems]*[AllMonths] } AS s
     ,
       s.current*
        TopCount
        (
            [DimCustomerView].[CustomerName].[CustomerName]
            ,1
            ,[Measures].[ItemPrice]
        )
    )
SELECT
  [Measures].[ItemPrice]
ON 0
 ,
[A] ON 1

FROM [Model]
WHERE (
[DimCompanyView].[CompanyKey].&[smr],
[DimDateView].[Year].&[2017],
[DimCurrencyParam].[CurrencyCode].&[TL],
[DimItemView].[ItemKey].&[03001], --Filtered for single item, just for simplicity. Will be all ItemKey s
[DimDateView].[MonthName].[All])

And the output is

What I would like to achieve is Left join two result in a single query, but containing TopPrice for each row for the left result for corresponding group (ItemName and MonthOfYear). Desired output is like

Any help appreciated.

Body:
ItemPrice=ExwAmount/QtyKg

Actually below code is gives me expected results, but too slow. Any improvments?

WITH
MEMBER [Measures].[GroupPrice] AS
max([DimCustomerView].[CustomerName].Members,[Measures].[ItemPrice])

SELECT
NON EMPTY
{
[Measures].[ItemPrice],
[Measures].[GroupPrice]
}
 ON COLUMNS ,
 NON EMPTY
[DimItemView].[ItemName].[ItemName]
*[DimDateView].[MonthOfYear].[MonthOfYear]
*[DimCustomerView].[CustomerName].[CustomerName]
having [Measures].[Fiili_Fiyat]<>0
on rows


问:
How to display thumbnail in floating container using Angular?
I've created a couple of sample product. Right now I able to display it just fine, but somehow the product is shown vertically. I would like it to appear horizontally once it max out the floating space next thumbnail can move onto the next line.

I've created a floating container and put my *ngfor inside it. Anything that I'm missing?

Here is my html code,

```<code><div class="text-center m-t-lg">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet">

  <h1>Public Shared Diary</h1>

  <div class="container-fluid">

  <div *ngFor="let pub_diary of diaries_temp;let i = index" [attr.data-index]="i">

    <div class="container-fluid">
      <div class="thumbnail" style="min-height:320px;height:320px;min-width:220px;width:220px;">
        <h2>Project title = {{pub_diary.project_name}}</h2>
        <img style="min-height:150px;height:150px;" src="{{pub_diary.project_image}}">
      </div>
    </div>

  </div>
  </div>

</div>
</code>```

and here is the current output. The red marking is where I would like the thumbnail to be.

答:
Add </p>

```<code>.thumbnail {display: inline-block; vertical-align: middle;}
</code>```

Body:
I've created a couple of sample product. Right now I able to display it just fine, but somehow the product is shown vertically. I would like it to appear horizontally once it max out the floating space next thumbnail can move onto the next line.

I've created a floating container and put my *ngfor inside it. Anything that I'm missing?

Here is my html code,

  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet">

Public Shared Diary

Project title = {{pub_diary.project_name}}

and here is the current output. The red marking is where I would like the thumbnail to be.

Body:
Add

.thumbnail {display: inline-block; vertical-align: middle;}