问:
Ionic Cordova: Is there a way to set fixed cordova-ios version
Currently I am building an Ionic App.

When i clone a fresh copy of my repo and add platform ios, cordova-ios@5.0.1 is used because of following line in config.xml

```<code><engine name="ios" spec="5.0.1" />
</code>```

But when i remove platform iOS, this line also gets removed.

Therefore, on the next read cordova-ios@4.x.x gets installed. But I need at least version 5.0.1 otherwise the Google Maps plugin wont work.

Can i somehow force the use of cordova-ios@5.0.1?

Tried to find resolutions to the problems and tried various different settings in package.json and config.xml, nothing helps.

答:
When adding the platform again (either in your build-script or manually), try

```<code>ionic cordova platform add ios@5.0.1
</code>```

or

```<code>ionic cordova platform add ios@latest
</code>```

Also the platform version is probably defined in your package.json. Maybe there the old version is set to 4.x.x, which is why it still downloads the older version, when not specifying the version yourself.

Body:
Currently I am building an Ionic App.

When i clone a fresh copy of my repo and add platform ios, cordova-ios@5.0.1 is used because of following line in config.xml

<engine name="ios" spec="5.0.1" />

But when i remove platform iOS, this line also gets removed.

Therefore, on the next read cordova-ios@4.x.x gets installed. But I need at least version 5.0.1 otherwise the Google Maps plugin wont work.

Can i somehow force the use of cordova-ios@5.0.1?

Tried to find resolutions to the problems and tried various different settings in package.json and config.xml, nothing helps.

Body:
When adding the platform again (either in your build-script or manually), try

ionic cordova platform add ios@5.0.1

or

ionic cordova platform add ios@latest

Also the platform version is probably defined in your package.json. Maybe there the old version is set to 4.x.x, which is why it still downloads the older version, when not specifying the version yourself.


来源: stackexchange

问:
Swift: How can i put cells together and adjust the cell width of a TableView depending on the amount of text
I am familiar with TableView/CollectionsView and TableViewCells/CollectionsViewCells and loading data onto them.

I am however facing a challenge, I have an array of sentences and i'm hoping to achieve the design below.

https://imgur.com/a/bI2qNDy

Think of it as though you are reading a book and each cell contains a sentence. So you would want a sentence to start after a full stop and not in a new line. Image should explain what i'm trying to achieve. In this case a cell should start when one cells ends.

So i'm not sure on how to approach this challenge. If you could please share your suggestions.

I have successfully loaded the data into the tableview and collectionview and i have tried adjusting the size of the cells. However, the cells are not wrapping.

答:
You can achieve that with UICollectionView using custom Flow layout.
Here it is.</p>

ContentLicense: CC BY-SA 4.0


问:
Combining objects in an array by common keys and values
I have a dataset, an array of objects, I need to combine by a common key (Date) and then merge the UserName as the key for the UserScore.
I am planning to graph this data with d3 and have the solution using some of d3's methods but would like to write it with vanilla JS. Here is a sample of the raw data

```<code>[
  {
    "Date": "2019-05-02 00:00:00 UTC",
    "UserName": "user1",
    "UserScore": "39"
  },
  {
    "Date": "2019-05-02 00:00:00 UTC",
    "UserName": "user2",
    "UserScore": "11"
  },
  {
    "Date": "2019-05-02 00:00:00 UTC",
    "UserName": "user3",
    "UserScore": "4"
  },
  {
    "Date": "2019-05-02 01:01:01 UTC",
    "UserName": "user1",
    "UserScore": "57"
  },
  {
    "Date": "2019-05-02 01:01:01 UTC",
    "UserName": "user2",
    "UserScore": "1"
  },
  {
    "Date": "2019-05-02 01:01:01 UTC",
    "UserName": "user3",
    "UserScore": "42"
  }
]

</code>```

Here is my desired output

```<code>   {
    "Date": "2019-05-02 00:00:00 UTC",
    "user1": "39",
    "user2": "11",
    "user3": "4"
   },
   {
    "Date": "2019-05-02 01:01:01 UTC",
    "user1": "57",
    "user2": "1",
    "user3": "42"
   }
]
</code>```

答:
You can use reduce() to group them.

const arr = [ { "Date": "2019-05-02 00:00:00 UTC", "UserName": "user1", "UserScore": "39" }, { "Date": "2019-05-02 00:00:00 UTC", "UserName": "user2", "UserScore": "11" }, { "Date": "2019-05-02 00:00:00 UTC", "UserName": "user3", "UserScore": "4" }, { "Date": "2019-05-02 01:01:01 UTC", "UserName": "user1", "UserScore": "57" }, { "Date": "2019-05-02 01:01:01 UTC", "UserName": "user2", "UserScore": "1" }, { "Date": "2019-05-02 01:01:01 UTC", "UserName": "user3", "UserScore": "42" } ]

const res = arr.reduce((ac,{Date,UserName,UserScore}) => {
  ac[Date] = ac[Date] || {Date};
  ac[Date][UserName] = UserScore;
  return ac;
},{})

console.log(Object.values(res))```

Body:
I have a dataset, an array of objects, I need to combine by a common key (Date) and then merge the UserName as the key for the UserScore.
I am planning to graph this data with d3 and have the solution using some of d3's methods but would like to write it with vanilla JS. Here is a sample of the raw data

[
  {
    "Date": "2019-05-02 00:00:00 UTC",
    "UserName": "user1",
    "UserScore": "39"
  },
  {
    "Date": "2019-05-02 00:00:00 UTC",
    "UserName": "user2",
    "UserScore": "11"
  },
  {
    "Date": "2019-05-02 00:00:00 UTC",
    "UserName": "user3",
    "UserScore": "4"
  },
  {
    "Date": "2019-05-02 01:01:01 UTC",
    "UserName": "user1",
    "UserScore": "57"
  },
  {
    "Date": "2019-05-02 01:01:01 UTC",
    "UserName": "user2",
    "UserScore": "1"
  },
  {
    "Date": "2019-05-02 01:01:01 UTC",
    "UserName": "user3",
    "UserScore": "42"
  }
]

Here is my desired output

   {
    "Date": "2019-05-02 00:00:00 UTC",
    "user1": "39",
    "user2": "11",
    "user3": "4"
   },
   {
    "Date": "2019-05-02 01:01:01 UTC",
    "user1": "57",
    "user2": "1",
    "user3": "42"
   }
]


问:
How I Do Dynamic Size box
I have a box that when I choose something , I want to see my choose there (like a shopping cart).
I want the box will be dynamic, which means that there will be no text overflow from the box (No text overflow down)

HTML

```<code><div class="box-s">
  <p  style="text-align: left; width:49%; display: inline-block;">{{mealService.getName()}}</p>
  <p  style="text-align: right; width:49%; display: inline-block;">{{mealService.getPrice()}}$</p>
</code>```

CSS

```<code>.box-s{
  position: absolute;
  top: 10px;
  right: 10px;
  width: 300px;
  height: 350px;
  background: #fff;
  color: #9e9e9e;
  margin: 0 auto;
  margin-bottom: 20px;
  text-align: center;
  line-height: 35px;
  font-family: "Forte";
  font-size: 20px;
}

</code>```

thanks:)

答:
my solution is in the css file need to change height to min-height</p>

```<code>.box-s{
  position: absolute;
  top: 10px;
  right: 10px;
  width: 300px;
  min-height: 350px;
  background: #fff;
  color: #9e9e9e;
  margin: 0 auto;
  margin-bottom: 20px;
  text-align: center;
  line-height: 35px;
  font-family: "Forte";
  font-size: 20px;
}
</code>```

Title: How I Do Dynamic Size box

Body:
I have a box that when I choose something , I want to see my choose there (like a shopping cart).
I want the box will be dynamic, which means that there will be no text overflow from the box (No text overflow down)

HTML

{{mealService.getName()}}

{{mealService.getPrice()}}$

CSS

.box-s{
  position: absolute;
  top: 10px;
  right: 10px;
  width: 300px;
  height: 350px;
  background: #fff;
  color: #9e9e9e;
  margin: 0 auto;
  margin-bottom: 20px;
  text-align: center;
  line-height: 35px;
  font-family: "Forte";
  font-size: 20px;
}

thanks:)

Body:
my solution is in the css file need to change height to min-height

.box-s{
  position: absolute;
  top: 10px;
  right: 10px;
  width: 300px;
  min-height: 350px;
  background: #fff;
  color: #9e9e9e;
  margin: 0 auto;
  margin-bottom: 20px;
  text-align: center;
  line-height: 35px;
  font-family: "Forte";
  font-size: 20px;
}


问:
How can I get DownloadableURL from firebase storage using the internal storage location in node.js app?
I'm relatively new to firebase and currently working on node.js (react-electron) app, my goal is to display some picture which was stored in firebase-storage.

In my app, I know the internal firebase storage URL gs://myapp.appspot.com/folders/image.jpg and want to get downloadableURL https://firebasestorage.googleapis.com/...

So here's the problem: I know that there is refFromURL() and getDownloadURL() method from firebase storage and I planned to do this

```<code>import firebase from 'firebase';
import config from './firebaseConfig.json';
firebase.initializeApp(config);
var storage = firebase.storage();

function fetchTrueImgsrc(internalSrc) {
  if (internalSrc === undefined) return null;
  return storage.refFromURL(internalSrc).getDownloadURL();
}
</code>```

And I got this

Line 4: Uncaught TypeError: firebase__WEBPACK_IMPORTED_MODULE_1___default.a.storage is not a function

I have found out that firebase.storage() is no longer support for node.js and all of document on https://firebase.google.com/docs/storage/web/start is totally useless for me

So the question is, how would I implement this in node.js client side if I can't use firebase.storage? please help.

I have tried:

```<code>const myappBucket='myapp.appspot.com';
import { Storage } from '@google-cloud/storage';
const bucket = new Storage().bucket(myappBucket);
const file = bucket.file(internalSrc);
file
  .getSignedUrl({
    action: 'read',
    expires: '03-09-2491'
  })
  .then(signedUrls => {
    console.log('signed URL', signedUrls[0]); // this will contain the picture's url
    return;
  })
  .catch(err => console.error(err));
</code>```

```<code>const myappBucket='myapp.appspot.com';
import config from './firebaseConfig.json';
import firebase_admin from 'firebase-admin';
firebase_admin.initializeApp(config);
var storage = firebase_admin.storage();
var bucket = storage.bucket(myappBucket);
bucket.file(internalSrc).getSignedUrl(
  {
    action: 'read',
    expires: '03-09-2491'
  },
  function(err, url) {
    if (err) {
      console.error(err);
    } else {
      console.log('Download model DL url: ' + url);
    }
  }
);
</code>```

Both got this error

SigningError: Unexpected error determining execution environment: Failed to fetch at GoogleAuth.

I tried to avoid Downgrading firebase to firebase@v4.7.0 but if there is no solution for this, I think i should try this too.

I'm using:
    - "@google-cloud/storage": "^2.5.0"
    - "firebase": "^6.0.2"
    - "firebase-admin": "^7.3.0"
    - "react": "^16.8.6"
    - "electron": "^3.0.10"

thanks.

答:
Here's a code example which returns the download url for your file after upload using the ADMIN SDK :

```<code>firebase.storage().bucket().upload('your/file', {
                destination: `where/you/want/it`,
            }).catch((error) => {
                throw error;
            }).then((result) => {
                result[0].getSignedUrl({
                    action: 'read'
                }).then((url) => {
                    url[0] // your url
                })
            });
</code>```

Here's the exact same question : Post

Body:
I'm relatively new to firebase and currently working on node.js (react-electron) app, my goal is to display some picture which was stored in firebase-storage.

In my app, I know the internal firebase storage URL gs://myapp.appspot.com/folders/image.jpg and want to get downloadableURL https://firebasestorage.googleapis.com/...

So here's the problem: I know that there is refFromURL() and getDownloadURL() method from firebase storage and I planned to do this

import firebase from 'firebase';
import config from './firebaseConfig.json';
firebase.initializeApp(config);
var storage = firebase.storage();

function fetchTrueImgsrc(internalSrc) {
  if (internalSrc === undefined) return null;
  return storage.refFromURL(internalSrc).getDownloadURL();
}

And I got this

Line 4: Uncaught TypeError: firebase__WEBPACK_IMPORTED_MODULE_1___default.a.storage is not a function

I have found out that firebase.storage() is no longer support for node.js and all of document on https://firebase.google.com/docs/storage/web/start is totally useless for me

So the question is, how would I implement this in node.js client side if I can't use firebase.storage? please help.

I have tried:

const myappBucket='myapp.appspot.com';
import { Storage } from '@google-cloud/storage';
const bucket = new Storage().bucket(myappBucket);
const file = bucket.file(internalSrc);
file
  .getSignedUrl({
    action: 'read',
    expires: '03-09-2491'
  })
  .then(signedUrls => {
    console.log('signed URL', signedUrls[0]); // this will contain the picture's url
    return;
  })
  .catch(err => console.error(err));

const myappBucket='myapp.appspot.com';
import config from './firebaseConfig.json';
import firebase_admin from 'firebase-admin';
firebase_admin.initializeApp(config);
var storage = firebase_admin.storage();
var bucket = storage.bucket(myappBucket);
bucket.file(internalSrc).getSignedUrl(
  {
    action: 'read',
    expires: '03-09-2491'
  },
  function(err, url) {
    if (err) {
      console.error(err);
    } else {
      console.log('Download model DL url: ' + url);
    }
  }
);

Both got this error

SigningError: Unexpected error determining execution environment: Failed to fetch at GoogleAuth.

I tried to avoid Downgrading firebase to firebase@v4.7.0 but if there is no solution for this, I think i should try this too.

I'm using:
    - "@google-cloud/storage": "^2.5.0"
    - "firebase": "^6.0.2"
    - "firebase-admin": "^7.3.0"
    - "react": "^16.8.6"
    - "electron": "^3.0.10"

thanks.

Body:
Here's a code example which returns the download url for your file after upload using the ADMIN SDK :

firebase.storage().bucket().upload('your/file', {
                destination: `where/you/want/it`,
            }).catch((error) => {
                throw error;
            }).then((result) => {
                result[0].getSignedUrl({
                    action: 'read'
                }).then((url) => {
                    url[0] // your url
                })
            });

Here's the exact same question : Post


问:
Is it possible to change multiple values, by different amounts concurrently?
I'm trying to resize and relocate an object, by changing the x, y and area values, all at the same time.
I can do them one after another by running 3 separate for loops, but the animation needs to be smooth and as one.

I tried nesting another for loop inside the function but that provides the same result as 1 loop has to finish before the next one starts.
The only way I can find to complete it is to make 3 separate scripts and run all 3 at the same time.

```<code>SSxPOSA =  0.00
SSxPOSB =  -12.00
SSyPOSA =  0.00
SSyPOSB =  -6.55
SSsizeA =  1.00
SSsizeB =  0.2

function SSBox1X()
    for i = SSxPOSA, SSxPOSB, 0.1
    do
    Object1X( i );
    end;
end;
function SSBox1Y()
    for i = SSyPOSA, SSyPOSB, 0.5
    do
    Object1Y( i );
    end;
end;
function SSBox1Scale()
    for i = SSsizeA, SSsizeB, 0.8
    do
    Object1Scale( i );
    end;
end;

SSBox1X();
SSBox1Y();
SSBox1Scale();
</code>```

Happy to read and learn best practice

答:
If I understood your problem correctly, something like this should work:

```<code>function xys()
  local x, y, s = SSxPOSA, SSyPOSA, SSsizeA
  return coroutine.wrap(
         function()
           while x >= SSxPOSB and y >= SSyPOSB and s >= SSsizeB do
             coroutine.yield(x,y,s)
             x = x - 0.1
             y = y - 0.5
             s = s - 0.8
           end
         end)
end

SSxPOSA =  0.00
SSxPOSB =  -12.00

SSyPOSA =  0.00
SSyPOSB =  -6.55

SSsizeA =  1.00
SSsizeB =  0.2

for x,y,s in xys() do
  print(x,y,s)
  --Object1X(x)
  --Object1Y(y)
  --Object1Scale(s)
end
</code>```

And, because of floating point comparison not always yielding the expected result, it's probably better to convert to integers and divide just before using.  Like so:

```<code>function xys()
  local x, y, s = SSxPOSA, SSyPOSA, SSsizeA
  return coroutine.wrap(
         function()
           while x >= SSxPOSB and y >= SSyPOSB and s >= SSsizeB do
             coroutine.yield(x/100,y/100,s/100)
             x = x - 10
             y = y - 50
             s = s - 80
           end
         end)
end

SSxPOSA =  0
SSxPOSB =  -1200

SSyPOSA =  0
SSyPOSB =  -655

SSsizeA =  100
SSsizeB =  20

for x,y,s in xys() do
  print(x,y,s)
  --Object1X(x)
  --Object1Y(y)
  --Object1Scale(s)
end
</code>```

You can also do it without coroutines:

```<code>function xys()
  local x, y, s = SSxPOSA, SSyPOSA, SSsizeA
  return function()
           if x < SSxPOSB or y < SSyPOSB or s < SSsizeB then return end
           local xx, yy, ss = x/100, y/100, s/100
           x = x - 10
           y = y - 50
           s = s - 80
           return xx,yy,ss
         end
end
</code>```

Body:
I'm trying to resize and relocate an object, by changing the x, y and area values, all at the same time.
I can do them one after another by running 3 separate for loops, but the animation needs to be smooth and as one.

I tried nesting another for loop inside the function but that provides the same result as 1 loop has to finish before the next one starts.
The only way I can find to complete it is to make 3 separate scripts and run all 3 at the same time.

SSxPOSA =  0.00
SSxPOSB =  -12.00
SSyPOSA =  0.00
SSyPOSB =  -6.55
SSsizeA =  1.00
SSsizeB =  0.2

function SSBox1X()
    for i = SSxPOSA, SSxPOSB, 0.1
    do
    Object1X( i );
    end;
end;
function SSBox1Y()
    for i = SSyPOSA, SSyPOSB, 0.5
    do
    Object1Y( i );
    end;
end;
function SSBox1Scale()
    for i = SSsizeA, SSsizeB, 0.8
    do
    Object1Scale( i );
    end;
end;

SSBox1X();
SSBox1Y();
SSBox1Scale();

Happy to read and learn best practice

Body:
If I understood your problem correctly, something like this should work:

function xys()
  local x, y, s = SSxPOSA, SSyPOSA, SSsizeA
  return coroutine.wrap(
         function()
           while x >= SSxPOSB and y >= SSyPOSB and s >= SSsizeB do
             coroutine.yield(x,y,s)
             x = x - 0.1
             y = y - 0.5
             s = s - 0.8
           end
         end)
end

SSxPOSA =  0.00
SSxPOSB =  -12.00

SSyPOSA =  0.00
SSyPOSB =  -6.55

SSsizeA =  1.00
SSsizeB =  0.2

for x,y,s in xys() do
  print(x,y,s)
  --Object1X(x)
  --Object1Y(y)
  --Object1Scale(s)
end

And, because of floating point comparison not always yielding the expected result, it's probably better to convert to integers and divide just before using.  Like so:

function xys()
  local x, y, s = SSxPOSA, SSyPOSA, SSsizeA
  return coroutine.wrap(
         function()
           while x >= SSxPOSB and y >= SSyPOSB and s >= SSsizeB do
             coroutine.yield(x/100,y/100,s/100)
             x = x - 10
             y = y - 50
             s = s - 80
           end
         end)
end

SSxPOSA =  0
SSxPOSB =  -1200

SSyPOSA =  0
SSyPOSB =  -655

SSsizeA =  100
SSsizeB =  20

for x,y,s in xys() do
  print(x,y,s)
  --Object1X(x)
  --Object1Y(y)
  --Object1Scale(s)
end

You can also do it without coroutines:

function xys()
  local x, y, s = SSxPOSA, SSyPOSA, SSsizeA
  return function()
           if x < SSxPOSB or y < SSyPOSB or s < SSsizeB then return end
           local xx, yy, ss = x/100, y/100, s/100
           x = x - 10
           y = y - 50
           s = s - 80
           return xx,yy,ss
         end
end


问:
How do I dynamically append html snippets into the web page?
I have the following markup:

```<code><div id="maincontainer">
  <div id="mainMenu">

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

     <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

  </div>
  <div id="legalDocument"></div>
</div>
</code>```

, where the
 element is repeated multiple (9) times.

What is the best way to append such blocks dynamically, through for(){} cycle for example? The innerHtml property is not recommended from what I've heard. and using a special recursive function that I made doesn't seem to be the right way either.

What should I do? I'd like to extend my Web pages with templates kinda like how Javascript classes behave.

答:
You can do this:</p>

```<code>const giver = `
  <div class="giver">
     <hr class = "giver-hr">
     <select class ="giver-subject"></select>
     <select class ="giver-status"></select>
     <label class = giver-isClient>
       <input type = "radio">
       <span>lorem ipsum</span>
     </label>
  </div>
`;

for (let i = 0; i < 9; i++) {
  document.getElementById("mainMenu").insertAdjacentHTML("beforeend", giver);
}
</code>```

Body:
I have the following markup:

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

, where the
 element is repeated multiple (9) times.

What is the best way to append such blocks dynamically, through for(){} cycle for example? The innerHtml property is not recommended from what I've heard. and using a special recursive function that I made doesn't seem to be the right way either.

What should I do? I'd like to extend my Web pages with templates kinda like how Javascript classes behave.

Body:
You can do this:

const giver = `
  <div class="giver">
     <hr class = "giver-hr">
     <select class ="giver-subject"></select>
     <select class ="giver-status"></select>
     <label class = giver-isClient>
       <input type = "radio">
       <span>lorem ipsum</span>
     </label>
  </div>
`;

for (let i = 0; i < 9; i++) {
  document.getElementById("mainMenu").insertAdjacentHTML("beforeend", giver);
}


问:
How to find whether a string has repeated characters?
I have written this code ...and the answer I am expecting is not correct
in this code, if a string has repeated characters, it should return False
but its returning True in all cases

I have done this much coding to try to solve this problem
This is in JUPYTER notebook

```<code>def is_isogram(string):
   for i in string:
       if string.count(i) == 1:
           print('True')
       elif string.count(i) > 1:
           print('False')
</code>```

I typed 'Hello' it should return False, but returnung true in all cases

答:
This is a simple snippet you can use to check if the string has repeated characters. Iterate through all the characters and check if it has already come before.</p>

```<code>def is_isogram(s):
    mp = {}
    for c in s:
        if c in mp.keys():
            return False
        mp[c] = 1
    return True
</code>```

Body:
I have written this code ...and the answer I am expecting is not correct
in this code, if a string has repeated characters, it should return False
but its returning True in all cases

I have done this much coding to try to solve this problem
This is in JUPYTER notebook

def is_isogram(string):
   for i in string:
       if string.count(i) == 1:
           print('True')
       elif string.count(i) > 1:
           print('False')

I typed 'Hello' it should return False, but returnung true in all cases

Body:
This is a simple snippet you can use to check if the string has repeated characters. Iterate through all the characters and check if it has already come before.

def is_isogram(s):
    mp = {}
    for c in s:
        if c in mp.keys():
            return False
        mp[c] = 1
    return True


问:
Generating a sequence of leap years using clpfd
The code below checks whether a given year is a leap year or not. The arithmetic is formulated using declarative integer arithmetic from the library clpfd, in order that the query can be run in 'reverse' to generate a sequence of leap years. There are two variants of the code, altering the test for whether the year is a century or not, but the behaviour of each variant differs and neither of them work correctly.

I want to generate a sequence of leap years from 1990 to 2005. To do this, I am entering the query Year in 1990..2005,leap_year1(Year),indomain(Year). (or leap_year2 to test the second variant).

The code that I've written is (using SWI-Prolog 8.0.2):

```<code>:- use_module(library(clpfd)).

leap_year1(Year) :-
  Year #> 0,
  Year mod 4 #= 0,
  (
    Year mod 100 #= 0 ->
      Year mod 400 #= 0      % 2000 is a leap year, 1900 is not
    ;
      true                   % Not a century
  ).

leap_year2(Year) :-
  Year #> 0,
  Year mod 4 #= 0,
  (
    Year mod 100 #\= 0 ->
      true                   % Not a century
    ;
      Year mod 400 #= 0      % 2000 is a leap year, 1900 is not
  ).
</code>```

The results of the queries are (SWI-Prolog 8.0.2):

```<code>?- Year in 1990..2005,leap_year1(Year),indomain(Year).
Year = 2000.

?- Year in 1990..2005,leap_year2(Year),indomain(Year).
Year = 1992 ;
Year = 1996 ;
Year = 2004.
</code>```

As you can see, neither query correctly generates the full sequence of leap years (1992, 1996, 2000, 2004).

Further, the following queries around the year 1900 also generate anomalous results (comments added):

```<code>% Verify that 1900 is not a leap year
?- not(leap_year1(1900)), not(leap_year2(1900)).
true.

% Verify that 1892, 1896, 1904 are leap years
?- leap_year1(1892), leap_year1(1896), leap_year1(1904).
true.

?- leap_year2(1892), leap_year2(1896), leap_year2(1904).
true.

% No solutions found (!)
?- Year in 1890..1905,leap_year1(Year),indomain(Year).
false.

% Solutions found as expected (complete result)
?- Year in 1890..1905,leap_year2(Year),indomain(Year).
Year = 1892 ;
Year = 1896 ;
Year = 1904.
</code>```

Is there an explanation for this behaviour? How should I modify leap_year() so that it generates a complete sequence?

Update: (more?) complete, but don't understand why (!)

Splitting out the check for centuries improves the completeness of the query:

```<code>leap_year_century_fix(Year) :-
  Year mod 100 #\= 0.

leap_year_century_fix(Year) :-
  Year mod 100 #= 0,
  Year mod 400 #= 0.      % 2000 is a leap year, 1900 is not

leap_year3(Year) :-
  Year #> 0,
  Year mod 4 #= 0,
  leap_year_century_fix(Year).
</code>```

Now:

```<code>?- Year in 1890..1905,leap_year3(Year),indomain(Year).
Year = 1892 ;
Year = 1896 ;
Year = 1904 ;
false.

?- Year in 1990..2015,leap_year3(Year),indomain(Year).
Year = 1992 ;
Year = 1996 ;
Year = 2004 ;
Year = 2008 ;
Year = 2012 ;
Year = 2000.
</code>```

答:
Express it simply using and and or, and use reification for the or:

```<code>leap(Y) :-
    Y #> 0,
    Y mod 4 #= 0,
    (Y mod 100 #\= 0) #\/ (Y mod 400 #= 0).
</code>```

Body:
The code below checks whether a given year is a leap year or not. The arithmetic is formulated using declarative integer arithmetic from the library clpfd, in order that the query can be run in 'reverse' to generate a sequence of leap years. There are two variants of the code, altering the test for whether the year is a century or not, but the behaviour of each variant differs and neither of them work correctly.

I want to generate a sequence of leap years from 1990 to 2005. To do this, I am entering the query Year in 1990..2005,leap_year1(Year),indomain(Year). (or leap_year2 to test the second variant).

The code that I've written is (using SWI-Prolog 8.0.2):

:- use_module(library(clpfd)).

leap_year1(Year) :-
  Year #> 0,
  Year mod 4 #= 0,
  (
    Year mod 100 #= 0 ->
      Year mod 400 #= 0      % 2000 is a leap year, 1900 is not
    ;
      true                   % Not a century
  ).

leap_year2(Year) :-
  Year #> 0,
  Year mod 4 #= 0,
  (
    Year mod 100 #\= 0 ->
      true                   % Not a century
    ;
      Year mod 400 #= 0      % 2000 is a leap year, 1900 is not
  ).

The results of the queries are (SWI-Prolog 8.0.2):

?- Year in 1990..2005,leap_year1(Year),indomain(Year).
Year = 2000.

?- Year in 1990..2005,leap_year2(Year),indomain(Year).
Year = 1992 ;
Year = 1996 ;
Year = 2004.

As you can see, neither query correctly generates the full sequence of leap years (1992, 1996, 2000, 2004).

Further, the following queries around the year 1900 also generate anomalous results (comments added):

% Verify that 1900 is not a leap year
?- not(leap_year1(1900)), not(leap_year2(1900)).
true.

% Verify that 1892, 1896, 1904 are leap years
?- leap_year1(1892), leap_year1(1896), leap_year1(1904).
true.

?- leap_year2(1892), leap_year2(1896), leap_year2(1904).
true.

% No solutions found (!)
?- Year in 1890..1905,leap_year1(Year),indomain(Year).
false.

% Solutions found as expected (complete result)
?- Year in 1890..1905,leap_year2(Year),indomain(Year).
Year = 1892 ;
Year = 1896 ;
Year = 1904.

Is there an explanation for this behaviour? How should I modify leap_year() so that it generates a complete sequence?

Update: (more?) complete, but don't understand why (!)

Splitting out the check for centuries improves the completeness of the query:

leap_year_century_fix(Year) :-
  Year mod 100 #\= 0.

leap_year_century_fix(Year) :-
  Year mod 100 #= 0,
  Year mod 400 #= 0.      % 2000 is a leap year, 1900 is not

leap_year3(Year) :-
  Year #> 0,
  Year mod 4 #= 0,
  leap_year_century_fix(Year).

Now:

?- Year in 1890..1905,leap_year3(Year),indomain(Year).
Year = 1892 ;
Year = 1896 ;
Year = 1904 ;
false.

?- Year in 1990..2015,leap_year3(Year),indomain(Year).
Year = 1992 ;
Year = 1996 ;
Year = 2004 ;
Year = 2008 ;
Year = 2012 ;
Year = 2000.

Body:
Express it simply using and and or, and use reification for the or:

leap(Y) :-
    Y #> 0,
    Y mod 4 #= 0,
    (Y mod 100 #\= 0) #\/ (Y mod 400 #= 0).


问:
How to get a ACCESS_TOKEN in splitwise
I'm new make apps, now I'm working with splitwise and I just create an app.

The splitwise server give me:

Consumer Key
Consumer Secret
Token URL
and Authorize URL

But I Don´t know how to get a ACCESS_TOKEN with this data.

Can you help me please?

答:
Hi @user2533184 you can use nodejs to install the splitwise first using yarn command.

Step 1:

```<code>yarn add splitwise
</code>```

Step 2:

```<code>const Splitwise = require('splitwise');
const sw = Splitwise({
  consumerKey: 'ConsumerKey',
  consumerSecret: 'ConsumerSecret'
})
</code>```

And thats all you have to do.

and after that to access your username you can do:

```<code>sw.getCurrentUser().then(console.log)
</code>```

The further Javascript API docs you can find at :
https://github.com/keriwarr/splitwise

Title: How to get a ACCESS_TOKEN in splitwise

Body:
Hi @user2533184 you can use nodejs to install the splitwise first using yarn command.

Step 1:

yarn add splitwise

Step 2:

const Splitwise = require('splitwise');
const sw = Splitwise({
  consumerKey: 'ConsumerKey',
  consumerSecret: 'ConsumerSecret'
})

And thats all you have to do.

and after that to access your username you can do:

sw.getCurrentUser().then(console.log)

The further Javascript API docs you can find at :
https://github.com/keriwarr/splitwise


答:
You can be sure that your word isn't an isogram as soon as you find a count greater than one, but you can only be sure that it is one once you have checked all letters:

```<code>def is_isogram(string):
    for i in string:
        if string.count(i) > 1:
            return False
    return True

print(is_isogram('pear'))
#  True

print(is_isogram('apple'))
# False
</code>```

Or, if you really want your function to print its output instead of returning it, which I would generally not recommend:

```<code>def is_isogram(string):
    for i in string:
        if string.count(i) > 1:
            print('False')
            return
    print('True')
</code>```

A shorter, classic solution would be to make a set of characters, and to check if the number of unique characters is equal to the length of the string

```<code>def is_isogram2(string):
    return len(set(string)) == len(string)
</code>```

Title: How to find whether a string has repeated characters?

Body:
You can be sure that your word isn't an isogram as soon as you find a count greater than one, but you can only be sure that it is one once you have checked all letters:

def is_isogram(string):
    for i in string:
        if string.count(i) > 1:
            return False
    return True

print(is_isogram('pear'))
#  True

print(is_isogram('apple'))
# False

Or, if you really want your function to print its output instead of returning it, which I would generally not recommend:

def is_isogram(string):
    for i in string:
        if string.count(i) > 1:
            print('False')
            return
    print('True')

A shorter, classic solution would be to make a set of characters, and to check if the number of unique characters is equal to the length of the string

def is_isogram2(string):
    return len(set(string)) == len(string)


问:
unable to import module in same directory when using pytest
I am having a problem running pytest in a situation when my app calls another script in the same directory. Here is my directory structure:

```<code>├── my_project/
│   ├── application/
│   |   ├──__init__.py
│   |   ├──app.py
│   |   ├──utils.py
│   ├── application_test/
│   |   ├── __init__.py
│   │   ├── unit_test.py
</code>```

The code in app.py has the statement: from utils import func1, func2, func3 and this works fine when I run $ python app.py. However, when I run $ py.test from the my_project directory level, I get the error "ModuleNotFoundError: No module named 'utils'." The errors comes from this line in unit_test.py:

```<code>import application.app
</code>```

Because that line triggers app.py which then tries to import from utils.py and somehow app.py does not see the utils.py file even though it is in the same directory.

I have tried using $ python -m pytest application_test, as well as having __init__.py in the root and without, but none of these or other answers on stackoverflow seem to work.

答: It appears that import statements are relative to the directory you are currently in. The solution to calling another script in the same directory is to use relative imports. In this case, from .utils import func1, func2, func3 worked!

Body:
I am having a problem running pytest in a situation when my app calls another script in the same directory. Here is my directory structure:

├── my_project/
│   ├── application/
│   |   ├──__init__.py
│   |   ├──app.py
│   |   ├──utils.py
│   ├── application_test/
│   |   ├── __init__.py
│   │   ├── unit_test.py

The code in app.py has the statement: from utils import func1, func2, func3 and this works fine when I run $ python app.py. However, when I run $ py.test from the my_project directory level, I get the error "ModuleNotFoundError: No module named 'utils'." The errors comes from this line in unit_test.py:

import application.app

Because that line triggers app.py which then tries to import from utils.py and somehow app.py does not see the utils.py file even though it is in the same directory.

I have tried using $ python -m pytest application_test, as well as having __init__.py in the root and without, but none of these or other answers on stackoverflow seem to work.


问:
How to cast a mmap.mmap Python object into a string?
I'm making a Bottle powered program and I use the yield keyword with mmap.mmap object to send multiples mapped files in the output stream like in this code :

for mapping in mappings:
  yield mapping
```

This doesn't work out of the box because Bottle want a string (see Iterables and generators section) and when I use str(mapping), this return the object itself not the content.

So, I want to cast the mmap object into a string which contain the file content.

I'm thinking as the C programmer who just want to put a raw pointer

答:
After Googling for hours. I found out that simply using bytes(mapping) work.

    for mapping in mappings:
        yield bytes(mapping)
```

This way doesn't seem to do a temporary copy of mapped data

Body:
I'm making a Bottle powered program and I use the yield keyword with mmap.mmap object to send multiples mapped files in the output stream like in this code :

for mapping in mappings:
  yield mapping

This doesn't work out of the box because Bottle want a string (see Iterables and generators section) and when I use str(mapping), this return the object itself not the content.

So, I want to cast the mmap object into a string which contain the file content.

I'm thinking as the C programmer who just want to put a raw pointer

Body:
After Googling for hours. I found out that simply using bytes(mapping) work.

    for mapping in mappings:
        yield bytes(mapping)

This way doesn't seem to do a temporary copy of mapped data


问:
Is SX lock in MySQL the same as a update lock
According to All about locking in SQL Server, a update lock can be transformed into a exclusive lock when there is something to write. Meanwhile, the compatibility of the three locks(X,S and U) can be refer to the following table.

```<code>    X   S   U
X   ✗   ✗   ✗
S   ✗   ✓   ✓
U   ✗   ✓   ✗
</code>```

However, It is mentioned in some blogs that there is a SX lock since MySQL 5.7 which implements an idea from the paper Concurrency of operations on B-trees(1977). From these blogs I find the SX lock is quite similar with the update lock. For example, they have the same compatibility table.

Since I can't find more "official" introduction about the SX lock in MySQL, I want to ask what's the difference between both of the locks?

答:
Since the compatibility matrix defines a lock, having the same matrix makes the update lock and the sx lock equivalent.

Actually, in database theory, an update lock should behave asymmetrical, disallowing a new shared lock when there is already an update lock, see e.g. these lecture notes, penultimate page. Your reference also mentions this:

It is important to understand that update lock is asymmetrical in regards of shared locks. While the update lock can be imposed on a record that has the shared lock, the shared lock cannot be imposed on the record that already has the update lock

Practically though, both the MySQL sx-lock and the SQL Server (and others) update lock are symmetrical, like in your matrix.

The purpose of an update lock is to allow other transactions to still read the data (using a shared lock) while preventing a deadlock when two transactions want to escalate to a exclusive lock (as neither can do that when the other has a shared lock).

So, to conclude, the lock types are, in principle, the same, although I could imagine that they are named differently to emphasize that they are not intended to be asymmetric, and maybe to leave an option to later add the "real" update lock, so you may or may not want to treat them as unequal in that regard.

But there are major differences in how they are used. For example, in contrast to SQL Server, MySQL does not use update locks on rows: MySQL uses exclusive locks for updates, and to allow for concurrent reads, usually does not lock while reading, unless you use locking reads.

After acid requirements, the detailled behaviour (when which lock is applied on what object for what operation) is mostly relevant for performance and concurrency. While you could just lock the whole database for every query, this would only allow one query at a time, so the more fine-grained you lock specific objects, the more concurrency you allow (with the tradeoff to increase the risk of deadlocks).

Now to the purpose of the sx-locks in MySQL:

They were introduced to allow a more fine-tuned locking of indexes, see MySQL-5.7 improves DML oriented workloads, as some operations on indexes required the complete index to be exclusively locked, hindering concurrency. So the reason they are not more present int the documentation is that, although there might be other use cases for this type in the future, they are currently limited to very specific internal locking.

Body:
According to All about locking in SQL Server, a update lock can be transformed into a exclusive lock when there is something to write. Meanwhile, the compatibility of the three locks(X,S and U) can be refer to the following table.

    X   S   U
X   ✗   ✗   ✗
S   ✗   ✓   ✓
U   ✗   ✓   ✗

However, It is mentioned in some blogs that there is a SX lock since MySQL 5.7 which implements an idea from the paper Concurrency of operations on B-trees(1977). From these blogs I find the SX lock is quite similar with the update lock. For example, they have the same compatibility table.

Since I can't find more "official" introduction about the SX lock in MySQL, I want to ask what's the difference between both of the locks?


问:
Moving Orthographic Camera to following a line
I want to plot a series of polling data along a time line, namely (ti, f(ti), 0).
To get a better view, I also modify the (ortho) camera x-position to follow the data line.

The stationary referencing grid showed up just fine ("moving to the left" as time progresses). But the line disappears as soon as it goes over the "right" bound of the orthographic camera.

I tried to comment out the camera moving code (camera.position.x += 5) (... so that the camera does not move) and the line showed up all the way until it moves out of bound. ... but this is not what I want.

(best explained in this jsfiddle:
http://jsfiddle.net/jmcjc5u/4wfhb1da/)

```<code>xx += 0.1;
pt = new THREE.Vector3(xx, 5 * Math.sin(xx), 0);
addPoint(pt);

if (xx - camera.position.x > 5) {
   camera.position.x += 5
}
</code>```

答:
Simple solution would be to always render the line

jsfiddle

```<code>myLine.frustumCulled = false;
</code>```

Body:
I want to plot a series of polling data along a time line, namely (ti, f(ti), 0).
To get a better view, I also modify the (ortho) camera x-position to follow the data line.

The stationary referencing grid showed up just fine ("moving to the left" as time progresses). But the line disappears as soon as it goes over the "right" bound of the orthographic camera.

I tried to comment out the camera moving code (camera.position.x += 5) (... so that the camera does not move) and the line showed up all the way until it moves out of bound. ... but this is not what I want.

(best explained in this jsfiddle:
http://jsfiddle.net/jmcjc5u/4wfhb1da/)

xx += 0.1;
pt = new THREE.Vector3(xx, 5 * Math.sin(xx), 0);
addPoint(pt);

if (xx - camera.position.x > 5) {
   camera.position.x += 5
}

Body:
Simple solution would be to always render the line

jsfiddle

myLine.frustumCulled = false;


答:
You are printing True and False for each character in the string. Running your code with input "hello" will give 5 lines of output, two True, two False and one more True.

def is_isogram(string):
   for i in string:
       if string.count(i) > 1:
           return False
   return True
```

<p>This code will return either True or False. If any character in the string appears more than once, the function returns False and exits. If none of the characters appear more than once, it returns True after exiting the loop.</p>

<h3>Explanation of the code</h3>

<p>You can be sure that the word is not an isogram if any letter appears more than once, ie, you don't have to traverse the whole string, just until you find a repeated character. But to be sure that you have an isogram, you need to check the whole string.</p>

<p><code>for i in string:</code></p>

<p>This statement iterates through the loop character by character.</p>

<pre class="lang-py prettyprint-override"><code>    if string.count(i) > 1:
        return False
</code>```

The if statement checks if the current character, i, appears more than once in the string. If it does, the function returns False. If not, it continues to the next iteration.

```<code>    return True
</code>```

If the control has reached this statement, it means that none of the characters appear twice, as the function would have returned False before reaching this statement. So, the function returns True

Example

Consider the input "hello".

Iteration 1: i = 'h' and string.count('h') = 1

So, do nothing

Iteration 2: i = 'e' and string.count('e') = 1

So, do nothing

Iteration 3: i = 'l' and string.count('l') = 2

So, return False.

If you called the function like, print(is_isogram("hello")), False will be printed.

Consider another input "abcd"
Iteration 1: i = 'a' and string.count('a') = 1

So, do nothing

Iteration 2: i = 'b' and string.count('b') = 1

So, do nothing

Iteration 3: i = 'c' and string.count('c') = 1

So, do nothing

Iteration 4: i = 'd' and string.count('d') = 1

So, do nothing

At this point, the loop is exhausted and the return True statement is executed

Body:
You are printing True and False for each character in the string. Running your code with input "hello" will give 5 lines of output, two True, two False and one more True.

def is_isogram(string):
   for i in string:
       if string.count(i) > 1:
           return False
   return True

This code will return either True or False. If any character in the string appears more than once, the function returns False and exits. If none of the characters appear more than once, it returns True after exiting the loop.

Explanation of the code

You can be sure that the word is not an isogram if any letter appears more than once, ie, you don't have to traverse the whole string, just until you find a repeated character. But to be sure that you have an isogram, you need to check the whole string.

for i in string:

This statement iterates through the loop character by character.

    if string.count(i) > 1:
        return False

The if statement checks if the current character, i, appears more than once in the string. If it does, the function returns False. If not, it continues to the next iteration.

    return True

If the control has reached this statement, it means that none of the characters appear twice, as the function would have returned False before reaching this statement. So, the function returns True

Example

Consider the input "hello".

Iteration 1: i = 'h' and string.count('h') = 1

So, do nothing

Iteration 2: i = 'e' and string.count('e') = 1

So, do nothing

Iteration 3: i = 'l' and string.count('l') = 2

So, return False.

If you called the function like, print(is_isogram("hello")), False will be printed.

Consider another input "abcd"
Iteration 1: i = 'a' and string.count('a') = 1

So, do nothing

Iteration 2: i = 'b' and string.count('b') = 1

So, do nothing

Iteration 3: i = 'c' and string.count('c') = 1

So, do nothing

Iteration 4: i = 'd' and string.count('d') = 1

So, do nothing

At this point, the loop is exhausted and the return True statement is executed


问:
What's the difference between a mock & stub?
I've read various articles about mocking vs stubbing in testing, including Martin Fowler's Mocks Aren't Stubs, but still don't understand the difference.</p>

答:
Both Stubs and Mocks override external dependencies but the difference is

Stubs -> To Test Data

Mocks -> To Test Behavior

A quote from Fowler's Mocks Aren't Stubs article:

Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test.

Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive.

This obviously tells the difference.

Fake/Dummy -> Test nothing (just override functionality with empty methods, eg replace Logger to avoid any logging noise while testing)

ContentLicense: CC BY-SA 3.0


问:
How to find closest lower value in array angular 6?
I have an array of objects where I need to find closest lower value from that array based on some value or current value in angular 6, I have already tried but its showing undefined.

app.component.html

```<code><button (click) ="getPrev()">Previous Value</button>
</code>```

app.component.ts

```<code>declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
    arrayVal:any;
    currentVal : any;
  title = 'projectchart';
  public array = [{"id":1},{"id":3},{"id":5}];

  getPrev(){
     this.currentVal = 5;
     this.arrayVal= this.array;
     let number = this.arrayVal.reverse().find(e => e <= this.currentVal);
     console.log(number);
  }
}
</code>```

答:
You could find the nearest closet number as below

let arr = [
    { "id" : 1 },
    { "id" : 3 },
    { "id" : 5 }
];

let referenceNumber = 4;

let nearestLowest = arr.reduce((acc, val) => {
    if(val['id'] < referenceNumber && val['id'] > acc)
        acc = val['id'];
    return acc;
}, Math.max());

console.log(nearestLowest);```

Body:
I have an array of objects where I need to find closest lower value from that array based on some value or current value in angular 6, I have already tried but its showing undefined.

app.component.html

<button (click) ="getPrev()">Previous Value</button>

app.component.ts

declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
    arrayVal:any;
    currentVal : any;
  title = 'projectchart';
  public array = [{"id":1},{"id":3},{"id":5}];

  getPrev(){
     this.currentVal = 5;
     this.arrayVal= this.array;
     let number = this.arrayVal.reverse().find(e => e <= this.currentVal);
     console.log(number);
  }
}


问:
Shall I use POJO or JSONObject for REST calls
Recently I have stumbled upon a situation where my new team is heavily using JsonObject for doing rest data interchange. Their view is while using pojo we are binding tightly with the rest service, while jsonObject gives freedom. Also it saves from unnecessary data serialisation at the same time reducing number of classes heavily.

I have some points to encounter them as:

Pojo gives more meaning to data and we are holding data with correct data type.

If we need only 2 fields of 10 fields of json, we can deserialize to 2 fields class with @JsonIgnore

I don't know exactly on the cost of deserialisation, but somehow I have a feeling it shouldn't be much difference.

Can someone help me understand which perspective is way to go ?

Please provide some pros and cons of using POJO and JSONObject.

Thanks

答:
Their view is while using pojo we are binding tightly with the rest service, while jsonObject gives freedom.

Ask them for how long this freedom is required? Is the API model going to change always? It WILL settle down at some point. Also, how is it binding tightly? If there is some part of the model that you are not sure of, you can create a generic object for that part, that will give you as much flexibility as you want.

Also it saves from unnecessary data serialisation at the same time reducing number of classes heavily.

I don't think it is unnecessary. Using JsonObject directly is simply cumbersome.
About reducing the number of classes, you should anyway have some model class for data that is being exchanged. It gives more clarity. If you are using Swagger, it will add to the specification of your REST endpoints. Swagger automatically creates forms to enter data based on the data model. API becomes easier to maintain (no extra documentation required). Testing becomes easier.

I don't know exactly on the cost of deserialisation, but somehow I have a feeling it shouldn't be much difference.

The only way to be sure is benchmarking. You can use this as a starting point to get an insight and compare the current implementation https://github.com/fabienrenaud/java-json-benchmark.


问:
Python's textract cuts lines
I'm using textract to get text from documents. I use it like this:

```<code>lines = textract.process(file).decode('utf-8').splitlines()
</code>```

But if the lines are too long, textract cuts them to 80 characters. As I know, textract uses antiword which has an option -w width and if the width is equal to 0, the whole paragraph is printed. Is there such option in textract?

答:
Found the solution, one has to edit the file /usr/local/lib/python<version>/dist-packages/textract/parsers/doc_parser.py (this is where it is in my system):

```<code>stdout, stderr = self.run(['antiword', filename])
</code>```

should be changed to

```<code>stdout, stderr = self.run(['antiword', '-w', '0', filename])
</code>```

Title: Python's textract cuts lines

Body:
I'm using textract to get text from documents. I use it like this:

lines = textract.process(file).decode('utf-8').splitlines()

But if the lines are too long, textract cuts them to 80 characters. As I know, textract uses antiword which has an option -w width and if the width is equal to 0, the whole paragraph is printed. Is there such option in textract?

Body:
Found the solution, one has to edit the file /usr/local/lib/python<version>/dist-packages/textract/parsers/doc_parser.py (this is where it is in my system):

stdout, stderr = self.run(['antiword', filename])

should be changed to

stdout, stderr = self.run(['antiword', '-w', '0', filename])


问:
How to render from fetching data api (It show on console log but I can't call it in render)
I want to fetch API data from https://memegenerator.net It show the data on console log but I don't know how to called it

I try some variable in console log but it still not show anything

here fetching code

```<code>  fetch("http://version1.api.memegenerator.net//Comment_Create?entityName=Instance&entityID=72628355&parentCommentID=&text=first%20post%20best%20post&apiKey=demo")
  .then(response => response.json())
  .then((responseJson)=> {
    this.setState({
     dataSource: responseJson
    })
    console.log(responseJson(commentID));
  })
  .catch(error=>console.log(error))
  }`````

i need it to show data if i call {this.sate.commnedId}  to show commendId
 see console log in this image [1]: https://i.stack.imgur.com/aLorh.png

```

答:
```<code> componentDidMount(){
       let dataSource = '';
      fetch("http://version1.api.memegenerator.net//Comment_Create?entityName=Instance&entityID=72628355&parentCommentID=&text=first%20post%20best%20post&apiKey=demo")
      .then(response => response.json())
      .then((responseJson)=> {
        this.setState({
         dataSource:responseJson.result.commentID
        })

       // console.log(responseJson.result.text); this show in console
        console.log(dataSource);
      })
      .catch(error=>console.log(error)) //to catch the errors if any
      }
</code>```

Body:
I want to fetch API data from https://memegenerator.net It show the data on console log but I don't know how to called it

I try some variable in console log but it still not show anything

here fetching code

  fetch("http://version1.api.memegenerator.net//Comment_Create?entityName=Instance&entityID=72628355&parentCommentID=&text=first%20post%20best%20post&apiKey=demo")
  .then(response => response.json())
  .then((responseJson)=> {
    this.setState({
     dataSource: responseJson
    })
    console.log(responseJson(commentID));
  })
  .catch(error=>console.log(error))
  }`````

i need it to show data if i call {this.sate.commnedId}  to show commendId
 see console log in this image [1]: https://i.stack.imgur.com/aLorh.png


问:
DataBinding: 'System.String' does not contain a property with the name 'Name'
i'm working with custom authentication with asp.net mvc , i'm using Role Provider. i have many to many relation User , Role , UserInRoles .
the error in binding roles values in checkboxs in view

i tried debugging controller create method it return all data in Role table then continue to view in foreach

error DataBinding: 'System.String' does not contain a property with the name 'Name'.

User Model

```<code>public class User
    {
        [Key]
        public string  UserId { get; set; }
        public string Name { get; set; }
        public virtual ICollection<UserInRoles> UserInRoles { get; set; }

    }
</code>```

Role Model

```<code>public class Role
    {
        public int RoleId { get; set; }
        public string Name { get; set; }
        public virtual ICollection<UserInRoles> UserInRoles { get; set; }

    }
</code>```

UserInRole Model

```<code> public class UserInRoles
    {
        [Key, Column(Order = 0)]
        public string UserId { get; set; }
        [Key, Column(Order = 1)]
        public int RoleId { get; set; }
        public virtual User User { get; set; }
        public virtual Role Role { get; set; }

    }
</code>```

Controller

```<code>public ActionResult Create()
        {
            ViewBag.RoleId = new SelectList(Roles.GetAllRoles().ToList(), "Name", "Name");
            return View();
        }
</code>```

View

```<code>@model AramexOneKnowledge.Models.RegisterViewModel
@{
    ViewBag.Title = "Create";
}
<h2>Create</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>User</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.UserId, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserId, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.UserId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">
            Select User Role
        </label>
        <div class="col-md-10">
            @foreach (var item in (SelectList)ViewBag.RoleId)
            {
                <input type="checkbox" name="SelectedRoles"
                       value="@item.Value" class="checkbox-inline" />
                @Html.Label(item.Value, new { @class = "control-label" })
            }
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-primary" />
        </div>
    </div>
</code>```

expected result display roles in checkbox

答:
this exception because Roles.GetAllRoles() returns string[] and you try to bind  property Name inside it which it not exists.

so to overcome this issue you can populate you checkbox list as following

```<code>ViewBag.RoleId = Roles.GetAllRoles().Select(r => new SelectListItem{Text = r, Value = r});
</code>```

in this case you SelectListItem Value and Text it will be the role name for both of them

Body:
i'm working with custom authentication with asp.net mvc , i'm using Role Provider. i have many to many relation User , Role , UserInRoles .
the error in binding roles values in checkboxs in view

i tried debugging controller create method it return all data in Role table then continue to view in foreach

error DataBinding: 'System.String' does not contain a property with the name 'Name'.

User Model

public class User
    {
        [Key]
        public string  UserId { get; set; }
        public string Name { get; set; }
        public virtual ICollection<UserInRoles> UserInRoles { get; set; }

    }

Role Model

public class Role
    {
        public int RoleId { get; set; }
        public string Name { get; set; }
        public virtual ICollection<UserInRoles> UserInRoles { get; set; }

    }

UserInRole Model

 public class UserInRoles
    {
        [Key, Column(Order = 0)]
        public string UserId { get; set; }
        [Key, Column(Order = 1)]
        public int RoleId { get; set; }
        public virtual User User { get; set; }
        public virtual Role Role { get; set; }

    }

Controller

public ActionResult Create()
        {
            ViewBag.RoleId = new SelectList(Roles.GetAllRoles().ToList(), "Name", "Name");
            return View();
        }

View

@model AramexOneKnowledge.Models.RegisterViewModel
@{
    ViewBag.Title = "Create";
}

Create

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

User

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.UserId, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.UserId, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.UserId, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

            Select User Role

            @foreach (var item in (SelectList)ViewBag.RoleId)
            {
                <input type="checkbox" name="SelectedRoles"
                       value="@item.Value" class="checkbox-inline" />
                @Html.Label(item.Value, new { @class = "control-label" })
            }

            <input type="submit" value="Create" class="btn btn-primary" />

expected result display roles in checkbox

Body:
this exception because Roles.GetAllRoles() returns string[] and you try to bind  property Name inside it which it not exists.

so to overcome this issue you can populate you checkbox list as following

ViewBag.RoleId = Roles.GetAllRoles().Select(r => new SelectListItem{Text = r, Value = r});

in this case you SelectListItem Value and Text it will be the role name for both of them


问:
reading matrices from a file and retriving their dimension
I have a text file containing two matrices in this form:

```
1 2 3
4 5 6
1 2 3
*
4 5 6
1 2 3]
```

I want to be able to read the dimension of the two matrices and the type of operation * + / -. I'd like to retrieve the dimension and read data at the same time.

In my code the get_dim() function goes through the data in the file to get the dimension of the two matrices. I don't know if there is a way to store the values of the matrices already at this point with dynamic memory allocation. With the function read_matrix() one that I know the dimension of the matrices I'm reading again the same data.

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>

#define IN 1
#define OUT 0

struct matrix{
    int rows;
    int cols;
    double *data;
};

void f(double x); /*truncate a double */
int get_dim(char *file, int *r, int *col);
void read_matrix(char *file, struct matrix *A, struct matrix *B);
void print_matrix(struct matrix *A);
void multiply(struct matrix *A, struct matrix *B, struct matrix *C);

int main (int argc, char *argv[])
{
    int rows[2]= {0,0};
    int cols[2]= {0,0};
    int operation; /*type of operation 1 for * and 2 for + */

    operation = get_dim(argv[1], rows, cols);

    struct matrix A;
    struct matrix B;
    struct matrix C;

    A.rows = rows[0];
    A.cols = cols[0];

    B.rows = rows[1];
    B.cols = cols[1];

    C.rows = rows[0];
    C.cols = cols[1];

    A.data = malloc(sizeof(double) * A.rows * A.cols);
    B.data = malloc(sizeof(double) * B.rows * B.cols);
    C.data = malloc(sizeof(double) * A.rows * B.cols);

    read_matrix(argv[1],&A,&B);

    print_matrix(&A);

    printf("\n*\n");

    print_matrix(&B);
    printf("\n=\n");

    multiply(&A,&B,&C);
    print_matrix(&C);

    free(A.data);
    free(B.data);
    free(C.data);

    return 0;
}

void read_matrix(char *file, struct matrix *A, struct matrix *B){

    int i,j;
    FILE *fp;
    int c=1;

    if((fp = fopen(file, "r")) != NULL ){

        for(i=0; i < A->rows; i++)
            for(j=0; j < A->cols; j++)
                fscanf(fp, "%lf", (A->data + (i * A->cols + j)));

        /*skip the character operator line */

        while(!isdigit(c))
            c=fgetc(fp);

        ungetc(c,fp);

        for(i=0; i < B->rows; i++)
           for(j=0; j < B->cols; j++)
                fscanf(fp, "%lf", (B->data + (i * B->cols + j)));
    }
    fclose(fp);
}

int get_dim(char *file, int *rows, int *cols){

    FILE *fp;
    double a;
    int c =1;
    int n = OUT;
    int op=0;

    if((fp = fopen(file, "r")) == NULL ){
        fprintf(stderr, "matrix: I cannot open %s\n",file);
        exit(1);
    }

    while(fscanf(fp,"%lf",&a)){

            if(n==OUT)
                cols[0]++;

            c=fgetc(fp);

            if(isdigit(c))
                ungetc(c,fp);

            else if(c =='\n'){
                rows[0]++;
                n=IN;
            }

            else if(c=='*'){
                op=1;
                break;
            }
    }

    n=OUT;
    printf("\n");

    while(!isdigit(c))
        c=fgetc(fp);

    ungetc(c,fp);

    while(fscanf(fp,"%lf",&a)){

        if(n==OUT)
            cols[1]++;

        c=fgetc(fp);

        if(isdigit(c))
            ungetc(c,fp);

        else if(c =='\n'){
            rows[1]++;
            n=IN;
        }

        else if(c == ']'){
                rows[1]++;
                break;
        }
    }
    fclose(fp);
    return op;
}

void print_matrix(struct matrix *A){

    int i,j;

/*printing the matrices*/

     double *tmp = A->data;

     for(i=0; i < A->rows; i++){
        for(j=0; j < A->cols; j++){
                f(*(tmp++));
        }
        printf("\n");
    }
}

void multiply(struct matrix *A, struct matrix *B, struct matrix *C)
{
    int i, j, k;

    /*initialize C to 0*/

   for (i=0; i< C->rows; i++){
    for (j=0; j < C->cols; j++)
        C->data[i * C->cols + j]=0;
   }
// Multiplying matrix A and B and storing in C.
   for(i = 0; i < A->rows; ++i)
        for(j = 0; j < B->cols; ++j)
            for(k=0; k < A->cols; ++k)
                C->data[i * C->cols + j] += A->data[i * A->cols + k] * B->data[k * B->cols + j];
}

void f(double x)
{
    double i,f= modf(x,&i);

    if(f<.00001)
        printf("%.f ",i);
    else printf("%f ",x);
}
</code>```

答:
Some remarks on the first version of your question

Your loop

```<code> while (chr != EOF)
 {
   //Count whenever new line is encountered
   if (chr == '\n')
       rows++;
   //take next character from file.
   chr = getc(fp);
 }
</code>```

read up to the end of the file so both matrices, you need to detect the "*" so you do separate the first and the second matrices

you do not detect the number of columns, you need to read line per line, then to count the number of values per line (at least the first)

In

```<code>str = (char *) malloc(6 * sizeof(char));

if( fgets (str, 24, fp)!=NULL ) {
</code>```

you can have an undefined behavior because you read up to 24 characters doing fgets (str, 24, fp) while you allocated only 6

c != EOF requires c is an int, not a char

Here is a proposal, I do not know what are the kind of number you expect so I do not try to read number, I just look at elements separated by space, you can add a sscanf or equivalent to check each element is a number. I also suppose the operator is a character alone on its line (there is a newline just after)

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int readMat(FILE * fp, int * cols, int * rows, char * oper)
{
  *cols = *rows = 0;
  *oper = 0;

  char * lineptr = NULL;
  size_t n = 0;

  while (getline(&lineptr, &n, fp) > 0) {
    if (((*lineptr == '*') || (*lineptr == '/') || (*lineptr == '-') || (*lineptr == '+'))
        && (lineptr[1] == '\n')) {
      *oper = *lineptr;
      break;
    }

    if (strtok(lineptr, " ") == NULL) {
      /* invalid input */
      *cols = 0;
      break;
    }

    *rows += 1;

    int c = 1;

    while (strtok(NULL, " ") != NULL)
      c += 1;

    if (*cols == 0)
      *cols = c;
    else if (*cols != c) {
      /* invalid input */
      *cols = 0;
      break;
    }
  }

  free(lineptr);

  return *cols != 0;
}

int main(int argc, char ** argv)
{
  if (argc != 2)
    printf("Usage: %s <file>\n", *argv);
  else {
    FILE * fp = fopen(argv[1], "r");

    if (fp == NULL)
      fprintf(stderr, "cannot open '%s'\n", argv[1]);
    else {
      int cols, rows;
      char oper;

      if (!readMat(fp, &cols, &rows, &oper))
        fputs("invalid first matrice", stderr);
      else if (oper == 0)
        fputs("operator is missing", stderr);
      else {
        printf("first matrice has %d columns and %d rows\noper is %c\n", cols, rows, oper);

        if (!readMat(fp, &cols, &rows, &oper))
          fputs("invalid second matrice", stderr);
        else if (oper != 0)
          fputs("unexpected operator", stderr);
        else
          printf("second matrice has %d columns and %d rows\n", cols, rows);
      }
      fclose(fp);
    }
  }

  return 0;
}
</code>```

Compilation and execution :

```<code>pi@raspberrypi:/tmp $ gcc -g -pedantic -Wall -Wextra m.c
pi@raspberrypi:/tmp $ cat m
1 2 3
4 5 6
1 2 3
*
  44  5.2   6e12
-1     2   333
pi@raspberrypi:/tmp $ ./a.out m
first matrice has 3 columns and 3 rows
oper is *
second matrice has 3 columns and 2 rows
pi@raspberrypi:/tmp $
</code>```

If you do not have getline replace

```<code>  char * lineptr = NULL;
  size_t n = 0;

  while (getline(&lineptr, &n, fp) > 0) {
</code>```

by for instance

```<code>  char * lineptr = malloc(1024);

  while (fgets(lineptr, 1024, fp) != NULL) {
</code>```

Body:
I have a text file containing two matrices in this form:

1 2 3
4 5 6
1 2 3
*
4 5 6
1 2 3]

I want to be able to read the dimension of the two matrices and the type of operation * + / -. I'd like to retrieve the dimension and read data at the same time.

In my code the get_dim() function goes through the data in the file to get the dimension of the two matrices. I don't know if there is a way to store the values of the matrices already at this point with dynamic memory allocation. With the function read_matrix() one that I know the dimension of the matrices I'm reading again the same data.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>

#define IN 1
#define OUT 0

struct matrix{
    int rows;
    int cols;
    double *data;
};

void f(double x); /*truncate a double */
int get_dim(char *file, int *r, int *col);
void read_matrix(char *file, struct matrix *A, struct matrix *B);
void print_matrix(struct matrix *A);
void multiply(struct matrix *A, struct matrix *B, struct matrix *C);

int main (int argc, char *argv[])
{
    int rows[2]= {0,0};
    int cols[2]= {0,0};
    int operation; /*type of operation 1 for * and 2 for + */

    operation = get_dim(argv[1], rows, cols);

    struct matrix A;
    struct matrix B;
    struct matrix C;

    A.rows = rows[0];
    A.cols = cols[0];

    B.rows = rows[1];
    B.cols = cols[1];

    C.rows = rows[0];
    C.cols = cols[1];

    A.data = malloc(sizeof(double) * A.rows * A.cols);
    B.data = malloc(sizeof(double) * B.rows * B.cols);
    C.data = malloc(sizeof(double) * A.rows * B.cols);

    read_matrix(argv[1],&A,&B);

    print_matrix(&A);

    printf("\n*\n");

    print_matrix(&B);
    printf("\n=\n");

    multiply(&A,&B,&C);
    print_matrix(&C);

    free(A.data);
    free(B.data);
    free(C.data);

    return 0;
}

void read_matrix(char *file, struct matrix *A, struct matrix *B){

    int i,j;
    FILE *fp;
    int c=1;

    if((fp = fopen(file, "r")) != NULL ){

        for(i=0; i rows; i++)
            for(j=0; j cols; j++)
                fscanf(fp, "%lf", (A->data + (i * A->cols + j)));

        /*skip the character operator line */

        while(!isdigit(c))
            c=fgetc(fp);

        ungetc(c,fp);

        for(i=0; i rows; i++)
           for(j=0; j cols; j++)
                fscanf(fp, "%lf", (B->data + (i * B->cols + j)));
    }
    fclose(fp);
}

int get_dim(char *file, int *rows, int *cols){

    FILE *fp;
    double a;
    int c =1;
    int n = OUT;
    int op=0;

    if((fp = fopen(file, "r")) == NULL ){
        fprintf(stderr, "matrix: I cannot open %s\n",file);
        exit(1);
    }

    while(fscanf(fp,"%lf",&a)){

            if(n==OUT)
                cols[0]++;

            c=fgetc(fp);

            if(isdigit(c))
                ungetc(c,fp);

            else if(c =='\n'){
                rows[0]++;
                n=IN;
            }

            else if(c=='*'){
                op=1;
                break;
            }
    }

    n=OUT;
    printf("\n");

    while(!isdigit(c))
        c=fgetc(fp);

    ungetc(c,fp);

    while(fscanf(fp,"%lf",&a)){

        if(n==OUT)
            cols[1]++;

        c=fgetc(fp);

        if(isdigit(c))
            ungetc(c,fp);

        else if(c =='\n'){
            rows[1]++;
            n=IN;
        }

        else if(c == ']'){
                rows[1]++;
                break;
        }
    }
    fclose(fp);
    return op;
}

void print_matrix(struct matrix *A){

    int i,j;

/*printing the matrices*/

     double *tmp = A->data;

     for(i=0; i rows; i++){
        for(j=0; j cols; j++){
                f(*(tmp++));
        }
        printf("\n");
    }
}

void multiply(struct matrix *A, struct matrix *B, struct matrix *C)
{
    int i, j, k;

    /*initialize C to 0*/

   for (i=0; i< C->rows; i++){
    for (j=0; j < C->cols; j++)
        C->data[i * C->cols + j]=0;
   }
// Multiplying matrix A and B and storing in C.
   for(i = 0; i rows; ++i)
        for(j = 0; j cols; ++j)
            for(k=0; k cols; ++k)
                C->data[i * C->cols + j] += A->data[i * A->cols + k] * B->data[k * B->cols + j];
}

void f(double x)
{
    double i,f= modf(x,&i);

    if(f<.00001)
        printf("%.f ",i);
    else printf("%f ",x);
}

Body:
Some remarks on the first version of your question

Your loop

 while (chr != EOF)
 {
   //Count whenever new line is encountered
   if (chr == '\n')
       rows++;
   //take next character from file.
   chr = getc(fp);
 }

read up to the end of the file so both matrices, you need to detect the "*" so you do separate the first and the second matrices

you do not detect the number of columns, you need to read line per line, then to count the number of values per line (at least the first)

In

str = (char *) malloc(6 * sizeof(char));

if( fgets (str, 24, fp)!=NULL ) {

you can have an undefined behavior because you read up to 24 characters doing fgets (str, 24, fp) while you allocated only 6

c != EOF requires c is an int, not a char

Here is a proposal, I do not know what are the kind of number you expect so I do not try to read number, I just look at elements separated by space, you can add a sscanf or equivalent to check each element is a number. I also suppose the operator is a character alone on its line (there is a newline just after)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int readMat(FILE * fp, int * cols, int * rows, char * oper)
{
  *cols = *rows = 0;
  *oper = 0;

  char * lineptr = NULL;
  size_t n = 0;

  while (getline(&lineptr, &n, fp) > 0) {
    if (((*lineptr == '*') || (*lineptr == '/') || (*lineptr == '-') || (*lineptr == '+'))
        && (lineptr[1] == '\n')) {
      *oper = *lineptr;
      break;
    }

    if (strtok(lineptr, " ") == NULL) {
      /* invalid input */
      *cols = 0;
      break;
    }

    *rows += 1;

    int c = 1;

    while (strtok(NULL, " ") != NULL)
      c += 1;

    if (*cols == 0)
      *cols = c;
    else if (*cols != c) {
      /* invalid input */
      *cols = 0;
      break;
    }
  }

  free(lineptr);

  return *cols != 0;
}

int main(int argc, char ** argv)
{
  if (argc != 2)
    printf("Usage: %s <file>\n", *argv);
  else {
    FILE * fp = fopen(argv[1], "r");

    if (fp == NULL)
      fprintf(stderr, "cannot open '%s'\n", argv[1]);
    else {
      int cols, rows;
      char oper;

      if (!readMat(fp, &cols, &rows, &oper))
        fputs("invalid first matrice", stderr);
      else if (oper == 0)
        fputs("operator is missing", stderr);
      else {
        printf("first matrice has %d columns and %d rows\noper is %c\n", cols, rows, oper);

        if (!readMat(fp, &cols, &rows, &oper))
          fputs("invalid second matrice", stderr);
        else if (oper != 0)
          fputs("unexpected operator", stderr);
        else
          printf("second matrice has %d columns and %d rows\n", cols, rows);
      }
      fclose(fp);
    }
  }

  return 0;
}

Compilation and execution :

pi@raspberrypi:/tmp $ gcc -g -pedantic -Wall -Wextra m.c
pi@raspberrypi:/tmp $ cat m
1 2 3
4 5 6
1 2 3
*
  44  5.2   6e12
-1     2   333
pi@raspberrypi:/tmp $ ./a.out m
first matrice has 3 columns and 3 rows
oper is *
second matrice has 3 columns and 2 rows
pi@raspberrypi:/tmp $

If you do not have getline replace

  char * lineptr = NULL;
  size_t n = 0;

  while (getline(&lineptr, &n, fp) > 0) {

by for instance

  char * lineptr = malloc(1024);

  while (fgets(lineptr, 1024, fp) != NULL) {


问:
when i use minifyEnabled app keep crashing
recently I developed an android app.
every thing goes well, but when I use "minifyEnabled true" app keep crashing with this error:

```<code>com.google.gson.internal.LinkedTreeMap$1
java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1344)
java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1651)
java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1497)
java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1461)
java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:959)
java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:360)
java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1054)
java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1384)
java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1651)
java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1497)
java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1461)
java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:959)
java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:360)
java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1054)
java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1384)
java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1651)
java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1497)
java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1461)
org.matrix.androidsdk.data.cryptostore.db.HelperKt.serializeForRealm(:102)
org.matrix.androidsdk.data.cryptostore.db.model.DeviceInfoEntity.putDeviceInfo(:43)
org.matrix.androidsdk.data.cryptostore.db.RealmCryptoStore$storeUserDevices$1.invoke(:244)
org.matrix.androidsdk.data.cryptostore.db.RealmCryptoStore$storeUserDevices$1.invoke(:44)
org.matrix.androidsdk.data.cryptostore.db.HelperKt$doRealmTransaction$1.execute(:86)
io.realm.Realm.a(:1493)
org.matrix.androidsdk.data.cryptostore.db.HelperKt.doRealmTransaction(:86)
org.matrix.androidsdk.data.cryptostore.db.RealmCryptoStore.storeUserDevices(:228)
org.matrix.androidsdk.crypto.MXDeviceList$4$1.run(:605)
android.os.Handler.handleCallback(Handler.java:815)
android.os.Handler.dispatchMessage(Handler.java:104)
android.os.Looper.loop(Looper.java:227)
android.os.HandlerThread.run(HandlerThread.java:61)
</code>```

I tried many changes in proguard config file, but problem still exist

答:
Looks like Proguard wasn't able to handle the LinkedTreeMap properly. try adding a rule to skip this class to proguard-rules.pro file located inside app folder</p>

```<code>-keep class [full class name] { *; }
</code>```

Body:
recently I developed an android app.
every thing goes well, but when I use "minifyEnabled true" app keep crashing with this error:

com.google.gson.internal.LinkedTreeMap$1
java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1344)
java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1651)
java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1497)
java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1461)
java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:959)
java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:360)
java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1054)
java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1384)
java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1651)
java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1497)
java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1461)
java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:959)
java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:360)
java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1054)
java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1384)
java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1651)
java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1497)
java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1461)
org.matrix.androidsdk.data.cryptostore.db.HelperKt.serializeForRealm(:102)
org.matrix.androidsdk.data.cryptostore.db.model.DeviceInfoEntity.putDeviceInfo(:43)
org.matrix.androidsdk.data.cryptostore.db.RealmCryptoStore$storeUserDevices$1.invoke(:244)
org.matrix.androidsdk.data.cryptostore.db.RealmCryptoStore$storeUserDevices$1.invoke(:44)
org.matrix.androidsdk.data.cryptostore.db.HelperKt$doRealmTransaction$1.execute(:86)
io.realm.Realm.a(:1493)
org.matrix.androidsdk.data.cryptostore.db.HelperKt.doRealmTransaction(:86)
org.matrix.androidsdk.data.cryptostore.db.RealmCryptoStore.storeUserDevices(:228)
org.matrix.androidsdk.crypto.MXDeviceList$4$1.run(:605)
android.os.Handler.handleCallback(Handler.java:815)
android.os.Handler.dispatchMessage(Handler.java:104)
android.os.Looper.loop(Looper.java:227)
android.os.HandlerThread.run(HandlerThread.java:61)

I tried many changes in proguard config file, but problem still exist

Body:
Looks like Proguard wasn't able to handle the LinkedTreeMap properly. try adding a rule to skip this class to proguard-rules.pro file located inside app folder

-keep class [full class name] { *; }


问:
Problem with Debugging in Eclipse CDT
I'm trying to debug the simple Hello World program that ships with Eclipse CDT. Running the program normally works fine, but when its run through debug mode, puts() doesn't print anything to the console.

I tried running the same program with gdb directly and it works fine, printing "!!!Hello World!!!" as expected.

Why doesn't puts() print anything when running in debug mode through Eclipse?

I'm on Windows with MinGW installed, running gcc 4.5.0, gdb 7.2, and CDT 7.0.1

答:
Thanks to Swiss pointed out the right direction.

Adding fflush(stdout) after every printf,puts sentence is not suitable for a large project when debugging (When releasing, your'd better using fflush() at a appropriate time).

Then, we can use Preprocessor directives #ifdef && setbuf().

In Eclipse , your C project -> properties -> C/C++ Build -> Settings :
 Confgiguration = "Debug [ Active ]"
-> Tool Settings -> GCC C Compiler -> Symbols -> Add "_DEBUG",

Then in your main(), using:

```<code>#ifdef _DEBUG
setbuf(stdout,NULL); // this disables buffering for stdout.
#endif
</code>```

ContentLicense: CC BY-SA 2.5

Title: Problem with Debugging in Eclipse CDT

Body:
Thanks to Swiss pointed out the right direction.

Adding fflush(stdout) after every printf,puts sentence is not suitable for a large project when debugging (When releasing, your'd better using fflush() at a appropriate time).

Then, we can use Preprocessor directives #ifdef && setbuf().

In Eclipse , your C project -> properties -> C/C++ Build -> Settings :
 Confgiguration = "Debug [ Active ]"
-> Tool Settings -> GCC C Compiler -> Symbols -> Add "_DEBUG",

Then in your main(), using:

#ifdef _DEBUG
setbuf(stdout,NULL); // this disables buffering for stdout.
#endif


问:
I'm trying to open external links from my app but it won't open
I have a wkwebview app, I need help with my code, I can't seems to open external links from my website inside my app.

```<code>import UIKit
import WebKit
import UserNotifications

class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
    var webView: WKWebView!
    var activityIndicator: UIActivityIndicatorView!
    var bgImage: UIImageView!
    var urlString = ""

    override func loadView() {
        super.loadView()
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        webView.navigationDelegate = self
        view = webView
    }

    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        if navigationAction.targetFrame == nil {
            let vc = ViewController()
            vc.urlString = navigationAction.request.url?.absoluteString ?? "https://mywebsite"
            vc.view.frame = UIScreen.main.bounds
            vc.webView = WKWebView(frame: UIScreen.main.bounds, configuration: configuration)
            navigationController?.pushViewController(vc, animated: false)
            return vc.webView
        }
        return nil
    }

    override var prefersStatusBarHidden: Bool{
        return true
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let image : UIImage = UIImage(named:"bgx1")!
        bgImage = UIImageView(image: image)
        bgImage.frame = CGRect(x: 0, y: 0, width: 1000, height: 2000)
        view.addSubview(bgImage)

        let myURL = URL(string: "https://mywebsite/")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
        webView.allowsBackForwardNavigationGestures = true

        activityIndicator = UIActivityIndicatorView()
        activityIndicator.frame = CGRect(x: 0, y: 0, width: 50, height: 50)

        self.activityIndicator.center = CGPoint(x:self.view.bounds.size.width/2.0,y: self.view.bounds.size.height/2.0);

        activityIndicator.autoresizingMask = (UIView.AutoresizingMask(rawValue: UIView.AutoresizingMask.RawValue(UInt8(UIView.AutoresizingMask.flexibleRightMargin.rawValue) | UInt8(UIView.AutoresizingMask.flexibleLeftMargin.rawValue) | UInt8(UIView.AutoresizingMask.flexibleBottomMargin.rawValue) | UInt8(UIView.AutoresizingMask.flexibleTopMargin.rawValue))))

        activityIndicator.hidesWhenStopped = true

        activityIndicator.style = UIActivityIndicatorView.Style.whiteLarge
        activityIndicator.color = UIColor.darkGray
        self.view.addSubview(activityIndicator)

    }

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        activityIndicator.startAnimating()
        bgImage.startAnimating()
    }

    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        print("It is an error")
        activityIndicator.stopAnimating()
        bgImage.stopAnimating()
        let alert = UIAlertController(title: "Network Error", message: "You have no internet connection", preferredStyle: .alert)

        let restartAction = UIAlertAction(title: "Reload page", style: .default, handler: { (UIAlertAction) in
            self.viewDidLoad()
        })

        alert.addAction(restartAction)
        present(alert, animated: true, completion: nil)
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        activityIndicator.stopAnimating()
        bgImage.stopAnimating()
        bgImage.isHidden = true
    }

}
</code>```

What am I doing wrong? Please help.

答:
You have to implement the webView(_:decidePolicyFor:decisionHandler:) function of WKNavigationDelegate protocol in order to allow following the links in your web view.

Here is the documentation

Body:
I have a wkwebview app, I need help with my code, I can't seems to open external links from my website inside my app.

import UIKit
import WebKit
import UserNotifications

class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
    var webView: WKWebView!
    var activityIndicator: UIActivityIndicatorView!
    var bgImage: UIImageView!
    var urlString = ""

    override func loadView() {
        super.loadView()
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        webView.navigationDelegate = self
        view = webView
    }

    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        if navigationAction.targetFrame == nil {
            let vc = ViewController()
            vc.urlString = navigationAction.request.url?.absoluteString ?? "https://mywebsite"
            vc.view.frame = UIScreen.main.bounds
            vc.webView = WKWebView(frame: UIScreen.main.bounds, configuration: configuration)
            navigationController?.pushViewController(vc, animated: false)
            return vc.webView
        }
        return nil
    }

    override var prefersStatusBarHidden: Bool{
        return true
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let image : UIImage = UIImage(named:"bgx1")!
        bgImage = UIImageView(image: image)
        bgImage.frame = CGRect(x: 0, y: 0, width: 1000, height: 2000)
        view.addSubview(bgImage)

        let myURL = URL(string: "https://mywebsite/")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
        webView.allowsBackForwardNavigationGestures = true

        activityIndicator = UIActivityIndicatorView()
        activityIndicator.frame = CGRect(x: 0, y: 0, width: 50, height: 50)

        self.activityIndicator.center = CGPoint(x:self.view.bounds.size.width/2.0,y: self.view.bounds.size.height/2.0);

        activityIndicator.autoresizingMask = (UIView.AutoresizingMask(rawValue: UIView.AutoresizingMask.RawValue(UInt8(UIView.AutoresizingMask.flexibleRightMargin.rawValue) | UInt8(UIView.AutoresizingMask.flexibleLeftMargin.rawValue) | UInt8(UIView.AutoresizingMask.flexibleBottomMargin.rawValue) | UInt8(UIView.AutoresizingMask.flexibleTopMargin.rawValue))))

        activityIndicator.hidesWhenStopped = true

        activityIndicator.style = UIActivityIndicatorView.Style.whiteLarge
        activityIndicator.color = UIColor.darkGray
        self.view.addSubview(activityIndicator)

    }

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        activityIndicator.startAnimating()
        bgImage.startAnimating()
    }

    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        print("It is an error")
        activityIndicator.stopAnimating()
        bgImage.stopAnimating()
        let alert = UIAlertController(title: "Network Error", message: "You have no internet connection", preferredStyle: .alert)

        let restartAction = UIAlertAction(title: "Reload page", style: .default, handler: { (UIAlertAction) in
            self.viewDidLoad()
        })

        alert.addAction(restartAction)
        present(alert, animated: true, completion: nil)
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        activityIndicator.stopAnimating()
        bgImage.stopAnimating()
        bgImage.isHidden = true
    }

}

What am I doing wrong? Please help.


问:
How to use token-based authentication with axios and react
There is 401 error(Invalid or not provided access token), How to pass token correctly with axios, This is my code &
API documentation: https://trefle.io

答:
It depends how you have organized your code/architecture.

You can store the token in session or local storages, but each time you make a call you need to pass the token through the headers each time OR you can create an interceptor which will handle that for you.

You can store the token in the cookie as well. This is good if you are running you React app with node using server-side rendering (SSR). In this case you don't need to do something, as cookie are being send through headers automatically.

You can also store the token in a session, but in case you care about auto-scaling, you need to use Redis and not a memory storage, so token will be available for all the instances your app is running on.

Small note - don't send the token through query params.


问:
Assign a task to two or more persons in Jira
I'm currently using Jira in a software development project and one of the activities on the project is a code review process. A developer creates a new code and then two or more other developer (usually senior developers) inspect that code.

I don't want to create two or more tasks for each code reviewer - instead I want to create a single task, name it like "New function - code review" and assign all code reviewer to this task. After having completed the code review each reviewer logs spent time into this single task.

Is it possible in Jira? If it isn't, then could you please advise me another approach?

答:
Apart from the other suggestions here, you could also create a custom user field that accepts multiple users, i.e. a "user picker" (or "multi user picker" in earlier Jira versions) field. However, this won't replace the typical "Assignee" field but could help you with your use case.

See also this question and answer on community.atlassian.com.


问:
Java String.format two decimal places with points as thousand seperators and a comma as the decimal seperator
I need to format a float with exactly to decimal places, "." as the thousand seperator and "," as the decimal seperator, like this: "1.234,56"

I have tried String.format("%,f", myFloat) but it gives me too many decimal places like this: "1.150,000000". Also, String.format("%,2f", myFloat) didn't work either.

答:
You can try using DecimalFormat class to format your numbers as you wish :

```<code>float number = 12344.12f;

DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator('.');
symbols.setDecimalSeparator(','); // to be sure it is ','

DecimalFormat decimalFormat = new DecimalFormat();
decimalFormat.setDecimalFormatSymbols(symbols);
decimalFormat.setMaximumFractionDigits(2);

String format = decimalFormat.format(number);

System.out.println(format);
</code>```

The output is :

```<code>12.344,12
</code>```

EDIT

For fixed decimal places try this :

```<code>DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator('.');
symbols.setDecimalSeparator(','); // to be sure it is ','

DecimalFormat decimalFormat = new DecimalFormat("#.###.00");
decimalFormat.setDecimalFormatSymbols(symbols);

String format = decimalFormat.format(number);
</code>```

Body:
You can try using DecimalFormat class to format your numbers as you wish :

float number = 12344.12f;

DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator('.');
symbols.setDecimalSeparator(','); // to be sure it is ','

DecimalFormat decimalFormat = new DecimalFormat();
decimalFormat.setDecimalFormatSymbols(symbols);
decimalFormat.setMaximumFractionDigits(2);

String format = decimalFormat.format(number);

System.out.println(format);

The output is :

12.344,12

EDIT

For fixed decimal places try this :

DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator('.');
symbols.setDecimalSeparator(','); // to be sure it is ','

DecimalFormat decimalFormat = new DecimalFormat("#.###.00");
decimalFormat.setDecimalFormatSymbols(symbols);

String format = decimalFormat.format(number);