问:
Display of Multiple JavaScript Countdowns
I found a way to display multiple countdowns, using javascript.
Having multiple countdown timer events intervals in javascript

I am trying to create a "warmer" display, in a grid.  I opted for an HTML table.  I have a draft here

I can't get the countdowns to display in the table cells, with separated time components. I just have the entire SPAN tag in the "Days" column.

答:
I'd take a different approach. First of all, instead of creating the table in your HTML, I would store the data about the countdown timers in an array of objects in your JavaScript code and generate the table using JS. Doing this will make it cleaner and more maintainable; to add new items you can just add an object to the array instead of mucking about with HTML.

Secondly, instead of starting an interval for each timer, I would create a single interval that updates all of the timers. Using a single interval means your DOM updates will be batched together and will minimize page reflow.

This code also recalculates the time left each time it updates. If you calculate it once and then just subtract each round, it could introduce drift into your counter. This is because setInterval only guarantees that it will wait at least as many milliseconds as you specify in the delay parameter, it could be more. It probably wouldn't matter much unless your timer was running continuously for a very long time, but over time it would be come inaccurate.

// data is an array of objects, each representing one of your categories.
// Each category has a .title to store its title and a .counters that
// stores an object for each counter in that category.
var data = [
  {
title: 'ASTRONOMY',
counters: [
  // Each counter has a .title and a .date that is parsed by new Date()
  {
    title: 'Total Solar Eclipse - (NE US)',
    date: 'August 21, 2017'
  },
  {
    title: 'Next Supermoon - Full',
    date: 'December 3, 2017'
  }
]
  },
  {
title: 'POLITICS',
  counters: [
    {
      title: 'Next Presidential Election',
      date: 'November 3, 2020'
    }
  ]
  },
  {
title: 'TEST',
counters: [
  {
    title: '30 seconds from page load',
    date: (new Date()).getTime() + (30 * 1000)
  },
  {
    title: 'Unix Epoch',
    date: 'January 1, 1970'
  }
]
  }
];
// this reduce generates the table
let table = data.reduce((acc, category, categoryIndex) => {
return acc + `<tr><td colspan="6" class="category">${category.title}</td></tr>` +
category.counters.reduce((acc, counter, index) => {
  return acc + `

  ${counter.title}
  ${counter.date}

`;
  }, '');
}, '

Event	Date	Days	Hours	Minutes	Seconds
');
table += '
';

// insert the table after the noscript tag
document.getElementById('countdown').insertAdjacentHTML('afterend', table);

// generate a flat list of counters
let counters = data.reduce((acc, category, categoryIndex) => {
return acc.concat(category.counters.reduce((counterAcc, counter, index) => {
    return counterAcc.concat([{
      // counters will be an array of the objects we generate here.
      // node contains a reference to the tr element for this counter
      node: document.getElementById(`counter-${categoryIndex}-${index}`),
      // date is the date for this counter parsed by Date and then converted
      // into a timestamp
      date: (new Date(counter.date)).getTime()
      }]);
    }, []));
}, []);

const msSecond = 1000,
  msMinute = msSecond * 60,
  msHour = msMinute * 60,
  msDay = msHour * 24;
let intervalId;

function updateCounters () {
  counters.forEach((counter, counterIndex) => {
  let remaining = counter.date - Date.now(),
    node = counter.node;
  let setText = (selector, text) => node.querySelector(selector).textContent = text;

  if (remaining > 0) {
    setText('.days', Math.floor(remaining / msDay));
    remaining %= msDay;
    setText('.hours', Math.floor(remaining / msHour));
    remaining %= msHour;
    setText('.minutes', Math.floor(remaining / msMinute));
    remaining %= msMinute;
    setText('.seconds', Math.floor(remaining / msSecond));
  } else {
    // make sure we don't accidentally display negative numbers if a timer
    // firing late returns a past timestamp (or the data contains a past date)
    setText('.days', 0);
    setText('.hours', 0);
    setText('.minutes', 0);
    setText('.seconds', 0);

    // This countdown has reached 0 seconds, stop updating it.
    counters.splice(counterIndex, 1);
    // no more counters? Stop the timer
    if (counters.length === 0) {
      clearInterval(intervalId);
    }
  }
  });
}
// display counters right away without waiting a second
updateCounters();
intervalId = setInterval(updateCounters, 1000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code> table {
 border-collapse: collapse;
 }
 tr:nth-child(even) {
 background-color: #edf;
 }
 .category {
 font-weight: bold;
 }
 td, th {
 padding: .5em;
 }
 .days, .hours, .minutes, .seconds {
 text-align: right;
 }</code>```

 Sorry, you need JavaScript enabled to view the count
 downs```

More Reading

Creating Accurate Timers in JavaScript

Critical rendering path

Repaints and Reflows: Manipulating the DOM responsibly

Body:
I'd take a different approach. First of all, instead of creating the table in your HTML, I would store the data about the countdown timers in an array of objects in your JavaScript code and generate the table using JS. Doing this will make it cleaner and more maintainable; to add new items you can just add an object to the array instead of mucking about with HTML.

Secondly, instead of starting an interval for each timer, I would create a single interval that updates all of the timers. Using a single interval means your DOM updates will be batched together and will minimize page reflow.

This code also recalculates the time left each time it updates. If you calculate it once and then just subtract each round, it could introduce drift into your counter. This is because setInterval only guarantees that it will wait at least as many milliseconds as you specify in the delay parameter, it could be more. It probably wouldn't matter much unless your timer was running continuously for a very long time, but over time it would be come inaccurate.

// data is an array of objects, each representing one of your categories.
// Each category has a .title to store its title and a .counters that
// stores an object for each counter in that category.
var data = [
  {
title: 'ASTRONOMY',
counters: [
  // Each counter has a .title and a .date that is parsed by new Date()
  {
    title: 'Total Solar Eclipse - (NE US)',
    date: 'August 21, 2017'
  },
  {
    title: 'Next Supermoon - Full',
    date: 'December 3, 2017'
  }
]
  },
  {
title: 'POLITICS',
  counters: [
    {
      title: 'Next Presidential Election',
      date: 'November 3, 2020'
    }
  ]
  },
  {
title: 'TEST',
counters: [
  {
    title: '30 seconds from page load',
    date: (new Date()).getTime() + (30 * 1000)
  },
  {
    title: 'Unix Epoch',
    date: 'January 1, 1970'
  }
]
  }
];
// this reduce generates the table
let table = data.reduce((acc, category, categoryIndex) => {
return acc + `<tr><td colspan="6" class="category">${category.title}</td></tr>` +
category.counters.reduce((acc, counter, index) => {
  return acc + `<tr id="counter-${categoryIndex}-${index}">
  <td>${counter.title}</td>
  <td>${counter.date}</td>
  <td class="days"></td>
  <td class="hours"></td>
  <td class="minutes"></td>
  <td class="seconds"></td>
  </tr>`;
  }, '');
}, '<table class="countdown"><tr><th>Event</th><th>Date</th><th>Days</th><th>Hours</th><th>Minutes</th><th>Seconds</th></tr>');
table += '</table>';

// insert the table after the noscript tag
document.getElementById('countdown').insertAdjacentHTML('afterend', table);

// generate a flat list of counters
let counters = data.reduce((acc, category, categoryIndex) => {
return acc.concat(category.counters.reduce((counterAcc, counter, index) => {
    return counterAcc.concat([{
      // counters will be an array of the objects we generate here.
      // node contains a reference to the tr element for this counter
      node: document.getElementById(`counter-${categoryIndex}-${index}`),
      // date is the date for this counter parsed by Date and then converted
      // into a timestamp
      date: (new Date(counter.date)).getTime()
      }]);
    }, []));
}, []);

const msSecond = 1000,
  msMinute = msSecond * 60,
  msHour = msMinute * 60,
  msDay = msHour * 24;
let intervalId;

function updateCounters () {
  counters.forEach((counter, counterIndex) => {
  let remaining = counter.date - Date.now(),
    node = counter.node;
  let setText = (selector, text) => node.querySelector(selector).textContent = text;

  if (remaining > 0) {
    setText('.days', Math.floor(remaining / msDay));
    remaining %= msDay;
    setText('.hours', Math.floor(remaining / msHour));
    remaining %= msHour;
    setText('.minutes', Math.floor(remaining / msMinute));
    remaining %= msMinute;
    setText('.seconds', Math.floor(remaining / msSecond));
  } else {
    // make sure we don't accidentally display negative numbers if a timer
    // firing late returns a past timestamp (or the data contains a past date)
    setText('.days', 0);
    setText('.hours', 0);
    setText('.minutes', 0);
    setText('.seconds', 0);

    // This countdown has reached 0 seconds, stop updating it.
    counters.splice(counterIndex, 1);
    // no more counters? Stop the timer
    if (counters.length === 0) {
      clearInterval(intervalId);
    }
  }
  });
}
// display counters right away without waiting a second
updateCounters();
intervalId = setInterval(updateCounters, 1000);

 table {
 border-collapse: collapse;
 }
 tr:nth-child(even) {
 background-color: #edf;
 }
 .category {
 font-weight: bold;
 }
 td, th {
 padding: .5em;
 }
 .days, .hours, .minutes, .seconds {
 text-align: right;
 }

 <noscript id="countdown">Sorry, you need JavaScript enabled to view the count
 downs</noscript>

More Reading

Creating Accurate Timers in JavaScript

Critical rendering path

Repaints and Reflows: Manipulating the DOM responsibly


来源: stackexchange

问:
Does C++ read binary numbers as two's complement by default?
I have a piece of code reading two bytes from a hardware's registers:

```<code>short MPU9250::combineRegisters(unsigned char msb, unsigned char lsb){
        //shift the MSB left by 8 bits and OR with LSB
        return ((short)msb<<8)|(short)lsb;
    }
</code>```

the actual data in the device is in big Endian format, so I read two bytes and combine them to get the real value in two's complement form. However, when I'm outputting the data to the console, like:

```<code>cout << combineRegisters(registerA, registerB) << endl;
</code>```

C++ automatically gives me integer values with appropriate plus/minus sign. I didn't specify that the binary value I got from the devices is of two's complement form.

How is that? Does that mean C++ reads binary values and assume that they are two's complement format?

答:
ostream::operator<<() detects in compile time types of argument - in your case short. It is a type with sign, so you can do 2 things

Cast value returned from function

```<code>cout << static_cast<unsigned short>(combineRegisters(registerA, registerB)) << endl;
</code>```

or modify function itself

```<code>unsigned short MPU9250::combineRegisters(unsigned char msb, unsigned char lsb) {
    //shift the MSB left by 8 bits and OR with LSB
    return (static_cast<unsigned short>(msb << 8) | static_cast<unsigned short>(lsb);
}
</code>```

I recomend second variant because you have no intention of returning negative values from MPU9250::combineRegisters function.

ContentLicense: CC BY-SA 3.0

Body:
I have a piece of code reading two bytes from a hardware's registers:

short MPU9250::combineRegisters(unsigned char msb, unsigned char lsb){
        //shift the MSB left by 8 bits and OR with LSB
        return ((short)msb<<8)|(short)lsb;
    }

the actual data in the device is in big Endian format, so I read two bytes and combine them to get the real value in two's complement form. However, when I'm outputting the data to the console, like:

cout << combineRegisters(registerA, registerB) << endl;

C++ automatically gives me integer values with appropriate plus/minus sign. I didn't specify that the binary value I got from the devices is of two's complement form.

How is that? Does that mean C++ reads binary values and assume that they are two's complement format?

Body:
ostream::operator<<() detects in compile time types of argument - in your case short. It is a type with sign, so you can do 2 things

Cast value returned from function

cout << static_cast<unsigned short>(combineRegisters(registerA, registerB)) << endl;

or modify function itself

unsigned short MPU9250::combineRegisters(unsigned char msb, unsigned char lsb) {
    //shift the MSB left by 8 bits and OR with LSB
    return (static_cast<unsigned short>(msb << 8) | static_cast<unsigned short>(lsb);
}

I recomend second variant because you have no intention of returning negative values from MPU9250::combineRegisters function.


问:
SAS: Merging two tables with identical columns while dropping null values
I'm not sure if the title does this question justice, but here it goes:

I have three datasets Forecasts1, Forecasts2 and Forecasts3. They are all time series data composed of a date variable and variables r1 through r241.

For a given r variable (lets just use r1-r3, and only Forecasts 1 and 2 for now) each dataset has only one row where the value isn't null, and it is a different row in each dataset.

Forecast 1 looks like this:

Forecast 2 looks like this:

I need to be able to combine them such that r1-r3 contain all the non-null values, without creating duplicate date rows to hold the null values.

So ideally the finished produce would look like this:

I've tried various types of merges and sets, but I keep getting duplicate date rows. How would I go about doing this properly for all 241 (or more) variables? (specifically in SAS or Proc SQL?)

LINKS TO GOOGLE DOCS CONTAINING DATA:

Forecasts1: https://docs.google.com/spreadsheets/d/1iUEwPltU6V6ijgnkALFiIdrwrolDFt8xaITZaFC4WN8/edit?usp=sharing

Forecasts2:
https://docs.google.com/spreadsheets/d/1lQGKYJlz6AAR-DWtoWnl8SwzCNAmSpj7yxRqRgnybr8/edit?usp=sharing

答:
Did you try the UPDATE statement?

```<code>data forecast1 ;
  input date r1-r3 ;
cards;
1 1 . .
2 . 2 .
3 . . 3
4 . . .
;
data forecast2 ;
  input date r1-r3 ;
cards;
2 2 . .
3 . 3 .
4 . . 4
5 . . .
;

data want ;
  update forecast1 forecast2 ;
  by date ;
run;

proc print; run;
</code>```

Results

```<code>date    r1    r2    r3
  1      1     .     .
  2      2     2     .
  3      .     3     3
  4      .     .     4
  5      .     .     .
</code>```

Body:
Did you try the UPDATE statement?

data forecast1 ;
  input date r1-r3 ;
cards;
1 1 . .
2 . 2 .
3 . . 3
4 . . .
;
data forecast2 ;
  input date r1-r3 ;
cards;
2 2 . .
3 . 3 .
4 . . 4
5 . . .
;

data want ;
  update forecast1 forecast2 ;
  by date ;
run;

proc print; run;

Results

date    r1    r2    r3
  1      1     .     .
  2      2     2     .
  3      .     3     3
  4      .     .     4
  5      .     .     .


问:
Change time string to double
So basically to change string time like "HH:MM:SS", I have to use TimeSpan.Parse. But my professor gave me the string form like this "MM:SS.FF". And surely I tried TimeSpan.Parse, but it threw some exception. So my question is what should i use in this case?</p>

```<code>string aTime = "00:30.19";
</code>```

答:
You will use TimeSpan.TryParseExact instead:

```<code>TimeSpan interval;
string aTime = "00:30.19";
TimeSpan.TryParseExact(aTime , @"mm\:ss\.ff", null, out interval);
Console.WriteLine("{0} --> {1}", aTime , interval.ToString("c"));
</code>```

Output would be:

```<code>00:30.19 --> 00:00:30.1900000
</code>```

Title: Change time string to double

Body:
So basically to change string time like "HH:MM:SS", I have to use TimeSpan.Parse. But my professor gave me the string form like this "MM:SS.FF". And surely I tried TimeSpan.Parse, but it threw some exception. So my question is what should i use in this case?

string aTime = "00:30.19";

Body:
You will use TimeSpan.TryParseExact instead:

TimeSpan interval;
string aTime = "00:30.19";
TimeSpan.TryParseExact(aTime , @"mm\:ss\.ff", null, out interval);
Console.WriteLine("{0} --> {1}", aTime , interval.ToString("c"));

Output would be:

00:30.19 --> 00:00:30.1900000


问:
Many to many query for postgresql
I have an elementary many-to-many relation in my Postgresql DB

Table - User

id
name
...

Table - Chat

id
name

Table - chatuser

id
userId
chatId

And I would like to get all chats (actually, there will be only one such chat), which will have only users, defined by their ids.

For example, I have user with id 1, user with id 2 and user with id 3. How can I get chats, which contain only these users, not less and not more. That means, that chats with only someone of these users will not be included in the result. Only chats which contain exactly these users

I understand, there`s got to be such question already, but I did not manage to find it.

答:
Here is one method using group by and having:

```<code>select cu.chatid
from chatuser cu
group by cu.chatid
having sum(case when cu.userid not in (1, 2, 3) then 1 else 0 end) = 0;
</code>```

This counts the number of users that are not in your list.  The = 0 says that the chatId has none of them.

In Postgres, you can shorten this to:

```<code>select cu.chatid
from chatuser cu
group by cu.chatid
having sum( (cu.userid not in (1, 2, 3))::int) = 0;
</code>```

Title: Many to many query for postgresql

Body:
Here is one method using group by and having:

select cu.chatid
from chatuser cu
group by cu.chatid
having sum(case when cu.userid not in (1, 2, 3) then 1 else 0 end) = 0;

This counts the number of users that are not in your list.  The = 0 says that the chatId has none of them.

In Postgres, you can shorten this to:

select cu.chatid
from chatuser cu
group by cu.chatid
having sum( (cu.userid not in (1, 2, 3))::int) = 0;


问:
How do I refactor css?
I have been tasked with refactoring the css of a website, and I am quite new to refactoring process. What is the exact process I can undergo in order to refactor the css of my website? What are the tools I can use in order to ease this process?</p>

答:
"Tidying up", and an ideal opportunity to switch to pre-processing

Basically I would think of refactoring as "tidying up". Personally if I were to undertake that process I would think about working my way through the existing CSS, and "refactoring" it into a pre-processing language like LESS or SASS. It would certainly cut down on the line count (pre-rendered) and carry all sorts of other bonuses that the bosses would like :)

Especially eliminating redundant or duplicated rules

A major part of the refactoring process would be the eliminating of redundant, or duplicated rules. Either rules targeting elements that don't exist (These grow over time usually) or rules that are accidentally duplicated.

Commenting, indenting and sectioning code

Commenting the code nicely part be seen as a part of the refactoring process, and would be greeted enthusiastically be co-workers and coders that might follow you. Another bonus of switching to a CSS pre-processor is that you can be generous with commenting, coding-indenting, sectioning etc and all that extra stuff will just get stripped away when the code compiles to the (usually minified) CSS that gets used in production.

Tools that might help

Tools like https://unused-css.com/ claim to identify/remove unused CSS rules, but I have no experience with them, and would rather do the task manually anyway.

Title: How do I refactor css?


问:
PHP send email message coding in utf-8
I have a problem with sending mail from php code. I want to use polish characters in email message. I searched many post on stack with the same problem but nothing works.

```<code><?php
if(isset($_POST['submit'])){
 $to = "...@gmail.com";
 $from = $_POST['email'];
 $name = $_POST['name'];
 $phone = $_POST['phone'];
 $subject = "Wiadomość ze strony";
 $message = "Imię i Nazwisko: " . $name . "\nTelefon kontaktowy: " . $phone . "\n\nTreść wiadomości:" . "\n\n" . $_POST['msg'];

 $headers = "From: $from \r\n".
            "MIME-Version: 1.0" . "\r\n" .
            "Content-type: text/html; charset=UTF-8" . "\r\n";

 mail($to,$subject,$message,$headers);
 header('Location: index.html');
}
?>
</code>```

I have asked my friend to check on his vps and this code work correctly. So there must be a problem with server. I use linuxpl.com.

I found the solution. Polish characters work fine when I added this line in html form.

```<code>accept-charset="ISO-8859-1"
</code>```

Title: PHP send email message coding in utf-8

Body:
I have a problem with sending mail from php code. I want to use polish characters in email message. I searched many post on stack with the same problem but nothing works.

<?php
if(isset($_POST['submit'])){
 $to = "...@gmail.com";
 $from = $_POST['email'];
 $name = $_POST['name'];
 $phone = $_POST['phone'];
 $subject = "Wiadomość ze strony";
 $message = "Imię i Nazwisko: " . $name . "\nTelefon kontaktowy: " . $phone . "\n\nTreść wiadomości:" . "\n\n" . $_POST['msg'];

 $headers = "From: $from \r\n".
            "MIME-Version: 1.0" . "\r\n" .
            "Content-type: text/html; charset=UTF-8" . "\r\n";

 mail($to,$subject,$message,$headers);
 header('Location: index.html');
}
?>

I have asked my friend to check on his vps and this code work correctly. So there must be a problem with server. I use linuxpl.com.

I found the solution. Polish characters work fine when I added this line in html form.

accept-charset="ISO-8859-1"

Body: mail($to,utf8_decode($subject),utf8_decode($message),utf8_decode($headers));


问:
pyodbc connection to Oracle database on Linux
Can anyone point me to a "free" resource that allows one to connect via pyodbc to an Oracle database?  We have a multi db environment we support.  I have DB2 and MSSQL ODBC drivers working but I cannot seem to find any information on connecting via ODBC/pyodbc to an Oracle server running on Linux.

Linux:  cat /etc/redhat-release
CentOS release 5.5 (Final)

Python: python -V
Python 2.4.3

I found a few links to some thing call mxODBC but it appears to be a closed, commercial ($$$) solution.

答: Not knowing thing one about pyodbc, I have to ask: would the oracle ODBC driver in the instant client software help you out? That's free.</p>

ContentLicense: CC BY-SA 2.5


问:
Do I need to know SQL when I work with Django
I am directing this question to experienced, Django developers, so as in subject, I have been learning Django since September 2016, but I've started to learn it without any knowledge about databases syntax. I know basic concepts and definitions, so I can easily implement in Django models. Summarizing, have I to know SQL to create web apps in Django? Thanks in advance.</p>

答:
In my opinion, yes. Of course the Django ORM will do most of the job for you when it comes to queries, but you should know SQL. Maybe not every single aspect of SQL but enough to now what you're doing.

For instance how can you join two or more tables if you don't know what a join is?
Or given a query, can you improve it and make it more efficient?

Moreover knowing what a relational database is and how to make one, will help you build better and more efficient database, so your application will work better, and will be easier to mantain.
So yes, between knowing and not knowing, always go for knowing!

Have a look at this if you wanna practice a bit:
https://sqlbolt.com/


问:
linker warning: 'WJLibrary has an install name beginning with "/", but it is not from the specified SDK'
My build is working, but the linker is giving this warning. I have no idea why, what it means, or what corrective action I am supposed to take. Can anyone explain any portion of the above?</p>

```<code>Ld /Users/william/Library/Developer/Xcode/DerivedData/GraphingCalculatorDeluxe-bgozykycmwegcwaobycglqsxfprk/Build/Intermediates/ArchiveIntermediates/FreeUnitConverter/IntermediateBuildFilesPath/GraphingCalculatorDeluxe.build/Release-iphoneos/FreeUnitConverter.build/Objects-normal/armv7/FreeUnitConverter normal armv7
cd /Users/william/Documents/GraphingCalculatorDeluxe/GraphingCalculatorDeluxe
export IPHONEOS_DEPLOYMENT_TARGET=8.0
export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch armv7 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk -L/Users/william/Library/Developer/Xcode/DerivedData/GraphingCalculatorDeluxe-bgozykycmwegcwaobycglqsxfprk/Build/Intermediates/ArchiveIntermediates/FreeUnitConverter/BuildProductsPath/Release-iphoneos -LWJLibrary -LWJLibrary/Ads -LWJLibrary/build -LWJLibrary/Classes -LWJLibrary/Generic -LWJLibrary/WJLibrary-macOS -LWJLibrary/WJLibraryFramework -LWJLibrary/WJLibraryFrameworkIOS -LWJLibrary/WJLibraryIOS -LWJLibrary/WJLibraryResources.bundle -LWJLibrary/build/Release-iphoneos -LWJLibrary/Classes/App\ Store -LWJLibrary/Classes/C -LWJLibrary/Classes/Categories -LWJLibrary/Classes/Debug -LWJLibrary/Classes/Game\ Center -LWJLibrary/Classes/Geometry -LWJLibrary/Classes/Graphics -LWJLibrary/Classes/Misc -LWJLibrary/Classes/Settings -LWJLibrary/WJLibraryResources.bundle/Licenses -LWJLibrary/Classes/Categories/NSCategories -LWJLibrary/Classes/Categories/UICategories -LWJLibrary/Classes/Graphics/WJOrientedGradient -LWJLibrary/Classes/Graphics/WJPartitions -LWJLibrary/Classes/Graphics/WJView -LWJLibrary/Classes/Settings/Settings\ Cells -LWJLibrary/Classes/Graphics/WJView/UILabelTest -LWJLibrary/Classes/Graphics/WJView/UILabelTest/UILabelTest -F/Users/william/Library/Developer/Xcode/DerivedData/GraphingCalculatorDeluxe-bgozykycmwegcwaobycglqsxfprk/Build/Intermediates/ArchiveIntermediates/FreeUnitConverter/BuildProductsPath/Release-iphoneos -FWJLibrary -FWJLibrary/Ads -FWJLibrary/build -FWJLibrary/Classes -FWJLibrary/Generic -FWJLibrary/WJLibrary-macOS -FWJLibrary/WJLibraryFramework -FWJLibrary/WJLibraryFrameworkIOS -FWJLibrary/WJLibraryIOS -FWJLibrary/WJLibraryResources.bundle -FWJLibrary/build/Release-iphoneos -FWJLibrary/Classes/App\ Store -FWJLibrary/Classes/C -FWJLibrary/Classes/Categories -FWJLibrary/Classes/Debug -FWJLibrary/Classes/Game\ Center -FWJLibrary/Classes/Geometry -FWJLibrary/Classes/Graphics -FWJLibrary/Classes/Misc -FWJLibrary/Classes/Settings -FWJLibrary/WJLibraryResources.bundle/Licenses -FWJLibrary/Classes/Categories/NSCategories -FWJLibrary/Classes/Categories/UICategories -FWJLibrary/Classes/Graphics/WJOrientedGradient -FWJLibrary/Classes/Graphics/WJPartitions -FWJLibrary/Classes/Graphics/WJView -FWJLibrary/Classes/Settings/Settings\ Cells -FWJLibrary/Classes/Graphics/WJView/UILabelTest -FWJLibrary/Classes/Graphics/WJView/UILabelTest/UILabelTest -filelist /Users/william/Library/Developer/Xcode/DerivedData/GraphingCalculatorDeluxe-bgozykycmwegcwaobycglqsxfprk/Build/Intermediates/ArchiveIntermediates/FreeUnitConverter/IntermediateBuildFilesPath/GraphingCalculatorDeluxe.build/Release-iphoneos/FreeUnitConverter.build/Objects-normal/armv7/FreeUnitConverter.LinkFileList -Xlinker -rpath -Xlinker @executable_path/Frameworks -miphoneos-version-min=8.0 -dead_strip -Xlinker -object_path_lto -Xlinker /Users/william/Library/Developer/Xcode/DerivedData/GraphingCalculatorDeluxe-bgozykycmwegcwaobycglqsxfprk/Build/Intermediates/ArchiveIntermediates/FreeUnitConverter/IntermediateBuildFilesPath/GraphingCalculatorDeluxe.build/Release-iphoneos/FreeUnitConverter.build/Objects-normal/armv7/FreeUnitConverter_lto.o -fembed-bitcode -Xlinker -bitcode_verify -Xlinker -bitcode_hide_symbols -Xlinker -bitcode_symbol_map -Xlinker /Users/william/Library/Developer/Xcode/DerivedData/GraphingCalculatorDeluxe-bgozykycmwegcwaobycglqsxfprk/Build/Intermediates/ArchiveIntermediates/FreeUnitConverter/BuildProductsPath/Release-iphoneos -Xlinker -final_output -Xlinker /Users/william/Applications/FreeUnitConverter.app/FreeUnitConverter -fobjc-arc -fobjc-link-runtime -ObjC -framework Accelerate -framework AVFoundation -framework CoreGraphics -framework CoreText -framework Foundation -framework MobileCoreServices -framework StoreKit -framework SystemConfiguration -framework QuartzCore -framework UIKit -framework WJLibraryIOS -Xlinker -dependency_info -Xlinker /Users/william/Library/Developer/Xcode/DerivedData/GraphingCalculatorDeluxe-bgozykycmwegcwaobycglqsxfprk/Build/Intermediates/ArchiveIntermediates/FreeUnitConverter/IntermediateBuildFilesPath/GraphingCalculatorDeluxe.build/Release-iphoneos/FreeUnitConverter.build/Objects-normal/armv7/FreeUnitConverter_dependency_info.dat -o /Users/william/Library/Developer/Xcode/DerivedData/GraphingCalculatorDeluxe-bgozykycmwegcwaobycglqsxfprk/Build/Intermediates/ArchiveIntermediates/FreeUnitConverter/IntermediateBuildFilesPath/GraphingCalculatorDeluxe.build/Release-iphoneos/FreeUnitConverter.build/Objects-normal/armv7/FreeUnitConverter

ld: warning: WJLibrary/build/Release-iphoneos/WJLibraryIOS.framework/WJLibraryIOS has install name beginning with "/" but it is not from the specified SDK
</code>```

答:
In my case, what I needed to do was:

```<code> DYLIB_INSTALL_NAME_BASE = @rpath
</code>```

in the build settings. And this warning becomes a failure when you submit the app.

Body:
My build is working, but the linker is giving this warning. I have no idea why, what it means, or what corrective action I am supposed to take. Can anyone explain any portion of the above?

Ld /Users/william/Library/Developer/Xcode/DerivedData/GraphingCalculatorDeluxe-bgozykycmwegcwaobycglqsxfprk/Build/Intermediates/ArchiveIntermediates/FreeUnitConverter/IntermediateBuildFilesPath/GraphingCalculatorDeluxe.build/Release-iphoneos/FreeUnitConverter.build/Objects-normal/armv7/FreeUnitConverter normal armv7
cd /Users/william/Documents/GraphingCalculatorDeluxe/GraphingCalculatorDeluxe
export IPHONEOS_DEPLOYMENT_TARGET=8.0
export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch armv7 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk -L/Users/william/Library/Developer/Xcode/DerivedData/GraphingCalculatorDeluxe-bgozykycmwegcwaobycglqsxfprk/Build/Intermediates/ArchiveIntermediates/FreeUnitConverter/BuildProductsPath/Release-iphoneos -LWJLibrary -LWJLibrary/Ads -LWJLibrary/build -LWJLibrary/Classes -LWJLibrary/Generic -LWJLibrary/WJLibrary-macOS -LWJLibrary/WJLibraryFramework -LWJLibrary/WJLibraryFrameworkIOS -LWJLibrary/WJLibraryIOS -LWJLibrary/WJLibraryResources.bundle -LWJLibrary/build/Release-iphoneos -LWJLibrary/Classes/App\ Store -LWJLibrary/Classes/C -LWJLibrary/Classes/Categories -LWJLibrary/Classes/Debug -LWJLibrary/Classes/Game\ Center -LWJLibrary/Classes/Geometry -LWJLibrary/Classes/Graphics -LWJLibrary/Classes/Misc -LWJLibrary/Classes/Settings -LWJLibrary/WJLibraryResources.bundle/Licenses -LWJLibrary/Classes/Categories/NSCategories -LWJLibrary/Classes/Categories/UICategories -LWJLibrary/Classes/Graphics/WJOrientedGradient -LWJLibrary/Classes/Graphics/WJPartitions -LWJLibrary/Classes/Graphics/WJView -LWJLibrary/Classes/Settings/Settings\ Cells -LWJLibrary/Classes/Graphics/WJView/UILabelTest -LWJLibrary/Classes/Graphics/WJView/UILabelTest/UILabelTest -F/Users/william/Library/Developer/Xcode/DerivedData/GraphingCalculatorDeluxe-bgozykycmwegcwaobycglqsxfprk/Build/Intermediates/ArchiveIntermediates/FreeUnitConverter/BuildProductsPath/Release-iphoneos -FWJLibrary -FWJLibrary/Ads -FWJLibrary/build -FWJLibrary/Classes -FWJLibrary/Generic -FWJLibrary/WJLibrary-macOS -FWJLibrary/WJLibraryFramework -FWJLibrary/WJLibraryFrameworkIOS -FWJLibrary/WJLibraryIOS -FWJLibrary/WJLibraryResources.bundle -FWJLibrary/build/Release-iphoneos -FWJLibrary/Classes/App\ Store -FWJLibrary/Classes/C -FWJLibrary/Classes/Categories -FWJLibrary/Classes/Debug -FWJLibrary/Classes/Game\ Center -FWJLibrary/Classes/Geometry -FWJLibrary/Classes/Graphics -FWJLibrary/Classes/Misc -FWJLibrary/Classes/Settings -FWJLibrary/WJLibraryResources.bundle/Licenses -FWJLibrary/Classes/Categories/NSCategories -FWJLibrary/Classes/Categories/UICategories -FWJLibrary/Classes/Graphics/WJOrientedGradient -FWJLibrary/Classes/Graphics/WJPartitions -FWJLibrary/Classes/Graphics/WJView -FWJLibrary/Classes/Settings/Settings\ Cells -FWJLibrary/Classes/Graphics/WJView/UILabelTest -FWJLibrary/Classes/Graphics/WJView/UILabelTest/UILabelTest -filelist /Users/william/Library/Developer/Xcode/DerivedData/GraphingCalculatorDeluxe-bgozykycmwegcwaobycglqsxfprk/Build/Intermediates/ArchiveIntermediates/FreeUnitConverter/IntermediateBuildFilesPath/GraphingCalculatorDeluxe.build/Release-iphoneos/FreeUnitConverter.build/Objects-normal/armv7/FreeUnitConverter.LinkFileList -Xlinker -rpath -Xlinker @executable_path/Frameworks -miphoneos-version-min=8.0 -dead_strip -Xlinker -object_path_lto -Xlinker /Users/william/Library/Developer/Xcode/DerivedData/GraphingCalculatorDeluxe-bgozykycmwegcwaobycglqsxfprk/Build/Intermediates/ArchiveIntermediates/FreeUnitConverter/IntermediateBuildFilesPath/GraphingCalculatorDeluxe.build/Release-iphoneos/FreeUnitConverter.build/Objects-normal/armv7/FreeUnitConverter_lto.o -fembed-bitcode -Xlinker -bitcode_verify -Xlinker -bitcode_hide_symbols -Xlinker -bitcode_symbol_map -Xlinker /Users/william/Library/Developer/Xcode/DerivedData/GraphingCalculatorDeluxe-bgozykycmwegcwaobycglqsxfprk/Build/Intermediates/ArchiveIntermediates/FreeUnitConverter/BuildProductsPath/Release-iphoneos -Xlinker -final_output -Xlinker /Users/william/Applications/FreeUnitConverter.app/FreeUnitConverter -fobjc-arc -fobjc-link-runtime -ObjC -framework Accelerate -framework AVFoundation -framework CoreGraphics -framework CoreText -framework Foundation -framework MobileCoreServices -framework StoreKit -framework SystemConfiguration -framework QuartzCore -framework UIKit -framework WJLibraryIOS -Xlinker -dependency_info -Xlinker /Users/william/Library/Developer/Xcode/DerivedData/GraphingCalculatorDeluxe-bgozykycmwegcwaobycglqsxfprk/Build/Intermediates/ArchiveIntermediates/FreeUnitConverter/IntermediateBuildFilesPath/GraphingCalculatorDeluxe.build/Release-iphoneos/FreeUnitConverter.build/Objects-normal/armv7/FreeUnitConverter_dependency_info.dat -o /Users/william/Library/Developer/Xcode/DerivedData/GraphingCalculatorDeluxe-bgozykycmwegcwaobycglqsxfprk/Build/Intermediates/ArchiveIntermediates/FreeUnitConverter/IntermediateBuildFilesPath/GraphingCalculatorDeluxe.build/Release-iphoneos/FreeUnitConverter.build/Objects-normal/armv7/FreeUnitConverter

ld: warning: WJLibrary/build/Release-iphoneos/WJLibraryIOS.framework/WJLibraryIOS has install name beginning with "/" but it is not from the specified SDK

Body:
In my case, what I needed to do was:

 DYLIB_INSTALL_NAME_BASE = @rpath

in the build settings. And this warning becomes a failure when you submit the app.


问:
Which npm packages will and will not work on Angular 2? How do I tell?
Does an NPM package need to be modified to be compatible with Angular 2 (eg. add in typings, make directives for them) or will any existing package work? If they're not all compatible, how do I know what is and what is not compatible?

For example, say I want to import this package (https://github.com/pvorb/node-md5). I'm aware there is a ts-md5 package for angular 2 to do md5 - I'm just using this package as an example.

How would I get this to work?

I've installed it using

```<code>npm install md5 --save
npm install @types/md5 --save
</code>```

but I can't seem to be import it

```<code>import {md5} from 'md5';
</code>```

I get this error message after I try to run

Module
  '"/Users/xxx/Source/tempProjects/ngUnderscore/node_modules/@types/md5/index"'
  resolves to a non-module entity and cannot be imported using this
  construct.

I'm not sure what this message means. Does it mean that in its current state, the package is not compatible or am I trying to use the package incorrectly?

答:
They usually say which Angular it is meant for, sometimes you have one package for both or for each.

If you are using an Angular 1x package and there is no Angular2 compatibility, then you can just use ngUpgrade.

But If you are using a common plugin then there must be an angular 2 solution.

If you want the other way around then you're probably going the wrong way.

Body:
Does an NPM package need to be modified to be compatible with Angular 2 (eg. add in typings, make directives for them) or will any existing package work? If they're not all compatible, how do I know what is and what is not compatible?

For example, say I want to import this package (https://github.com/pvorb/node-md5). I'm aware there is a ts-md5 package for angular 2 to do md5 - I'm just using this package as an example.

How would I get this to work?

I've installed it using

npm install md5 --save
npm install @types/md5 --save

but I can't seem to be import it

import {md5} from 'md5';

I get this error message after I try to run

Module
  '"/Users/xxx/Source/tempProjects/ngUnderscore/node_modules/@types/md5/index"'
  resolves to a non-module entity and cannot be imported using this
  construct.

I'm not sure what this message means. Does it mean that in its current state, the package is not compatible or am I trying to use the package incorrectly?


问:
Unity touch input for Rolling Sky x axis control
I have written some code that I would image would be a very simplistic version of something found in the player controller of a game like Rolling Sky.

```<code>void Update () {
    if (Input.GetMouseButton(0)) {
        NewX = Camera.main.ScreenToViewportPoint (Input.mousePosition).x;
        float xMotion = (LastX - NewX) * -NavigationMultiplier / Screen.width;
        this.transform.position = new Vector3 (this.transform.position.x + xMotion, this.transform.position.y, this.transform.position.z);
    }
    LastX = Camera.main.ScreenToViewportPoint(Input.mousePosition).x;
}
</code>```

This code works well on desktop, but as expected, it doesn't perform so well on mobile (the platform of choice)
Interestingly it just appears as if the player follows the finger similarly to simply using:

```<code>this.transform.position = new Vector3 (Input.mousePosition.x, this.transform.position.y, this.transform.position.z);
</code>```

Can anyone help make the first code block work correctly on mobile?

Desktop behavior (Desired)
https://www.youtube.com/watch?v=PjSzEresQI8

Mobile behavior (undesired)
https://www.youtube.com/watch?v=OooJ_NJW7V0

Thanks in advance

答:
I am assuming you want smoother movement of the ball, kinda like in the game, not instantly teleport it to where the player touches. To do so you could use a function called Lerp. Read more here

To achieve this you could replace this line of code

```<code>this.transform.position = new Vector3 (this.transform.position.x + xMotion, this.transform.position.y, this.transform.position.z);
</code>```

with this one

```<code>this.transform.position = Vector3.Lerp(this.transform.position, new Vector3 (this.transform.position.x , this.transform.position.y, this.transform.position.z),Time.deltaTime)
</code>```

Hope that helps!

Body:
I have written some code that I would image would be a very simplistic version of something found in the player controller of a game like Rolling Sky.

void Update () {
    if (Input.GetMouseButton(0)) {
        NewX = Camera.main.ScreenToViewportPoint (Input.mousePosition).x;
        float xMotion = (LastX - NewX) * -NavigationMultiplier / Screen.width;
        this.transform.position = new Vector3 (this.transform.position.x + xMotion, this.transform.position.y, this.transform.position.z);
    }
    LastX = Camera.main.ScreenToViewportPoint(Input.mousePosition).x;
}

This code works well on desktop, but as expected, it doesn't perform so well on mobile (the platform of choice)
Interestingly it just appears as if the player follows the finger similarly to simply using:

this.transform.position = new Vector3 (Input.mousePosition.x, this.transform.position.y, this.transform.position.z);

Can anyone help make the first code block work correctly on mobile?

Desktop behavior (Desired)
https://www.youtube.com/watch?v=PjSzEresQI8

Mobile behavior (undesired)
https://www.youtube.com/watch?v=OooJ_NJW7V0

Thanks in advance

Body:
I am assuming you want smoother movement of the ball, kinda like in the game, not instantly teleport it to where the player touches. To do so you could use a function called Lerp. Read more here

To achieve this you could replace this line of code

this.transform.position = new Vector3 (this.transform.position.x + xMotion, this.transform.position.y, this.transform.position.z);

with this one

this.transform.position = Vector3.Lerp(this.transform.position, new Vector3 (this.transform.position.x , this.transform.position.y, this.transform.position.z),Time.deltaTime)

Hope that helps!


问:
Node.JS - Mongoose won't save data to MongoDB and Object not getting information correctly?
So firstly, I checked the relevant question but since I'm not using the same  middleware, I don't think it helped me. I have a regular form and while it successfully goes through req.body and I can print all the form values. However the problems are when I try to create a new object because when I print it, it doesn't have the correct fields that I assigned it...? And secondly, when I try to save it, it doesn't show up in the Db when I check via Terminal. I have successfully run Mongod and am connected to the correct Db and collection so I'm confused. Any help would be greatly appreciated!

Here is the relevant code

App.js:

```<code>    var express = require('express');
var app = express();
var db = require('./db.js');
var path = require('path');

var bodyParser = require('body-parser');
var handlebars = require('hbs');

var mongoose = require('mongoose');
var museumObj = mongoose.model('MuseumObject');

//For Images
var fs = require('fs');
var multer = require('multer');
//Saves to memory storage
var upload = multer({ storage: multer.memoryStorage({}) });

//Port setting
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'hbs');
app.set('views', path.join(__dirname, 'views'));
//app.use(bodyParser.json());
//app.use(bodyParser.urlencoded({ extended: false }));

app.get('/', function(req, res) {
    res.render('index');
});

app.get('/AdvancedSearch', function(req, res) {
    res.render('AdvancedSearch');
});

app.get('/AskUs', function(req, res) {
    res.render('AskUs');
});

app.get('/Themes', function(req, res) {
    res.render('Themes');
});

app.get('/AddObj',  function(req, res) {
    res.render('AddObj');
});

app.post('/AddObj',upload.single('pic'),function(req,res){
    console.log("here is the req.body");
    console.log(req.body);
    var base64 = req.file.buffer.toString('base64');

    var dim='';
    if(req.body.length && req.body.width && req.body.height){
        dim = req.body.req.body.length +" x "+req.body.width+" x "+req.body.height
    }

    var newObj = new museumObj({
        accessionNum: req.body.accession,
        maker: req.body.maker,
        manufacturer: req.body.manufacturer,
        title: req.body.title,
        date: req.body.date,
        medium: req.body.medium,
        dimesions: dim,
        marks: req.body.marks,
        description: req.body.description,
        pic: base64,
    });
    console.log('here is the new object before calling the save function');
    console.log(newObj);
    newObj.save(function(err,item, count){
        if (err){
            console.log("there is an error");
            console.log(err);
        }
        else{
            console.log('here is the "successfully" saved item');
            console.log(item);
            //res.redirect('/');
        }
    });

});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});
</code>```

Db.js:

```<code>var mongoose = require('mongoose');
var URLSlugs = require('mongoose-url-slugs');

var MuseumObject = new mongoose.Schema({
  accessionNum: String,
  maker: {String, default: ''},
  manufacturer: {String, default: ''},
  title: String,
  date: {String, default: ''},
  medium: {String, default: ''},
  dimensions: {String, default: ''},
  marks: {String, default: ''},
  description: {String, default: ''},
  pic: {String, default: ''}
});

MuseumObject.plugin(URLSlugs('title'));
mongoose.model('MuseumObject', MuseumObject);

// is the environment variable, NODE_ENV, set to PRODUCTION?
if (process.env.NODE_ENV == 'PRODUCTION') {
  console.log("in production");
 // if we're in PRODUCTION mode, then read the configration from a file
 // use blocking file io to do this...
 var fs = require('fs');
 var path = require('path');
 var fn = path.join(__dirname, 'config.json');
 var data = fs.readFileSync(fn);

 // our configuration file will be in json, so parse it and set the
 // conenction string appropriately!
 var conf = JSON.parse(data);
 var dbconf = conf.dbconf;
}
else {
 // if we're not in PRODUCTION mode, then use
 dbconf = 'mongodb://localhost/BKMuseum';
}

mongoose.connect(dbconf);
</code>```

HTML File:

```<code><h1>Add an Object to the Collection<h1>

<h3>

 <form method="POST" action="AddObj" id="AddObj" enctype='multipart/form-data'>
        *Accession #:  <input type="text" name = "accession" value ="" required>
        <BR>
        Maker/Designer/Artist: <input type="text" name = "maker" value ="">
        <BR>
        Manufacturer: <input type="text" name = "manufacturer" value ="" >
        <BR>
        *Title: <input type="text" name = "title" value ="" required >
        <BR>
        {{!-- Dates can be in string format: ca. 1930 vs. 1932-1934--}}
        *Date : <input type="text" name="date" value="" required>
        <BR>
        *Medium: <input type="text" name="medium" value="" required>
        <BR>
        <div>
            Dimensions:
            <blockquote>
                <input type="number" name="length" form="AddObj"> X <input type="number" name="width" form="AddObj"> X <input type="number" name="height" form="AddObj">
            </blockquote>
        </div>
        Marks: <input type="text" name="marks" value="">
        <div> Description
                <BR>
                <textarea name="description" form="AddObj" cols='50' style="resize:none; font-size:16px;"></textarea>
        </div>
        <br>
        <div>
            Image Upload
            <BR>
            <input type="file" name="pic" accept="image/*" form="AddObj" required>
        </div>
        <br>
        <input type="submit" value="Submit" form="AddObj">
    </form>

</3>
    <p>
        <a href="/">Go Back to Research Center's Home Page </a href>
    </p>
</code>```

Here is the relevant outputs

Console output

- Mongo console output:

use BKMuseum

  switched to db BKMuseum

  db.BKMuseum.count()

  0

  db.BKMuseum.find({})

Form Input

答:
Add second parameter which is your collection name</p>

```<code> var MuseumObject = new mongoose.Schema({
      accessionNum: String,
      maker: {String, default: ''},
      manufacturer: {String, default: ''},
      title: String,
      date: {String, default: ''},
      medium: {String, default: ''},
      dimensions: {String, default: ''},
      marks: {String, default: ''},
      description: {String, default: ''},
      pic: {String, default: ''}
    },
    {collection:"your_collection_name"});
</code>```

Body:
So firstly, I checked the relevant question but since I'm not using the same  middleware, I don't think it helped me. I have a regular form and while it successfully goes through req.body and I can print all the form values. However the problems are when I try to create a new object because when I print it, it doesn't have the correct fields that I assigned it...? And secondly, when I try to save it, it doesn't show up in the Db when I check via Terminal. I have successfully run Mongod and am connected to the correct Db and collection so I'm confused. Any help would be greatly appreciated!

Here is the relevant code

App.js:

    var express = require('express');
var app = express();
var db = require('./db.js');
var path = require('path');

var bodyParser = require('body-parser');
var handlebars = require('hbs');

var mongoose = require('mongoose');
var museumObj = mongoose.model('MuseumObject');

//For Images
var fs = require('fs');
var multer = require('multer');
//Saves to memory storage
var upload = multer({ storage: multer.memoryStorage({}) });

//Port setting
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'hbs');
app.set('views', path.join(__dirname, 'views'));
//app.use(bodyParser.json());
//app.use(bodyParser.urlencoded({ extended: false }));

app.get('/', function(req, res) {
    res.render('index');
});

app.get('/AdvancedSearch', function(req, res) {
    res.render('AdvancedSearch');
});

app.get('/AskUs', function(req, res) {
    res.render('AskUs');
});

app.get('/Themes', function(req, res) {
    res.render('Themes');
});

app.get('/AddObj',  function(req, res) {
    res.render('AddObj');
});

app.post('/AddObj',upload.single('pic'),function(req,res){
    console.log("here is the req.body");
    console.log(req.body);
    var base64 = req.file.buffer.toString('base64');

    var dim='';
    if(req.body.length && req.body.width && req.body.height){
        dim = req.body.req.body.length +" x "+req.body.width+" x "+req.body.height
    }

    var newObj = new museumObj({
        accessionNum: req.body.accession,
        maker: req.body.maker,
        manufacturer: req.body.manufacturer,
        title: req.body.title,
        date: req.body.date,
        medium: req.body.medium,
        dimesions: dim,
        marks: req.body.marks,
        description: req.body.description,
        pic: base64,
    });
    console.log('here is the new object before calling the save function');
    console.log(newObj);
    newObj.save(function(err,item, count){
        if (err){
            console.log("there is an error");
            console.log(err);
        }
        else{
            console.log('here is the "successfully" saved item');
            console.log(item);
            //res.redirect('/');
        }
    });

});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

Db.js:

var mongoose = require('mongoose');
var URLSlugs = require('mongoose-url-slugs');

var MuseumObject = new mongoose.Schema({
  accessionNum: String,
  maker: {String, default: ''},
  manufacturer: {String, default: ''},
  title: String,
  date: {String, default: ''},
  medium: {String, default: ''},
  dimensions: {String, default: ''},
  marks: {String, default: ''},
  description: {String, default: ''},
  pic: {String, default: ''}
});

MuseumObject.plugin(URLSlugs('title'));
mongoose.model('MuseumObject', MuseumObject);

// is the environment variable, NODE_ENV, set to PRODUCTION?
if (process.env.NODE_ENV == 'PRODUCTION') {
  console.log("in production");
 // if we're in PRODUCTION mode, then read the configration from a file
 // use blocking file io to do this...
 var fs = require('fs');
 var path = require('path');
 var fn = path.join(__dirname, 'config.json');
 var data = fs.readFileSync(fn);

 // our configuration file will be in json, so parse it and set the
 // conenction string appropriately!
 var conf = JSON.parse(data);
 var dbconf = conf.dbconf;
}
else {
 // if we're not in PRODUCTION mode, then use
 dbconf = 'mongodb://localhost/BKMuseum';
}

mongoose.connect(dbconf);

HTML File:

Add an Object to the Collection

 <form method="POST" action="AddObj" id="AddObj" enctype='multipart/form-data'>
        *Accession #:  <input type="text" name = "accession" value ="" required>

        Maker/Designer/Artist: <input type="text" name = "maker" value ="">

        Manufacturer: <input type="text" name = "manufacturer" value ="" >

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

        {{!-- Dates can be in string format: ca. 1930 vs. 1932-1934--}}
        *Date : <input type="text" name="date" value="" required>

        *Medium: <input type="text" name="medium" value="" required>

            Dimensions:

                <input type="number" name="length" form="AddObj"> X <input type="number" name="width" form="AddObj"> X <input type="number" name="height" form="AddObj">

        Marks: <input type="text" name="marks" value="">

 Description

                <textarea name="description" form="AddObj" cols='50' style="resize:none; font-size:16px;"></textarea>

            Image Upload

            <input type="file" name="pic" accept="image/*" form="AddObj" required>

        <input type="submit" value="Submit" form="AddObj">
    </form>

</3>

        Go Back to Research Center's Home Page

Here is the relevant outputs

Console output

- Mongo console output:

use BKMuseum

  switched to db BKMuseum

  db.BKMuseum.count()

  0

  db.BKMuseum.find({})

Form Input

Body:
Add second parameter which is your collection name

 var MuseumObject = new mongoose.Schema({
      accessionNum: String,
      maker: {String, default: ''},
      manufacturer: {String, default: ''},
      title: String,
      date: {String, default: ''},
      medium: {String, default: ''},
      dimensions: {String, default: ''},
      marks: {String, default: ''},
      description: {String, default: ''},
      pic: {String, default: ''}
    },
    {collection:"your_collection_name"});


问:
Why is the length of my arraylist generated by a for loop always zero (Java)?
First of all, thank you for taking the time to read this. I am quite new to android development and appreciate all the help I can get. I'll keep the description brief.

I'm developing an app as a side project to speed up the d&d sessions of me and my friends by automating the initiative rolls (rolling a 20-sided dice, adding a personal modifier and sorting from largest to smallest). Everything was going great until I hit a bug which to my frustration I haven't been able to fix. The length of the sorted Arraylist with names and of the complimentary dictionary always seems to be zero and I cannot find out why. Code is posted below.

First step is to collect user data from the input. the input works like this (this explains the weird ID's)

```<code>//updates player database with user input
private void updateDictionaryManager(int _partySize) {
    listManager.empty();

    if (_partySize > 0) {
        for (int i = 0; i < _partySize + 1; i++) {
            EditText Name = (EditText)findViewById(i);
            EditText dexMod = (EditText)findViewById(i + 10);
            String playerName = "player " + String.valueOf(i);
            int playerDexMod = 0;

            if (Name.getText() != null) {
                playerName = Name.getText().toString();
            }

            if (dexMod.getText() != null) {
                try {
                    playerDexMod = Integer.parseInt(dexMod.getText().toString());
                } catch (Exception e) {
                    playerDexMod = 0;
                }
            }
            listManager.append(playerName, playerDexMod, i);
        }
    }
}
</code>```

This is the code from the listmanager class

```<code>public void append(String _name, int _dexMod, int _playerNumber) {
    if (!_name.equals("")) {
        playerNames.add(_name);
    } else {
        String defaultName = "player " + String.valueOf(_playerNumber);
        playerNames.add(defaultName);
    }
    dexMod.add(_dexMod);
}

public void empty() {
    playerNames.clear();
    dexMod.clear();
}
</code>```

I guess the problem hides here (but I send the prvious just in case I missed something there)

```<code>final class InitiativeRoller extends ListManager{
Map<Integer, List<String>> playerRolls = new HashMap<>();
Map<String, Integer> outputDictionary = new HashMap<>();

List<Integer> alreadyRolled = new ArrayList<>();
List<String> outputOrder = new ArrayList<>();

public void roll() {
    //retrieve lists from manager
    List<String> _names = getPlayerNames();
    List<Integer> _dexMod = getDexMod();

    //rolling the dice and saving values
    for (int i = 0; i < getSize(); i++) {
        int _roll = (int) Math.round(Math.random() * 19) + 1 + _dexMod.get(i);

        if (alreadyRolled.contains(_roll)) {
            //add name to list in dictionary with corresponding roll
            playerRolls.get(_roll).add(_names.get(i));
        } else {
            //generate new list for players with this roll and add to playerRolls
            List<String> _list = new ArrayList<>();
            _list.add(_names.get(i));
            playerRolls.put(_roll, _list);

            alreadyRolled.add(_roll);
        }
    }

    //sorting the rolls from largest to smallest
    Collections.sort(alreadyRolled);
    Collections.reverse(alreadyRolled);

    //generating output dictionary
    for (int i = 0; i < alreadyRolled.size(); i++) {
        int _roll = alreadyRolled.get(i);
        List<String> list = playerRolls.get(_roll);

        //shuffling order of players with the same roll
        Collections.shuffle(list);

        //add to output dictionary and list
        for (int x = 0; x < list.size(); x++) {
            outputDictionary.put(list.get(x), _roll);
            outputOrder.add(list.get(x));
        }
    }
}

public Map<String, Integer> getOutputDictionary() {
    return outputDictionary;
}

public List<String> getOutputOrder() {
    return outputOrder;
}
</code>```

}

Every time I check, the resulting outputDictionary and outputorder have a length of zero. What am I missing? Sorry for the long post.

EDIT: I have checked the code and there does not seem to be a problem with the length of the list until the point where getPlayerNames and getDexMod are called inside the InitiativeRollerClass.

EDIT: Here are the get-methods

```<code>public List<String> getPlayerNames() {
    return playerNames;
}

public List<Integer> getDexMod() {
    return dexMod;
}
</code>```

UPDATE: This is the code bound to the roll-button:

```<code>rollInitiative.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //update dictionary
            int roundedProgress = Math.round(playerSlider.getProgress());

            try {
                updateDictionaryManager(roundedProgress);
            } catch (Exception e) {
                updateDictionaryManagerOnException(roundedProgress, playerList);
            }

            initiativeRoller.roll();
            displayResult(initiativeRoller.getOutputOrder(), initiativeRoller.getOutputDictionary(), InitiativeList);
        }
    });
</code>```

the method is described here, this is just for debugging

```<code>//displays output to user
    private void displayResult(List<String> _outputOrder, Map<String, Integer> _outputDictionary, TextView _initiativelist) {
        _initiativelist.setText(listManager.getDexMod() + "\n" + listManager.getPlayerNames()
        + "\n" + initiativeRoller.getOutputOrder());
    }
</code>```

This brings me the following

I also checked online if the code itself for the roll class was even functioning, it was. Here is the result for four hard coded names and values after a number of runs:

[Aaron, Josh, Clide, Li]

{Aaron=24, Clide=20, Josh=22, Li=8}

sh-4.3$ java -Xmx128M -Xms16M HelloWorld

[Josh, Li, Aaron, Clide]

{Aaron=6, Clide=6, Josh=20, Li=12}

sh-4.3$ java -Xmx128M -Xms16M HelloWorld

[Aaron, Clide, Li, Josh]

{Aaron=20, Clide=17, Josh=10, Li=11}

sh-4.3$ java -Xmx128M -Xms16M HelloWorld

[Li, Aaron, Clide, Josh]

{Aaron=19, Clide=18, Josh=18, Li=21}

Everything seems to be working just fine, I just don't understand why the returned list has a length of zero.

p.s. the code for the getSize() method

```<code>public int getSize() {
    return playerNames.size();
}
</code>```

答: Ok, this might be the error: keep in mind that in Java every variable just as any other compiled language has a scope. Now you decleare playerName and playerDexMod inside the for and you append them inside that for, up until now everything is in check. When you exit the for however those variables just die, and by that I mean that the java garbage collector, since they're out of scope, should deallocate them. Now the listManager ( which I suppose is an ArrayList) finds itself with objects that don't exist anymore, so basically null. And that's just an empty array list. If the listManager you use is decleared in a class try to decleare also the other variables in a class, so they won't get out of scope. Tell me if this helps.</p>

Body:
First of all, thank you for taking the time to read this. I am quite new to android development and appreciate all the help I can get. I'll keep the description brief.

I'm developing an app as a side project to speed up the d&d sessions of me and my friends by automating the initiative rolls (rolling a 20-sided dice, adding a personal modifier and sorting from largest to smallest). Everything was going great until I hit a bug which to my frustration I haven't been able to fix. The length of the sorted Arraylist with names and of the complimentary dictionary always seems to be zero and I cannot find out why. Code is posted below.

First step is to collect user data from the input. the input works like this (this explains the weird ID's)

//updates player database with user input
private void updateDictionaryManager(int _partySize) {
    listManager.empty();

    if (_partySize > 0) {
        for (int i = 0; i < _partySize + 1; i++) {
            EditText Name = (EditText)findViewById(i);
            EditText dexMod = (EditText)findViewById(i + 10);
            String playerName = "player " + String.valueOf(i);
            int playerDexMod = 0;

            if (Name.getText() != null) {
                playerName = Name.getText().toString();
            }

            if (dexMod.getText() != null) {
                try {
                    playerDexMod = Integer.parseInt(dexMod.getText().toString());
                } catch (Exception e) {
                    playerDexMod = 0;
                }
            }
            listManager.append(playerName, playerDexMod, i);
        }
    }
}

This is the code from the listmanager class

public void append(String _name, int _dexMod, int _playerNumber) {
    if (!_name.equals("")) {
        playerNames.add(_name);
    } else {
        String defaultName = "player " + String.valueOf(_playerNumber);
        playerNames.add(defaultName);
    }
    dexMod.add(_dexMod);
}

public void empty() {
    playerNames.clear();
    dexMod.clear();
}

I guess the problem hides here (but I send the prvious just in case I missed something there)

final class InitiativeRoller extends ListManager{
Map<Integer, List<String>> playerRolls = new HashMap<>();
Map<String, Integer> outputDictionary = new HashMap<>();

List<Integer> alreadyRolled = new ArrayList<>();
List<String> outputOrder = new ArrayList<>();

public void roll() {
    //retrieve lists from manager
    List<String> _names = getPlayerNames();
    List<Integer> _dexMod = getDexMod();

    //rolling the dice and saving values
    for (int i = 0; i < getSize(); i++) {
        int _roll = (int) Math.round(Math.random() * 19) + 1 + _dexMod.get(i);

        if (alreadyRolled.contains(_roll)) {
            //add name to list in dictionary with corresponding roll
            playerRolls.get(_roll).add(_names.get(i));
        } else {
            //generate new list for players with this roll and add to playerRolls
            List<String> _list = new ArrayList<>();
            _list.add(_names.get(i));
            playerRolls.put(_roll, _list);

            alreadyRolled.add(_roll);
        }
    }

    //sorting the rolls from largest to smallest
    Collections.sort(alreadyRolled);
    Collections.reverse(alreadyRolled);

    //generating output dictionary
    for (int i = 0; i < alreadyRolled.size(); i++) {
        int _roll = alreadyRolled.get(i);
        List<String> list = playerRolls.get(_roll);

        //shuffling order of players with the same roll
        Collections.shuffle(list);

        //add to output dictionary and list
        for (int x = 0; x < list.size(); x++) {
            outputDictionary.put(list.get(x), _roll);
            outputOrder.add(list.get(x));
        }
    }
}

public Map<String, Integer> getOutputDictionary() {
    return outputDictionary;
}

public List<String> getOutputOrder() {
    return outputOrder;
}

}

Every time I check, the resulting outputDictionary and outputorder have a length of zero. What am I missing? Sorry for the long post.

EDIT: I have checked the code and there does not seem to be a problem with the length of the list until the point where getPlayerNames and getDexMod are called inside the InitiativeRollerClass.

EDIT: Here are the get-methods

public List<String> getPlayerNames() {
    return playerNames;
}

public List<Integer> getDexMod() {
    return dexMod;
}

UPDATE: This is the code bound to the roll-button:

rollInitiative.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //update dictionary
            int roundedProgress = Math.round(playerSlider.getProgress());

            try {
                updateDictionaryManager(roundedProgress);
            } catch (Exception e) {
                updateDictionaryManagerOnException(roundedProgress, playerList);
            }

            initiativeRoller.roll();
            displayResult(initiativeRoller.getOutputOrder(), initiativeRoller.getOutputDictionary(), InitiativeList);
        }
    });

the method is described here, this is just for debugging

//displays output to user
    private void displayResult(List<String> _outputOrder, Map<String, Integer> _outputDictionary, TextView _initiativelist) {
        _initiativelist.setText(listManager.getDexMod() + "\n" + listManager.getPlayerNames()
        + "\n" + initiativeRoller.getOutputOrder());
    }

This brings me the following

I also checked online if the code itself for the roll class was even functioning, it was. Here is the result for four hard coded names and values after a number of runs:

[Aaron, Josh, Clide, Li]

{Aaron=24, Clide=20, Josh=22, Li=8}

sh-4.3$ java -Xmx128M -Xms16M HelloWorld

[Josh, Li, Aaron, Clide]

{Aaron=6, Clide=6, Josh=20, Li=12}

sh-4.3$ java -Xmx128M -Xms16M HelloWorld

[Aaron, Clide, Li, Josh]

{Aaron=20, Clide=17, Josh=10, Li=11}

sh-4.3$ java -Xmx128M -Xms16M HelloWorld

[Li, Aaron, Clide, Josh]

{Aaron=19, Clide=18, Josh=18, Li=21}

Everything seems to be working just fine, I just don't understand why the returned list has a length of zero.

p.s. the code for the getSize() method

public int getSize() {
    return playerNames.size();
}


问:
Why is my string output printing out weird characters?
So I have this method that prints out a few lines from a textfile to a listview but whenever it does it it takes characters such as "Å å , Ä ä, Ö ö" and makes them weird symbols like triangles and stuff.
I tried converting them to UTF-8 Characters but it gave me the same output.

```<code>private void btnSort_Click(object sender, EventArgs e)
{
    //Convert to utf8

    string[] Accounts = File.ReadAllLines(filePath); // if null do something

    foreach (string account in Accounts)
    {
        ListViewItem lvi = new ListViewItem(account);
        listView1.Items.Add(lvi);
    }

}
</code>```

This is what the textfile list looks like

Gräsklippare@hotmail.com
 Åkerström@gmail.com

Yep, thats it.

答: File.ReadAllLines has an overload that takes an encoding. Call it with whatever encoding was used for that file (apparently not UTF8)

Body:
So I have this method that prints out a few lines from a textfile to a listview but whenever it does it it takes characters such as "Å å , Ä ä, Ö ö" and makes them weird symbols like triangles and stuff.
I tried converting them to UTF-8 Characters but it gave me the same output.

private void btnSort_Click(object sender, EventArgs e)
{
    //Convert to utf8

    string[] Accounts = File.ReadAllLines(filePath); // if null do something

    foreach (string account in Accounts)
    {
        ListViewItem lvi = new ListViewItem(account);
        listView1.Items.Add(lvi);
    }

}

This is what the textfile list looks like

Gräsklippare@hotmail.com
 Åkerström@gmail.com

Yep, thats it.


问:
How do C++ containers work together with the Liskov Substitution Principle?
For return types Covariance of the return values are required by the Liskov Substitiution Principle.

Lets assume the small type hierarchy for return types:

```<code>class B {};
class D : public B {};
</code>```

The working classes then could have

```<code>class Base {
    virtual B& func();
};
class Derived : public Base {
    virtual D& func();
};
</code>```

and this would be compliant to the LSP because the return types are covariant (the hierarchy of Base and Derived is "co" to B and D).

What if containers do come into play?

```<code>class Base {
    virtual vector<B>& func();
};
class Derived : public Base {
    virtual vector<D>& func();
};
</code>```

Is this still LSP compliant? Are vector and vector<D> "covariant" to Base and Derived?

Additional question: Does it make a difference for the LSP if I use pointers as container types (allowing for dynamic polymorphism), i.e. vector etc?

Note: I tried not to rely on the real C++ override rules but mainly want to understand LSP. I did nor use the override keyword intentionally. First I want to understand LSP then I could try out if C++ supports these rules.

答:
vector and vector<D> are two completely unrelated types, so it is not LSP compliant.

vector and vector<D*> are also two completely unrelated types as far as the C++ type system is concerned.  Since B is a base class of D, you could just use vector for both, and covariance would not then be an issue.

Body:
For return types Covariance of the return values are required by the Liskov Substitiution Principle.

Lets assume the small type hierarchy for return types:

class B {};
class D : public B {};

The working classes then could have

class Base {
    virtual B& func();
};
class Derived : public Base {
    virtual D& func();
};

and this would be compliant to the LSP because the return types are covariant (the hierarchy of Base and Derived is "co" to B and D).

What if containers do come into play?

class Base {
    virtual vector& func();
};
class Derived : public Base {
    virtual vector<D>& func();
};

Is this still LSP compliant? Are vector and vector<D> "covariant" to Base and Derived?

Additional question: Does it make a difference for the LSP if I use pointers as container types (allowing for dynamic polymorphism), i.e. vector etc?

Note: I tried not to rely on the real C++ override rules but mainly want to understand LSP. I did nor use the override keyword intentionally. First I want to understand LSP then I could try out if C++ supports these rules.

Body:
vector<B> and vector<D> are two completely unrelated types, so it is not LSP compliant.

vector<B*> and vector<D*> are also two completely unrelated types as far as the C++ type system is concerned.  Since B is a base class of D, you could just use vector<B*> for both, and covariance would not then be an issue.


问:
How can I change the background color of a header from a TListView?
I need change the background color of all header of my listView for them to be highlighted. I found nothing on Object Inspector and nothing on Style Designer, can you guys give me some direction?

答:
Try this one, it worked for me. You can delete the Rectangle component.

right click the LV

edit custom style

select header

click on SourceLink property (...)

there you can either chose one of the existing colors, or create your own

close the BitmapLinks Editor

Close and save the Style Designer
Should work


答:
As @KevinGosse pointed out, the File.ReadAllLines() has an overload that takes an encoding and the encoding that was needed for this set of characters was UTF-7

Working Code

```<code>private void btnSort_Click(object sender, EventArgs e)
        {
            //Convert to utf8

            string[] Accounts = File.ReadAllLines(filePath, Encoding.UTF7); // if null do something

            foreach (string account in Accounts)
            {
                ListViewItem lvi = new ListViewItem(account);
                listView1.Items.Add(lvi);
            }

        }
</code>```

Title: Why is my string output printing out weird characters?

Body:
As @KevinGosse pointed out, the File.ReadAllLines() has an overload that takes an encoding and the encoding that was needed for this set of characters was UTF-7

Working Code

private void btnSort_Click(object sender, EventArgs e)
        {
            //Convert to utf8

            string[] Accounts = File.ReadAllLines(filePath, Encoding.UTF7); // if null do something

            foreach (string account in Accounts)
            {
                ListViewItem lvi = new ListViewItem(account);
                listView1.Items.Add(lvi);
            }

        }


问:
ERROR 2003 (HY000): Can't connect to MySQL server (111)
This question is related to the following questions:

Can't connect to MySQL server error 111

Trying to connect to remote MySQL host (error 2003)

I am configuring a new MySQL (5.1) server on my local machine. I need to provide remote access to the database. I did the following steps:

Comment bind-address in my.cnf:

```<code># bind-address      = 192.168.1.3
</code>```

Grant privileges:

```<code>GRANT ALL PRIVILEGES ON *.* TO 'nickruiz'@'%' IDENTIFIED BY PASSWORD 'xxxx';
</code>```

Set port forwarding on router (TCP and UDP, port 3306, 192.168.1.3)

Configure iptables for firewall

```<code>sudo iptables -I INPUT -p udp --dport 3306 -j ACCEPT

sudo iptables -I INPUT -p tcp --dport 3306 --syn -j ACCEPT

sudo iptables-save
</code>```

Restart mysql server sudo /etc/init.d/mysql restart

When testing, I get the following:

LAN:

```<code>mysql -h 192.168.1.3 -u nickruiz -p
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 95
Server version: 5.1.63-0ubuntu0.11.04.1 (Ubuntu)
</code>```

Remote:

```<code>mysql -h 1xx.xx.4.136 -u nickruiz -p
ERROR 2003 (HY000): Can't connect to MySQL server on '1xx.xx.4.136' (111)
</code>```

Clearly there's something wrong that's preventing me from being able to use my global IP address.

Notes:

I've tried testing the remote connection on the same machine and also
via SSH from a remote machine.

I'm not sure if my ISP has given me a static IP.

Any ideas?

Update:
telnet doesn't seem to be working.

```<code>telnet 192.168.1.3 3306
Trying 192.168.1.3...
Connected to 192.168.1.3.
Escape character is '^]'.
E
5.1.63-0ubuntu0.11.04.1,0g8!:@pX;]DyY0#\)SIConnection closed by foreign host.
</code>```

答: i set my bind-address correctly as above but forgot to restart the mysql server (or reboot) :) face palm - so that's the source of this error for me!

Body:
This question is related to the following questions:

Can't connect to MySQL server error 111

Trying to connect to remote MySQL host (error 2003)

I am configuring a new MySQL (5.1) server on my local machine. I need to provide remote access to the database. I did the following steps:

Comment bind-address in my.cnf:

# bind-address      = 192.168.1.3

Grant privileges:

GRANT ALL PRIVILEGES ON *.* TO 'nickruiz'@'%' IDENTIFIED BY PASSWORD 'xxxx';

Set port forwarding on router (TCP and UDP, port 3306, 192.168.1.3)

Configure iptables for firewall

sudo iptables -I INPUT -p udp --dport 3306 -j ACCEPT

sudo iptables -I INPUT -p tcp --dport 3306 --syn -j ACCEPT

sudo iptables-save

Restart mysql server sudo /etc/init.d/mysql restart

When testing, I get the following:

LAN:

mysql -h 192.168.1.3 -u nickruiz -p
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 95
Server version: 5.1.63-0ubuntu0.11.04.1 (Ubuntu)

Remote:

mysql -h 1xx.xx.4.136 -u nickruiz -p
ERROR 2003 (HY000): Can't connect to MySQL server on '1xx.xx.4.136' (111)

Clearly there's something wrong that's preventing me from being able to use my global IP address.

Notes:

I've tried testing the remote connection on the same machine and also
via SSH from a remote machine.

I'm not sure if my ISP has given me a static IP.

Any ideas?

Update:
telnet doesn't seem to be working.

telnet 192.168.1.3 3306
Trying 192.168.1.3...
Connected to 192.168.1.3.
Escape character is '^]'.
E
5.1.63-0ubuntu0.11.04.1,0g8!:@pX;]DyY0#\)SIConnection closed by foreign host.


问:
How to refresh registry value
I am uninstalling some application and reading the software installation enumeration value from registry.

The problem is after uninstallation it is not changing the registry value untill unless the screen or regedit is not refreshed. after refreshing only i am getting the correct value.

Could some one help me out to refresh the regedit in python codes.

Regards,
upendra

答:
I am modifying the registry key and want to read that values without restarting the system.

I am able to read manually if I refresh the screen (F5 Button), but could you let me know how to capture this through python.

Title: How to refresh registry value


问:
ffmpeg-normalize pip install failing
I am trying to pip install ffmpeg-normalize in Python 3.6.1. This used to work fine in Python 2.7.13 but not in the latest version, it seems.

In an elevated command prompt i type: pip install ffmpeg-normalize

I continue to  get Command "python setup.py egg_info" failed with error code 1 for some reason and I am not sure what this means...

```<code>C:\Users\Arete>python --version
Python 3.6.1

C:\Users\Arete>pip install ffmpeg-normalize
Collecting ffmpeg-normalize
  Using cached ffmpeg-normalize-0.4.3.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\Arete\AppData\Local\Temp\pip-build-rcxpzvv4\ffmpeg-normalize\setup.py", line 7, in <module>
        readme = readme_file.read()
      File "c:\program files\python36\lib\encodings\cp1252.py", line 23, in decode
        return codecs.charmap_decode(input,self.errors,decoding_table)[0]
    UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 2117: character maps to <undefined>

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\Arete\AppData\Local\Temp\pip-build-rcxpzvv4\ffmpeg-normalize\

C:\Users\Arete>
</code>```

I am using Windows 10. and I have already tried the accepted answer on a very similar question without any luck...

What is causing the problem here and how can I get ffmpeg-normalize installed?

答:
This looks like a bug in setup.py to me. Since the default encoding used in python 3 when opening a file in text mode is platform-dependent, an encoding should be explicitly provided. Otherwise the result of a read operation will be unpredictable and it will fail if the default encoding can't handle the file's content, as happened in your case.

You should be able to fix it by checking out the source code and changing this line:

```<code>with open('README.rst') as readme_file:
</code>```

to use UTF-8

```<code>with open('README.rst', encoding='utf8') as readme_file:
</code>```

To install open a command prompt, cd to the directory containing setup.py and then:

```<code>pip install .
</code>```

Title: ffmpeg-normalize pip install failing

Body:
I am trying to pip install ffmpeg-normalize in Python 3.6.1. This used to work fine in Python 2.7.13 but not in the latest version, it seems.

In an elevated command prompt i type: pip install ffmpeg-normalize

I continue to  get Command "python setup.py egg_info" failed with error code 1 for some reason and I am not sure what this means...

C:\Users\Arete>python --version
Python 3.6.1

C:\Users\Arete>pip install ffmpeg-normalize
Collecting ffmpeg-normalize
  Using cached ffmpeg-normalize-0.4.3.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\Arete\AppData\Local\Temp\pip-build-rcxpzvv4\ffmpeg-normalize\setup.py", line 7, in <module>
        readme = readme_file.read()
      File "c:\program files\python36\lib\encodings\cp1252.py", line 23, in decode
        return codecs.charmap_decode(input,self.errors,decoding_table)[0]
    UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 2117: character maps to <undefined>

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\Arete\AppData\Local\Temp\pip-build-rcxpzvv4\ffmpeg-normalize\

C:\Users\Arete>

I am using Windows 10. and I have already tried the accepted answer on a very similar question without any luck...

What is causing the problem here and how can I get ffmpeg-normalize installed?

Body:
This looks like a bug in setup.py to me. Since the default encoding used in python 3 when opening a file in text mode is platform-dependent, an encoding should be explicitly provided. Otherwise the result of a read operation will be unpredictable and it will fail if the default encoding can't handle the file's content, as happened in your case.

You should be able to fix it by checking out the source code and changing this line:

with open('README.rst') as readme_file:

to use UTF-8

with open('README.rst', encoding='utf8') as readme_file:

To install open a command prompt, cd to the directory containing setup.py and then:

pip install .


问:
Check if a particular time is in a range in R
I have two dataframes having different time interval: first one is every 3 hours; the 2nd one is every 15mins. I want to write a 'for' loop, something like this

```<code>for(time in levels(15mins interval), e.g. (00:00,00:15,00:30,...){
    if(time is between 3h interval, e.g. 00:15 is between 00:00 and 03:00){
         regress 00:15 data onto 00:00 and 03:00 data
      }else{regress 00:00 data in 2nd data frame onto 00:00 data in 1st data frame}
</code>```

I don't know how to implement this. Is there a way to compare the time?
Thanks in advance.

答:
I figured out a way, may not be perfect. Produce a dataframe of two columns: 1st column is 1:96, 2nd column is the 15min time interval; and make use of the modulus operation.</p>

```<code>df_time=data.frame(cbind(index=1:96, time=levels(df1$time)))
for(ind in 1:96){
    if(ind %% 12 ==1){
        do something with df_time[ind,2]
    }else{
        tim1=df_time[ind %/% 12 +1 , 2]
        tim2=df_time[ind %/% 12 +13, 2]
        do something with tim1 & tim2
     }}
</code>```

Body:
I have two dataframes having different time interval: first one is every 3 hours; the 2nd one is every 15mins. I want to write a 'for' loop, something like this

for(time in levels(15mins interval), e.g. (00:00,00:15,00:30,...){
    if(time is between 3h interval, e.g. 00:15 is between 00:00 and 03:00){
         regress 00:15 data onto 00:00 and 03:00 data
      }else{regress 00:00 data in 2nd data frame onto 00:00 data in 1st data frame}

I don't know how to implement this. Is there a way to compare the time?
Thanks in advance.

Body:
I figured out a way, may not be perfect. Produce a dataframe of two columns: 1st column is 1:96, 2nd column is the 15min time interval; and make use of the modulus operation.

df_time=data.frame(cbind(index=1:96, time=levels(df1$time)))
for(ind in 1:96){
    if(ind %% 12 ==1){
        do something with df_time[ind,2]
    }else{
        tim1=df_time[ind %/% 12 +1 , 2]
        tim2=df_time[ind %/% 12 +13, 2]
        do something with tim1 & tim2
     }}


问:
Can't type in InputType 'text' in React
I am using NodeJS.

Here is my componenet in my coursePage.js. Ihe problem is that when I run it I can't type in my InputType, although I can't see any error in my code (neither the console shows me anything).

```<code>import React , {PropTypes} from 'react';
import {connect} from 'react-redux';
import * as courseActions from '../../actions/courseActions';

class coursesPage extends React.Component{

  constructor(props, context) {
    super(props, context);

    this.state = {
      course: {title: ""}
    };

    this.onTitleChange= this.onTitleChange.bind(this);
    this.onClickSave= this.onClickSave.bind(this);
  }

  onTitleChange(event){
    const course = this.state.course;
    course.title = event.target.value;
    this.setState=({course: course});
  }

  onClickSave(){
    this.props.dispatch(courseActions.createCourse(this.state.course));
  }
  courseRow(course,index){
    return <div key = {index}>{course.title}</div>;
  }

  render(){
    return(
      <div>
        <h1>Courses</h1>
        {this.props.courses.map(this.courseRow)}
        <h2>Add Course</h2>
        <input
          type="text"
          onChange={this.onTitleChange}
          value={this.state.course.title}/>

        <input
          type="submit"
          value="Save"
          onClick={this.onClickSave}/>
      </div>
    );
  }
}
coursesPage.propTypes = {
  dispatch: PropTypes.func.isRequired,
  courses: PropTypes.array.isRequired
};

function mapStateToProps(state, ownProps){
  return{
    courses : state.courses
  };

}
export default connect(mapStateToProps)(coursesPage);
</code>```

答:
Issue is, you are updating the state value in a wrong way, try this:

```<code>const course = this.state.course;
course.title = event.target.value;
this.setState({course});
</code>```

To update the state value, we need to pass an object in setState, instead of assigning the object;

Title: Can't type in InputType 'text' in React

Body:
I am using NodeJS.

Here is my componenet in my coursePage.js. Ihe problem is that when I run it I can't type in my InputType, although I can't see any error in my code (neither the console shows me anything).

import React , {PropTypes} from 'react';
import {connect} from 'react-redux';
import * as courseActions from '../../actions/courseActions';

class coursesPage extends React.Component{

  constructor(props, context) {
    super(props, context);

    this.state = {
      course: {title: ""}
    };

    this.onTitleChange= this.onTitleChange.bind(this);
    this.onClickSave= this.onClickSave.bind(this);
  }

  onTitleChange(event){
    const course = this.state.course;
    course.title = event.target.value;
    this.setState=({course: course});
  }

  onClickSave(){
    this.props.dispatch(courseActions.createCourse(this.state.course));
  }
  courseRow(course,index){
    return
{course.title}
;
  }

  render(){
    return(

Courses

        {this.props.courses.map(this.courseRow)}

Add Course

        <input
          type="text"
          onChange={this.onTitleChange}
          value={this.state.course.title}/>

        <input
          type="submit"
          value="Save"
          onClick={this.onClickSave}/>

    );
  }
}
coursesPage.propTypes = {
  dispatch: PropTypes.func.isRequired,
  courses: PropTypes.array.isRequired
};

function mapStateToProps(state, ownProps){
  return{
    courses : state.courses
  };

}
export default connect(mapStateToProps)(coursesPage);

Body:
Issue is, you are updating the state value in a wrong way, try this:

const course = this.state.course;
course.title = event.target.value;
this.setState({course});

To update the state value, we need to pass an object in setState, instead of assigning the object;


问:
Excel-VBA MultiPage: move/reorder/index pages at runtime?
I'm working on a little Excel-VBA GUI/Form for the user to read and write data from/to an .ini file. The UserForm has a MultiPage in which the user creates pages at runtime and each page will represent an ini section. Furthermore, these sections are also indexed in a master section for further processing: at this point I'm looping through the MultiPage pages to create this index. Problem is, the user needs to be able to change the order of this index. Now, is it possible to move the pages within a MultiPage at runtime? I was thinking something to the effect of

```<code>Me.MultiPage1.Pages(i).Index = i + 1
</code>```

but obviously that doesn't work. Alternatively, is there a way I can pass a before:= or anything similar to Multipage.Pages.Add to work around it?
If none of this works, I think I'll create a seperate ListBox control with MoveUp/Down buttons. Open for any better solutions.

答:
For anybody looking for this in the future, here's the complete solution using Robin's code (Thanks!), but put in a Class for the pages created at runtime. I'm only pasting the relevant code to this question, the CopyPage procedure can also be called by the user to add pages during runtime. Now the user can also move them left and right between pages 2 (index 1) and n.

In my main module:

```<code>Public arrLeftButton() As New CButton
Public arrRightButton() As New CButton
</code>```

In my CButton Class Module:

```<code>Option Explicit
Public WithEvents CopyButton As MSForms.CommandButton
Public WithEvents DeleteButton As MSForms.CommandButton
Public WithEvents MoveLeft As MSForms.CommandButton
Public WithEvents MoveRight As MSForms.CommandButton

Private Sub MoveLeft_Click()
    Dim pag As MSForms.Page
    Dim lngPageCount As Long
    Set pag = UFmodproject.MultiPage1.SelectedItem
    lngPageCount = UFmodproject.MultiPage1.Pages.Count
    If pag.Index > 1 Then
        pag.Index = pag.Index - 1
    End If
End Sub

Private Sub MoveRight_Click()
    Dim pag As MSForms.Page
    Dim lngPageCount As Long
    Set pag = UFmodproject.MultiPage1.SelectedItem
    lngPageCount = UFmodproject.MultiPage1.Pages.Count
    If pag.Index < lngPageCount - 1 Then
        pag.Index = pag.Index + 1
    End If
End Sub
</code>```

And my UserForm_Initialize:

```<code>Private Sub userform_initialize()
    ReDim Preserve arrLeftButton(1 To 1)
    ReDim Preserve arrRightButton(1 To 1)
    Set arrLeftButton(1).MoveLeft = MultiPage1.Pages(1).Controls("MoveLeft1")
    Set arrRightButton(1).MoveRight = MultiPage1.Pages(1).Controls("MoveRight1")
    For i = 2 To GetINIString("Project", "NumberOfShipmentTypes", strINIPATH)
        Call FormControls.CopyPage
    Next
End Sub
</code>```

Yet in another standard module, so it can be called from elsewhere too:

```<code>Sub CopyPage()
    Dim l As Double, r As Double
    Dim Ctrl As Control
    Dim newCtrl As Object
    Dim pCount As Long
    pCount = UFmodproject.MultiPage1.Pages.Count

    '[...add pages and copy all controls]

    For Each newCtrl In UFmodproject.MultiPage1.Pages(pCount).Controls
        If Left(newCtrl.Name, Len(newCtrl.Name) - 1) = "MoveLeft" Then
            ReDim Preserve arrLeftButton(1 To pCount)
            Set arrLeftButton(pCount).MoveLeft = newCtrl
        End If
        If Left(newCtrl.Name, Len(newCtrl.Name) - 1) = "MoveRight" Then
            ReDim Preserve arrRightButton(1 To pCount)
            Set arrRightButton(pCount).MoveRight = newCtrl
        End If
    Next
End Sub
</code>```

Body:
I'm working on a little Excel-VBA GUI/Form for the user to read and write data from/to an .ini file. The UserForm has a MultiPage in which the user creates pages at runtime and each page will represent an ini section. Furthermore, these sections are also indexed in a master section for further processing: at this point I'm looping through the MultiPage pages to create this index. Problem is, the user needs to be able to change the order of this index. Now, is it possible to move the pages within a MultiPage at runtime? I was thinking something to the effect of

Me.MultiPage1.Pages(i).Index = i + 1

but obviously that doesn't work. Alternatively, is there a way I can pass a before:= or anything similar to Multipage.Pages.Add to work around it?
If none of this works, I think I'll create a seperate ListBox control with MoveUp/Down buttons. Open for any better solutions.

Body:
For anybody looking for this in the future, here's the complete solution using Robin's code (Thanks!), but put in a Class for the pages created at runtime. I'm only pasting the relevant code to this question, the CopyPage procedure can also be called by the user to add pages during runtime. Now the user can also move them left and right between pages 2 (index 1) and n.

In my main module:

Public arrLeftButton() As New CButton
Public arrRightButton() As New CButton

In my CButton Class Module:

Option Explicit
Public WithEvents CopyButton As MSForms.CommandButton
Public WithEvents DeleteButton As MSForms.CommandButton
Public WithEvents MoveLeft As MSForms.CommandButton
Public WithEvents MoveRight As MSForms.CommandButton

Private Sub MoveLeft_Click()
    Dim pag As MSForms.Page
    Dim lngPageCount As Long
    Set pag = UFmodproject.MultiPage1.SelectedItem
    lngPageCount = UFmodproject.MultiPage1.Pages.Count
    If pag.Index > 1 Then
        pag.Index = pag.Index - 1
    End If
End Sub

Private Sub MoveRight_Click()
    Dim pag As MSForms.Page
    Dim lngPageCount As Long
    Set pag = UFmodproject.MultiPage1.SelectedItem
    lngPageCount = UFmodproject.MultiPage1.Pages.Count
    If pag.Index < lngPageCount - 1 Then
        pag.Index = pag.Index + 1
    End If
End Sub

And my UserForm_Initialize:

Private Sub userform_initialize()
    ReDim Preserve arrLeftButton(1 To 1)
    ReDim Preserve arrRightButton(1 To 1)
    Set arrLeftButton(1).MoveLeft = MultiPage1.Pages(1).Controls("MoveLeft1")
    Set arrRightButton(1).MoveRight = MultiPage1.Pages(1).Controls("MoveRight1")
    For i = 2 To GetINIString("Project", "NumberOfShipmentTypes", strINIPATH)
        Call FormControls.CopyPage
    Next
End Sub

Yet in another standard module, so it can be called from elsewhere too:

Sub CopyPage()
    Dim l As Double, r As Double
    Dim Ctrl As Control
    Dim newCtrl As Object
    Dim pCount As Long
    pCount = UFmodproject.MultiPage1.Pages.Count

    '[...add pages and copy all controls]

    For Each newCtrl In UFmodproject.MultiPage1.Pages(pCount).Controls
        If Left(newCtrl.Name, Len(newCtrl.Name) - 1) = "MoveLeft" Then
            ReDim Preserve arrLeftButton(1 To pCount)
            Set arrLeftButton(pCount).MoveLeft = newCtrl
        End If
        If Left(newCtrl.Name, Len(newCtrl.Name) - 1) = "MoveRight" Then
            ReDim Preserve arrRightButton(1 To pCount)
            Set arrRightButton(pCount).MoveRight = newCtrl
        End If
    Next
End Sub


问:
Compare length of 2 variables and assign longest to another variable
I have 2 arrays of differing length assigned to $array1 and $array2,

Is there a more graceful way of checking each of there lengths and then assigning the biggest to a new variable?

Below is what i already have, but it seems a bit to 'dirty'.

```<code>if ($array1 > $array2) {
    $PlayerSum = $array1;
}
elseif ($array2 > $array1) {
    $PlayerSum = $array2;
}
else {
    $error = "<div class='alert alert-danger error'>Invalid Entry!</div>";
}
</code>```

答:
Use sizeof()

```<code> if (sizeof($array1) > sizeof($array2) {
    $PlayerSum = $array1;
}
elseif (sizeof($array2) > sizeof($array1) {
    $PlayerSum = $array2;
    }
    else {
        $error = "<div class='alert alert-danger error'>Invalid Entry!</div>";
    }
</code>```

Body:
I have 2 arrays of differing length assigned to $array1 and $array2,

Is there a more graceful way of checking each of there lengths and then assigning the biggest to a new variable?

Below is what i already have, but it seems a bit to 'dirty'.

if ($array1 > $array2) {
    $PlayerSum = $array1;
}
elseif ($array2 > $array1) {
    $PlayerSum = $array2;
}
else {
    $error = "
Invalid Entry!
";
}

Body:
Use sizeof()

 if (sizeof($array1) > sizeof($array2) {
    $PlayerSum = $array1;
}
elseif (sizeof($array2) > sizeof($array1) {
    $PlayerSum = $array2;
    }
    else {
        $error = "<div class='alert alert-danger error'>Invalid Entry!</div>";
    }