Use .map without return in simple way. Also start using let and const instead of var because let and const is more recommended
const rockets = [_x000D_
{ country:'Russia', launches:32 },_x000D_
{ country:'US', launches:23 },_x000D_
{ country:'China', launches:16 },_x000D_
{ country:'Europe(ESA)', launches:7 },_x000D_
{ country:'India', launches:4 },_x000D_
{ country:'Japan', launches:3 }_x000D_
];_x000D_
_x000D_
const launchOptimistic = rockets.map(elem => (_x000D_
{_x000D_
country: elem.country,_x000D_
launches: elem.launches+10_x000D_
} _x000D_
));_x000D_
_x000D_
console.log(launchOptimistic);
_x000D_
Logits often are the values of Z function of the output layer in Tensorflow.
This might be a little bit late, but in my case (angular 6), I created a simple pipe on top of DatePipe, something like this:
private _regionSub: Subscription;
private _localeId: string;
constructor(private _datePipe: DatePipe, private _store: Store<any>) {
this._localeId = 'en-AU';
this._regionSub = this._store.pipe(select(selectLocaleId))
.subscribe((localeId: string) => {
this._localeId = localeId || 'en-AU';
});
}
ngOnDestroy() { // Unsubscribe }
transform(value: string | number, format?: string): string {
const dateFormat = format || getLocaleDateFormat(this._localeId, FormatWidth.Short);
return this._datePipe.transform(value, dateFormat, undefined, this._localeId);
}
May not be the best solution, but simple and works.
In my case (reading a date from a MySQL db in a Lumen 5.1 project) the only solution that worked is using Carbon to set timezone of variables:
$carbonDate = new Carbon($dateFromDBInUTC);
$carbonDate->timezone = 'America/New_York';
return $carbonDate->toDayDateTimeString(); // or $carbonDate->toDateTimeString() for ISO format
Using DB_TIMEZONE=-05:00
in the .env
file almost worked but does not handle DST changes.
Using the APP_TIMEZONE=America/New_York
in the .env
file had no effect on a timezone value retrieved in a Lumen 5.1 webapp from a MySQL database, but it works in Lavarel 5.1.
Also Lumen didn't read at all the [lumen_project]/config/app.php
file that I created (it didn't complain when I put a syntax error there).
Using date_default_timezone_set
didn't work either.
let usDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "en-US"))
//usDateFormat now contains an optional string "MM/dd/yyyy"
let gbDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "en-GB"))
//gbDateFormat now contains an optional string "dd/MM/yyyy"
let geDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "de-DE"))
//geDateFormat now contains an optional string "dd.MM.yyyy"
You can use it in following way to get the current format from device:
let currentDateFormat = DateFormatter.dateFormat(fromTemplate: "MMddyyyy", options: 0, locale: Locale.current)
It seems to work fine in Postgresql 9.5:
SELECT current_setting('TIMEZONE');
var mydate = "2017-06-28T00:00:00";
var weekDayName = moment(mydate).format('ddd');
console.log(weekDayName);
Result: Wed
var mydate = "2017-06-28T00:00:00";
var weekDayName = moment(mydate).format('dddd');
console.log(weekDayName);
Result: Wednesday
Any time you get the...
"Fatal error: Call to a member function bind_param() on boolean"
...it is likely because there is an issue with your query. The prepare()
might return FALSE
(a Boolean), but this generic failure message doesn't leave you much in the way of clues. How do you find out what is wrong with your query? You ask!
First of all, make sure error reporting is turned on and visible: add these two lines to the top of your file(s) right after your opening <?php
tag:
error_reporting(E_ALL);
ini_set('display_errors', 1);
If your error reporting has been set in the php.ini you won't have to worry about this. Just make sure you handle errors gracefully and never reveal the true cause of any issues to your users. Revealing the true cause to the public can be a gold engraved invitation for those wanting to harm your sites and servers. If you do not want to send errors to the browser you can always monitor your web server error logs. Log locations will vary from server to server e.g., on Ubuntu the error log is typically located at /var/log/apache2/error.log
. If you're examining error logs in a Linux environment you can use tail -f /path/to/log
in a console window to see errors as they occur in real-time....or as you make them.
Once you're squared away on standard error reporting adding error checking on your database connection and queries will give you much more detail about the problems going on. Have a look at this example where the column name is incorrect. First, the code which returns the generic fatal error message:
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
$query = $mysqli->prepare($sql)); // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
The error is generic and not very helpful to you in solving what is going on.
With a couple of more lines of code you can get very detailed information which you can use to solve the issue immediately. Check the prepare()
statement for truthiness and if it is good you can proceed on to binding and executing.
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
if($query = $mysqli->prepare($sql)) { // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
// any additional code you need would go here.
} else {
$error = $mysqli->errno . ' ' . $mysqli->error;
echo $error; // 1054 Unknown column 'foo' in 'field list'
}
If something is wrong you can spit out an error message which takes you directly to the issue. In this case there is no foo
column in the table, solving the problem is trivial.
If you choose, you can include this checking in a function or class and extend it by handling the errors gracefully as mentioned previously.
To get the current time in the local timezone as a naive datetime object:
from datetime import datetime
naive_dt = datetime.now()
If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).
To get the current time in UTC as a naive datetime object:
naive_utc_dt = datetime.utcnow()
To get the current time as an aware datetime object in Python 3.3+:
from datetime import datetime, timezone
utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time
To get the current time in the given time zone from the tz database:
import pytz
tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)
It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.
Another solution:
public class CountryInfoResponse {
private List<Object> geonames;
}
Usage of a generic Object-List solved my problem, as there were other Datatypes like Boolean too.
The classes LocalDate
and LocalDateTime
do not contain information about the timezone or time offset, and seconds since epoch would be ambigious without this information. However, the objects have several methods to convert them into date/time objects with timezones by passing a ZoneId
instance.
LocalDate
LocalDate date = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = date.atStartOfDay(zoneId).toEpochSecond();
LocalDateTime
LocalDateTime time = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = time.atZone(zoneId).toEpochSecond();
A .tex file should be a LaTeX source file.
If this is the case, that file contains the source code for a LaTeX document. You can open it with any text editor (notepad, notepad++ should work) and you can view the source code. But if you want to view the final formatted document, you need to install a LaTeX distribution and compile the .tex file.
Of course, any program can write any file with any extension, so if this is not a LaTeX document, then we can't know what software you need to install to open it. Maybe if you upload the file somewhere and link it in your question we can see the file and provide more help to you.
Yes, this is the source code of a LaTeX document. If you were able to paste it here, then you are already viewing it. If you want to view the compiled document, you need to install a LaTeX distribution. You can try to install MiKTeX then you can use that to compile the document to a .pdf file.
You can also check out this question and answer for how to do it: How to compile a LaTeX document?
Also, there's an online LaTeX editor and you can paste your code in there to preview the document: https://www.overleaf.com/.
Try enabling openssl extension in your php.ini if it is disabled. This way I could access the web service without need of any extra arguments, i.e.,
$client = new SoapClient(url);
You want to convert it to an object first and then access normally making sure to cast it.
JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];
Imports Newtonsoft.Json.Linq
Dim json As JObject = JObject.Parse(Me.TextBox1.Text)
MsgBox(json.SelectToken("Venue").SelectToken("ID"))
<?php
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
require_once '../Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$sheet = $objPHPExcel->getActiveSheet();
$sheet->setCellValueByColumnAndRow(0, 1, "test");
$sheet->mergeCells('A1:B1');
$sheet->getActiveSheet()->getStyle('A1:B1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save("test.xlsx");
?>
Found a similar way to fix this issue (at least it did for me).
First check where the CLI php.ini
is located:
php -i | grep "php.ini"
In my case I ended up with : Configuration File (php.ini) Path => /etc
Then cd ..
all the way back and cd
into /etc
, do ls
in my case php.ini didn't show up, only a php.ini.default
Now, copy the php.ini.default file named as php.ini:
sudo cp php.ini.default php.ini
In order to edit, change the permissions of the file:
sudo chmod ug+w php.ini
sudo chgrp staff php.ini
Open directory and edit the php.ini file:
open .
Tip: If you are not able to edit the php.ini due to some permissions issue then copy 'php.ini.default' and paste it on your desktop and rename it to 'php.ini' then open it and edit it following step 7. Then move (copy+paste) it in /etc folder. Issue will be resolved.
Search for [Date] and make sure the following line is in the correct format:
date.timezone = "Europe/Amsterdam"
I hope this could help you out.
you should use this code:
$json = json_encode(array_map('utf8_encode', $arr))
array_map function converts special characters in UTF8 standard
There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:
url: 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',
to this line:
url: '/path/to/phpscript.php',
and then in the php script (if you have permission to use the file_get_contents() function):
<?php
header('Content-type: application/xml');
echo file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
?>
Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.
Edit: If you want to cache the result in php, here's the php file you would use:
<?php
$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
$contents = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
file_put_contents($cacheName, $contents);
}
$xml = simplexml_load_file($cacheName);
header('Content-type: application/xml');
echo $xml;
?>
Caching code take from here.
For the first question I think answer would be:
<your DataFrame>.rename(columns={'count':'Total_Numbers'})
or
<your DataFrame>.columns = ['ID', 'Region', 'Total_Numbers']
As for second one I'd say the answer would be no. It's possible to use it like 'df.ID' because of python datamodel:
Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.dict["x"]
I just wanted to add that I got this error when my database name was spelled wrong in my settings.py
file so the DB couldn't be created.
I found a solution: use :hover
with cursor: pointer
if nothing else helps.
I ran into the same problem and then remembered something wonky about a legacy project I was working on and how they handled this issue. I didn't understand it at the time and didn't really care until I ran into the problem myself
var date = '2014-01-02T00:00:00.000Z'
date = date.substring(0,10).split('-')
date = date[1] + '-' + date[2] + '-' + date[0]
new Date(date) #Thu Jan 02 2014 00:00:00 GMT-0600
For whatever reason passing the date in as '01-02-2014' sets the timezone to zero and ignores the user's timezone. This may be a fluke in the Date class but it existed some time ago and exists today. And it seems to work cross-browser. Try it for yourself.
This code is implemented in a global project where timezones matter a lot but the person looking at the date did not care about the exact moment it was introduced.
The accepted solution does not work when there are multiple different timezones in a Series. It throws ValueError: Tz-aware datetime.datetime cannot be converted to datetime64 unless utc=True
The solution is to use the apply
method.
Please see the examples below:
# Let's have a series `a` with different multiple timezones.
> a
0 2019-10-04 16:30:00+02:00
1 2019-10-07 16:00:00-04:00
2 2019-09-24 08:30:00-07:00
Name: localized, dtype: object
> a.iloc[0]
Timestamp('2019-10-04 16:30:00+0200', tz='Europe/Amsterdam')
# trying the accepted solution
> a.dt.tz_localize(None)
ValueError: Tz-aware datetime.datetime cannot be converted to datetime64 unless utc=True
# Make it tz-naive. This is the solution:
> a.apply(lambda x:x.tz_localize(None))
0 2019-10-04 16:30:00
1 2019-10-07 16:00:00
2 2019-09-24 08:30:00
Name: localized, dtype: datetime64[ns]
# a.tz_convert() also does not work with multiple timezones, but this works:
> a.apply(lambda x:x.tz_convert('America/Los_Angeles'))
0 2019-10-04 07:30:00-07:00
1 2019-10-07 13:00:00-07:00
2 2019-09-24 08:30:00-07:00
Name: localized, dtype: datetime64[ns, America/Los_Angeles]
numpy.random.rand(row, column) generates random numbers between 0 and 1, according to the specified (m,n) parameters given. So use it to create a (m,n) matrix and multiply the matrix for the range limit and sum it with the high limit.
Analyzing: If zero is generated just the low limit will be held, but if one is generated just the high limit will be held. In order words, generating the limits using rand numpy you can generate the extreme desired numbers.
import numpy as np
high = 10
low = 5
m,n = 2,2
a = (high - low)*np.random.rand(m,n) + low
Output:
a = array([[5.91580065, 8.1117106 ],
[6.30986984, 5.720437 ]])
If you are using Windows command line to print the data, you should use
chcp 65001
This worked for me!
The solutions is in fact
p{
white-space:normal;
}
You can change the break behaviors by modifying, word-break property
p{
word-break: break-all; // will break at end of line
}
break-all: Will break the string at the very end, breaking at the last word word-break: is more of pretty brake, will break nicely for example at ? point normal: same as word-break
Use this:
countries='Paris, France, Europe'
OIFS="$IFS"
IFS=', ' array=($countries)
IFS="$OIFS"
#${array[1]} == Paris
#${array[2]} == France
#${array[3]} == Europe
I've run into this problem a few times opening old projects that include other Android libraries. What works for me is to:
move Android to the top in the Order and Export tab and deselecting it.
Yes, this really makes the difference. Maybe it's time for me to ditch ADT for Android Studio!
The numerical value seems to be missing from your price definition. Try the following:
<xs:simpleType name="curr">
<xs:restriction base="xs:string">
<xs:enumeration value="pounds" />
<xs:enumeration value="euros" />
<xs:enumeration value="dollars" />
</xs:restriction>
</xs:simpleType>
<xs:element name="price">
<xs:complexType>
<xs:extension base="xs:decimal">
<xs:attribute name="currency" type="curr"/>
</xs:extension>
</xs:complexType>
</xs:element>
I had this same problem with a datalist I"m dynamically binding, adding EnableViewState="false" quieted the error message. I figure if I'm binding programmatically, then the control is being populated on each post back, the view state doesn't have to be maintained if it may or may not change on each call back, that's why I'm dynamically binding it, lol.
Maybe not related to the question, but I needed to use CST, set the system timezone to the desired tz (America/...) and then in postgresql conf set the value of the timezone to 'localtime' and it worked as a charm, current_time printing the right time (Postgresql 9.5 on Ubuntu 16)
General purpose normalisation function to format any timestamp from any timezone to other.
Very useful for storing datetimestamps of users from different timezones in a relational database. For database comparisons store timestamp as UTC and use with gmdate('Y-m-d H:i:s')
/**
* Convert Datetime from any given olsonzone to other.
* @return datetime in user specified format
*/
function datetimeconv($datetime, $from, $to)
{
try {
if ($from['localeFormat'] != 'Y-m-d H:i:s') {
$datetime = DateTime::createFromFormat($from['localeFormat'], $datetime)->format('Y-m-d H:i:s');
}
$datetime = new DateTime($datetime, new DateTimeZone($from['olsonZone']));
$datetime->setTimeZone(new DateTimeZone($to['olsonZone']));
return $datetime->format($to['localeFormat']);
} catch (\Exception $e) {
return null;
}
}
Usage:
$from = ['localeFormat' => "d/m/Y H:i A", 'olsonZone' => 'Asia/Calcutta']; $to = ['localeFormat' => "Y-m-d H:i:s", 'olsonZone' => 'UTC']; datetimeconv("14/05/1986 10:45 PM", $from, $to); // returns "1986-05-14 17:15:00"
Also add to your beans :
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<array>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg index="0" name="defaultCharset" value="UTF-8"/>
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
<value>application/x-www-form-urlencoded;charset=UTF-8</value>
</list>
</property>
</bean></bean>
For @ExceptionHandler :
enter code<bean class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver">
<property name="messageConverters">
<array>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg index="0" name="defaultCharset" value="UTF-8"/>
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
<value>application/x-www-form-urlencoded;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
<value>application/x-www-form-urlencoded;charset=UTF-8</value>
</list>
</property>
</bean>
</array>
</property>
</bean>
If you use <mvc:annotation-driven/>
it should be after beans.
If you aren't sure how to run a rake task, first find out first what tasks you have and it will also list the commands to run the tasks.
Run rake --tasks
on the terminal.
It will list the tasks like the following:
rake gobble:dev:prime
rake gobble:dev:reset_number_of_kits
rake gobble:dev:scrub_prod_data
You can then run your task with: rake gobble:dev:prime
as listed.
This worked in my case:
DecimalFormat df2 = new DecimalFormat("#.##");
df2.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.ENGLISH));
When a there are 2 columns for primary keys they make up a composite primary key therefore you have to make sure that in the table that is being referenced there are also 2 columns of the same data type.
To see a list of the Eclipse release name and it's corresponding version number go to this website. http://en.wikipedia.org/wiki/Eclipse_%28software%29#Release
I too dislike the way that the Eclipse foundation DOES NOT use the version number for their downloads or on the Help -> About Eclipse dialog. They do display the version on the download webpage, but the actual file name is something like:
But over time, you forget what release name goes with what version number. I would much prefer a file naming convention like:
This way you get BOTH from the file name and it is sortable in a directory listing. Fortunately, they mostly choose names are alphabetically after the previous one (except for 3.4-Ganymede vs the newer 3.5-Galileo).
val() is more like a shortcut for attr('value'). For your usage use text() or html() instead
It's more than 8 years passed and I am surprised, this issue isn't fixed yet...
I struggled with this simple issue since the most upvoted answer by @Martin lets typing multiple separators, i.e. user can type in "12,,,,,,12,1,,21,2,"
Also, the second concern is that on some devices comma is not shown on the numerical keyboard (or requires multiple pressing of a dot button)
Here is my workaround solution, which solves the mentioned problems and lets user typing '.' and ',', but in EditText he will see the only decimal separator which corresponds to current locale:
editText.apply { addTextChangedListener(DoubleTextChangedListener(this)) }
And the text watcher:
open class DoubleTextChangedListener(private val et: EditText) : TextWatcher {
init {
et.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
et.keyListener = DigitsKeyListener.getInstance("0123456789.,")
}
private val separator = DecimalFormatSymbols.getInstance().decimalSeparator
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
//empty
}
@CallSuper
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
et.run {
removeTextChangedListener(this@DoubleTextChangedListener)
val formatted = toLocalizedDecimal(s.toString(), separator)
setText(formatted)
setSelection(formatted.length)
addTextChangedListener(this@DoubleTextChangedListener)
}
}
override fun afterTextChanged(s: Editable?) {
// empty
}
/**
* Formats input to a decimal. Leaves the only separator (or none), which matches [separator].
* Examples:
* 1. [s]="12.12", [separator]=',' -> result= "12,12"
* 2. [s]="12.12", [separator]='.' -> result= "12.12"
* 4. [s]="12,12", [separator]='.' -> result= "12.12"
* 5. [s]="12,12,,..,,,,,34..,", [separator]=',' -> result= "12,1234"
* 6. [s]="12.12,,..,,,,,34..,", [separator]='.' -> result= "12.1234"
* 7. [s]="5" -> result= "5"
*/
private fun toLocalizedDecimal(s: String, separator: Char): String {
val cleared = s.replace(",", ".")
val splitted = cleared.split('.').filter { it.isNotBlank() }
return when (splitted.size) {
0 -> s
1 -> cleared.replace('.', separator).replaceAfter(separator, "")
2 -> splitted.joinToString(separator.toString())
else -> splitted[0]
.plus(separator)
.plus(splitted.subList(1, splitted.size - 1).joinToString(""))
}
}
}
A Date object's underlying value is actually in UTC. To prove this, notice that if you type new Date(0)
you'll see something like: Wed Dec 31 1969 16:00:00 GMT-0800 (PST)
. 0 is treated as 0 in GMT, but .toString()
method shows the local time.
Big note, UTC stands for Universal time code. The current time right now in 2 different places is the same UTC, but the output can be formatted differently.
What we need here is some formatting
var _date = new Date(1270544790922);
// outputs > "Tue Apr 06 2010 02:06:30 GMT-0700 (PDT)", for me
_date.toLocaleString('fi-FI', { timeZone: 'Europe/Helsinki' });
// outputs > "6.4.2010 klo 12.06.30"
_date.toLocaleString('en-US', { timeZone: 'Europe/Helsinki' });
// outputs > "4/6/2010, 12:06:30 PM"
This works but.... you can't really use any of the other date methods for your purposes since they describe the user's timezone. What you want is a date object that's related to the Helsinki timezone. Your options at this point are to use some 3rd party library (I recommend this), or hack-up the date object so you can use most of it's methods.
Option 1 - a 3rd party like moment-timezone
moment(1270544790922).tz('Europe/Helsinki').format('YYYY-MM-DD HH:mm:ss')
// outputs > 2010-04-06 12:06:30
moment(1270544790922).tz('Europe/Helsinki').hour()
// outputs > 12
This looks a lot more elegant than what we're about to do next.
Option 2 - Hack up the date object
var currentHelsinkiHoursOffset = 2; // sometimes it is 3
var date = new Date(1270544790922);
var helsenkiOffset = currentHelsinkiHoursOffset*60*60000;
var userOffset = _date.getTimezoneOffset()*60000; // [min*60000 = ms]
var helsenkiTime = new Date(date.getTime()+ helsenkiOffset + userOffset);
// Outputs > Tue Apr 06 2010 12:06:30 GMT-0700 (PDT)
It still thinks it's GMT-0700 (PDT), but if you don't stare too hard you may be able to mistake that for a date object that's useful for your purposes.
I conveniently skipped a part. You need to be able to define currentHelsinkiOffset
. If you can use date.getTimezoneOffset()
on the server side, or just use some if statements to describe when the time zone changes will occur, that should solve your problem.
Conclusion - I think especially for this purpose you should use a date library like moment-timezone.
Just save some one time. I spent 3 hours to find out that it was just html encoding problem. Try this
if(get_magic_quotes_gpc()){
$param = stripslashes($row['your column name']);
}else{
$param = $row['your column name'];
}
$param = json_decode(html_entity_decode($param),true);
$json_errors = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
);
echo 'Last error : ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;
print_r($param);
You didn't say what you needed this list for. If something used as a blacklist for password checks is enough cracklib might be good for you. It contains over 1.5M words.
For those unable to configure the mysql environment (e.g. due to lack of SUPER access) to use human-friendly timezone names like "America/Denver" or "GMT" you can also use the function with numeric offsets like this:
CONVERT_TZ(date,'+00:00','-07:00')
Here's a class I put together, mixing what I thought was the best of all suggestions here, and with Carbon as a dependency:
namespace App\Support;
use Carbon\Carbon;
use DateTimeZone;
class Timezone
{
protected static $timezones;
public static function all(): array
{
if (static::$timezones) {
return static::$timezones;
}
$offsets = [];
$timezones = [];
foreach (DateTimeZone::listIdentifiers() as $timezone) {
$offsets[] = $offset = Carbon::now()->timezone($timezone)->offset;
$timezones[$timezone] = static::formatTimezoneDisplay($timezone, $offset);
array_multisort($offsets, $timezones);
}
return static::$timezones = $timezones;
}
protected static function formatTimezoneDisplay(string $timezone, string $offset): string
{
return static::formatOffset($offset) . ' (' . static::formatTimezone($timezone) . ')';
}
protected static function formatOffset(string $offset): string
{
if (!$offset) {
return 'UTC±00:00';
}
$hours = intval($offset / 3600);
$minutes = abs(intval($offset % 3600 / 60));
return 'UTC' . sprintf('%+03d:%02d', $hours, $minutes);
}
protected static function formatTimezone(string $timezone): string
{
return str_replace(['/', '_', 'St '], [', ', ' ', 'St. '], $timezone);
}
}
You simply Timezone:all()
, and that gets you an array in the format of UTC-5:00 (America, New York)
, so you could easily display a select field on your frontend.
Date
is always UTC-based... or time-zone neutral, depending on how you want to view it. A Date
only represents a point in time; it is independent of time zone, just a number of milliseconds since the Unix epoch. There's no notion of a "local instance of Date
." Use Date
in conjunction with Calendar
and/or TimeZone.getDefault()
to use a "local" time zone. Use TimeZone.getTimeZone("Europe/Madrid")
to get the Madrid time zone.
... or use Joda Time, which tends to make the whole thing clearer, IMO. In Joda Time you'd use a DateTime
value, which is an instant in time in a particular calendar system and time zone.
In Java 8 you'd use java.time.ZonedDateTime
, which is the Java 8 equivalent of Joda Time's DateTime
.
Be aware that running
import os
os.system("tzutil /s \"Central Standard Time\"");
will alter Windows system time, NOT just the local python environment time (so is definitley NOT the same as:
>>> os.environ['TZ'] = 'Europe/London'
>>> time.tzset()
which will only set in the current environment time (in Unix only)
Besides using multiple proxies or proxy-networks, you might want to try the planet-lab. (And probably there are other similar institutions around).
The social solution would be to post a question on some board that you are searching for volunteers that proxy your requests. (They only have to allow for one destination in their proxy config thus the danger of becoming spam-whores is relatively low.) You should prepare credentials that ensure your partners of the authenticity of the claim that the destination is indeed your computer.
If all you need is the "MST" or the "EST" time zone abbreviation:
function getTimeZone(){
var now = new Date().toString();
var timeZone = now.replace(/.*[(](.*)[)].*/,'$1');//extracts the content between parenthesis
return timeZone;
}
console.log(getTimeZone());
_x000D_
Use money-rails gem. It nicely handles money and currencies in your model and also has a bunch of helpers to format your prices.
The answer probably depends how critical it is for you to receive support and possible customization for this service.
Google can certainly do this. Look into their XML and Geocoding API's. You should be able to craft an XML message asking Google to return Map coordinates for a given address. If the address is not found (invalid), you will receive an appropriate response. Here's a useful page: http://code.google.com/apis/maps/documentation/services.html#XML_Requests
Note that Google's aim in providing the Maps API is to plot addresses on actual maps. While you can certainly use the data for other purposes, you are at the mercy of Google should one of their maps not exactly correspond to your legal or commercial address validation needs. If you paid for one of the services you mentioned, you would likely be able to receive support should certain addresses not resolve the way you expect them to.
In other words, you get what you pay for ;) . If you have the time, though, why not try implementing a Google-based solution then going from there? The API looks pretty slick, and it's free, after all.
I simplified the code Mikael Svensson provided which is correct for many countries in Europe.
public static DateTime FirstDateOfWeekIso8601(int year, int week)
{
var firstThursdayOfYear = new DateTime(year, 1, 1);
while (firstThursdayOfYear.DayOfWeek != DayOfWeek.Thursday)
{
firstThursdayOfYear = firstThursdayOfYear.AddDays(1);
}
var startDateOfWeekOne = firstThursdayOfYear.AddDays(-(DayOfWeek.Thursday - DayOfWeek.Monday));
return startDateOfWeekOne.AddDays(7 * (week - 1));
}
TL;DR;
Unicode - (nchar, nvarchar, and ntext)
Non-unicode - (char, varchar, and text).
Collations in SQL Server provide sorting rules, case, and accent sensitivity properties for your data. Collations that are used with character data types such as char and varchar dictate the code page and corresponding characters that can be represented for that data type.
Assuming you are using default SQL collation SQL_Latin1_General_CP1_CI_AS
then following script should print out all the symbols that you can fit in VARCHAR
since it uses one byte to store one character (256 total) if you don't see it on the list printed - you need NVARCHAR
.
declare @i int = 0;
while (@i < 256)
begin
print cast(@i as varchar(3)) + ' '+ char(@i) collate SQL_Latin1_General_CP1_CI_AS
print cast(@i as varchar(3)) + ' '+ char(@i) collate Japanese_90_CI_AS
set @i = @i+1;
end
If you change collation to lets say japanese you will notice that all the weird European letters turned into normal and some symbols into ?
marks.
Unicode is a standard for mapping code points to characters. Because it is designed to cover all the characters of all the languages of the world, there is no need for different code pages to handle different sets of characters. If you store character data that reflects multiple languages, always use Unicode data types (nchar, nvarchar, and ntext) instead of the non-Unicode data types (char, varchar, and text).
Otherwise your sorting will go weird.
The challenge I see with the solution:
FROM(
SELECT top(100) *
FROM Customers
UNION
SELECT top(100) *
FROM CustomerEurope
UNION
SELECT top(100) *
FROM CustomerAsia
UNION
SELECT top(100) *
FROM CustomerAmericas
)
is that this creates a windowed data set that will reside in the RAM and on larger data sets this solution will create severe performance issues as it must first create the partition and then it will use the partition to write to the temp table.
A better solution would be the following:
SELECT top(100)* into #tmpFerdeen
FROM Customers
Insert into #tmpFerdeen
SELECT top(100)*
FROM CustomerEurope
Insert into #tmpFerdeen
SELECT top(100)*
FROM CustomerAsia
Insert into #tmpFerdeen
SELECT top(100)*
FROM CustomerAmericas
to select insert into the temp table and then add additional rows. However the draw back here is if there are any duplicate rows in the data.
The Best Solution would be the following:
Insert into #tmpFerdeen
SELECT top(100)*
FROM Customers
UNION
SELECT top(100)*
FROM CustomerEurope
UNION
SELECT top(100)*
FROM CustomerAsia
UNION
SELECT top(100)*
FROM CustomerAmericas
This method should work for all purposes that require distinct rows. If, however, you want the duplicate rows simply swap out the UNION for UNION ALL
Best of luck!
My personal preference is to delete the branch name after I’m done with a topic branch.
Instead of trying to use the branch name to explain the meaning of the branch, I start the subject line of the commit message in the first commit on that branch with “Branch:” and include further explanations in the body of the message if the subject does not give me enough space.
The branch name in my use is purely a handle for referring to a topic branch while working on it. Once work on the topic branch has concluded, I get rid of the branch name, sometimes tagging the commit for later reference.
That makes the output of git branch
more useful as well: it only lists long-lived branches and active topic branches, not all branches ever.
What worked for me was this-- On Ubuntu
The "in" in Linq-To-Sql uses a reverse logic compared to a SQL query.
Let's say you have a list of integers, and want to find the items that match those integers.
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var items = from p in context.Items
where numbers.Contains(p.ItemId)
select p;
Anyway, the above works fine in linq-to-sql but not in EF 1.0. Haven't tried it in EF 4.0
you can use enumerate keeping the ind/index of the elements is in vm, if you make vm
a set you will also have 0(1)
lookups:
vm = {-1, -1, -1, -1}
print([ind if q in vm else 9999 for ind,ele in enumerate(vm) ])
1.) Create an arraylist of appropriate type, in this case i.e String
2.) Create a JSONObject
while passing your string to JSONObject
constructor as input
JSONObject
notation is represented by braces i.e {}
JSONArray
notation is represented by square brackets i.e []
3.) Retrieve JSONArray
from JSONObject
(created at 2nd step) using "interests"
as index.
4.) Traverse JASONArray
using loops upto the length of array provided by length()
function
5.) Retrieve your JSONObjects
from JSONArray
using getJSONObject(index)
function
6.) Fetch the data from JSONObject
using index '"interestKey"'.
Note : JSON
parsing uses the escape sequence for special nested characters if the json response (usually from other JSON response APIs) contains quotes ("
) like this
`"{"key":"value"}"`
should be like this
`"{\"key\":\"value\"}"`
so you can use JSONParser
to achieve escaped sequence format for safety as
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(inputString);
Code :
JSONParser parser = new JSONParser();
String response = "{interests : [{interestKey:Dogs}, {interestKey:Cats}]}";
JSONObject jsonObj = (JSONObject) parser.parse(response);
or
JSONObject jsonObj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
List<String> interestList = new ArrayList<String>();
JSONArray jsonArray = jsonObj.getJSONArray("interests");
for(int i = 0 ; i < jsonArray.length() ; i++){
interestList.add(jsonArray.getJSONObject(i).optString("interestKey"));
}
Note : Sometime you may see some exceptions when the values are not available in appropriate type or is there is no mapping key
so in those cases when you are not sure about the presence of value so use optString
, optInt
, optBoolean
etc which will simply return the default value if it is not present and even try to convert value to int if it is of string type and vice-versa so Simply No null or NumberFormat exceptions at all in case of missing key or value
Get an optional string associated with a key. It returns the defaultValue if there is no such key.
public String optString(String key, String defaultValue) {
String missingKeyValue = json_data.optString("status","N/A");
// note there is no such key as "status" in response
// will return "N/A" if no key found
or To get empty string i.e ""
if no key found then simply use
String missingKeyValue = json_data.optString("status");
// will return "" if no key found where "" is an empty string
Further reference to study
I just re-invented this wheel today, and thought I'd share it.
This implementation does not require any changes to the code that defines the constants, which can be enumerations or #define
s or anything else that devolves to an integer - in my case I had symbols defined in terms of other symbols. It also works well with sparse values. It even allows multiple names for the same value, returning the first one always. The only downside is that it requires you to make a table of the constants, which might become out-of-date as new ones are added for example.
struct IdAndName
{
int id;
const char * name;
bool operator<(const IdAndName &rhs) const { return id < rhs.id; }
};
#define ID_AND_NAME(x) { x, #x }
const char * IdToName(int id, IdAndName *table_begin, IdAndName *table_end)
{
if ((table_end - table_begin) > 1 && table_begin[0].id > table_begin[1].id)
std::stable_sort(table_begin, table_end);
IdAndName searchee = { id, NULL };
IdAndName *p = std::lower_bound(table_begin, table_end, searchee);
return (p == table_end || p->id != id) ? NULL : p->name;
}
template<int N>
const char * IdToName(int id, IdAndName (&table)[N])
{
return IdToName(id, &table[0], &table[N]);
}
An example of how you'd use it:
static IdAndName WindowsErrorTable[] =
{
ID_AND_NAME(INT_MAX), // flag value to indicate unsorted table
ID_AND_NAME(NO_ERROR),
ID_AND_NAME(ERROR_INVALID_FUNCTION),
ID_AND_NAME(ERROR_FILE_NOT_FOUND),
ID_AND_NAME(ERROR_PATH_NOT_FOUND),
ID_AND_NAME(ERROR_TOO_MANY_OPEN_FILES),
ID_AND_NAME(ERROR_ACCESS_DENIED),
ID_AND_NAME(ERROR_INVALID_HANDLE),
ID_AND_NAME(ERROR_ARENA_TRASHED),
ID_AND_NAME(ERROR_NOT_ENOUGH_MEMORY),
ID_AND_NAME(ERROR_INVALID_BLOCK),
ID_AND_NAME(ERROR_BAD_ENVIRONMENT),
ID_AND_NAME(ERROR_BAD_FORMAT),
ID_AND_NAME(ERROR_INVALID_ACCESS),
ID_AND_NAME(ERROR_INVALID_DATA),
ID_AND_NAME(ERROR_INVALID_DRIVE),
ID_AND_NAME(ERROR_CURRENT_DIRECTORY),
ID_AND_NAME(ERROR_NOT_SAME_DEVICE),
ID_AND_NAME(ERROR_NO_MORE_FILES)
};
const char * error_name = IdToName(GetLastError(), WindowsErrorTable);
The IdToName
function relies on std::lower_bound
to do quick lookups, which requires the table to be sorted. If the first two entries in the table are out of order, the function will sort it automatically.
Edit: A comment made me think of another way of using the same principle. A macro simplifies the generation of a big switch
statement.
#define ID_AND_NAME(x) case x: return #x
const char * WindowsErrorToName(int id)
{
switch(id)
{
ID_AND_NAME(ERROR_INVALID_FUNCTION);
ID_AND_NAME(ERROR_FILE_NOT_FOUND);
ID_AND_NAME(ERROR_PATH_NOT_FOUND);
ID_AND_NAME(ERROR_TOO_MANY_OPEN_FILES);
ID_AND_NAME(ERROR_ACCESS_DENIED);
ID_AND_NAME(ERROR_INVALID_HANDLE);
ID_AND_NAME(ERROR_ARENA_TRASHED);
ID_AND_NAME(ERROR_NOT_ENOUGH_MEMORY);
ID_AND_NAME(ERROR_INVALID_BLOCK);
ID_AND_NAME(ERROR_BAD_ENVIRONMENT);
ID_AND_NAME(ERROR_BAD_FORMAT);
ID_AND_NAME(ERROR_INVALID_ACCESS);
ID_AND_NAME(ERROR_INVALID_DATA);
ID_AND_NAME(ERROR_INVALID_DRIVE);
ID_AND_NAME(ERROR_CURRENT_DIRECTORY);
ID_AND_NAME(ERROR_NOT_SAME_DEVICE);
ID_AND_NAME(ERROR_NO_MORE_FILES);
default: return NULL;
}
}
What I do in my projects is to activate the following option in the "Constant conditions & exceptions" code inspection:
Suggest @Nullable annotation for methods that may possibly return null and report nullable values passed to non-annotated parameters
When activated, all non-annotated parameters will be treated as non-null and thus you will also see a warning on your indirect call:
clazz.indirectPathToA(null);
For even stronger checks the Checker Framework may be a good choice (see this nice tutorial.
Note: I have not used that yet and there may be problems with the Jack compiler: see this bugreport
It looks like you're getting back an array. If it's always going to consist of just one element, you could do this (yes, it's pretty much the same thing as Tomalak's answer):
$.each(result[0], function(key, value){
console.log(key, value);
});
If you might have more than one element and you'd like to iterate over them all, you could nest $.each()
:
$.each(result, function(key, value){
$.each(value, function(key, value){
console.log(key, value);
});
});
For Android mobile $(window).scroll(function() and $(document).scroll(function() may or may not work. So instead use the following.
jQuery(document.body).scroll(function() {
var scroll = jQuery(document.body).scrollTop();
if (scroll >= 300) {
//alert();
header.addClass("sticky");
} else {
header.removeClass('sticky');
}
});
This code worked for me. Hope it will help you.
Assuming terminal Vim on a flavor of *nix:
Ctrl + Z
will suspend the process and get back to your shell
fg
will resume (bring to foreground) your suspended Vim.
Start a subshell using:
:sh
(as configured by)
:set shell?
:!bash
followed by:
Ctrl+D (or exit
, but why type so much?)
to kill the shell and return to Vim.
Add this to your dependencies in build.gradle
:
dependencies {
implementation 'com.squareup.picasso:picasso:2.71828'
...
The latest version can be found here
Make sure you are connected to the Internet. When you sync Gradle, all related files will be added to your project
Take a look at your libraries folder, the library you just added should be in there.
Unless you have sudo permissions to change it or its in your own usergroup/account you will not be able to get into it.
Check out man chmod
in the terminal for more information about changing permissions of a directory.
<input type="text" id="input_id" />
$('#input_id').keydown(function (event) {
if (event.keyCode == 13) {
// Call your function here or add code here
}
});
With openssl
:
openssl x509 -enddate -noout -in file.pem
The output is on the form:
notAfter=Nov 3 22:23:50 2014 GMT
Also see MikeW's answer for how to easily check whether the certificate has expired or not, or whether it will within a certain time period, without having to parse the date above.
Note as of Symfony 3.3 EntityManager is depreciated. Use EntityManagerInterface instead.
namespace AppBundle\Service;
use Doctrine\ORM\EntityManagerInterface;
class Someclass {
protected $em;
public function __construct(EntityManagerInterface $entityManager)
{
$this->em = $entityManager;
}
public function somefunction() {
$em = $this->em;
...
}
}
In sequelize you can easily add order by clauses.
exports.getStaticCompanies = function () {
return Company.findAll({
where: {
id: [46128, 2865, 49569, 1488, 45600, 61991, 1418, 61919, 53326, 61680]
},
// Add order conditions here....
order: [
['id', 'DESC'],
['name', 'ASC'],
],
attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at']
});
};
See how I've added the order
array of objects?
order: [
['COLUMN_NAME_EXAMPLE', 'ASC'], // Sorts by COLUMN_NAME_EXAMPLE in ascending order
],
Edit:
You might have to order the objects once they've been recieved inside the .then()
promise. Checkout this question about ordering an array of objects based on a custom order:
How do I sort an array of objects based on the ordering of another array?
this expression is to get only numbers
If Regex.IsMatch(mystring, "^[A-Za-z ].*|\s") Then
MessageBox.Show("please fill the box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
ElseIf (mystring = "") Then
MessageBox.Show("please fill the box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
I just had to play with the divo's ConsoleSpinner
class. Mine is nowhere near as concise, but it just didn't sit well with me that users of that class have to write their own while(true)
loop. I'm shooting for an experience more like this:
static void Main(string[] args)
{
Console.Write("Working....");
ConsoleSpinner spin = new ConsoleSpinner();
spin.Start();
// Do some work...
spin.Stop();
}
And I realized it with the code below. Since I don't want my Start()
method to block, I don't want the user to have to worry about writing a while(spinFlag)
-like loop, and I want to allow multiple spinners at the same time I had to spawn a separate thread to handle the spinning. And that means the code has to be a lot more complicated.
Also, I haven't done that much multi-threading so it's possible (likely even) that I've left a subtle bug or three in there. But it seems to work pretty well so far:
public class ConsoleSpinner : IDisposable
{
public ConsoleSpinner()
{
CursorLeft = Console.CursorLeft;
CursorTop = Console.CursorTop;
}
public ConsoleSpinner(bool start)
: this()
{
if (start) Start();
}
public void Start()
{
// prevent two conflicting Start() calls ot the same instance
lock (instanceLocker)
{
if (!running )
{
running = true;
turner = new Thread(Turn);
turner.Start();
}
}
}
public void StartHere()
{
SetPosition();
Start();
}
public void Stop()
{
lock (instanceLocker)
{
if (!running) return;
running = false;
if (! turner.Join(250))
turner.Abort();
}
}
public void SetPosition()
{
SetPosition(Console.CursorLeft, Console.CursorTop);
}
public void SetPosition(int left, int top)
{
bool wasRunning;
//prevent other start/stops during move
lock (instanceLocker)
{
wasRunning = running;
Stop();
CursorLeft = left;
CursorTop = top;
if (wasRunning) Start();
}
}
public bool IsSpinning { get { return running;} }
/* --- PRIVATE --- */
private int counter=-1;
private Thread turner;
private bool running = false;
private int rate = 100;
private int CursorLeft;
private int CursorTop;
private Object instanceLocker = new Object();
private static Object console = new Object();
private void Turn()
{
while (running)
{
counter++;
// prevent two instances from overlapping cursor position updates
// weird things can still happen if the main ui thread moves the cursor during an update and context switch
lock (console)
{
int OldLeft = Console.CursorLeft;
int OldTop = Console.CursorTop;
Console.SetCursorPosition(CursorLeft, CursorTop);
switch (counter)
{
case 0: Console.Write("/"); break;
case 1: Console.Write("-"); break;
case 2: Console.Write("\\"); break;
case 3: Console.Write("|"); counter = -1; break;
}
Console.SetCursorPosition(OldLeft, OldTop);
}
Thread.Sleep(rate);
}
lock (console)
{ // clean up
int OldLeft = Console.CursorLeft;
int OldTop = Console.CursorTop;
Console.SetCursorPosition(CursorLeft, CursorTop);
Console.Write(' ');
Console.SetCursorPosition(OldLeft, OldTop);
}
}
public void Dispose()
{
Stop();
}
}
Not only can you add raw strings to matplotlib but you can also specify the font in matplotlibrc or locally with:
from matplotlib import rc
rc('font', **{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
This would change your serif latex font. You can also specify the sans-serif Helvetica like so
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
Other options are cursive
and monospace
with their respective font names.
Your label would then be
fig.gca().set_xlabel(r'wavelength $5000 \AA$')
If the font doesn't supply an Angstrom symbol you can try using \mathring{A}
This is Pythoncode
Problem with alert boxes (especially sweet-alerts is that they have a delay and Selenium is pretty much too fast)
An Option that worked for me is:
while True:
try:
driver.find_element_by_xpath('//div[@class="sweet-alert showSweetAlert visible"]')
break
except:
wait = WebDriverWait(driver, 1000)
confirm_button = driver.find_element_by_xpath('//button[@class="confirm"]')
confirm_button.click()
In my case:
1 - set text
2 - set typeface
holder.title.setText(item.nome);
holder.title.setTypeface(null, Typeface.BOLD);
At the present time, Intel graphics chips do not support CUDA. It is possible that, in the nearest future, these chips will support OpenCL (which is a standard that is very similar to CUDA), but this is not guaranteed and their current drivers do not support OpenCL either. (There is an Intel OpenCL SDK available, but, at the present time, it does not give you access to the GPU.)
Newest Intel processors (Sandy Bridge) have a GPU integrated into the CPU core. Your processor may be a previous-generation version, in which case "Intel(HD) graphics" is an independent chip.
I usually use something similar to version 3. It works well c/c++/bash/... :P
no different, as declare in javadoc:
public boolean add(E e) {
return offer(e);
}
Use ECMA2015. Arrow functions make "this" a lot more intuitive.
import React from 'react';
class TestApp extends React.Component {
getComponent(e, index) {
$(e.target).css({
'background-color': '#ccc'
});
}
render() {
return (
<div>
<ul>
<li onClick={(e) => this.getComponent(e, 1)}>Component 1</li>
<li onClick={(e) => this.getComponent(e, 2)}>Component 2</li>
<li onClick={(e) => this.getComponent(e, 3)}>Component 3</li>
</ul>
</div>
);
}
});
React.renderComponent(<TestApp /> , document.getElementById('soln1'));`
Try this regex:
"href\\s*=\\s*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))"
You will get more help from discussions over:
Regular expression to extract URL from an HTML link
and
Regex to get the link in href. [asp.net]
Hope its helpful.
The documentation has the complete answer. Anyway this is how it is done:
<input type="text" ng-model="filterValue">
<li ng-repeat="i in data | filter:{age:filterValue}:true"> {{i | json }}</li>
will filter only age
in data
array and true
is for exact match.
For deep filtering,
<li ng-repeat="i in data | filter:{$:filterValue}:true"> {{i}}</li>
The $
is a special property for deep filter and the true
is for exact match like above.
Converting SecretKeySpec to String and vice-versa:
you can use getEncoded()
method in SecretKeySpec
which will give byteArray
, from that you can use encodeToString()
to get string
value of SecretKeySpec
in Base64
object.
While converting SecretKeySpec
to String
: use decode()
in Base64
will give byteArray
, from that you can create instance for SecretKeySpec
with the params as the byteArray
to reproduce your SecretKeySpec
.
String mAesKey_string;
SecretKeySpec mAesKey= new SecretKeySpec(secretKey.getEncoded(), "AES");
//SecretKeySpec to String
byte[] byteaes=mAesKey.getEncoded();
mAesKey_string=Base64.encodeToString(byteaes,Base64.NO_WRAP);
//String to SecretKeySpec
byte[] aesByte = Base64.decode(mAesKey_string, Base64.NO_WRAP);
mAesKey= new SecretKeySpec(aesByte, "AES");
As per my usage above v.4 this gonna work
$('#selectID').on("select2:select", function(e) {
//var value = e.params.data; Using {id,text format}
});
And for less then v.4 this gonna work:
$('#selectID').on("change", function(e) {
//var value = e.params.data; Using {id,text} format
});
IF you want more data in you confusion matrix, including "totals column" and "totals line", and percents (%) in each cell, like matlab default (see image below)
including the Heatmap and other options...
You should have fun with the module above, shared in the github ; )
https://github.com/wcipriano/pretty-print-confusion-matrix
This module can do your task easily and produces the output above with a lot of params to customize your CM:
I believe you are looking for the setTimeout function.
To make your code a little neater, define a separate function for onclick in a <script>
block:
function myClick() {
setTimeout(
function() {
document.getElementById('div1').style.display='none';
document.getElementById('div2').style.display='none';
}, 5000);
}
then call your function from onclick
onclick="myClick();"
It looks like you forgot the prefix on the color attribute. Try
<stroke android:width="2dp" android:color="#ff00ffff"/>
Controller not supposed to be called from view. That's the whole idea of MVC - clear separation of concerns.
If you need to call controller from View - you are doing something wrong. Time for refactoring.
SELECT
resultIn the Navigator, right click on the table > Table Data Export Wizard
All columns and rows are included by default, so click on Next.
Select File Path, type, Field Separator (by default it is ;
, not ,
!!!) and click on Next.
Click Next > Next > Finish and the file is created in the specified location
One could also consider:
def foo():
try:
foo.counter += 1
except AttributeError:
foo.counter = 1
Reasoning:
if
branch (think StopIteration exception)As an alternative to homebrew, you could download and install macports. Once you have macports, you can use:
sudo port install apache-ant
The simplest way I've ever found is this. It works correctly for the US and western europe locales. Can't speak to other locales, especially places like China. 4 extra compares, at most, following the initial computation of age.
public int AgeInYears(DateTime birthDate, DateTime referenceDate)
{
Debug.Assert(referenceDate >= birthDate,
"birth date must be on or prior to the reference date");
DateTime birth = birthDate.Date;
DateTime reference = referenceDate.Date;
int years = (reference.Year - birth.Year);
//
// an offset of -1 is applied if the birth date has
// not yet occurred in the current year.
//
if (reference.Month > birth.Month);
else if (reference.Month < birth.Month)
--years;
else // in birth month
{
if (reference.Day < birth.Day)
--years;
}
return years ;
}
I was looking over the answers to this and noticed that nobody has made reference to regulatory/legal implications of leap day births. For instance, per Wikipedia, if you're born on February 29th in various jurisdictions, you're non-leap year birthday varies:
And as near as I can tell, in the US, the statutes are silent on the matter, leaving it up to the common law and to how various regulatory bodies define things in their regulations.
To that end, an improvement:
public enum LeapDayRule
{
OrdinalDay = 1 ,
LastDayOfMonth = 2 ,
}
static int ComputeAgeInYears(DateTime birth, DateTime reference, LeapYearBirthdayRule ruleInEffect)
{
bool isLeapYearBirthday = CultureInfo.CurrentCulture.Calendar.IsLeapDay(birth.Year, birth.Month, birth.Day);
DateTime cutoff;
if (isLeapYearBirthday && !DateTime.IsLeapYear(reference.Year))
{
switch (ruleInEffect)
{
case LeapDayRule.OrdinalDay:
cutoff = new DateTime(reference.Year, 1, 1)
.AddDays(birth.DayOfYear - 1);
break;
case LeapDayRule.LastDayOfMonth:
cutoff = new DateTime(reference.Year, birth.Month, 1)
.AddMonths(1)
.AddDays(-1);
break;
default:
throw new InvalidOperationException();
}
}
else
{
cutoff = new DateTime(reference.Year, birth.Month, birth.Day);
}
int age = (reference.Year - birth.Year) + (reference >= cutoff ? 0 : -1);
return age < 0 ? 0 : age;
}
It should be noted that this code assumes:
return el instanceof jQuery ? el.size() > 0 : (el && el.tagName);
You can simple try String(); to remove the quotes.
Refer the first example here: https://www.w3schools.com/jsref/jsref_string.asp
Thank me later.
PS: TO MODs: don't mistaken me for digging the dead old question. I faced this issue today and I came across this post while searching for the answer and I'm just posting the answer.
Breadth first is a queue, depth first is a stack.
For breadth first, add all children to the queue, then pull the head and do a breadth first search on it, using the same queue.
For depth first, add all children to the stack, then pop and do a depth first on that node, using the same stack.
A major difference between them is that value-type variables store values, so specifying a value-type variable in a method call passes a copy of that variable's value to the method. Reference-type variables store references to objects, so specifying a reference-type variable as an argument passes the method a copy of the actual reference that refers to the object. Even though the reference itself is passed by value, the method can still use the reference it receives to interact with—and possibly modify—the original object. Similarly, when returning information from a method via a return statement, the method returns a copy of the value stored in a value-type variable or a copy of the reference stored in a reference-type variable. When a reference is returned, the calling method can use that reference to interact with the referenced object. So, in effect, objects are always passed by reference.
In c#, to pass a variable by reference so the called method can modify the variable's, C# provides keywords ref and out. Applying the ref keyword to a parameter declaration allows you to pass a variable to a method by reference—the called method will be able to modify the original variable in the caller. The ref keyword is used for variables that already have been initialized in the calling method. Normally, when a method call contains an uninitialized variable as an argument, the compiler generates an error. Preceding a parameter with keyword out creates an output parameter. This indicates to the compiler that the argument will be passed into the called method by reference and that the called method will assign a value to the original variable in the caller. If the method does not assign a value to the output parameter in every possible path of execution, the compiler generates an error. This also prevents the compiler from generating an error message for an uninitialized variable that is passed as an argument to a method. A method can return only one value to its caller via a return statement, but can return many values by specifying multiple output (ref and/or out) parameters.
see c# discussion and examples here link text
See ?read.table
. Basically, when you use read.table
, you specify a number indicating the column:
##Row names in the first column
read.table(filname.txt, row.names=1)
Maybe you can add a step to the generate-sources phase that moves the folder?
you can use one of the following:
(falseVal, trueVal)[TEST]
TEST and trueVal or falseVal
You can use the CONCAT
with CURDATE()
to the entire time of the day and then filter by using the BETWEEN
in WHERE
condition:
SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d')
FROM users
WHERE (users.signup_date BETWEEN CONCAT(CURDATE(), ' 00:00:00') AND CONCAT(CURDATE(), ' 23:59:59'))
The maximum value of an integer (which is signed) is 2147483647
. If that value overflows, an exception is thrown to prevent unexpected behavior of your program.
If that exception wouldn't be thrown, you'd have a value of -2145629296
for your Volume
, which is most probably not wanted.
Solution: Use an Int64
for your volume. With a max value of 9223372036854775807
, you're probably more on the safe side.
sqrt=x**(1/2)
is doing integer division. 1/2 == 0
.
So you're computing x(1/2) in the first instance, x(0) in the second.
So it's not wrong, it's the right answer to a different question.
Merge byte arrays of multiple PDF files:
public static byte[] MergePDFs(List<byte[]> pdfFiles)
{
if (pdfFiles.Count > 1)
{
PdfReader finalPdf;
Document pdfContainer;
PdfWriter pdfCopy;
MemoryStream msFinalPdf = new MemoryStream();
finalPdf = new PdfReader(pdfFiles[0]);
pdfContainer = new Document();
pdfCopy = new PdfSmartCopy(pdfContainer, msFinalPdf);
pdfContainer.Open();
for (int k = 0; k < pdfFiles.Count; k++)
{
finalPdf = new PdfReader(pdfFiles[k]);
for (int i = 1; i < finalPdf.NumberOfPages + 1; i++)
{
((PdfSmartCopy)pdfCopy).AddPage(pdfCopy.GetImportedPage(finalPdf, i));
}
pdfCopy.FreeReader(finalPdf);
}
finalPdf.Close();
pdfCopy.Close();
pdfContainer.Close();
return msFinalPdf.ToArray();
}
else if (pdfFiles.Count == 1)
{
return pdfFiles[0];
}
return null;
}
That would only happen if PostCode
is missing a space.
You could add conditionality such that all of PostCode
is retrieved should a space not be found as follows
select SUBSTRING(PostCode, 1 ,
case when CHARINDEX(' ', PostCode ) = 0 then LEN(PostCode)
else CHARINDEX(' ', PostCode) -1 end)
For pre PHP 5:
function iso8601($time=false) {
if(!$time) $time=time();
return date("Y-m-d", $time) . 'T' . date("H:i:s", $time) .'+00:00';
}
If you want to hover the popover itself as well you have to use a manual trigger.
This is what i came up with:
function enableThumbPopover() {
var counter;
$('.thumbcontainer').popover({
trigger: 'manual',
animation: false,
html: true,
title: function () {
return $(this).parent().find('.thumbPopover > .title').html();
},
content: function () {
return $(this).parent().find('.thumbPopover > .body').html();
},
container: 'body',
placement: 'auto'
}).on("mouseenter",function () {
var _this = this; // thumbcontainer
console.log('thumbcontainer mouseenter')
// clear the counter
clearTimeout(counter);
// Close all other Popovers
$('.thumbcontainer').not(_this).popover('hide');
// start new timeout to show popover
counter = setTimeout(function(){
if($(_this).is(':hover'))
{
$(_this).popover("show");
}
$(".popover").on("mouseleave", function () {
$('.thumbcontainer').popover('hide');
});
}, 400);
}).on("mouseleave", function () {
var _this = this;
setTimeout(function () {
if (!$(".popover:hover").length) {
if(!$(_this).is(':hover')) // change $(this) to $(_this)
{
$(_this).popover('hide');
}
}
}, 200);
});
}
If a class is declared as static then the variables and methods need to be declared as static.
A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
->The main features of a static class are:
Example
static class CollegeRegistration
{
//All static member variables
static int nCollegeId; //College Id will be same for all the students studying
static string sCollegeName; //Name will be same
static string sColegeAddress; //Address of the college will also same
//Member functions
public static int GetCollegeId()
{
nCollegeId = 100;
return (nCollegeID);
}
//similarly implementation of others also.
} //class end
public class student
{
int nRollNo;
string sName;
public GetRollNo()
{
nRollNo += 1;
return (nRollNo);
}
//similarly ....
public static void Main()
{
//Not required.
//CollegeRegistration objCollReg= new CollegeRegistration();
//<ClassName>.<MethodName>
int cid= CollegeRegistration.GetCollegeId();
string sname= CollegeRegistration.GetCollegeName();
} //Main end
}
I think the answer to the question is because .net uses string interning something that might cause equal strings to point to the same object (since a strings are mutable this is not a problem)
(I'm not talking about the overridden equality operator on the string class)
This worked for me:
Check the current role you are logged into by using: SELECT CURRENT_USER, SESSION_USER;
Note: It must match with Owner of the schema.
Schema | Name | Type | Owner
--------+--------+-------+----------
If the owner is different, then give all the grants to the current user role from the admin role by :
GRANT 'ROLE_OWNER' to 'CURRENT ROLENAME';
Then try to execute the query, it will give the output as it has access to all the relations now.
I know this is a late reply but maybe it can help someone.
Removing whitespace can be done by using the trim() function. After that if you want to sort the array with case sensitive manner you can just use:
Arrays.sort(yourArray);
and for case insensitive manner:
Arrays.sort(yourArray,String.CASE_INSENSITIVE_ORDER);
Hope this helps!
use encodeURIComponent function to fix url, it works on Browser and node.js
res.redirect("/signin?email="+encodeURIComponent("[email protected]"));
> encodeURIComponent("http://a.com/a+b/c")
'http%3A%2F%2Fa.com%2Fa%2Bb%2Fc'
I had the same problem today, here's how I solved it so I could keep lexical_cast<>
typedef unsigned int uint32;
typedef signed int int32;
class uint32_from_hex // For use with boost::lexical_cast
{
uint32 value;
public:
operator uint32() const { return value; }
friend std::istream& operator>>( std::istream& in, uint32_from_hex& outValue )
{
in >> std::hex >> outValue.value;
}
};
class int32_from_hex // For use with boost::lexical_cast
{
uint32 value;
public:
operator int32() const { return static_cast<int32>( value ); }
friend std::istream& operator>>( std::istream& in, int32_from_hex& outValue )
{
in >> std::hex >> outvalue.value;
}
};
uint32 material0 = lexical_cast<uint32_from_hex>( "0x4ad" );
uint32 material1 = lexical_cast<uint32_from_hex>( "4ad" );
uint32 material2 = lexical_cast<uint32>( "1197" );
int32 materialX = lexical_cast<int32_from_hex>( "0xfffefffe" );
int32 materialY = lexical_cast<int32_from_hex>( "fffefffe" );
// etc...
(Found this page when I was looking for a less sucky way :-)
Cheers, A.
Martin's solution is very similar to mine, however how would you handle a default descriptions when the desired translation isn't found ?
Would that require an IFNULL() and another SELECT statement for each field ?
The default translation would be stored in the same table, where a flag like "isDefault" indicates wether that description is the default description in case none has been found for the current language.
Create Common Method to Convert String to Date format
public static void main(String[] args) throws Exception {
long test = ConvertStringToDate("May 26 10:41:23", "MMM dd hh:mm:ss");
long test2 = ConvertStringToDate("Tue, Jun 06 2017, 12:30 AM", "EEE, MMM dd yyyy, hh:mm a");
long test3 = ConvertStringToDate("Jun 13 2003 23:11:52.454 UTC", "MMM dd yyyy HH:mm:ss.SSS zzz");
}
private static long ConvertStringToDate(String dateString, String format) {
try {
return new SimpleDateFormat(format).parse(dateString).getTime();
} catch (ParseException e) {}
return 0;
}
You may choose to store the whole form as a JSON string.
Not sure about your requirement, but this approach would work in some circumstances.
You should form the command with the contents of the textboxes:
sql = "insert into Main (Firt Name, Last Name) values(" + textbox2.Text + "," + textbox3.Text+ ")";
This, of course, provided that you manage to open the connection correctly.
It would be helpful to know what's happening with your current code. If you are getting some error displayed in that message box, it would be great to know what it's saying.
You should also validate the inputs before actually running the command (i.e. make sure they don't contain malicious code...).
Adding my localhost on Valid OAuth redirect URIs at https://developers.facebook.com/apps/YOUR_APP_ID/fb-login/ solved the problem!
And pay attention for one detail here:
In this case http://localhost:3000 is not the same of http://0.0.0.0:3000 or http://127.0.0.1:3000
Make sure you are using exactly the running url of you sandbox server. I spend some time to discover that...
You may simply want a UNIQUE CONSTRAINT. Especially if you already have a surrogate key. (example of an already existing surrogate key would be a single column that is an AUTO_INCREMENT )
Below is the sql code for a Unique Constraint
ALTER TABLE `MyDatabase`.`Provider`
ADD CONSTRAINT CK_Per_Place_Thing_Unique UNIQUE (person,place,thing)
;
viewDidLoad is things you have to do once. viewWillAppear gets called every time the view appears. You should do things that you only have to do once in viewDidLoad - like setting your UILabel texts. However, you may want to modify a specific part of the view every time the user gets to view it, e.g. the iPod application scrolls the lyrics back to the top every time you go to the "Now Playing" view.
However, when you are loading things from a server, you also have to think about latency. If you pack all of your network communication into viewDidLoad or viewWillAppear, they will be executed before the user gets to see the view - possibly resulting a short freeze of your app. It may be good idea to first show the user an unpopulated view with an activity indicator of some sort. When you are done with your networking, which may take a second or two (or may even fail - who knows?), you can populate the view with your data. Good examples on how this could be done can be seen in various twitter clients. For example, when you view the author detail page in Twitterrific, the view only says "Loading..." until the network queries have completed.
Answer below the dotted line below is the original that's now outdated.
Here is the latest information ( Thank you @deadfish ):
add &hl=<language>
like &hl=pl
or &hl=en
example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl
All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en
......................................................................
To change the actual local market:
Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html
To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720
In Python 3, dict.values()
(along with dict.keys()
and dict.items()
) returns a view
, rather than a list. See the documentation here. You therefore need to wrap your call to dict.values()
in a call to list
like so:
v = list(d.values())
{names[i]:v[i] for i in range(len(names))}
Better just create a XLSX file with field names on top row. Create it manually or using Mockaroo. Export it to Excel(or CSV) and then import it to Access using New Data Source -> From File
IMHO it's the best and most performant way to do it in Access.
In your case
var KeyVal = string.split(", ");
var obj = {};
var i;
for (i in KeyVal) {
KeyVal[i] = KeyVal[i].split(":");
obj[eval(KeyVal[i][0])] = eval(KeyVal[i][1]);
}
I can do the following using Mockito:
<bean id="stateMachine" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="com.abcd.StateMachine"/>
</bean>
// app.js
let db = ...; // your db object initialized
const contextMiddleware = (req, res, next) => {
req.db=db;
next();
};
app.use(contextMiddleware);
// routes.js It's just a mapping.
exports.routes = [
['/', controllers.index],
['/posts', controllers.posts.index],
['/posts/:post', controllers.posts.show]
];
// app.js
var { routes } = require('./routes');
routes.forEach(route => app.get(...route));
// You can customize this according to your own needs, like adding post request
The final app.js:
// app.js
var express = require('express');
var app = express.createServer();
let db = ...; // your db object initialized
const contextMiddleware = (req, res, next) => {
req.db=db;
next();
};
app.use(contextMiddleware);
var { routes } = require('./routes');
routes.forEach(route => app.get(...route));
app.listen(3000, function() {
console.log('Application is listening on port 3000');
});
Another version: you can customize this according to your own needs, like adding post request
// routes.js It's just a mapping.
let get = ({path, callback}) => ({app})=>{
app.get(path, callback);
}
let post = ({path, callback}) => ({app})=>{
app.post(path, callback);
}
let someFn = ({path, callback}) => ({app})=>{
// ...custom logic
app.get(path, callback);
}
exports.routes = [
get({path: '/', callback: controllers.index}),
post({path: '/posts', callback: controllers.posts.index}),
someFn({path: '/posts/:post', callback: controllers.posts.show}),
];
// app.js
var { routes } = require('./routes');
routes.forEach(route => route({app}));
The thread dump is written to the system out of the VM on which you executed the kill -3
. If you are redirecting the console output of the JVM to a file, the thread dump will be in that file. If the JVM is running in an open console, then the thread dump will be displayed in its console.
To get the value of a pointer, just de-reference the pointer.
int *ptr;
int value;
*ptr = 9;
value = *ptr;
value is now 9.
I suggest you read more about pointers, this is their base functionality.
sprintf can do this:
#include <stdio.h>
int main() {
float w = 234.567;
char x[__SIZEOF_FLOAT__];
sprintf(x, "%g", w);
puts(x);
}
A Thread dump is a dump of all threads's stack traces, i.e. as if each Thread suddenly threw an Exception and printStackTrace'ed that. This is so that you can see what each thread is doing at some specific point, and is for example very good to catch deadlocks.
A heap dump is a "binary dump" of the full memory the JVM is using, and is for example useful if you need to know why you are running out of memory - in the heap dump you could for example see that you have one billion User objects, even though you should only have a thousand, which points to a memory retention problem.
This might be helpful
I converted this from C# ('From: http://www.dotnetpools.com/Article/ArticleDetiail/?articleId=74)
Private Sub dgv_EmployeeTraining_RowPostPaint(sender As Object, e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs)
Handles dgv_EmployeeTraining.RowPostPaint
If e.RowIndex < Me.dgv_EmployeeTraining.RowCount - 1 Then
Dim dgvRow As DataGridViewRow = Me.dgv_EmployeeTraining.Rows(e.RowIndex)
'<== This is the header Name
'If CInt(dgvRow.Cells("EmployeeStatus_Training_e26").Value) <> 2 Then
'<== But this is the name assigned to it in the properties of the control
If CInt(dgvRow.Cells("DataGridViewTextBoxColumn15").Value.ToString) <> 2 Then
dgvRow.DefaultCellStyle.BackColor = Color.FromArgb(236, 236, 255)
Else
dgvRow.DefaultCellStyle.BackColor = Color.LightPink
End If
End If
End Sub
The Jquery .on
works ok but I had some problems with the rendering implementing some of the solutions above. My problem using the .on
is that somehow it was rendering the events differently than the .hover
method.
Just fyi for anyone else that may also have the problem. I solved my problem by re-registering the hover event for the dynamically added item:
re-register the hover event because hover doesn't work for dynamically created items. so every time i create the new/dynamic item i add the hover code again. works perfectly
$('#someID div:last').hover(
function() {
//...
},
function() {
//...
}
);
BlobBuilder
is obsolete, use Blob
constructor instead:
URL.createObjectURL(new Blob([/*whatever content*/] , {type:'text/plain'}));
This returns a blob URL which you can then use in an anchor's href
. You can also modify an anchor's download
attribute to manipulate the file name:
<a href="/*assign url here*/" id="link" download="whatever.txt">download me</a>
Fiddled. If I recall correctly, there are arbitrary restrictions on trusted non-user initiated downloads; thus we'll stick with a link clicking which is seen as sufficiently user-initiated :)
Update: it's actually pretty trivial to save current document's html! Whenever our interactive link is clicked, we'll update its href
with a relevant blob. After executing the click-bound event, that's the download URL that will be navigated to!
$('#link').on('click', function(e){
this.href = URL.createObjectURL(
new Blob([document.documentElement.outerHTML] , {type:'text/html'})
);
});
Have you tried Build -> Rebuild project?
Chkconfig is no longer available in Ubuntu.
Chkconfig is a script. You can download it from here.
I DO NOT recommend setTimeout()
hack as it slows down the performance!
Instead, you can use DOM mutation observers for listening to Div size change.
JS:
var observer = new MutationObserver(function(mutations) {
console.log('size changed!');
});
var target = document.querySelector('.mydiv');
observer.observe(target, {
attributes: true
});
HTML:
<div class='mydiv'>
</div>
Here's the fiddle
Try to change the div size.
You can further wrap your method in the debounce
method to improve efficiency. debounce
will trigger your method every x milliseconds instead of triggering every millisecond the DIV is being resized.
No, this is not possible, because static member functions lack a this
pointer. And static members (both functions and variables) are not really class members per-se. They just happen to be invoked by ClassName::member
, and adhere to the class access specifiers. Their storage is defined somewhere outside the class; storage is not created each time you instantiated an object of the class. Pointers to class members are special in semantics and syntax. A pointer to a static member is a normal pointer in all regards.
virtual functions in a class needs the this
pointer, and is very coupled to the class, hence they can't be static.
puts foo.to_json
might come in handy since the json module is loaded by default
What worked for me on an Amazon EC2 server was:
sudo service mysqld restart
just to extend @GabLeRoux's answer:
[<img src="https://img.youtube.com/vi/<VIDEO ID>/maxresdefault.jpg" width="50%">](https://youtu.be/<VIDEO ID>)
this way you will be able to adjust the size of the thumbnail image in the README.md file on you Github repo.
if You want daily backup // following sql script store in C:\Users\admin\Desktop\DBScript\DBBackUpSQL.sql
DECLARE @pathName NVARCHAR(512),
@databaseName NVARCHAR(512) SET @databaseName = 'Databasename' SET @pathName = 'C:\DBBackup\DBData\DBBackUp' + Convert(varchar(8), GETDATE(), 112) + '_' + Replace((Convert(varchar(8), GETDATE(), 108)),':','-')+ '.bak' BACKUP DATABASE @databaseName TO DISK = @pathName WITH NOFORMAT,
INIT,
NAME = N'',
SKIP,
NOREWIND,
NOUNLOAD,
STATS = 10
GO
open the Task scheduler
create task-> select Triggers
tab Select New
.
Button Select Daily Radio button
click Ok
Button
then click Action
tab Select New.
Button Put "C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE"
-S ADMIN-PC -i "C:\Users\admin\Desktop\DBScript\DBBackUpSQL.sql"
in the program/script text box(make sure Match your files path and Put the double quoted path in start-> search box and if it find then click it and see the backup is there or not)
-- the above path may be insted 100 write 90 "C:\Program Files\Microsoft SQL Server\90\Tools\Binn\SQLCMD.EXE" -S ADMIN-PC -i
"C:\Users\admin\Desktop\DBScript\DBBackUpSQL.sql"
then click ok button
the Script will execute on time which you select on Trigger tab on daily basis
enjoy it.............
Better way:
encodeURIComponent escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )
To avoid unexpected requests to the server, you should call encodeURIComponent on any user-entered parameters that will be passed as part of a URI. For example, a user could type "Thyme &time=again" for a variable comment. Not using encodeURIComponent on this variable will give comment=Thyme%20&time=again. Note that the ampersand and the equal sign mark a new key and value pair. So instead of having a POST comment key equal to "Thyme &time=again", you have two POST keys, one equal to "Thyme " and another (time) equal to again.
For application/x-www-form-urlencoded (POST), per http://www.w3.org/TR/html401/interac...m-content-type, spaces are to be replaced by '+', so one may wish to follow a encodeURIComponent replacement with an additional replacement of "%20" with "+".
If one wishes to be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:
function fixedEncodeURIComponent (str) {
return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}
Probably the quick easiest way is using the sqlite .dump command, in this case create a dump of the sample database.
sqlite3 sample.db .dump > dump.sql
You can then (in theory) import this into the mysql database, in this case the test database on the database server 127.0.0.1, using user root.
mysql -p -u root -h 127.0.0.1 test < dump.sql
I say in theory as there are a few differences between grammars.
In sqlite transactions begin
BEGIN TRANSACTION;
...
COMMIT;
MySQL uses just
BEGIN;
...
COMMIT;
There are other similar problems (varchars and double quotes spring back to mind) but nothing find and replace couldn't fix.
Perhaps you should ask why you are migrating, if performance/ database size is the issue perhaps look at reoginising the schema, if the system is moving to a more powerful product this might be the ideal time to plan for the future of your data.
Though this question is asking about group by class properties, if you want to group by multiple columns against a ADO object (like a DataTable), you have to assign your "new" items to variables:
EnumerableRowCollection<DataRow> ClientProfiles = CurrentProfiles.AsEnumerable()
.Where(x => CheckProfileTypes.Contains(x.Field<object>(ProfileTypeField).ToString()));
// do other stuff, then check for dups...
var Dups = ClientProfiles.AsParallel()
.GroupBy(x => new { InterfaceID = x.Field<object>(InterfaceField).ToString(), ProfileType = x.Field<object>(ProfileTypeField).ToString() })
.Where(z => z.Count() > 1)
.Select(z => z);
Working with Windows environment variables is always a horrible experience. Recently, I found an amazing tool called Rapid Environment Editor, which gives an awesomely simple GUI for managing them.
If you use chocolatey, you can install it using choco install rapidee
. Otherwise, take a look at http://www.rapidee.com/en/download
Re-reading this, it sounds like a paid shill, but I swear I'm not! It's just been one of the most useful utilities in my toolkit for a while and I'm surprised no one seems to know about it.
The sa
user uses NTFS accounts SQLServerMSSQLUser$<computer_name>$<instance_name>
and SQLServerSQLAgentUser$<computer_name>$<instance_name>
to access the database files. You may want to try adding permissions for one or both these users.
I don't know if solves your problem since you say you have no problems with the sa
user, but I hope it helps.
I came up with a mix of defining a class like David's answer, but not requiring a Where class to go with it. It looks something like:
var resultsGroupings = resultsRecords.GroupBy(r => new { r.IdObj1, r.IdObj2, r.IdObj3})
.Select(r => new ResultGrouping {
IdObj1= r.Key.IdObj1,
IdObj2= r.Key.IdObj2,
IdObj3= r.Key.IdObj3,
Results = r.ToArray(),
Count = r.Count()
});
private class ResultGrouping
{
public short IdObj1{ get; set; }
public short IdObj2{ get; set; }
public int IdObj3{ get; set; }
public ResultCsvImport[] Results { get; set; }
public int Count { get; set; }
}
Where resultRecords
is my initial list I'm grouping, and its a List<ResultCsvImport>
. Note that the idea here to is that, I'm grouping by 3 columns, IdObj1 and IdObj2 and IdObj3
select * from temptable
where rnum --unique key
in
(
SELECT RNUM --unique key
FROM temptable
WHERE ( HistoryStatus
) IN (SELECT HistoryStatus
FROM temptable
GROUP BY
HistoryStatus
HAVING COUNT(*) <= 1));
I have not tested this code. I have used similar code and it works. The syntax is in Oracle.
Try this: It works in any case, if the file doesn't exists, it will create it and then write to it. And if already exists, no problem it will open and write to it :
using (FileStream fs= new FileStream(@"File.txt",FileMode.Create,FileAccess.ReadWrite))
{
fs.close();
}
using (StreamWriter sw = new StreamWriter(@"File.txt"))
{
sw.WriteLine("bla bla bla");
sw.Close();
}
Try the Date
function. It will give you today's date in a MM/DD/YYYY format. If you're looking for today's date in the MM-DD-YYYY format try Date$
. Now()
also includes the current time (which you might not need). It all depends on what you need. :)
Note : In order to set multiple environment variable, script should goes like this
"scripts": {
"start": "set NODE_ENV=production&& set MONGO_USER=your_DB_USER_NAME&& set MONGO_PASSWORD=DB_PASSWORD&& set MONGO_DEFAULT_DATABASE=DB_NAME&& node app.js",
},
Yes, the Session object might be null, but only in certain circumstances, which you will only rarely run into:
If you only have code in pages, you won't run into this. Most of my ASP .NET code uses Session without checking for null repeatedly. It is, however, something to think about if you are developing an IHttpModule or otherwise is down in the grittier details of ASP .NET.
In answer to the comment: Whether or not session state is available depends on whether the AcquireRequestState event has run for the request. This is where the session state module does it's work by reading the session cookie and finding the appropiate set of session variables for you.
AcquireRequestState runs before control is handed to your Page. So if you are calling other functionality, including static classes, from your page, you should be fine.
If you have some classes doing initialization logic during startup, for example on the Application_Start event or by using a static constructor, Session state might not be available. It all boils down to whether there is a current request and AcquireRequestState has been run.
Also, should the client have disabled cookies, the Session object will still be available - but on the next request, the user will return with a new empty Session. This is because the client is given a Session statebag if he does not have one already. If the client does not transport the session cookie, we have no way of identifying the client as the same, so he will be handed a new session again and again.
Timestamptz vs Timestamp
The timestamptz field in Postgres is basically just the timestamp field where Postgres actually just stores the “normalised” UTC time, even if the timestamp given in the input string has a timezone.
If your input string is: 2018-08-28T12:30:00+05:30 , when this timestamp is stored in the database, it will be stored as 2018-08-28T07:00:00.
The advantage of this over the simple timestamp field is that your input to the database will be timezone independent, and will not be inaccurate when apps from different timezones insert timestamps, or when you move your database server location to a different timezone.
To quote from the docs:
For timestamp with time zone, the internally stored value is always in UTC (Universal Coordinated Time, traditionally known as Greenwich Mean Time, GMT). An input value that has an explicit time zone specified is converted to UTC using the appropriate offset for that time zone. If no time zone is stated in the input string, then it is assumed to be in the time zone indicated by the system’s TimeZone parameter, and is converted to UTC using the offset for the timezone zone. To give a simple analogy, a timestamptz value represents an instant in time, the same instant for anyone viewing it. But a timestamp value just represents a particular orientation of a clock, which will represent different instances of time based on your timezone.
For pretty much any use case, timestamptz is almost always a better choice. This choice is made easier with the fact that both timestamptz and timestamp take up the same 8 bytes of data.
source: https://hasura.io/blog/postgres-date-time-data-types-on-graphql-fd926e86ee87/
Run this in the command line (or git bash on windows):
echo "" > $(npm config get userconfig)
npm config edit
echo "" > $(npm config get globalconfig)
npm config --global edit
sudo sh -c 'echo "" > $(npm config get globalconfig)'
these are controlled in variables, no need to muck around in source. with bootstrap, try variables first, then overrides. then go back and try variables again ;)
i used bootstrap-sass with rails, but it's the same with the default LESS.
FILE: main.css.scss
-------------------
// control the screen sizes
$screen-xs-min: 300px;
$screen-sm-min: 400px;
$screen-md-min: 800px;
$screen-lg-min: 1200px;
// this tells which screen size to use to start breaking on
// will tell navbar when to collapse
$grid-float-breakpoint: $screen-md-min;
// then import your bootstrap
@import "bootstrap";
that's it! this variables reference page is super handy: https://github.com/twbs/bootstrap/blob/master/less/variables.less
Sometimes it's more simple to implement a copy constructor:
public MyObject (MyObject toClone) {
}
It saves you the trouble of handling CloneNotSupportedException
, works with final
fields and you don't have to worry about the type to return.
My UTF-8 compliant version:
preg_replace('/[^\p{L}\s]/u','',$value);
Powershell users:
foreach($package in ls node_modules){npm uninstall $package}
Thanks @JustMailer
Vue.js uses vue-loader
, a loader for WebPack which is set up to rewrite/convert paths at compile time, in order to allow you to not worry about static paths that would differ between deployments (local, dev, one hosting platform or the other), by allowing you to use relative local filesystem paths. It also adds other benefits like asset caching and versioning (you can probably see this by checking the actual src
URL being generated).
So having a src that would normally be handled by vue-loader
/WebPack set to a dynamic expression, evaluated at runtime, will circumvent this mechanism and the dynamic URL generated will be invalid in the context of the actual deployment (unless it's fully qualified, that's an exception).
If instead, you would use a require
function call in the dynamic expression, vue-loader
/WebPack will see it and apply the usual magic.
For example, this wouldn't work:
<img alt="Logo" :src="logo" />
computed: {
logo() {
return this.colorMode === 'dark'
? './assets/logo-dark.png'
: './assets/logo-white.png';
}
}
While this would work:
<img alt="Logo" :src="logo" />
computed: {
logo() {
return this.colorMode === 'dark'
? require('./assets/logo-dark.png')
: require('./assets/logo-white.png');
}
}
I just found out about this myself. Took me an hour but... you live, you learn, right?
As per RFC2368 which defines mailto:
, further reinforced by an example in RFC1738, it is explicitly stated that the only valid way to generate a line break is with %0D%0A
.
This also applies to all url schemes such as gopher, smtp, sdp, imap, ldap, etc..
Although the best way to do this is to use % if you insist on using strings this will work
public int lastDigit(int number)
{
return Integer.parseInt(String.valueOf(Integer.toString(number).charAt(Integer.toString(number).length() - 1)));
}
but I just wrote this for completeness. Do not use this code. it is just awful.
Here is a check list for you:
1) Is your app published? (Production APK is not required for publishing)
2) Did your alpha/beta testers "Accept invitation" to Google+ community or Google group?
3) Are your alpha/beta testers logged in their Google+ account?
4) Are your alpha/beta testers using your link from Google Play developer console? It has format like this: https://play.google.com/apps/testing/com.yourdomain.package
I had this problem too. But there is very simple solution. Just declare your variable in constructor.
My example:
application.propperties:
#Session
session.timeout=15
SessionServiceImpl class:
private final int SESSION_TIMEOUT;
private final SessionRepository sessionRepository;
@Autowired
public SessionServiceImpl(@Value("${session.timeout}") int sessionTimeout,
SessionRepository sessionRepository) {
this.SESSION_TIMEOUT = sessionTimeout;
this.sessionRepository = sessionRepository;
}
600851475143
cannot be represented as a 32-bit integer (type int
). It can be represented as a 64-bit integer (type long
). long literals in Java end with an "L": 600851475143L
You can't stretch a background image (until CSS 3).
You would have to use absolute positioning, so that you can put an image tag inside the cell and stretch it to cover the entire cell, then put the content on top of the image.
table {_x000D_
width: 230px;_x000D_
}_x000D_
_x000D_
.style1 {_x000D_
text-align: center;_x000D_
height: 35px;_x000D_
}_x000D_
_x000D_
.bg {_x000D_
position: relative;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.bg img {_x000D_
display: block;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.bg .linkcontainer {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
overflow: hidden;_x000D_
width: 100%;_x000D_
}
_x000D_
<table cellpadding="0" cellspacing="0" border="10">_x000D_
<tr>_x000D_
<td class="style1">_x000D_
<div class="bg">_x000D_
<img src="http://placekitten.com/20/20" alt="" />_x000D_
<div class="linkcontainer">_x000D_
<a class="link" href="#">_x000D_
<span>Answer</span>_x000D_
</a>_x000D_
</div>_x000D_
</div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Try this:
private void cmbLineColor_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView drv = (DataRowView)cmbLineColor.SelectedItem;
int selectedValue = (int)drv.Row.ItemArray[1];
}
Instead of naming my invoking class, I started using the following:
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
In this way, I can use the same line of code in every class that uses log4net without having to remember to change code when I copy and paste. Alternatively, i could create a logging class, and have every other class inherit from my logging class.
You can use the following class to pinpoint transitivity bugs in your Comparators:
/**
* @author Gili Tzabari
*/
public final class Comparators
{
/**
* Verify that a comparator is transitive.
*
* @param <T> the type being compared
* @param comparator the comparator to test
* @param elements the elements to test against
* @throws AssertionError if the comparator is not transitive
*/
public static <T> void verifyTransitivity(Comparator<T> comparator, Collection<T> elements)
{
for (T first: elements)
{
for (T second: elements)
{
int result1 = comparator.compare(first, second);
int result2 = comparator.compare(second, first);
if (result1 != -result2)
{
// Uncomment the following line to step through the failed case
//comparator.compare(first, second);
throw new AssertionError("compare(" + first + ", " + second + ") == " + result1 +
" but swapping the parameters returns " + result2);
}
}
}
for (T first: elements)
{
for (T second: elements)
{
int firstGreaterThanSecond = comparator.compare(first, second);
if (firstGreaterThanSecond <= 0)
continue;
for (T third: elements)
{
int secondGreaterThanThird = comparator.compare(second, third);
if (secondGreaterThanThird <= 0)
continue;
int firstGreaterThanThird = comparator.compare(first, third);
if (firstGreaterThanThird <= 0)
{
// Uncomment the following line to step through the failed case
//comparator.compare(first, third);
throw new AssertionError("compare(" + first + ", " + second + ") > 0, " +
"compare(" + second + ", " + third + ") > 0, but compare(" + first + ", " + third + ") == " +
firstGreaterThanThird);
}
}
}
}
}
/**
* Prevent construction.
*/
private Comparators()
{
}
}
Simply invoke Comparators.verifyTransitivity(myComparator, myCollection)
in front of the code that fails.
Remember - if you set the buttons to vbOkOnly
- it will always return 1.
So you can't decide if a user clicked on the close or the OK button. You just have to add a vbOk
option.
You could pass in the command-line option -v
with a variable name (v
) and a value (=
) of the environment variable ("${v}"
):
% awk -vv="${v}" 'BEGIN { print v }'
123test
Or to make it clearer (with far fewer v
s):
% environment_variable=123test
% awk -vawk_variable="${environment_variable}" 'BEGIN { print awk_variable }'
123test
The first line occurrences of "foo" will be replaced with "bar". And you can using the second line to check.
grep -rl 'foo' . | xargs sed -i 's/foo/bar/g'
grep 'foo' -r * | awk -F: {'print $1'} | sort -n | uniq -c
numbers = [1, 2, 3]
numsum = sum(list(numbers))
print(numsum)
This would work, if your are trying to Sum up a list.
Good question- and there is wealth of information in the question itself.
The article Refresh Tokens: When to Use Them and How They Interact with JWTs gives a good idea for this scenario. Some points are:-
Also take a look at auth0/angular-jwt angularjs
For Web API. read Enable OAuth Refresh Tokens in AngularJS App using ASP .NET Web API 2, and Owin
A lot of these answers are pretty old, so I thought I would update with a solution that I think is helpful.
Our issue was similar to OP's, we upgraded 32 bit XP machines to 64 bit windows 7 and our application software that uses a 32 bit ODBC driver stopped being able to write to our database.
Turns out, there are two ODBC Data Source Managers, one for 32 bit and one for 64 bit. So I had to run the 32 bit version which is found in C:\Windows\SysWOW64\odbcad32.exe. Inside the ODBC Data Source Manager, I was able to go to the System DSN tab and Add my driver to the list using the Add button. (You can check the Drivers tab to see a list of the drivers you can add, if your driver isn't in this list then you may need to install it).
The next issue was the software that we ran was compiled to use 'Any CPU'. This would see the operating system was 64 bit, so it would look at the 64 bit ODBC Data Sources. So I had to force the program to compile as an x86 program, which then tells it to look at the 32 bit ODBC Data Sources. To set your program to x86, in Visual Studio go to your project properties and under the build tab at the top there is a platform drop down list, and choose x86. If you don't have the source code and can't compile the program as x86, you might be able to right click the program .exe and go to the compatibility tab and choose a compatibility that works for you.
Once I had the drivers added and the program pointing to the right drivers, everything worked like it use to. Hopefully this helps anyone working with older software.
I think the question has already been answered. I was also looking for something a webApi controller that has same signatured mehtods but different names. I was trying to implement the Calculator as WebApi. Calculator has 4 methods with the same signature but different names.
public class CalculatorController : ApiController
{
[HttpGet]
[ActionName("Add")]
public string Add(int num1 = 1, int num2 = 1, int timeDelay = 1)
{
Thread.Sleep(1000 * timeDelay);
return string.Format("Add = {0}", num1 + num2);
}
[HttpGet]
[ActionName("Sub")]
public string Sub(int num1 = 1, int num2 = 1, int timeDelay = 1)
{
Thread.Sleep(1000 * timeDelay);
return string.Format("Subtract result = {0}", num1 - num2);
}
[HttpGet]
[ActionName("Mul")]
public string Mul(int num1 = 1, int num2 = 1, int timeDelay = 1)
{
Thread.Sleep(1000 * timeDelay);
return string.Format("Multiplication result = {0}", num1 * num2);
}
[HttpGet]
[ActionName("Div")]
public string Div(int num1 = 1, int num2 = 1, int timeDelay = 1)
{
Thread.Sleep(1000 * timeDelay);
return string.Format("Division result = {0}", num1 / num2);
}
}
and in the WebApiConfig file you already have
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });
Just set the authentication / authorisation on IIS and you are done!
Hope this helps!
The printf
command will print the complete strings:
(gdb) printf "%s\n", string
http://repo.or.cz, while fairly good tends to have some issues with some users.
If you are one of them I recommend that you try out http://unfuddle.com since you come from a subversion background.
Check out "The 30 Second Tour": http://unfuddle.com/about/tour/plans
I had the same issue with UnitTestingProject, where in the MainProject I was using "System.Web.Mvc, Version=3.0.0.0" and in UnitTestingProject I was using "System.Web.Mvc, Version=3.0.0.1"
Change the following in the
<Reference Include="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.Mvc.3.0.50813.1\lib\net40\System.Web.Mvc.dll</HintPath>
</Reference>
1. Using the x509 module
openssl x509 ...
...
2 Using the ca module
openssl ca ...
...
You are missing the prelude to those commands.
This is a two-step process. First you set up your CA, and then you sign an end entity certificate (a.k.a server or user). Both of the two commands elide the two steps into one. And both assume you have a an OpenSSL configuration file already setup for both CAs and Server (end entity) certificates.
First, create a basic configuration file:
$ touch openssl-ca.cnf
Then, add the following to it:
HOME = .
RANDFILE = $ENV::HOME/.rnd
####################################################################
[ ca ]
default_ca = CA_default # The default ca section
[ CA_default ]
default_days = 1000 # How long to certify for
default_crl_days = 30 # How long before next CRL
default_md = sha256 # Use public key default MD
preserve = no # Keep passed DN ordering
x509_extensions = ca_extensions # The extensions to add to the cert
email_in_dn = no # Don't concat the email in the DN
copy_extensions = copy # Required to copy SANs from CSR to cert
####################################################################
[ req ]
default_bits = 4096
default_keyfile = cakey.pem
distinguished_name = ca_distinguished_name
x509_extensions = ca_extensions
string_mask = utf8only
####################################################################
[ ca_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = US
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = Maryland
localityName = Locality Name (eg, city)
localityName_default = Baltimore
organizationName = Organization Name (eg, company)
organizationName_default = Test CA, Limited
organizationalUnitName = Organizational Unit (eg, division)
organizationalUnitName_default = Server Research Department
commonName = Common Name (e.g. server FQDN or YOUR name)
commonName_default = Test CA
emailAddress = Email Address
emailAddress_default = [email protected]
####################################################################
[ ca_extensions ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always, issuer
basicConstraints = critical, CA:true
keyUsage = keyCertSign, cRLSign
The fields above are taken from a more complex openssl.cnf
(you can find it in /usr/lib/openssl.cnf
), but I think they are the essentials for creating the CA certificate and private key.
Tweak the fields above to suit your taste. The defaults save you the time from entering the same information while experimenting with configuration file and command options.
I omitted the CRL-relevant stuff, but your CA operations should have them. See openssl.cnf
and the related crl_ext
section.
Then, execute the following. The -nodes
omits the password or passphrase so you can examine the certificate. It's a really bad idea to omit the password or passphrase.
$ openssl req -x509 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM
After the command executes, cacert.pem
will be your certificate for CA operations, and cakey.pem
will be the private key. Recall the private key does not have a password or passphrase.
You can dump the certificate with the following.
$ openssl x509 -in cacert.pem -text -noout
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 11485830970703032316 (0x9f65de69ceef2ffc)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=US, ST=MD, L=Baltimore, CN=Test CA/[email protected]
Validity
Not Before: Jan 24 14:24:11 2014 GMT
Not After : Feb 23 14:24:11 2014 GMT
Subject: C=US, ST=MD, L=Baltimore, CN=Test CA/[email protected]
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (4096 bit)
Modulus:
00:b1:7f:29:be:78:02:b8:56:54:2d:2c:ec:ff:6d:
...
39:f9:1e:52:cb:8e:bf:8b:9e:a6:93:e1:22:09:8b:
59:05:9f
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Key Identifier:
4A:9A:F3:10:9E:D7:CF:54:79:DE:46:75:7A:B0:D0:C1:0F:CF:C1:8A
X509v3 Authority Key Identifier:
keyid:4A:9A:F3:10:9E:D7:CF:54:79:DE:46:75:7A:B0:D0:C1:0F:CF:C1:8A
X509v3 Basic Constraints: critical
CA:TRUE
X509v3 Key Usage:
Certificate Sign, CRL Sign
Signature Algorithm: sha256WithRSAEncryption
4a:6f:1f:ac:fd:fb:1e:a4:6d:08:eb:f5:af:f6:1e:48:a5:c7:
...
cd:c6:ac:30:f9:15:83:41:c1:d1:20:fa:85:e7:4f:35:8f:b5:
38:ff:fd:55:68:2c:3e:37
And test its purpose with the following (don't worry about the Any Purpose: Yes
; see "critical,CA:FALSE" but "Any Purpose CA : Yes").
$ openssl x509 -purpose -in cacert.pem -inform PEM
Certificate purposes:
SSL client : No
SSL client CA : Yes
SSL server : No
SSL server CA : Yes
Netscape SSL server : No
Netscape SSL server CA : Yes
S/MIME signing : No
S/MIME signing CA : Yes
S/MIME encryption : No
S/MIME encryption CA : Yes
CRL signing : Yes
CRL signing CA : Yes
Any Purpose : Yes
Any Purpose CA : Yes
OCSP helper : Yes
OCSP helper CA : Yes
Time Stamp signing : No
Time Stamp signing CA : Yes
-----BEGIN CERTIFICATE-----
MIIFpTCCA42gAwIBAgIJAJ9l3mnO7y/8MA0GCSqGSIb3DQEBCwUAMGExCzAJBgNV
...
aQUtFrV4hpmJUaQZ7ySr/RjCb4KYkQpTkOtKJOU1Ic3GrDD5FYNBwdEg+oXnTzWP
tTj//VVoLD43
-----END CERTIFICATE-----
For part two, I'm going to create another configuration file that's easily digestible. First, touch
the openssl-server.cnf
(you can make one of these for user certificates also).
$ touch openssl-server.cnf
Then open it, and add the following.
HOME = .
RANDFILE = $ENV::HOME/.rnd
####################################################################
[ req ]
default_bits = 2048
default_keyfile = serverkey.pem
distinguished_name = server_distinguished_name
req_extensions = server_req_extensions
string_mask = utf8only
####################################################################
[ server_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = US
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = MD
localityName = Locality Name (eg, city)
localityName_default = Baltimore
organizationName = Organization Name (eg, company)
organizationName_default = Test Server, Limited
commonName = Common Name (e.g. server FQDN or YOUR name)
commonName_default = Test Server
emailAddress = Email Address
emailAddress_default = [email protected]
####################################################################
[ server_req_extensions ]
subjectKeyIdentifier = hash
basicConstraints = CA:FALSE
keyUsage = digitalSignature, keyEncipherment
subjectAltName = @alternate_names
nsComment = "OpenSSL Generated Certificate"
####################################################################
[ alternate_names ]
DNS.1 = example.com
DNS.2 = www.example.com
DNS.3 = mail.example.com
DNS.4 = ftp.example.com
If you are developing and need to use your workstation as a server, then you may need to do the following for Chrome. Otherwise Chrome may complain a Common Name is invalid (ERR_CERT_COMMON_NAME_INVALID
). I'm not sure what the relationship is between an IP address in the SAN and a CN in this instance.
# IPv4 localhost
IP.1 = 127.0.0.1
# IPv6 localhost
IP.2 = ::1
Then, create the server certificate request. Be sure to omit -x509
*. Adding -x509
will create a certificate, and not a request.
$ openssl req -config openssl-server.cnf -newkey rsa:2048 -sha256 -nodes -out servercert.csr -outform PEM
After this command executes, you will have a request in servercert.csr
and a private key in serverkey.pem
.
And you can inspect it again.
$ openssl req -text -noout -verify -in servercert.csr
Certificate:
verify OK
Certificate Request:
Version: 0 (0x0)
Subject: C=US, ST=MD, L=Baltimore, CN=Test Server/[email protected]
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (2048 bit)
Modulus:
00:ce:3d:58:7f:a0:59:92:aa:7c:a0:82:dc:c9:6d:
...
f9:5e:0c:ba:84:eb:27:0d:d9:e7:22:5d:fe:e5:51:
86:e1
Exponent: 65537 (0x10001)
Attributes:
Requested Extensions:
X509v3 Subject Key Identifier:
1F:09:EF:79:9A:73:36:C1:80:52:60:2D:03:53:C7:B6:BD:63:3B:61
X509v3 Basic Constraints:
CA:FALSE
X509v3 Key Usage:
Digital Signature, Key Encipherment
X509v3 Subject Alternative Name:
DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
Netscape Comment:
OpenSSL Generated Certificate
Signature Algorithm: sha256WithRSAEncryption
6d:e8:d3:85:b3:88:d4:1a:80:9e:67:0d:37:46:db:4d:9a:81:
...
76:6a:22:0a:41:45:1f:e2:d6:e4:8f:a1:ca:de:e5:69:98:88:
a9:63:d0:a7
Next, you have to sign it with your CA.
You are almost ready to sign the server's certificate by your CA. The CA's openssl-ca.cnf
needs two more sections before issuing the command.
First, open openssl-ca.cnf
and add the following two sections.
####################################################################
[ signing_policy ]
countryName = optional
stateOrProvinceName = optional
localityName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
####################################################################
[ signing_req ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
basicConstraints = CA:FALSE
keyUsage = digitalSignature, keyEncipherment
Second, add the following to the [ CA_default ]
section of openssl-ca.cnf
. I left them out earlier, because they can complicate things (they were unused at the time). Now you'll see how they are used, so hopefully they will make sense.
base_dir = .
certificate = $base_dir/cacert.pem # The CA certifcate
private_key = $base_dir/cakey.pem # The CA private key
new_certs_dir = $base_dir # Location for new certs after signing
database = $base_dir/index.txt # Database index file
serial = $base_dir/serial.txt # The current serial number
unique_subject = no # Set to 'no' to allow creation of
# several certificates with same subject.
Third, touch index.txt
and serial.txt
:
$ touch index.txt
$ echo '01' > serial.txt
Then, perform the following:
$ openssl ca -config openssl-ca.cnf -policy signing_policy -extensions signing_req -out servercert.pem -infiles servercert.csr
You should see similar to the following:
Using configuration from openssl-ca.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName :PRINTABLE:'US'
stateOrProvinceName :ASN.1 12:'MD'
localityName :ASN.1 12:'Baltimore'
commonName :ASN.1 12:'Test CA'
emailAddress :IA5STRING:'[email protected]'
Certificate is to be certified until Oct 20 16:12:39 2016 GMT (1000 days)
Sign the certificate? [y/n]:Y
1 out of 1 certificate requests certified, commit? [y/n]Y
Write out database with 1 new entries
Data Base Updated
After the command executes, you will have a freshly minted server certificate in servercert.pem
. The private key was created earlier and is available in serverkey.pem
.
Finally, you can inspect your freshly minted certificate with the following:
$ openssl x509 -in servercert.pem -text -noout
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 9 (0x9)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=US, ST=MD, L=Baltimore, CN=Test CA/[email protected]
Validity
Not Before: Jan 24 19:07:36 2014 GMT
Not After : Oct 20 19:07:36 2016 GMT
Subject: C=US, ST=MD, L=Baltimore, CN=Test Server
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (2048 bit)
Modulus:
00:ce:3d:58:7f:a0:59:92:aa:7c:a0:82:dc:c9:6d:
...
f9:5e:0c:ba:84:eb:27:0d:d9:e7:22:5d:fe:e5:51:
86:e1
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Key Identifier:
1F:09:EF:79:9A:73:36:C1:80:52:60:2D:03:53:C7:B6:BD:63:3B:61
X509v3 Authority Key Identifier:
keyid:42:15:F2:CA:9C:B1:BB:F5:4C:2C:66:27:DA:6D:2E:5F:BA:0F:C5:9E
X509v3 Basic Constraints:
CA:FALSE
X509v3 Key Usage:
Digital Signature, Key Encipherment
X509v3 Subject Alternative Name:
DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
Netscape Comment:
OpenSSL Generated Certificate
Signature Algorithm: sha256WithRSAEncryption
b1:40:f6:34:f4:38:c8:57:d4:b6:08:f7:e2:71:12:6b:0e:4a:
...
45:71:06:a9:86:b6:0f:6d:8d:e1:c5:97:8d:fd:59:43:e9:3c:
56:a5:eb:c8:7e:9f:6b:7a
Earlier, you added the following to CA_default
: copy_extensions = copy
. This copies extension provided by the person making the request.
If you omit copy_extensions = copy
, then your server certificate will lack the Subject Alternate Names (SANs) like www.example.com
and mail.example.com
.
If you use copy_extensions = copy
, but don't look over the request, then the requester might be able to trick you into signing something like a subordinate root (rather than a server or user certificate). Which means he/she will be able to mint certificates that chain back to your trusted root. Be sure to verify the request with openssl req -verify
before signing.
If you omit unique_subject
or set it to yes
, then you will only be allowed to create one certificate under the subject's distinguished name.
unique_subject = yes # Set to 'no' to allow creation of
# several ctificates with same subject.
Trying to create a second certificate while experimenting will result in the following when signing your server's certificate with the CA's private key:
Sign the certificate? [y/n]:Y
failed to update database
TXT_DB error number 2
So unique_subject = no
is perfect for testing.
If you want to ensure the Organizational Name is consistent between self-signed CAs, Subordinate CA and End-Entity certificates, then add the following to your CA configuration files:
[ policy_match ]
organizationName = match
If you want to allow the Organizational Name to change, then use:
[ policy_match ]
organizationName = supplied
There are other rules concerning the handling of DNS names in X.509/PKIX certificates. Refer to these documents for the rules:
RFC 6797 and RFC 7469 are listed, because they are more restrictive than the other RFCs and CA/B documents. RFC's 6797 and 7469 do not allow an IP address, either.
As an alternative to using the import approach described in several answers, have a look a the configparser module.
The ConfigParser class implements a basic configuration file parser language which provides a structure similar to what you would find on Microsoft Windows INI files. You can use this to write Python programs which can be customized by end users easily.
VBA stands for Visual Basic For Applications and its a Visual Basic implementation intended to be used in the Office Suite.
The difference between them is that VBA is embedded inside Office documents (its an Office feature). VB is the ide/language for developing applications.
To me, it seems as if your actual intention is to put different words on different lines. But let me answer your first question:
JLabel lab=new JLabel("text");
lab.setHorizontalAlignment(SwingConstants.LEFT);
And if you have an image:
JLabel lab=new Jlabel("text");
lab.setIcon(new ImageIcon("path//img.png"));
lab.setHorizontalTextPosition(SwingConstants.LEFT);
But, I believe you want to make the label such that there are only 2 words on 1 line.
In that case try this:
String urText="<html>You can<br>use basic HTML<br>in Swing<br> components,"
+"Hope<br> I helped!";
JLabel lac=new JLabel(urText);
lac.setAlignmentX(Component.RIGHT_ALIGNMENT);
A simple example: We have the following array
li = [{"id":1,"name":"ronaldo"},{"id":2,"name":"messi"}]
Now, we want to find the object in the array that has id equal to 1
next
with list comprehensionnext(x for x in li if x["id"] == 1 )
[x for x in li if x["id"] == 1 ][0]
def find(arr , id):
for x in arr:
if x["id"] == id:
return x
find(li , 1)
Output all the above methods is {'id': 1, 'name': 'ronaldo'}
You can use plain javascript, this will call your_func once, after 5 seconds:
setTimeout(function() { your_func(); }, 5000);
If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)
There is also a plugin I've used once. It has oneTime
and everyTime
methods.
although not specifically addressed by this question, I would add that there's a very good reason not to ever use for...in with a NodeList
(as one would obtain from a querySelectorAll
call, as it doesn't see the returned elements at all, instead iterating only over the NodeList properties.
in the case of a single result, I got:
var nodes = document.querySelectorAll(selector);
nodes
? NodeList [a._19eb]
for (node in nodes) {console.log(node)};
VM505:1 0
VM505:1 length
VM505:1 item
VM505:1 entries
VM505:1 forEach
VM505:1 keys
VM505:1 values
which explained why my for (node in nodes) node.href = newLink;
was failing.
Not Material solution:
final double floatingButtonSize = 60;
final IconData floatingButtonIcon;
TouchableOpacity(
onTap: () {
/// Do something...
},
activeOpacity: 0.7,
child: Container(
height: floatingButtonSize,
width: floatingButtonSize,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(floatingButtonSize / 2),
color: Theme.of(context).primaryColor,
boxShadow: [
BoxShadow(
blurRadius: 25,
color: Colors.black.withOpacity(0.2),
offset: Offset(0, 10),
)
],
),
child: Icon(
floatingButtonIcon ?? Icons.add,
color: Colors.white,
),
),
)
You can use GestureDetector instead of TouchableOpacity library.
Not 100% sure what you mean:
Trusted_Connection=True;
IS using Windows credentials and is 100% equivalent to:
Integrated Security=SSPI;
or
Integrated Security=true;
If you don't want to use integrated security / trusted connection, you need to specify user id and password explicitly in the connection string (and leave out any reference to Trusted_Connection
or Integrated Security
)
server=yourservername;database=yourdatabase;user id=YourUser;pwd=TopSecret
Only in this case, the SQL Server authentication mode is used.
If any of these two settings is present (Trusted_Connection=true
or Integrated Security=true/SSPI
), then the Windows credentials of the current user are used to authenticate against SQL Server and any user iD=
setting will be ignored and not used.
For reference, see the Connection Strings site for SQL Server 2005 with lots of samples and explanations.
Using Windows Authentication is the preferred and recommended way of doing things, but it might incur a slight delay since SQL Server would have to authenticate your credentials against Active Directory (typically). I have no idea how much that slight delay might be, and I haven't found any references for that.
Summing up:
If you specify either Trusted_Connection=True;
or Integrated Security=SSPI;
or Integrated Security=true;
in your connection string
==> THEN (and only then) you have Windows Authentication happening. Any user id=
setting in the connection string will be ignored.
If you DO NOT specify either of those settings,
==> then you DO NOT have Windows Authentication happening (SQL Authentication mode will be used)
From the docs:-
Your app gradle file now has to explicitly list
com.google.firebase:firebase-core
as a dependency for Firebase services to work as expected.
Add:
implementation 'com.google.firebase:firebase-core:16.0.1'
and in top level gradle file use the latest version of google play services:
classpath 'com.google.gms:google-services:4.0.2'
https://firebase.google.com/support/release-notes/android
https://bintray.com/android/android-tools/com.google.gms.google-services
Note:
You need to add the google()
repo in the top level gradle file, as specified in the firebase docs and also it should be before jcenter()
:
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.3'
classpath 'com.google.gms:google-services:4.0.2'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Justin(above) is accurate. However, keep in mind that depending on who you get the certificate from (intermediate CA, root CA involved or not) or how the pfx is created/exported, sometimes they could be missing the certificate chain. After Import, You would have a certificate of PrivateKeyEntry type, but with a chain of length of 1.
To fix this, there are several options. The easier option in my mind is to import and export the pfx file in IE(choosing the option of Including all the certificates in the chain). The import and export process of certificates in IE should be very easy and well documented elsewhere.
Once exported, import the keystore as Justin pointed above. Now, you would have a keystore with certificate of type PrivateKeyEntry and with a certificate chain length of more than 1.
Certain .Net based Web service clients error out(unable to establish trust relationship), if you don't do the above.
Based on ExceptionLimeCat's answer, an improvement:
Color farbe;
string ph = "Placeholder-Text";
private void Form1_Load(object sender, EventArgs e)
{
farbe = myTxtbx.ForeColor;
myTxtbx.GotFocus += RemoveText;
myTxtbx.LostFocus += AddText;
myTxtbx.Text = ph;
}
public void RemoveText(object sender, EventArgs e)
{
myTxtbx.ForeColor = farbe;
if (myTxtbx.Text == ph)
myTxtbx.Text = "";
}
public void AddText(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(myTxtbx.Text))
{
myTxtbx.ForeColor = Color.Gray;
myTxtbx.Text = ph;
}
}
Uilabel code
var label: UILabel = UILabel()
label.frame = CGRectMake(50, 50, 200, 21)
label.backgroundColor = UIColor.blackColor()
label.textColor = UIColor.whiteColor()
label.textAlignment = NSTextAlignment.Center
label.text = "test label"
self.view.addSubview(label)
Here's a way to write watchers for nested properties:
new Vue({
...allYourOtherStuff,
watch: {
['foo.bar'](newValue, oldValue) {
// Do stuff here
}
}
});
You can even use this syntax for asynchronous watchers:
new Vue({
...allYourOtherStuff,
watch: {
async ['foo.bar'](newValue, oldValue) {
// Do stuff here
}
}
});
From man githooks
:
pre-commit
This hook is invoked by git commit, and can be bypassed with --no-verify option. It takes no parameter, and is invoked before obtaining the proposed commit log message and making a commit. Exiting with non-zero status from this script causes the git commit to abort.
Try pm2
to make your application run forever.
npm install -g pm2
and then use
pm2 start server.js
to list and stop apps, use commnds
pm2 list
pm2 stop 0
For me, it was very difficult to identify the problem because of a large number of methods and class involved.
What I did is commented (removed) some methods from the WebService interface and try, and then comment another bunch of methods and try, I kept doing this until I found the method that cause the problem.
In my case, it was using a complex object which cannot be serialized.
Good luck!
My problem was that the old assemblies were in the _bin_deployableAssemblies folder under the Web Application. This meant the old assemblies were overwriting the GAC assemblies when building the project.
With Protractor, you can use the following approach
var EC = protractor.ExpectedConditions;
// Wait for new page url to contain newPageName
browser.wait(EC.urlContains('newPageName'), 10000);
So your code will look something like,
emailEl.sendKeys('jack');
passwordEl.sendKeys('123pwd');
btnLoginEl.click();
var EC = protractor.ExpectedConditions;
// Wait for new page url to contain efg
ptor.wait(EC.urlContains('efg'), 10000);
expect(ptor.getCurrentUrl()).toEqual(url + 'abc#/efg');
Note: This may not mean that new page has finished loading and DOM is ready. The subsequent 'expect()' statement will ensure Protractor waits for DOM to be available for test.
Reference: Protractor ExpectedConditions
Try this code:
bool appNotRestarted = true;
This code must also be in the function:
if (appNotRestarted == true) {
appNotRestarted = false;
Application.Restart();
Application.ExitThread();
}
You can also get them with pure javascript.
For example:
new URL(location.href).searchParams.get('page')
For this url: websitename.com/user/?page=1, it would return a value of 1
Mockito can now mock constructors (since version 3.5.0) https://javadoc.io/static/org.mockito/mockito-core/3.5.13/org/mockito/Mockito.html#mocked_construction
try (MockedConstruction mocked = mockConstruction(Foo.class)) {
Foo foo = new Foo();
when(foo.method()).thenReturn("bar");
assertEquals("bar", foo.method());
verify(foo).method();
}
Chrome and Safari has a restriction on using ajax with local resources. That's why it's throwing an error like
Origin null is not allowed by Access-Control-Allow-Origin.
Solution: Use firefox or upload your data to a temporary server. If you still want to use Chrome, start it with the below option;
--allow-file-access-from-files
More info how to add the above parameter to your Chrome: Right click the Chrome icon on your task bar, right click the Google Chrome on the pop-up window and click properties and add the above parameter inside the Target textbox under Shortcut tab. It will like as below;
C:\Users\XXX_USER\AppData\Local\Google\Chrome\Application\chrome.exe --allow-file-access-from-files
Hope this will help!
That's a simple linear conversion.
new_value = ( (old_value - old_min) / (old_max - old_min) ) * (new_max - new_min) + new_min
So converting 10000 on the scale of -16000 to 16000 to a new scale of 0 to 100 yields:
old_value = 10000
old_min = -16000
old_max = 16000
new_min = 0
new_max = 100
new_value = ( ( 10000 - -16000 ) / (16000 - -16000) ) * (100 - 0) + 0
= 81.25
Adding on to @Alexandre Aimbiré
's answer - sometimes you may need to specify z-index:1
to have the element always on top while scrolling.
Like this:
position: -webkit-sticky; /* Safari & IE */
position: sticky;
top: 0;
z-index: 1;
Just make a comparison function/functor:
bool my_cmp(const data& a, const data& b)
{
// smallest comes first
return a.word.size() < b.word.size();
}
std::sort(info.begin(), info.end(), my_cmp);
Or provide an bool operator<(const data& a) const
in your data
class:
struct data {
string word;
int number;
bool operator<(const data& a) const
{
return word.size() < a.word.size();
}
};
or non-member as Fred said:
struct data {
string word;
int number;
};
bool operator<(const data& a, const data& b)
{
return a.word.size() < b.word.size();
}
and just call std::sort()
:
std::sort(info.begin(), info.end());
There is a way to create war file of your project from eclipse.
First a create an xml file with the following code,
Replace HistoryCheck with your project name.
<?xml version="1.0" encoding="UTF-8"?>
<project name="HistoryCheck" basedir="." default="default">
<target name="default" depends="buildwar,deploy"></target>
<target name="buildwar">
<war basedir="war" destfile="HistoryCheck.war" webxml="war/WEB-INF/web.xml">
<exclude name="WEB-INF/**" />
<webinf dir="war/WEB-INF/">
<include name="**/*.jar" />
</webinf>
</war>
</target>
<target name="deploy">
<copy file="HistoryCheck.war" todir="." />
</target>
</project>
Now, In project explorer right click on that xml file and Run as-> ant build
You can see the war file of your project in your project folder.
Use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit
<div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]">
{{$index}} - {{day.iso}} - {{day.name}}
Temperature: {{f.temperature}}<br>
Humidity: {{f.humidity}}<br>
...
</div>
Example: http://jsfiddle.net/coma/UV4qF/
simple way for make notifications
NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher) //icon
.setContentTitle("Test") //tittle
.setAutoCancel(true)//swipe for delete
.setContentText("Hello Hello"); //content
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build()
);
Check http://msdn.microsoft.com/en-us/library/dd203099.aspx
under Cryptography Application Block.
Don't know if you will get your answer, but it's worth a try.
Edit after Comment.
Ok then check this code.
using System.Security.Cryptography;
public static string DecryptEncryptedData(stringBase64EncryptedData, stringPathToPrivateKeyFile) {
X509Certificate2 myCertificate;
try{
myCertificate = new X509Certificate2(PathToPrivateKeyFile);
} catch{
throw new CryptographicException("Unable to open key file.");
}
RSACryptoServiceProvider rsaObj;
if(myCertificate.HasPrivateKey) {
rsaObj = (RSACryptoServiceProvider)myCertificate.PrivateKey;
} else
throw new CryptographicException("Private key not contained within certificate.");
if(rsaObj == null)
return String.Empty;
byte[] decryptedBytes;
try{
decryptedBytes = rsaObj.Decrypt(Convert.FromBase64String(Base64EncryptedData), false);
} catch {
throw new CryptographicException("Unable to decrypt data.");
}
// Check to make sure we decrpyted the string
if(decryptedBytes.Length == 0)
return String.Empty;
else
return System.Text.Encoding.UTF8.GetString(decryptedBytes);
}
netstat -b -a
lists the ports in use and gives you the executable that's using each one. I believe you need to be in the administrator group to do this, and I don't know what security implications there are on Vista.
I usually add -n
as well to make it a little faster, but adding -b
can make it quite slow.
Edit: If you need more functionality than netstat provides, vasac suggests that you try TCPView.
Bootstrap 3 now has a built-in class for this .center-block
.center-block {
display: block;
margin-left: auto;
margin-right: auto;
}
If you are still using 2.X then just add this to your CSS.
Don't know how I got to this question, but even if it's many years since this has been asked, I would like to add a quick and simple method I follow and it has never let me down:
var num = response_from_a_function_or_something();
var fixedNum = parseFloat(num).toFixed( 2 );
try this:
String str = "9B7D2C34A366BF890C730641E6CECF6F";
String[] temp = str.split(",");
bytesArray = new byte[temp.length];
int index = 0;
for (String item: temp) {
bytesArray[index] = Byte.parseByte(item);
index++;
}
As of Python 3.6 (2016) you can use f-strings to substitute variables:
>>> origin = "London"
>>> destination = "Paris"
>>> f"from {origin} to {destination}"
'from London to Paris'
Note the f"
prefix. If you try this in Python 3.5 or earlier, you'll get a SyntaxError
.
See https://docs.python.org/3.6/reference/lexical_analysis.html#f-strings
I wouldn't set the ngmodel via an attribute, you can specify it right in the template:
template: '<div class="some"><label>{{label}}</label><input data-ng-model="ngModel"></div>',
For anyone that this might be handy for, here is a jQuery dependent function I had success with for applying a CSS animation via a CSS class, then getting a callback from afterwards. It may not work perfectly since I had it being used in a Backbone.js App, but maybe useful.
var cssAnimate = function(cssClass, callback) {
var self = this;
// Checks if correct animation has ended
var setAnimationListener = function() {
self.one(
"webkitAnimationEnd oanimationend msAnimationEnd animationend",
function(e) {
if(
e.originalEvent.animationName == cssClass &&
e.target === e.currentTarget
) {
callback();
} else {
setAnimationListener();
}
}
);
}
self.addClass(cssClass);
setAnimationListener();
}
I used it kinda like this
cssAnimate.call($("#something"), "fadeIn", function() {
console.log("Animation is complete");
// Remove animation class name?
});
Original idea from http://mikefowler.me/2013/11/18/page-transitions-in-backbone/
And this seems handy: http://api.jqueryui.com/addClass/
Update
After struggling with the above code and other options, I would suggest being very cautious with any listening for CSS animation ends. With multiple animations going on, this can get messy very fast for event listening. I would strongly suggest an animation library like GSAP for every animation, even the small ones.
Also for eg. you can use IPC::Run:
use IPC::Run qw(run);
my $pid = 5892;
run [qw(top -H -n 1 -p), $pid],
'|', sub { print grep { /myprocess/ } <STDIN> },
'|', [qw(wc -l)],
'>', \my $out;
print $out;
Yep:
WITH tab (
bla bla
)
INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos ( BatchID, AccountNo,
APartyNo,
SourceRowID)
SELECT * FROM tab
Note that this is for SQL Server, which supports multiple CTEs:
WITH x AS (), y AS () INSERT INTO z (a, b, c) SELECT a, b, c FROM y
Teradata allows only one CTE and the syntax is as your example.
In my case it was a connection problem. I was connected to an internal wifi network, in which I had limited access to ressources. That was letting git do the fetch but at a certain time it crashed. This means it can be a network-connection problem. Check if everything is running properly: Antivirus, Firewall, etc.
The answer of elin3t is therefore important because ssh improves the performance of the downloading so that network problems can be avoided
While Loop is an obsolete structure, I would recommend you to replace "While loop" to "Do While..loop", and you will able to use Exit clause.
check = 0
Do while not rs.EOF
if rs("reg_code") = rcode then
check = 1
Response.Write ("Found")
Exit do
else
rs.MoveNext
end if
Loop
if check = 0 then
Response.Write "Not Found"
end if}
This solution supports tab, backspace, enter, minus in intuitive way
<input type=text onkeypress="return /^-?[0-9]*$/.test(this.value+event.key)">
_x000D_
however it not allow to change already typed number to minus and not handle copy-paste case.
As alternative you can use solution based on R. Yaghoobi answer which allow to put minus and handle copy-paste case, but it delete whole number when user type forbidden character
<input type=text oninput="this.value= ['','-'].includes(this.value) ? this.value : this.value|0">
_x000D_
Use r.URL.Query()
when you appending to existing query, if you are building new set of params use the url.Values
struct like so
package main
import (
"fmt"
"log"
"net/http"
"net/url"
"os"
)
func main() {
req, err := http.NewRequest("GET","http://api.themoviedb.org/3/tv/popular", nil)
if err != nil {
log.Print(err)
os.Exit(1)
}
// if you appending to existing query this works fine
q := req.URL.Query()
q.Add("api_key", "key_from_environment_or_flag")
q.Add("another_thing", "foo & bar")
// or you can create new url.Values struct and encode that like so
q := url.Values{}
q.Add("api_key", "key_from_environment_or_flag")
q.Add("another_thing", "foo & bar")
req.URL.RawQuery = q.Encode()
fmt.Println(req.URL.String())
// Output:
// http://api.themoviedb.org/3/tv/popularanother_thing=foo+%26+bar&api_key=key_from_environment_or_flag
}
You can use the Gson library for parsing
void getJson() throws IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("some url of json");
HttpResponse httpResponse = httpClient.execute(httpGet);
String response = EntityUtils.toString(httpResponse.getEntity());
Gson gson = new Gson();
MyClass myClassObj = gson.fromJson(response, MyClass.class);
}
here is sample json file which is fetchd from server
{
"id":5,
"name":"kitkat",
"version":"4.4"
}
here is my class
class MyClass{
int id;
String name;
String version;
}
refer this
$data = '+11234567890';
if( preg_match( '/^\+\d(\d{3})(\d{3})(\d{4})$/', $data, $matches ) )
{
$result = $matches[1] . '-' .$matches[2] . '-' . $matches[3];
return $result;
}
It looks like you are passing an NSString
parameter where you should be passing an NSData
parameter:
NSError *jsonError;
NSData *objectData = [@"{\"2\":\"3\"}" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
OK, so this is a little bit more complex then a simple regex, but it allows for different types of urls.
Examples:
All which should be marked as valid.
function is_valid_url($url) {
// First check: is the url just a domain name? (allow a slash at the end)
$_domain_regex = "|^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,})/?$|";
if (preg_match($_domain_regex, $url)) {
return true;
}
// Second: Check if it's a url with a scheme and all
$_regex = '#^([a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))$#';
if (preg_match($_regex, $url, $matches)) {
// pull out the domain name, and make sure that the domain is valid.
$_parts = parse_url($url);
if (!in_array($_parts['scheme'], array( 'http', 'https' )))
return false;
// Check the domain using the regex, stops domains like "-example.com" passing through
if (!preg_match($_domain_regex, $_parts['host']))
return false;
// This domain looks pretty valid. Only way to check it now is to download it!
return true;
}
return false;
}
Note that there is a in_array check for the protocols that you want to allow (currently only http and https are in that list).
var_dump(is_valid_url('google.com')); // true
var_dump(is_valid_url('google.com/')); // true
var_dump(is_valid_url('http://google.com')); // true
var_dump(is_valid_url('http://google.com/')); // true
var_dump(is_valid_url('https://google.com')); // true
git pull
is really equivalent to running git fetch
and then git merge
. The git fetch
updates your so-called "remote-tracking branches" - typically these are ones that look like origin/master
, github/experiment
, etc. that you see with git branch -r
. These are like a cache of the state of branches in the remote repository that are updated when you do git fetch
(or a successful git push
).
So, suppose you've got a remote called origin
that refers to your GitHub repository, you would do:
git fetch origin
... and then do:
git diff master origin/master
... in order to see the difference between your master
, and the one on GitHub. If you're happy with those differences, you can merge them in with git merge origin/master
, assuming master
is your current branch.
Personally, I think that doing git fetch
and git merge
separately is generally a good idea.
The heap is the place in memory where your dynamically allocated objects live. If you used new
then it's on the heap. That's as opposed to stack space, which is where the function stack lives. If you have a local variable then that reference is on the stack.
Java's heap is subject to garbage collection and the objects are usable directly.
EHCache's off-heap storage takes your regular object off the heap, serializes it, and stores it as bytes in a chunk of memory that EHCache manages. It's like storing it to disk but it's still in RAM. The objects are not directly usable in this state, they have to be deserialized first. Also not subject to garbage collection.
I have had same problem with my scripts. But when I did some modifications it worked for me. I did like this :-
export k=$(date "+%k");
if [ $k -ge 16 ]
then exit 0;
else
echo "good job for nothing";
fi;
that way I resolved my problem. Hope that will help for you too.
In your Execute SQL Task, make sure SQLSourceType is set to Direct Input, then your SQL Statement is the name of the stored proc, with questionmarks for each paramter of the proc, like so:
Click the parameter mapping in the left column and add each paramter from your stored proc and map it to your SSIS variable:
Now when this task runs it will pass the SSIS variables to the stored proc.
If this still isn't working try unchecking "Enable Protected Mode" in IE.
Add your site to Local Intranet in
Tools -> Internet Option -> Security Tab
Then uncheck "Enable Protected Mode"
Restart IE
The official MS line is "because it's not a functional operation" (ie it's a stateful operation).
Couldn't you do something like:
list.Select( x => x+1 )
or if you really need it in a List:
var someValues = new List<int>( list.Select( x => x+1 ) );
Jeff has a post about it, otherwise I found some useful documents on Apple's website, in Cocoa tutorials (this one for example).
My path of -javaagent argument was having Spacial characters like '&'. I placed the Lambok jar in different place and gave the path to that place. It worked for me.
previously it was
-javaagent:C:\Software & Tool\lambok.jar
i changed it to
-javaagent:C:\Labmok\lambok.jar
end(...[explode('.', $file_name)])
has worked since PHP 5.6. This is documented in the RFC although not in PHP docs themselves.
What’s the difference between compiled and interpreted language?
The difference is not in the language; it is in the implementation.
Having got that out of my system, here's an answer:
In a compiled implementation, the original program is translated into native machine instructions, which are executed directly by the hardware.
In an interpreted implementation, the original program is translated into something else. Another program, called "the interpreter", then examines "something else" and performs whatever actions are called for. Depending on the language and its implementation, there are a variety of forms of "something else". From more popular to less popular, "something else" might be
Binary instructions for a virtual machine, often called bytecode, as is done in Lua, Python, Ruby, Smalltalk, and many other systems (the approach was popularized in the 1970s by the UCSD P-system and UCSD Pascal)
A tree-like representation of the original program, such as an abstract-syntax tree, as is done for many prototype or educational interpreters
A tokenized representation of the source program, similar to Tcl
The characters of the source program, as was done in MINT and TRAC
One thing that complicates the issue is that it is possible to translate (compile) bytecode into native machine instructions. Thus, a successful intepreted implementation might eventually acquire a compiler. If the compiler runs dynamically, behind the scenes, it is often called a just-in-time compiler or JIT compiler. JITs have been developed for Java, JavaScript, Lua, and I daresay many other languages. At that point you can have a hybrid implementation in which some code is interpreted and some code is compiled.
Usually number validation is done with regular expressions. This code will determine if something is numeric as well as check for undefined variables as to not throw warnings:
sub is_integer {
defined $_[0] && $_[0] =~ /^[+-]?\d+$/;
}
sub is_float {
defined $_[0] && $_[0] =~ /^[+-]?\d+(\.\d+)?$/;
}
Here's some reading material you should look at.
System.getProperty("user.name")
A simple method
private boolean isValidEmail(String email)
{
String emailRegex ="^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
if(email.matches(emailRegex))
{
return true;
}
return false;
}
http://dev.mysql.com/doc/refman/5.0/en/insert-select.html
For case1:
INSERT INTO TAB_STUDENT(name_student, id_teacher_fk)
SELECT 'Joe The Student', id_teacher
FROM TAB_TEACHER
WHERE name_teacher = 'Professor Jack'
LIMIT 1
For case2 you just have to do 2 separate insert statements
You could use an image submit button:
<input type="image" src="images/login.jpg" alt="Submit Form" />
PowerShell code to find all document library files modified from last 2 days.
$web = Get-SPWeb -Identity http://siteName:9090/
$list = $web.GetList("http://siteName:9090/Style Library/")
$folderquery = New-Object Microsoft.SharePoint.SPQuery
$foldercamlQuery =
'<Where> <Eq>
<FieldRef Name="ContentType" /> <Value Type="text">Folder</Value>
</Eq> </Where>'
$folderquery.Query = $foldercamlQuery
$folders = $list.GetItems($folderquery)
foreach($folderItem in $folders)
{
$folder = $folderItem.Folder
if($folder.ItemCount -gt 0){
Write-Host " find Item count " $folder.ItemCount
$oldest = $null
$files = $folder.Files
$date = (Get-Date).AddDays(-2).ToString(“MM/dd/yyyy”)
foreach ($file in $files){
if($file.Item["Modified"]-Ge $date)
{
Write-Host "Last 2 days modified folder name:" $folder " File Name: " $file.Item["Name"] " Date of midified: " $file.Item["Modified"]
}
}
}
else
{
Write-Warning "$folder['Name'] is empty"
}
}
According to the curl man page:
You can specify any amount of URLs on the command line. They will be fetched in a sequential manner in the specified order.
So the simplest and most efficient (curl will send them all down a single TCP connection [those to the same origin]) approach would be put them all on a single invocation of curl e.g.:
curl http://example.com/?update_=1 http://example.com/?update_=2
Here are some guideline steps...
Give this a go and if you get stuck then come back and ask more specific questions relating to your problems
For Add and Remove ViewController
var secondViewController :SecondViewController?
// Adding
func add_ViewController() {
let controller = self.storyboard?.instantiateViewController(withIdentifier: "secondViewController")as! SecondViewController
controller.view.frame = self.view.bounds
self.view.addSubview(controller.view)
self.addChild(controller)
controller.didMove(toParent: self)
self.secondViewController = controller
}
// Removing
func remove_ViewController(secondViewController:SecondViewController?) {
if secondViewController != nil {
if self.view.subviews.contains(secondViewController!.view) {
secondViewController!.view.removeFromSuperview()
}
}
}
I think the biggest confusion is that xml namespace is pointing to some kind of URL that doesn't have any information. But the truth is that the person who invented below namespace:
xmlns:android="http://schemas.android.com/apk/res/android"
could also call it like that:
xmlns:android="asjkl;fhgaslifujhaslkfjhliuqwhrqwjlrknqwljk.rho;il"
This is just a unique identifier. However it is established that you should put there URL that is unique and can potentially point to the specification of used tags/attributes in that namespace. It's not required tho.
Why it should be unique? Because namespaces purpose is to have them unique so the attribute for example called background from your namespace can be distinguished from the background from another namespace.
Because of that uniqueness you do not need to worry that if you create your custom attribute you gonna have name collision.
For me it was a ternary statement:
It was complaining about this line in particular, about the semicolon:
let num_coin = val.num_coin ? val.num_coin || 2;
I changed it to:
let num_coin = val.num_coin || 2;
Found another case which results in bloody Certificate has either expired or has been revoked
error in Xcode 9
. If you're trying to sign with valid certificate but you do have another revoked certificate in the same team on your keychain, Xcode throws this error. To check if you do have revoked certificate see Xcode -> Preferences -> Accounts -> Your Apple ID -> Your Team -> Manage Certificates
. Deleting revoked certificate with Keychain Access
solves this. Looks like another code sign bug in Xcode.
Use the following code it worked for me:
# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Generate the values
x_vals = X_iso[:, 0:1]
y_vals = X_iso[:, 1:2]
z_vals = X_iso[:, 2:3]
# Plot the values
ax.scatter(x_vals, y_vals, z_vals, c = 'b', marker='o')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
plt.show()
while X_iso is my 3-D array and for X_vals, Y_vals, Z_vals I copied/used 1 column/axis from that array and assigned to those variables/arrays respectively.
This works too:
System.DateTime dTime = DateTime.Now();
// tSpan is 0 days, 1 hours, 30 minutes and 0 second.
System.TimeSpan tSpan = new System.TimeSpan(0, 1, 3, 0);
System.DateTime result = dTime + tSpan;
To subtract a year:
DateTime DateEnd = DateTime.Now;
DateTime DateStart = DateEnd - new TimeSpan(365, 0, 0, 0);
You can create a small class to hold the key and value, and then store objects of that class in the collection.
Class KeyValue:
Public key As String
Public value As String
Public Sub Init(k As String, v As String)
key = k
value = v
End Sub
Then to use it:
Public Sub Test()
Dim col As Collection, kv As KeyValue
Set col = New Collection
Store col, "first key", "first string"
Store col, "second key", "second string"
Store col, "third key", "third string"
For Each kv In col
Debug.Print kv.key, kv.value
Next kv
End Sub
Private Sub Store(col As Collection, k As String, v As String)
If (Contains(col, k)) Then
Set kv = col(k)
kv.value = v
Else
Set kv = New KeyValue
kv.Init k, v
col.Add kv, k
End If
End Sub
Private Function Contains(col As Collection, key As String) As Boolean
On Error GoTo NotFound
Dim itm As Object
Set itm = col(key)
Contains = True
MyExit:
Exit Function
NotFound:
Contains = False
Resume MyExit
End Function
This is of course similar to the Dictionary suggestion, except without any external dependencies. The class can be made more complex as needed if you want to store more information.
Recently I am working with the 1.8.0_25 JDK version on Windows 8.1 and I had the same problem with this. But as PankaJ Jakhar said
The real solution for me was pretty simple:
The path I introduced for this variable was:
C:\Program Files\Java\jdk1.8.0_25\
And it works for me!
For the GET parameters there are two alternatives:
First: As suggested in a comment bellow the question you can just use String and replace the parameters placeholders with their values like:
String uri = String.format("http://somesite.com/some_endpoint.php?param1=%1$s¶m2=%2$s",
num1,
num2);
StringRequest myReq = new StringRequest(Method.GET,
uri,
createMyReqSuccessListener(),
createMyReqErrorListener());
queue.add(myReq);
where num1 and num2 are String variables that contain your values.
Second: If you are using newer external HttpClient (4.2.x for example) you can use URIBuilder to build your Uri. Advantage is that if your uri string already has parameters in it it will be easier to pass it to the URIBuilder
and then use ub.setQuery(URLEncodedUtils.format(getGetParams(), "UTF-8"));
to add your additional parameters. That way you will not bother to check if "?" is already added to the uri or to miss some & thus eliminating a source for potential errors.
For the POST parameters probably sometimes will be easier than the accepted answer to do it like:
StringRequest myReq = new StringRequest(Method.POST,
"http://somesite.com/some_endpoint.php",
createMyReqSuccessListener(),
createMyReqErrorListener()) {
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("param1", num1);
params.put("param2", num2);
return params;
};
};
queue.add(myReq);
e.g. to just override the getParams()
method.
You can find a working example (along with many other basic Volley examples) in the Andorid Volley Examples project.
I found this multidrop-down menu which work great in all device.
Also, have hover style
It supports multi-level submenus with bootstrap 4.
$( document ).ready( function () {_x000D_
$( '.navbar a.dropdown-toggle' ).on( 'click', function ( e ) {_x000D_
var $el = $( this );_x000D_
var $parent = $( this ).offsetParent( ".dropdown-menu" );_x000D_
$( this ).parent( "li" ).toggleClass( 'show' );_x000D_
_x000D_
if ( !$parent.parent().hasClass( 'navbar-nav' ) ) {_x000D_
$el.next().css( { "top": $el[0].offsetTop, "left": $parent.outerWidth() - 4 } );_x000D_
}_x000D_
$( '.navbar-nav li.show' ).not( $( this ).parents( "li" ) ).removeClass( "show" );_x000D_
return false;_x000D_
} );_x000D_
} );
_x000D_
.navbar-light .navbar-nav .nav-link {_x000D_
color: rgb(64, 64, 64);_x000D_
}_x000D_
.btco-menu li > a {_x000D_
padding: 10px 15px;_x000D_
color: #000;_x000D_
}_x000D_
_x000D_
.btco-menu .active a:focus,_x000D_
.btco-menu li a:focus ,_x000D_
.navbar > .show > a:focus{_x000D_
background: transparent;_x000D_
outline: 0;_x000D_
}_x000D_
_x000D_
.dropdown-menu .show > .dropdown-toggle::after{_x000D_
transform: rotate(-90deg);_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded btco-menu">_x000D_
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">Navbar</a>_x000D_
<div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
<ul class="navbar-nav">_x000D_
<li class="nav-item active">_x000D_
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Features</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Pricing</a>_x000D_
</li>_x000D_
<li class="nav-item dropdown">_x000D_
<a class="nav-link dropdown-toggle" href="https://bootstrapthemes.co" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown link</a>_x000D_
<ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
<li><a class="dropdown-item" href="#">Action</a></li>_x000D_
<li><a class="dropdown-item" href="#">Another action</a></li>_x000D_
<li><a class="dropdown-item dropdown-toggle" href="#">Submenu</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a class="dropdown-item" href="#">Submenu action</a></li>_x000D_
<li><a class="dropdown-item" href="#">Another submenu action</a></li>_x000D_
_x000D_
<li><a class="dropdown-item dropdown-toggle" href="#">Subsubmenu</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
<li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a class="dropdown-item dropdown-toggle" href="#">Second subsubmenu</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
<li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
</nav>
_x000D_
Try subtracting the first Time.now from the second. Like so:
a = Time.now
sleep(3)
puts Time.now - a # about 3.0
This gives you a floating-point number of the seconds between the two times (and with that, the milliseconds).
It is always C:\Windows\System32\WindowsPowershell\v1.0. It was left like that for backward compability is what I heard or read somewhere.
According to the latest documentation about PyMongo titled Insert a Document (insert is deprecated) and following defensive approach, you should insert and update as follows:
result = mycollection.insert_one(post)
post = mycollection.find_one({'_id': result.inserted_id})
if post is not None:
post['newfield'] = "abc"
mycollection.save(post)