Additional to Jerry Coffin's first paragraph. Ie, ARM design gives lower power consumption.
The company ARM
, only licenses the CPU technology. They don't make physical chips. This allows other companies to add various peripheral technologies, typically called SOC or system-on-chip. Whether the device is a tablet, a cell phone, or an in-car entertainment system. This allows chip vendors to tailor the rest of the chip to a particular application. This has additional benefits,
ARM
supports SOC vendors with AMBA, allowing SOC implementers to purchase off the shelf 3rd party modules; like an Ethernet, memory and interrupt controllers. Some other CPU platforms support this, like MIPS, but MIPS is not as power conscious.
All of these are beneficial to a handheld/battery operated design. Some are just good all around. As well, ARM
has a history of battery operated devices; Apple Newton, Psion Organizers. The PDA software infra-structure was leveraged by some companies to create smart phone type devices. Although, more success was had by those who re-invented the GUI for use with a smart phone.
The rise of Open source
tool sets and operating systems
also facilitated the various SOC
chips. A closed organization would have issues trying to support all the various devices available for the ARM. The two most popular cellular platforms, Andriod and OSx/IOS, are based up Linux and FreeBSD, Mach and NetBSD os's. Open Source
helps SOC
vendors provide software support for their chip sets.
Hopefully, why x86 is used for the keyboard is self-evident. It has the software, and more importantly people trained to use that software. Netwinder is one ARM
system that was originally designed for the keyboard. Also, manufacturer's are currently looking at ARM64 for the server market. Power/heat is a concern at 24/7 data centers.
So I would say that the ecosystem that grows around these chips is as important as features like low power consumption. ARM
has been striving for low power, higher performance computing for some time (mid to late 1980's) and they have a lot of people on board.
Note1: Multiple chips need bus drivers to inter-communicate at known voltages and drive. Also, typically separate chips need support capacitors and other power components which can be shared in an SOC system.
In Eclipse, go to Window → Preferences → General → Network Connections. In the Active Provider combo box, choose "Manual". In the proxy entries table, for each entry click "Edit..." and supply your proxy host, port, username and password details.
Rename file extensions for all files under current directory and sub directories without any other packages (only use shell script):
Create a shell script rename.sh
under current directory with the following code:
#!/bin/bash
for file in $(find . -name "*$1"); do
mv "$file" "${file%$1}$2"
done
Run it by ./rename.sh .old .new
.
Eg. ./rename.sh .html .txt
Don't worry...! Follow these below steps and you will get your signed .apk file. I was also worry about that, but these step get ride me off from the frustration. Steps to sign your application:
Right click on the project in Eclipse -> Android Tools -> Export Unsigned Application Package (like here we export our GoogleDriveApp.apk to Desktop)
Sign the application using your keystore and the jarsigner tool (follow below steps):
Open cmd-->change directory where your "jarsigner.exe" exist (like here in my system it exist at "C:\Program Files\Java\jdk1.6.0_17\bin"
Now enter belwo command in cmd:
jarsigner -verbose -keystore c:\users\android\debug.keystore c:\users\pir fahim\Desktops\GoogleDriveApp.apk my_keystore_alias
It will ask you to provide your password: Enter Passphrase for keystore: It will sign your apk.To verify that the signing is successful you can run:
jarsigner -verify c:\users\pir fahim\Desktops\GoogleDriveApp.apk
It should come back with: jar verified.
Method 2
If you are using eclipse with ADT, then it is simple to compiled, signed, aligned, and ready the file for distribution.what you have to do just follow this steps.
These steps will compiled, signed and zip aligned your project and now you are ready to distribute your project or upload at Google Play store.
Just to add to how to use map files. I use chrome for ubuntu and if I go to sources and click on a file, if there is a map file a message comes up telling me that I can view the original file and how to do it.
For the Angular files that I worked with today I click
Ctrl-P and a list of original files comes up in a small window.
I can then browse through the list to view the file that I would like to inspect and check where the issue might be.
There are a few ways of doing that... the simplest is to have the async method also do the follow-on operation. Another popular approach is to pass in a callback, i.e.
void RunFooAsync(..., Action<bool> callback) {
// do some stuff
bool result = ...
if(callback != null) callback(result);
}
Another approach would be to raise an event (with the result in the event-args data) when the async operation is complete.
Also, if you are using the TPL, you can use ContinueWith
:
Task<bool> outerTask = ...;
outerTask.ContinueWith(task =>
{
bool result = task.Result;
// do something with that
});
$content = '';
for($rowth=0; $rowth<=100; $rowth++){
$content .= $selenium->getTable("tblReports.{$rowth}.0") . "\n";
//$content .= $selenium->getTable("tblReports.{$rowth}.1") . "\n";
$content .= $selenium->getTable("tblReports.{$rowth}.2") . " ";
$content .= $selenium->getTable("tblReports.{$rowth}.3") . " ";
$content .= $selenium->getTable("tblReports.{$rowth}.4") . " ";
$content .= $selenium->getTable("tblReports.{$rowth}.5") . " ";
$content .= $selenium->getTable("tblReports.{$rowth}.6") . "\n";
}
Use .get()
, which if the key is not found, returns None
.
for i in keySet:
temp = myDict.get(i)
if temp is not None:
print temp
break
As per the docs select, the following piece of code worked for me.
<div ng-controller="ExampleController">
<form name="myForm">
<label for="mySelect">Make a choice:</label>
<select name="mySelect" id="mySelect"
ng-options="option.name for option in data.availableOptions track by option.id"
ng-model="data.selectedOption"></select>
</form>
<hr>
<tt>option = {{data.selectedOption}}</tt><br/>
</div>
Microsoft now has an extension for VS 2010 that provides this functionality:
For references you can call
rails generate migration AddUserIdColumnToTable user:references
If in the future you need to add a general index you can launch this
rails g migration AddOrdinationNumberToTable ordination_number:integer:index
Generate code:
class AddOrdinationNumberToTable < ActiveRecord::Migration
def change
add_column :tables, :ordination_number, :integer
add_index :tables, :ordination_number, unique: true
end
end
I had tried the most voted answers here and a few others to no avail. My WORK_QUEUE
table was empty and I wasn't able to try a clean up at a higher folder. What did work was the following (this is via Tortoise SVN);
Break Locks
is ticked and click OKThe Clean Up operation now completes successfully and I can continue. No downloading of sqlite3 or other convoluted solutions required.
if you are on Mac as myself, try in terminal: xcode-select --install
Then accept the installation request, then it works afterward https://github.com/python-pillow/Pillow/issues/3438
I fixed this by checking Delete all existing files prior to publish
in Visual Studio:
Indeed, Python does garbage collection through reference counting. As soon as the last reference to an object falls out of scope, it is deleted. In your example:
a = A()
a.kill()
I don't believe there's any way for variable 'a' to implicitly set itself to None.
ngOnInit() {
const $ = window["$"];
$('.flexslider').flexslider({
animation: 'slide',
start: function (slider) {
$('body').removeClass('loading')
}
})
}
Aergistal's answer works, but I found that converting to mp4 can make some m3u8 videos broken. If you are stuck with this problem, try to convert them to mkv, and convert them to mp4 later.
Thomas's solution is good enough for this matter.
If you want to use loop to access these three Answers, you first need to put there three into an array-like data structure ---- kind of like a principle. So loop is used for operating on an array-like data structure, not just simply to simplify typing task. And you cannot use FOR loop by simply just giving increasing-number-names to the elements.
Just to chime in here, what fixed the issue for me was I simply canceled out of the initial prompt, the ssh one opened up with my bitbucket account, I entered the password there and everything worked as expected.
String
values are not implementation dependent, according the ECMA-262 3rd Edition Specification, each character represents a single 16-bit unit of UTF-16 text:
4.3.16 String Value
A string value is a member of the type String and is a finite ordered sequence of zero or more 16-bit unsigned integer values.
NOTE Although each value usually represents a single 16-bit unit of UTF-16 text, the language does not place any restrictions or requirements on the values except that they be 16-bit unsigned integers.
The Date
constructor that takes a single number is expecting the number of milliseconds since December 31st, 1969.
Date.getDate()
returns the day index for the current date object. In your example, the day is 30
. The final expression is 31
, therefore it's returning 31 milliseconds after December 31st, 1969.
A simple solution using your existing approach is to use Date.getTime()
instead. Then, add a days worth of milliseconds instead of 1
.
For example,
var dateString = 'Mon Jun 30 2014 00:00:00';
var startDate = new Date(dateString);
// seconds * minutes * hours * milliseconds = 1 day
var day = 60 * 60 * 24 * 1000;
var endDate = new Date(startDate.getTime() + day);
Please note that this solution doesn't handle edge cases related to daylight savings, leap years, etc. It is always a more cost effective approach to instead, use a mature open source library like moment.js to handle everything.
jquerys 'beforeunload' worked great for me
$(window).bind('beforeunload', function(){
if( $('input').val() !== '' ){
return "It looks like you have input you haven't submitted."
}
});
I think groupby should work.
df.groupby(['A', 'B']).max()['C']
If you need a dataframe back you can chain the reset index call.
df.groupby(['A', 'B']).max()['C'].reset_index()
Also you have to give permission if you are using >1.6 SDK
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
in AndroidManifest.xml
file
LocalDateTime.parse(
"2012-07-10 14:58:00.000000".replace( " " , "T" )
)
You are attempting to squeeze a value with microseconds (six decimal digits) into a data type capable only of milliseconds resolution (three decimal digits). That is impossible.
Instead, use a data type with fine enough resolution. The java.time classes use nanosecond resolution (nine decimal digits).
You are attempting to put a value lacking any offset-from-UTC or time zone into a data type (Date
) that only represents values in UTC. So you are adding information (UTC offset) not intended by the input.
Use an appropriate data type instead. Specifically, java.time.LocalDateTime
.
Other Answers and Comments correctly explain that the formatting pattern codes are case-sensitive. So MM
and mm
have different effects.
The troublesome old date-time classes bundled with the earliest versions of Java are now legacy, supplanted by the java.time classes built into Java 8 and later.
Your input strings nearly comply with the ISO 8601 standard formats. Replace the SPACE in the middle with a T
to comply fully.
The java.time classes use the standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
and I need the resultant date object to be of the same format.
No, date-time objects do not have a "format". Do not conflate date-time objects with mere strings. Strings are inputs and outputs of the objects. The objects maintain their own internal representions of the date-time info, the details of which are irrelevant to us as calling programmers.
Your input lacks any indicator of offset-from-UTC or troublesome me zone. So we parse as a LocalDateTime
objects which lacks those concepts.
String input = "2012-07-10 14:58:00.000000".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
To generate a String representing the value of your LocalDateTime
:
toString
to get a String in standard ISO 8601 format.DateTimeFormatter
for producing strings in either custom formats or automatically-localized formats. Search Stack Overflow for more info as these topics have been covered many many times already.
ZonedDateTime
A LocalDateTime
does not represent an exact point on the timeline.
To determine an actual moment, assign a time zone. For example noon in Kolkata India comes much earlier than noon in Paris France. Noon without a time zone could be happening at any point over a range of about 26-27 hours.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
/([1-9][0-9]*)|0/
Only this is necessary
session_start();
unset($_SESSION["nome"]); // where $_SESSION["nome"] is your own variable. if you do not have one use only this as follow **session_unset();**
header("Location: home.php");
corrected Code:
jQuery('#testID2').addClass('test3').removeClass('test2');
I recently found and modified this snippet from an existing SO post that I have not been able to find again but I've found it very useful
// specify any elements you've attached listeners to here
const nodes = [document]
// https://developer.mozilla.org/en-US/docs/Web/Events
const logBrowserEvents = () => {
const AllEvents = {
AnimationEvent: ['animationend', 'animationiteration', 'animationstart'],
AudioProcessingEvent: ['audioprocess'],
BeforeUnloadEvent: ['beforeunload'],
CompositionEvent: [
'compositionend',
'compositionstart',
'compositionupdate',
],
ClipboardEvent: ['copy', 'cut', 'paste'],
DeviceLightEvent: ['devicelight'],
DeviceMotionEvent: ['devicemotion'],
DeviceOrientationEvent: ['deviceorientation'],
DeviceProximityEvent: ['deviceproximity'],
DragEvent: [
'drag',
'dragend',
'dragenter',
'dragleave',
'dragover',
'dragstart',
'drop',
],
Event: [
'DOMContentLoaded',
'abort',
'afterprint',
'beforeprint',
'cached',
'canplay',
'canplaythrough',
'change',
'chargingchange',
'chargingtimechange',
'checking',
'close',
'dischargingtimechange',
'downloading',
'durationchange',
'emptied',
'ended',
'error',
'fullscreenchange',
'fullscreenerror',
'input',
'invalid',
'languagechange',
'levelchange',
'loadeddata',
'loadedmetadata',
'noupdate',
'obsolete',
'offline',
'online',
'open',
'open',
'orientationchange',
'pause',
'play',
'playing',
'pointerlockchange',
'pointerlockerror',
'ratechange',
'readystatechange',
'reset',
'seeked',
'seeking',
'stalled',
'submit',
'success',
'suspend',
'timeupdate',
'updateready',
'visibilitychange',
'volumechange',
'waiting',
],
FocusEvent: [
'DOMFocusIn',
'DOMFocusOut',
'Unimplemented',
'blur',
'focus',
'focusin',
'focusout',
],
GamepadEvent: ['gamepadconnected', 'gamepaddisconnected'],
HashChangeEvent: ['hashchange'],
KeyboardEvent: ['keydown', 'keypress', 'keyup'],
MessageEvent: ['message'],
MouseEvent: [
'click',
'contextmenu',
'dblclick',
'mousedown',
'mouseenter',
'mouseleave',
'mousemove',
'mouseout',
'mouseover',
'mouseup',
'show',
],
// https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events
MutationNameEvent: ['DOMAttributeNameChanged', 'DOMElementNameChanged'],
MutationEvent: [
'DOMAttrModified',
'DOMCharacterDataModified',
'DOMNodeInserted',
'DOMNodeInsertedIntoDocument',
'DOMNodeRemoved',
'DOMNodeRemovedFromDocument',
'DOMSubtreeModified',
],
OfflineAudioCompletionEvent: ['complete'],
OtherEvent: ['blocked', 'complete', 'upgradeneeded', 'versionchange'],
UIEvent: [
'DOMActivate',
'abort',
'error',
'load',
'resize',
'scroll',
'select',
'unload',
],
PageTransitionEvent: ['pagehide', 'pageshow'],
PopStateEvent: ['popstate'],
ProgressEvent: [
'abort',
'error',
'load',
'loadend',
'loadstart',
'progress',
],
SensorEvent: ['compassneedscalibration', 'Unimplemented', 'userproximity'],
StorageEvent: ['storage'],
SVGEvent: [
'SVGAbort',
'SVGError',
'SVGLoad',
'SVGResize',
'SVGScroll',
'SVGUnload',
],
SVGZoomEvent: ['SVGZoom'],
TimeEvent: ['beginEvent', 'endEvent', 'repeatEvent'],
TouchEvent: [
'touchcancel',
'touchend',
'touchenter',
'touchleave',
'touchmove',
'touchstart',
],
TransitionEvent: ['transitionend'],
WheelEvent: ['wheel'],
}
const RecentlyLoggedDOMEventTypes = {}
Object.keys(AllEvents).forEach((DOMEvent) => {
const DOMEventTypes = AllEvents[DOMEvent]
if (Object.prototype.hasOwnProperty.call(AllEvents, DOMEvent)) {
DOMEventTypes.forEach((DOMEventType) => {
const DOMEventCategory = `${DOMEvent} ${DOMEventType}`
nodes.forEach((node) => {
node.addEventListener(
DOMEventType,
(e) => {
if (RecentlyLoggedDOMEventTypes[DOMEventCategory]) return
RecentlyLoggedDOMEventTypes[DOMEventCategory] = true
// NOTE: throttle continuous events
setTimeout(() => {
RecentlyLoggedDOMEventTypes[DOMEventCategory] = false
}, 1000)
const isActive = e.target === document.activeElement
// https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement
const hasActiveElement = document.activeElement !== document.body
const msg = [
DOMEventCategory,
'target:',
e.target,
...(hasActiveElement
? ['active:', document.activeElement]
: []),
]
if (isActive) {
console.info(...msg)
}
},
true,
)
})
})
}
})
}
logBrowserEvents()
// export default logBrowserEvents
Yes, this program has likely used less than a millsecond. Try using microsecond resolution with timeval
.
e.g:
#include <sys/time.h>
struct timeval stop, start;
gettimeofday(&start, NULL);
//do stuff
gettimeofday(&stop, NULL);
printf("took %lu us\n", (stop.tv_sec - start.tv_sec) * 1000000 + stop.tv_usec - start.tv_usec);
You can then query the difference (in microseconds) between stop.tv_usec - start.tv_usec
. Note that this will only work for subsecond times (as tv_usec
will loop). For the general case use a combination of tv_sec
and tv_usec
.
Edit 2016-08-19
A more appropriate approach on system with clock_gettime
support would be:
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
//do stuff
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
uint64_t delta_us = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;
EDIT : this answer used to claim that it isn't possible to center an absolutely positioned element with margin: auto;
, but this simply isn't true. Because this is the most up-voted and accepted answer, I guessed I'd just change it to be correct.
When you apply the following CSS to an element
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
And then give the element a fixed width and height, such as 200px or 40%, the element will center itself.
Here's a Fiddle that demonstrates the effect.
If you don't want to place the watch inside a specific controller, you can add the watch for the whole aplication in Angular app run()
var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
$rootScope.$on("$locationChangeStart", function(event, next, current) {
// handle route changes
});
});
I always use this:
function validEmail($email){
// First, we check that there's one @ symbol, and that the lengths are right
if (!preg_match("/^[^@]{1,64}@[^@]{1,255}$/", $email)) {
// Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("@", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
return false;
}
}
if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/", $domain_array[$i])) {
return false;
}
}
}
return true;
}
The APK file is in the /workspace/PROJECT_FOLDER/bin
directory. To install the APK file in a real device:
Connect your real device with a PC/laptop.
Go to sdk/tools/
using a terminal or command prompt.
adb install <FILE PATH OF .APK FILE>
That's it...
If your not overly worried about the size of the file then it may be easier for you to store the data as a JS object in another file and import it in your . Either synchronously or asynchronously using the syntax <script src="countries.js" async></script>
. Saves on you needing to import the file and parse it.
However, i can see why you wouldnt want to rewrite 10000 entries so here's a basic object orientated csv parser i wrote.
function requestCSV(f,c){return new CSVAJAX(f,c);};
function CSVAJAX(filepath,callback)
{
this.request = new XMLHttpRequest();
this.request.timeout = 10000;
this.request.open("GET", filepath, true);
this.request.parent = this;
this.callback = callback;
this.request.onload = function()
{
var d = this.response.split('\n'); /*1st separator*/
var i = d.length;
while(i--)
{
if(d[i] !== "")
d[i] = d[i].split(','); /*2nd separator*/
else
d.splice(i,1);
}
this.parent.response = d;
if(typeof this.parent.callback !== "undefined")
this.parent.callback(d);
};
this.request.send();
};
Which can be used like this;
var foo = requestCSV("csvfile.csv",drawlines(lines));
The first parameter is the file, relative to the position of your html file in this case. The second parameter is an optional callback function the runs when the file has been completely loaded.
If your file has non-separating commmas then it wont get on with this, as it just creates 2d arrays by chopping at returns and commas. You might want to look into regexp if you need that functionality.
//THIS works
"1234","ABCD" \n
"!@£$" \n
//Gives you
[
[
1234,
'ABCD'
],
[
'!@£$'
]
]
//This DOESN'T!
"12,34","AB,CD" \n
"!@,£$" \n
//Gives you
[
[
'"12',
'34"',
'"AB',
'CD'
]
[
'"!@',
'£$'
]
]
If your not used to the OO methods; they create a new object (like a number, string, array) with their own local functions and variables via a 'constructor' function. Very handy in certain situations. This function could be used to load 10 different files with different callbacks all at the same time(depending on your level of csv love! )
What I did is first check what are the running processes by
SELECT * FROM pg_stat_activity WHERE state = 'active';
Find the process you want to kill, then type:
SELECT pg_cancel_backend(<pid of the process>)
This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.
If the process cannot be killed, try:
SELECT pg_terminate_backend(<pid of the process>)
Angular-CLI is the recommended method and is the standard in the Angular 2+ community.
Crete a new project with SCSS
ng new My-New-Project --style=sass
Convert an existing project (CLI less than v6)
ng set defaults.styleExt scss
(must rename all .css files manually with this approach, don't forget to rename in your component files)
Convert an existing project (CLI greater than v6)
"@schematics/angular:component": {
"styleext": "sass"
}
The simplest way to get tooltips in most browsers is to set some text in the title attribute.
eg.
<img src="myimage.jpg" alt="a cat" title="My cat sat on a table" />
produces (hover your mouse over the image):
a cat http://www.imagechicken.com/uploads/1275939952008633500.jpg
Title attributes can be applied to most HTML elements.
From the documentation,
Positioning your Toast
A standard toast notification appears near the bottom of the screen, centered horizontally. You can change this position with the
setGravity(int, int, int)
method. This accepts three parameters: aGravity
constant, anx-position
offset, and ay-position
offset.For example, if you decide that the toast should appear in the top-left corner, you can set the gravity like this:
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
If you want to nudge the position to the right, increase the value of the second parameter. To nudge it down, increase the value of the last parameter.
Here is the solution total html with php and database connections
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>database connections</title>
</head>
<body>
<?php
$username = "database-username";
$password = "database-password";
$host = "localhost";
$connector = mysql_connect($host,$username,$password)
or die("Unable to connect");
echo "Connections are made successfully::";
$selected = mysql_select_db("test_db", $connector)
or die("Unable to connect");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM table_one ");
?>
<table border="2" style= "background-color: #84ed86; color: #761a9b; margin: 0 auto;" >
<thead>
<tr>
<th>Employee_id</th>
<th>Employee_Name</th>
<th>Employee_dob</th>
<th>Employee_Adress</th>
<th>Employee_dept</th>
<td>Employee_salary</td>
</tr>
</thead>
<tbody>
<?php
while( $row = mysql_fetch_assoc( $result ) ){
echo
"<tr>
<td>{$row\['employee_id'\]}</td>
<td>{$row\['employee_name'\]}</td>
<td>{$row\['employee_dob'\]}</td>
<td>{$row\['employee_addr'\]}</td>
<td>{$row\['employee_dept'\]}</td>
<td>{$row\['employee_sal'\]}</td>
</tr>\n";
}
?>
</tbody>
</table>
<?php mysql_close($connector); ?>
</body>
</html>
In case you want store the value:
Pair.of<List<>, List<>> output = opt.map(details -> Pair.of(details.a, details.b))).orElseGet(() -> Pair.of(Collections.emptyList(), Collections.emptyList()));
Those other variables would have to be declared public (use extern, public is for C++), and you would have to include that .c file. However, I recommend creating appropriate .h files to define all of your variables.
For example, for hello.c, you would have a hello.h, and hello.h would store your variable definitions. Then another .c file, such as world.c would have this piece of code at the top:
#include "hello.h"
That will allow world.c to use variables that are defined in hello.h
It's slightly more complicated than that though. You may use < > to include library files found on your OS's path. As a beginner I would stick all of your files in the same folder and use the " " syntax.
this also works:
$url = "http://www.some-url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xmlresponse = curl_exec($ch);
$xml=simplexml_load_string($xmlresponse);
then I just run a forloop to grab the stuff from the nodes.
like this:`
for($i = 0; $i < 20; $i++) {
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$desc = $xml->channel->item[$i]->description;
$html .="<div><h3>$title</h3>$link<br />$desc</div><hr>";
}
echo $html;
***note that your node names will differ, obviously..and your HTML might be structured differently...also your loop might be set to higher or lower amount of results.
If you need something from super's __init__
to be done in addition to what is being done in the current class's __init__,
you must call it yourself, since that will not happen automatically. But if you don't need anything from super's __init__,
no need to call it. Example:
>>> class C(object):
def __init__(self):
self.b = 1
>>> class D(C):
def __init__(self):
super().__init__() # in Python 2 use super(D, self).__init__()
self.a = 1
>>> class E(C):
def __init__(self):
self.a = 1
>>> d = D()
>>> d.a
1
>>> d.b # This works because of the call to super's init
1
>>> e = E()
>>> e.a
1
>>> e.b # This is going to fail since nothing in E initializes b...
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
e.b # This is going to fail since nothing in E initializes b...
AttributeError: 'E' object has no attribute 'b'
__del__
is the same way, (but be wary of relying on __del__
for finalization - consider doing it via the with statement instead).
I rarely use __new__.
I do all the initialization in __init__.
If you use Apache Commons / Lang, you can do it in one step using DateUtils.addHours()
:
Date newDate = DateUtils.addHours(oldDate, 3);
(The original object is unchanged)
First drop constraints
https://stackoverflow.com/a/49393045/2547164
DECLARE @ConstraintName nvarchar(200)
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS
WHERE PARENT_OBJECT_ID = OBJECT_ID('__TableName__')
AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns
WHERE NAME = N'__ColumnName__'
AND object_id = OBJECT_ID(N'__TableName__'))
IF @ConstraintName IS NOT NULL
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)
Second create default value
ALTER TABLE [table name] ADD DEFAULT [default value] FOR [column name]
Run ipconfig /flushdns from a command prompt. Apparently some people seem to think I posted this answer for sheer fun. That's why they down voted my answer. Perhaps an explanation would help them. When I used "SVN Update" it said it can't connect to the SVN repository although I could ping the server. After running ipconfig /flushdns the issue was fixed.
You can just say
callback();
Alternately you can use the call
method if you want to adjust the value of this
within the callback.
callback.call( newValueForThis);
Inside the function this
would be whatever newValueForThis
is.
NOTE: This is an incorrect solution as @benlemasurier proved
Here is a way to copy a slice. I'm a bit late, but there is a simpler, and faster answer than @Dave's. This are the instructions generated from a code like @Dave's. These is the instructions generated by mine. As you can see there are far fewer instructions. What is does is it just does append(slice)
, which copies the slice. This code:
package main
import "fmt"
func main() {
var foo = []int{1, 2, 3, 4, 5}
fmt.Println("foo:", foo)
var bar = append(foo)
fmt.Println("bar:", bar)
bar = append(bar, 6)
fmt.Println("foo after:", foo)
fmt.Println("bar after:", bar)
}
Outputs this:
foo: [1 2 3 4 5]
bar: [1 2 3 4 5]
foo after: [1 2 3 4 5]
bar after: [1 2 3 4 5 6]
Interface is the class that contains an abstract method that cannot create any object.Since Interface cannot create the object and its not a pure class, Its no worth implementing it.
To do this job in storyboard (Interface Builder Inspector)
With help of IBDesignable
, we can add more options to Interface Builder Inspector for UINavigationController
and tweak them on storyboard. First, add the following code to your project.
@IBDesignable extension UINavigationController {
@IBInspectable var barTintColor: UIColor? {
set {
navigationBar.barTintColor = newValue
}
get {
guard let color = navigationBar.barTintColor else { return nil }
return color
}
}
@IBInspectable var tintColor: UIColor? {
set {
navigationBar.tintColor = newValue
}
get {
guard let color = navigationBar.tintColor else { return nil }
return color
}
}
@IBInspectable var titleColor: UIColor? {
set {
guard let color = newValue else { return }
navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: color]
}
get {
return navigationBar.titleTextAttributes?["NSForegroundColorAttributeName"] as? UIColor
}
}
}
Then simply set the attributes for UINavigationController on storyboard.
People often sort stacks of documents using a recursive method. For example, imagine you are sorting 100 documents with names on them. First place documents into piles by the first letter, then sort each pile.
Looking up words in the dictionary is often performed by a binary-search-like technique, which is recursive.
In organizations, bosses often give commands to department heads, who in turn give commands to managers, and so on.
In your application android manifest file, under the application tag you can try several of these themes.
Replace
<application
android:theme="@style/AppTheme" >
with different themes defined by the android system. They can be like:-
android:theme="@android:style/Theme.Black"
android:theme="@android:style/Theme.DeviceDefault"
android:theme="@android:style/Theme.DeviceDefault.Dialog"
android:theme="@android:style/Theme.Holo"
android:theme="@android:style/Theme.Translucent"
Each of these themes will have a different effect on your application like the DeviceDefault.Dialog will make your application look like a dialog box. You should try more of these. You can have a look from the android sdk or simply use auto complete in Eclipse IDE to explore the various available options.
A correct way to define your own theme would be to edit the styles.xml
file present in the resources folder of your application.
/// ************************************************ cookie_exists
/// global entry point, export to global namespace
/// <synopsis>
/// cookie_exists ( name );
///
/// <summary>
/// determines if a cookie with name exists
///
/// <param name="name">
/// string containing the name of the cookie to test for
// existence
///
/// <returns>
/// true, if the cookie exists; otherwise, false
///
/// <example>
/// if ( cookie_exists ( name ) );
/// {
/// // do something with the existing cookie
/// }
/// else
/// {
/// // cookies does not exist, do something else
/// }
function cookie_exists ( name )
{
var exists = false;
if ( document.cookie )
{
if ( document.cookie.length > 0 )
{
// trim name
if ( ( name = name.replace ( /^\s*/, "" ).length > 0 ) )
{
var cookies = document.cookie.split ( ";" );
var name_with_equal = name + "=";
for ( var i = 0; ( i < cookies.length ); i++ )
{
// trim cookie
var cookie = cookies [ i ].replace ( /^\s*/, "" );
if ( cookie.indexOf ( name_with_equal ) === 0 )
{
exists = true;
break;
}
}
}
}
}
return ( exists );
} // cookie_exists
I have just tried to install that extension on my dev server.
First, make sure that the extension is correctly enabled. Your phpinfo()
output doesn't seem complete.
If it is indeed installed properly, your phpinfo()
should have a section that looks like this:
If you do not get that section in your phpinfo()
. Make sure that you are using the right version. There are both non-thread-safe and thread-safe versions of the extension.
Finally, check your extension_dir
setting. By default it's this: extension_dir = "ext"
, for most of the time it works fine, but if it doesn't try: extension_dir = "C:\PHP\ext"
.
===========================================================================
EDIT given new info:
You are using the wrong function. mssql_connect()
is part of the Mssql extension. You are using microsoft's extension, so use sqlsrv_connect()
, for the API for the microsoft driver, look at SQLSRV_Help.chm
which should be extracted to your ext
directory when you extracted the extension.
Private Sub main()
'replace "J2" with the cell you want to insert the drop down list
With Range("J2").Validation
.Delete
'replace "=A1:A6" with the range the data is in.
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=Sheet1!A1:A6"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End Sub
Try this:
Rect rect = new Rect();
Window win = this.getWindow();
win.getDecorView().getWindowVisibleDisplayFrame(rect);
int statusBarHeight = rect.top;
int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop();
int titleBarHeight = contentViewTop - statusBarHeight;
Log.d("ID-ANDROID-CONTENT", "titleBarHeight = " + titleBarHeight );
it didn't work for me in the onCreate method for the activity, but did when I put it in an onClickListener and gave me a measurement of 25
I used Matchers.refEq
for this.
Your item
variable holds Array
instance (in [hash_key, hash_value]
format), so it doesn't expect Symbol
in []
method.
This is how you could do it using Hash#each
:
def format(hash)
output = Hash.new
hash.each do |key, value|
output[key] = cleanup(value)
end
output
end
or, without this:
def format(hash)
output = hash.dup
output[:company_name] = cleanup(output[:company_name])
output[:street] = cleanup(output[:street])
output
end
if you have added a new line, Make sure you have added next line syntax in previous line. typically if "\" is missing in your previous line of changes, you will get this error.
I use a very old java. Jdk 1.4.08 and I had the same issue. The Node
class for me did not had the getTextContent()
method. I had to use Node.getFirstChild().getNodeValue()
instead of Node.getNodeValue()
to get the value of the node. This fixed for me.
use the net use
command:
net use Z: \\10.0.1.1\DRIVENAME
Edit 1: Also, I believe the password should be simply appended:
net use Z: \\10.0.1.1\DRIVENAME PASSWORD
You can find out more about this command and its arguments via:
net use ?
Edit 2: As Tomalak mentioned in comments, you can later un-map it via
net use Z: \delete
It depends on the nature of your site.
I happen to work on a bit of software where IP tracking is important, and within a field consumed by parter sites I'd guess some 20% - 40% of requests are either detectably spoofed IPs or headers blanked out, depending on the time of day and where they came from. For a site which gets organic traffic (i.e. not through partners) I'd expect a much higher ratio of good IPs.
As Kosi said, be careful what you're doing with this - IPs are in no way a reliable way to identify unique visitors.
I have this issue where sshd only reads from authorized_keys2
.
Copying or renaming the file fixed the problem for me.
cd ~/.ssh
sudo cat authorized_keys >> authorized_keys2
P.S. I'm using Putty from Windows and used PuTTyKeygen for key pair generation.
It depends, if your function only consists of the switch statement, then I think that its fine. However, if you want to perform any other operations within that function, its probably not a great idea. You also may have to consider your requirements right now versus in the future. If you want to change your function from option one to option two, more refactoring will be needed.
However, given that within if/else statements it is best practice to do the following:
var foo = "bar";
if(foo == "bar") {
return 0;
}
else {
return 100;
}
Based on this, the argument could be made that option one is better practice.
In short, there's no clear answer, so as long as your code adheres to a consistent, readable, maintainable standard - that is to say don't mix and match options one and two throughout your application, that is the best practice you should be following.
System.TypeInitializationException
happens when the code that gets executed during the process of loading the type throws an exception.
When .NET loads the type, it must prepare all its static fields before the first time that you use the type. Sometimes, initialization requires running code. It is when that code fails that you get a System.TypeInitializationException
.
In your specific case, the following three static fields run some code:
private static string s_bstCommonAppData = Path.Combine(s_commonAppData, "XXXX");
private static string s_bstUserDataDir = Path.Combine(s_bstCommonAppData, "UserData");
private static string s_commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
Note that s_bstCommonAppData
depends on s_commonAppData
, but it is declared ahead of its dependency. Therefore, the value of s_commonAppData
is null
at the time that the Path.Combine
is called, resulting in ArgumentNullException
. Same goes for the s_bstUserDataDir
and s_bstCommonAppData
: they are declared in reverse order to the desired order of initialization.
Re-order the lines to fix this problem:
private static string s_commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
private static string s_bstCommonAppData = Path.Combine(s_commonAppData, "XXXX");
private static string s_bstUserDataDir = Path.Combine(s_bstCommonAppData, "UserData");
You can also do string concat with template literals. I updated the other posters' JSPerf tests to include it.
for (var res = '', i = 0; i < data.length; i++) {
res = `${res}${data[i]}`;
}
In case it helps anyone... I was having a lot of trouble with setting up notifications using the support package when testing against newer an older API's. I was able to get them to work on the newer device but would get an error testing on the old device. What finally got it working for me was to delete all the imports related to the notification functions. In particular the NotificationCompat and the TaskStackBuilder. It seems that while setting up my code in the beginning the imports where added from the newer build and not from the support package. Then when I wanted to implement these items later in eclipse, I wasn't prompted to import them again. Hope that makes sense, and that it helps someone else out :)
Here are the basics. I'm not sure that any of these count as "clear and simple" though.
ps(1)
For process-level view:
$ ps -opid,vsz,rss,osz,args
PID VSZ RSS SZ COMMAND
1831 1776 1008 222 ps -opid,vsz,rss,osz,args
1782 3464 2504 433 -bash
$
vsz/VSZ: total virtual process size (kb)
rss/RSS: resident set size (kb, may be inaccurate(!), see man)
osz/SZ: total size in memory (pages)
To compute byte size from pages:
$ sz_pages=$(ps -o osz -p $pid | grep -v SZ )
$ sz_bytes=$(( $sz_pages * $(pagesize) ))
$ sz_mbytes=$(( $sz_bytes / ( 1024 * 1024 ) ))
$ echo "$pid OSZ=$sz_mbytes MB"
vmstat(1M)
$ vmstat 5 5
kthr memory page disk faults cpu
r b w swap free re mf pi po fr de sr rm s3 -- -- in sy cs us sy id
0 0 0 535832 219880 1 2 0 0 0 0 0 -0 0 0 0 402 19 97 0 1 99
0 0 0 514376 203648 1 4 0 0 0 0 0 0 0 0 0 402 19 96 0 1 99
^C
prstat(1M)
PID USERNAME SIZE RSS STATE PRI NICE TIME CPU PROCESS/NLWP
1852 martin 4840K 3600K cpu0 59 0 0:00:00 0.3% prstat/1
1780 martin 9384K 2920K sleep 59 0 0:00:00 0.0% sshd/1
...
swap(1)
"Long listing" and "summary" modes:
$ swap -l
swapfile dev swaplo blocks free
/dev/zvol/dsk/rpool/swap 256,1 16 1048560 1048560
$ swap -s
total: 42352k bytes allocated + 20192k reserved = 62544k used, 607672k available
$
top(1)
An older version (3.51) is available on the Solaris companion CD from Sun, with the disclaimer that this is "Community (not Sun) supported". More recent binary packages available from sunfreeware.com or blastwave.org.
load averages: 0.02, 0.00, 0.00; up 2+12:31:38 08:53:58
31 processes: 30 sleeping, 1 on cpu
CPU states: 98.0% idle, 0.0% user, 2.0% kernel, 0.0% iowait, 0.0% swap
Memory: 1024M phys mem, 197M free mem, 512M total swap, 512M free swap
PID USERNAME LWP PRI NICE SIZE RES STATE TIME CPU COMMAND
1898 martin 1 54 0 3336K 1808K cpu 0:00 0.96% top
7 root 11 59 0 10M 7912K sleep 0:09 0.02% svc.startd
sar(1M)
And just what's wrong with sar
? :)
There is also var_export and print_r more commonly known for printing debug output but both functions can take an optional argument to return a string instead.
Using the example from the question as data.
$array = ["item1"=>"object1", "item2"=>"object2","item-n"=>"object-n"];
print_r
to turn the array into a stringThis will output a human readable representation of the variable.
$string = print_r($array, true);
echo $string;
Will output:
Array
(
[item1] => object1
[item2] => object2
[item-n] => object-n
)
var_export
to turn the array into a stringWhich will output a php string representation of the variable.
$string = var_export($array, true);
echo $string;
Will output:
array (
'item1' => 'object1',
'item2' => 'object2',
'item-n' => 'object-n',
)
Because it is valid php we can evaluate it.
eval('$array2 = ' . var_export($array, true) . ';');
var_dump($array2 === $array);
Outputs:
bool(true)
I used PowerShell (Admin) with this command.
docker cp {container id}:{container path}/error.html C:\\error.html
Example
docker cp ff3a6608467d:/var/www/app/error.html C:\\error.html
Then just delete it:
x = [0, 1, 2, 3, 4]
del x[0]
print x
# [1, 2, 3, 4]
i'd particularly want to add unserialize() to this list. It has had a long history of various vulnerabilities including arbitrary code execution, denial of service and memory information leakage. It should never be called on user-supplied data. Many of these vuls have been fixed in releases over the last dew years, but it still retains a couple of nasty vuls at the current time of writing.
For other information about dodgy php functions/usage look around the Hardened PHP Project and its advisories. Also the recent Month of PHP Security and 2007's Month of PHP Bugs projects
Also note that, by design, unserializing an object will cause the constructor and destructor functions to execute; another reason not to call it on user-supplied data.
Ok, I know that this question is actually solved but I decided to share my solution for this. I've created abstract parent class for my Fragment
:
public abstract class ABaseFragment extends Fragment{
protected IActivityEnabledListener aeListener;
protected interface IActivityEnabledListener{
void onActivityEnabled(FragmentActivity activity);
}
protected void getAvailableActivity(IActivityEnabledListener listener){
if (getActivity() == null){
aeListener = listener;
} else {
listener.onActivityEnabled(getActivity());
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (aeListener != null){
aeListener.onActivityEnabled((FragmentActivity) activity);
aeListener = null;
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (aeListener != null){
aeListener.onActivityEnabled((FragmentActivity) context);
aeListener = null;
}
}
}
As you can see, I've added a listener so, whenever I'll need to get Fragments
Activity
instead of standard getActivity()
, I'll need to call
getAvailableActivity(new IActivityEnabledListener() {
@Override
public void onActivityEnabled(FragmentActivity activity) {
// Do manipulations with your activity
}
});
I am running DB2/LINUXX8664 10.5.3 and describe select * from schema_name.table_name
works for me.
However, describe table schema_name.table_name
fails with this error:
SQL0100W No row was found for FETCH, UPDATE or DELETE; or the result of a
query is an empty table. SQLSTATE=02000
You shouldn't use both ngRoute
and UI-router
. Here's a sample code for UI-router:
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
_x000D_
$stateProvider_x000D_
.state('state1', {_x000D_
url: "/state1",_x000D_
templateUrl: "partials/state1.html",_x000D_
controller: 'YourCtrl'_x000D_
})_x000D_
_x000D_
.state('state2', {_x000D_
url: "/state2",_x000D_
templateUrl: "partials/state2.html",_x000D_
controller: 'YourOtherCtrl'_x000D_
});_x000D_
$urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?
You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router
No java.util.List.isEmpty()
doesn't check if a list is null
.
If you are using Spring framework you can use the CollectionUtils
class to check if a list is empty or not. It also takes care of the null
references. Following is the code snippet from Spring framework's CollectionUtils
class.
public static boolean isEmpty(Collection<?> collection) {
return (collection == null || collection.isEmpty());
}
Even if you are not using Spring, you can go on and tweak this code to add in your AppUtil
class.
I crossed the same error, but it is not due to the file is locked, but the file is missing.
The reason why VS tried to copy an not existing file, is because of the Post-build event command.
After I cleared that, problem solved.
UPDATE:
As @rhughes commented:
The real issue is how to get the command here to work, rather than to remove it.
and he is absolutely right.
You're looking for the .filter()
function:
$scope.appIds = $scope.applicationsHere.filter(function(obj) {
return obj.selected;
});
That'll produce an array that contains only those objects whose "selected" property is true
(or truthy).
edit sorry I was getting some coffee and I missed the comments - yes, as jAndy noted in a comment, to filter and then pluck out just the "id" values, it'd be:
$scope.appIds = $scope.applicationsHere.filter(function(obj) {
return obj.selected;
}).map(function(obj) { return obj.id; });
Some functional libraries (like Functional, which in my opinion doesn't get enough love) have a .pluck()
function to extract property values from a list of objects, but native JavaScript has a pretty lean set of such tools.
No, you have no way to get the "name" from the value in C++ because all the symbols are discarded during compilation.
You may need this way X Macros
Hi we can use default method "first" in jQuery
Here some examples:
When you want to add class for first div
$('.alldivs div').first().addClass('active');
When you want to change the remove the "onediv" class and add only to first child
$('.alldivs div').removeClass('onediv').first().addClass('onediv');
You can wrap your canvas element in a parent div, relatively positioned, then give that div the height you want, setting maintainAspectRatio: false in your options
//HTML
<div id="canvasWrapper" style="position: relative; height: 80vh/500px/whatever">
<canvas id="chart"></canvas>
</div>
<script>
new Chart(somechart, {
options: {
responsive: true,
maintainAspectRatio: false
/*, your other options*/
}
});
</script>
this is output of this program
Scanner s=new Scanner (System.in);
int row, elem, col;
Systm.out.println("Enter Element to insert");
elem = s.nextInt();
System.out.println("Enter row");
row=s.nextInt();
System.out.println("Enter row");
col=s.nextInt();
for (int c=row-1; c < row; c++)
{
for (d = col-1 ; d < col ; d++)
array[c][d] = elem;
}
for(c = 0; c < size; c++)
{
for (d = 0 ; d < size ; d++)
System.out.print( array[c] [d] +" ");
System.out.println();
}
I wrote a small class to test which has the better performance of the two and + comes ahead of format. by a factor of 5 to 6. Try it your self
import java.io.*;
import java.util.Date;
public class StringTest{
public static void main( String[] args ){
int i = 0;
long prev_time = System.currentTimeMillis();
long time;
for( i = 0; i< 100000; i++){
String s = "Blah" + i + "Blah";
}
time = System.currentTimeMillis() - prev_time;
System.out.println("Time after for loop " + time);
prev_time = System.currentTimeMillis();
for( i = 0; i<100000; i++){
String s = String.format("Blah %d Blah", i);
}
time = System.currentTimeMillis() - prev_time;
System.out.println("Time after for loop " + time);
}
}
Running the above for different N shows that both behave linearly, but String.format
is 5-30 times slower.
The reason is that in the current implementation String.format
first parses the input with regular expressions and then fills in the parameters. Concatenation with plus, on the other hand, gets optimized by javac (not by the JIT) and uses StringBuilder.append
directly.
In my case, apart from these steps:
I have needed to put the class as public in order to create productName-Swift.h file:
import UIKit
@objc public class TestSwift: NSObject {
func sayHello() {
print("Hi there!")
}
}
First, follow the instructions in this question to squash everything to a single commit. Then make a forced push to the remote:
$ git push origin +master
And optionally delete all other branches both locally and remotely:
$ git push origin :<branch>
$ git branch -d <branch>
As in your example, the fit_start_time
is not later than the fit_end_time
.
Try it the other way round:
var fit_start_time = $("#fit_start_time").val(); //2013-09-5
var fit_end_time = $("#fit_end_time").val(); //2013-09-10
if(Date.parse(fit_start_time) <= Date.parse(fit_end_time)){
alert("Please select a different End Date.");
}
Update
Your code implies that you want to see the alert
with the current variables you have. If this is the case then the above code is correct. If you're intention (as per the implication of the alert message
) is to make sure their fit_start_time
variable is a date that is before the fit_end_time
, then your original code is fine, but the data you're getting from the jQuery .val()
methods is not parsing correctly. It would help if you gave us the actual HTML which the selector is sniffing at.
Try to use anyMatch
of Lambda Expression. It is much better approach.
boolean idExists = tabPane.getTabs().stream()
.anyMatch(t -> t.getId().equals(idToCheck));
it can been used the format specifier %x02
that format and output a hex value. For example:
>>> foo = b"tC\xfc}\x05i\x8d\x86\x05\xa5\xb4\xd3]Vd\x9cZ\x92~'6"
>>> res = ""
>>> for b in foo:
... res += "%02x" % b
...
>>> print(res)
7443fc7d05698d8605a5b4d35d56649c5a927e2736
Err, what about just calling Directory.Delete(path, true);
?
Put your floating div(s)
in a div
and in CSS give it overflow:hidden;
it will work fine.
int days = DateTime.DaysInMonth(int year,int month);
or
int days=System.Globalization.CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(int year,int month);
you have to pass year and month as int
then days in month will be return on currespoting year and month
mylist[c(5,7,9)]
should do it.
You want the sublists returned as sublists of the result list; you don't use [[]]
(or rather, the function is [[
) for that -- as Dason mentions in comments, [[
grabs the element.
Binary Serialization method works fine but in my tests it showed to be 10x slower than a non-serialization implementation of clone. Tested it on Dictionary<string , List<double>>
I've done this with pure CSS (probably because I come from the future - 3 years later than everyone else :P )
Supposing we have a list:
<ul id="nav">
<li><span>Category 1</span></li>
<li><span>Category 2</span></li>
<li><span>Category 3</span></li>
</ul>
Then we can easily make the text of the last item red with:
ul#nav li:last-child span {
color: Red;
}
(I don't have enough rep points to add a comment, but I want to add some clarity on the answers here)
Application.AskToUpdateLinks = False is probably not what you want.
If set to False, then MS Excel will attempt to update the links automatically it just won't prompt the user beforehand, sorta counter-intuitive.
The correct solution, if you're looking to open a file without updating links should be:
Workbook.Open(UpdateLinks:=0)
Related link: Difference in AskToUpdateLinks=False and UpdateLinks:=0
The following code works well (On FireFox, IE and Chrome) :
var display_out = "This is line 1" + "<br>" + "This is line 2";
document.getElementById("demo").innerHTML = display_out;
There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:
With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.
Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/
Update 2019:
A simple return
statement will 'stop' or return the function; in precise terms, it 'returns' function execution to the point at which the function was called - the function is terminated without further action.
That means you could have a number of places throughout your function where it might return. Like this:
def player():
# do something here
check_winner_variable = check_winner() # check something
if check_winner_variable == '1':
return
second_test_variable = second_test()
if second_test_variable == '1':
return
# let the computer do something
computer()
Try this it's working for me
RequestOptions requestOptions = new RequestOptions();
Glide.with(getContext())
.load("video_url")
.apply(requestOptions)
.thumbnail(Glide.with(getContext()).load("video_url"))
.into("yourimageview");
Because you didn't tell the linker about location of math library. Compile with gcc test.c -o test -lm
The "Mark as Excluded" option isn't there anymore.
The current (Android Studio 0.8.x - 2.2.x) way to do this is via the Project Structure dialog. It can be accessed via "File -> Project Structure" or by right-clicking on a Module and selecting "Module Settings".
Then select the module, and click the "minus" button to remove it.
The directory will still be visible in the "Project" view (though not in the "Android" view) since it's not actually deleted, but it will no longer be treated as a module.
If you want, you can then physically delete the files it by right-clicking on it and pressing "Delete".
@AnsgarWiechers - it's not my experience that querying everything and then pruning the result is more efficient when you're doing a targeted search of known accounts. Although, yes, it is also more efficient to select just the properties you need to return.
The below examples are based on a domain in the range of 20,000 account objects.
measure-command {Get-ADUser -Filter '*' -Properties DisplayName,st }
...
Seconds : 16
Milliseconds : 208
measure-command {$userlist | get-aduser -Properties DisplayName,st}
...
Seconds : 3
Milliseconds : 496
In the second example, $userlist contains 368 account names (just strings, not pre-fetched account objects).
Note that if I include the where
clause per your suggestion to prune to the actually desired results, it's even more expensive.
measure-command {Get-ADUser -Filter '*' -Properties DisplayName,st |where {$userlist -Contains $_.samaccountname } }
...
Seconds : 17
Milliseconds : 876
Indexed attributes seem to have similar performance (I tried just returning displayName
).
Even if I return all user account properties in my set, it's more efficient. (Adding a select statement to the below brings it down by a half-second).
measure-command {$userlist | get-aduser -Properties *}
...
Seconds : 12
Milliseconds : 75
I can't find a good document that was written in ye olde days about AD queries to link to, but you're hitting every account in your search scope to return the properties. This discusses the basics of doing effective AD queries - scoping and filtering: https://msdn.microsoft.com/en-us/library/ms808539.aspx#efficientadapps_topic01
When your search scope is "*", you're still building a (big) list of the objects and iterating through each one. An LDAP search filter is always more efficient to build the list first (or a narrow search base, which is again building a smaller list to query).
In order to remove any URL within a string in Python, you can use this RegEx function :
import re
def remove_URL(text):
"""Remove URLs from a text string"""
return re.sub(r"http\S+", "", text)
In PHP use .=
to append strings, and not +=
.
Why does this output 0? [...] Does PHP not like += with strings?
+=
is an arithmetic operator to add a number to another number. Using that operator with strings leads to an automatic type conversion. In the OP's case the strings have been converted to integers of the value 0
.
More about operators in PHP:
Just killing time... A recursive function
void foo(Node* node)
{
if(node == NULL)
return;
// Do something with node...
foo(node->left);
foo(node->right);
}
can be converted to
void foo(Node* node)
{
if(node == NULL)
return;
// Do something with node...
stack.push(node->right);
stack.push(node->left);
while(!stack.empty()) {
node1 = stack.pop();
if(node1 == NULL)
continue;
// Do something with node1...
stack.push(node1->right);
stack.push(node1->left);
}
}
The .net framework supports JSON through JavaScriptSerializer. Here is a good example to get you started.
using System.Collections.Generic;
using System.Web.Script.Serialization;
namespace GoogleTranslator.GoogleJSON
{
public class FooTest
{
public void Test()
{
const string json = @"{
""DisplayFieldName"" : ""ObjectName"",
""FieldAliases"" : {
""ObjectName"" : ""ObjectName"",
""ObjectType"" : ""ObjectType""
},
""PositionType"" : ""Point"",
""Reference"" : {
""Id"" : 1111
},
""Objects"" : [
{
""Attributes"" : {
""ObjectName"" : ""test name"",
""ObjectType"" : ""test type""
},
""Position"" :
{
""X"" : 5,
""Y"" : 7
}
}
]
}";
var ser = new JavaScriptSerializer();
ser.Deserialize<Foo>(json);
}
}
public class Foo
{
public Foo() { Objects = new List<SubObject>(); }
public string DisplayFieldName { get; set; }
public NameTypePair FieldAliases { get; set; }
public PositionType PositionType { get; set; }
public Ref Reference { get; set; }
public List<SubObject> Objects { get; set; }
}
public class NameTypePair
{
public string ObjectName { get; set; }
public string ObjectType { get; set; }
}
public enum PositionType { None, Point }
public class Ref
{
public int Id { get; set; }
}
public class SubObject
{
public NameTypePair Attributes { get; set; }
public Position Position { get; set; }
}
public class Position
{
public int X { get; set; }
public int Y { get; set; }
}
}
While former answer is absolutely correct, I prefer using the JOIN ON
syntax to be sure that I know how do I join and on what fields. It would look something like this:
SELECT bc.firstname, bc.lastname, b.title, TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order Date", p.publishername
FROM books b
JOIN book_customer bc ON bc.costumer_id = b.book_id
LEFT JOIN book_order bo ON bo.book_id = b.book_id
(etc.)
WHERE b.publishername = 'PRINTING IS US';
This syntax seperates completely the WHERE
clause from the JOIN
clause, making the statement more readable and easier for you to debug.
Using file:///// just doesn't work if security settings are set to even a moderate level.
If you just want users to be able to download/view files* located on a network or share you can set up a Virtual Directory in IIS. On the Properties tab make sure the "A share located on another computer" is selected and the "Connect as..." is an account that can see the network location.
Link to the virtual directory from your webpage (e.g. http://yoursite/yourvirtualdir/) and this will open up a view of the directory in the web browser.
*You can allow write permissions on the virtual directory to allow users to add files but not tried it and assume network permissions would override this setting.
You could also, higlight the text you want to change, then navigate to - 'Edit' > 'Convert Case to' choose UPPERCASE or lowercase (as required).
For Pycharm CE 2018.3 and Ubuntu 18.04 with snap installation:
env BAMF_DESKTOP_FILE_HINT=/var/lib/snapd/desktop/applications/pycharm-community_pycharm-community.desktop /snap/bin/pycharm-community %f
I get this command from KDE desktop launch icon.
Sorry for the language but I am a Spanish developer so I have my system in Spanish.
I used Mercury/32 and Pegasus Mail to get the mail() functional. It works great too as a mail server if you want an email address ending with your domain name.
If you mean milliseconds since epoch you could do
ptime time_t_epoch(date(1970,1,1));
ptime now = microsec_clock::local_time();
time_duration diff = now - time_t_epoch;
x = diff.total_milliseconds();
However, it's not particularly clear what you're after.
Have a look at the example in the documentation for DateTime at Boost Date Time
This is untested, but I believe the syntax should work for a lambda query. As you join more tables with this syntax you have to drill further down into the new objects to reach the values you want to manipulate.
var fullEntries = dbContext.tbl_EntryPoint
.Join(
dbContext.tbl_Entry,
entryPoint => entryPoint.EID,
entry => entry.EID,
(entryPoint, entry) => new { entryPoint, entry }
)
.Join(
dbContext.tbl_Title,
combinedEntry => combinedEntry.entry.TID,
title => title.TID,
(combinedEntry, title) => new
{
UID = combinedEntry.entry.OwnerUID,
TID = combinedEntry.entry.TID,
EID = combinedEntry.entryPoint.EID,
Title = title.Title
}
)
.Where(fullEntry => fullEntry.UID == user.UID)
.Take(10);
For people with only one IP address and multiple sites on one server, you can configure IIS to listen on a port other than 80
, e.g 8080
by setting the TCP port in the properties of each of its sites (including the default one).
In Apache, enable mod_proxy
and mod_proxy_http
, then add a catch-all VirtualHost (after all others) so that requests Apache isn't explicitly handling get "forwarded" on to IIS.
<VirtualHost *:80>
ServerName foo.bar
ServerAlias *
ProxyPreserveHost On
ProxyPass / http://127.0.0.1:8080/
</VirtualHost>
Now you can have Apache serve some sites and IIS serve others, with no visible difference to the user.
Edit: your IIS sites must not include their port number in any URLs within their responses, including headers.
If you have downloaded Github Desktop Client 1.0.9
then the path for git.exe
will be
C:\Users\Username\AppData\Local\GitHubDesktop\app-1.0.9\resources\app\git\cmd\git.exe
get
takes a second optional value. If the specified key does not exist in your dictionary, then this value will be returned.
dictionary = {"Name": "Harry", "Age": 17}
dictionary.get('Year', 'No available data')
>> 'No available data'
If you do not give the second parameter, None
will be returned.
If you use indexing as in dictionary['Year']
, nonexistent keys will raise KeyError
.
Problem can be also in different types of object's PK ("User" in your case) and type you ask hibernate to get session.get(type, id);
.
In my case error was identifier of an instance of <skipped> was altered from 16 to 32
.
Object's PK type was Integer
, hibernate was asked for Long
type.
Another simple solution is to use map()
as follows:
tensor_shape = map(int, my_tensor.shape)
This converts all the Dimension
objects to int
If you're using Perl, download a module to parse the XML: XML::Simple, XML::Twig, or XML::LibXML. Don't re-invent the wheel.
If you want to change what the x button does or make it so that you cannot close it at all try this.
yourwindow.protocol("WM_DELETE_WINDOW", whatever)
then defy what "whatever" means
def whatever():
#Replace this with what you want python to do when the user hits the x button
You can also make it so that when you close that window you can call it back like this
yourwindow.withdraw()
This hides the window but does not close it
yourwindow.deiconify()
This makes the window visible again
Super has no side effects
Base = ChildB
Base()
works as expected
Base = ChildA
Base()
gets into infinite recursion.
You don't need to parse the string, it's defined as a string already.
Just do:
private static String getStringInput (String prompt) {
String input = EZJ.getUserInput(prompt);
return input;
}
Running a simple test, I thought I'd document what works and what doesn't. Often I see people checking to see if the object's class is a member of the other class or is equal to the other class.
For the line below, we have some poorly formed data that can be an NSArray
, an NSDictionary
or (null)
.
NSArray *hits = [[[myXML objectForKey: @"Answer"] objectForKey: @"hits"] objectForKey: @"Hit"];
These are the tests that were performed:
NSLog(@"%@", [hits class]);
if ([hits isMemberOfClass:[NSMutableArray class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isMemberOfClass:[NSMutableDictionary class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isMemberOfClass:[NSArray class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isMemberOfClass:[NSDictionary class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isKindOfClass:[NSMutableDictionary class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isKindOfClass:[NSDictionary class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isKindOfClass:[NSArray class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isKindOfClass:[NSMutableArray class]]) {
NSLog(@"%@", [hits class]);
}
isKindOfClass
worked rather well while isMemberOfClass
didn't.
-- IN arguments : you get them. You can modify them locally but caller won't see it
-- IN OUT arguments: initialized by caller, already have a value, you can modify them and the caller will see it
-- OUT arguments: they're reinitialized by the procedure, the caller will see the final value.
CREATE PROCEDURE f (p IN NUMBER, x IN OUT NUMBER, y OUT NUMBER)
IS
BEGIN
x:=x * p;
y:=4 * p;
END;
/
SET SERVEROUTPUT ON
declare
foo number := 30;
bar number := 0;
begin
f(5,foo,bar);
dbms_output.put_line(foo || ' ' || bar);
end;
/
-- Procedure output can be collected from variables x and y (ans1:= x and ans2:=y) will be: 150 and 20 respectively.
-- Answer borrowed from: https://stackoverflow.com/a/9484228/1661078
I don't think it will make a significant difference in compile time but #pragma once
is very well supported across compilers but not actually part of the standard. The preprocessor may be a little faster with it as it is more simple to understand your exact intent.
#pragma once
is less prone to making mistakes and it is less code to type.
To speed up compile time more just forward declare instead of including in .h files when you can.
I prefer to use #pragma once
.
See this wikipedia article about the possibility of using both.
Most people recommend using notifyDataSetChanged()
, but I found this link pretty useful. In fact using clear
and add
you can accomplish the same goal using less memory footprint, and more responsibe app.
For example:
notesListAdapter.clear();
notes = new ArrayList<Note>();
notesListAdapter.add(todayNote);
if (birthdayNote != null) notesListAdapter.add(birthdayNote);
/* no need to refresh, let the adaptor do its job */
For those of you, who doesn't like this monstrous new AClass[] { ... }
syntax, here's some sugar:
public AClass[] c(AClass... arr) { return arr; }
Use this little function as you like:
AClass[] array;
...
array = c(object1, object2);
JsonP only works with type: GET,
More info (PHP) http://www.fbloggs.com/2010/07/09/how-to-access-cross-domain-data-with-ajax-using-jsonp-jquery-and-php/
.NET: http://www.west-wind.com/weblog/posts/2007/Jul/04/JSONP-for-crosssite-Callbacks
OK, so looking at Comparison of file systems if you only care about the main players file systems:
NUL
, \
, /
, :
, *
, "
, <
, >
, |
. Also, no space character at the start or end, and no period at the end.:
or /
NUL
or /
so any byte except NUL
, \
, /
, :
, *
, "
, <
, >
, |
and you can't have files/folders call .
or ..
and no control characters (of course).
Why don't you just divide by 5 and multiply by 7, and then round? (Granted, you would have to use floating-point no.s)
It's much easier and more reliable (really?) than the other solutions. E.g. in Python:
def ranndomNo7():
import random
rand5 = random.randint(4) # Produces range: [0, 4]
rand7 = int(rand5 / 5 * 7) # /5, *7, +0.5 and floor()
return rand7
Wasn't that easy?
http://localhost:(port number of phpmyadmin)/phpmyadmin/
For example: http://localhost:8080/phpmyadmin/
It works great!
Finally, I found the solution to my problem.
I looked into the Magento system log file (var/log/system.log). There I saw the exact error.
The error is as below:-
Recoverable Error: Argument 1 passed to Mage_Core_Model_Store::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 555 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store.php on line 285
Recoverable Error: Argument 1 passed to Mage_Core_Model_Store_Group::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 575 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store\Group.php on line 227
Actually, I had this error before. But, error display message like Error: 404 Not Found
was new to me.
The reason for this error is that store_id
and website_id
for admin should be set to 0 (zero). But, when you import database to new server, somehow these values are not set to 0.
Open PhpMyAdmin and run the following query in your database:-
SET FOREIGN_KEY_CHECKS=0;
UPDATE `core_store` SET store_id = 0 WHERE code='admin';
UPDATE `core_store_group` SET group_id = 0 WHERE name='Default';
UPDATE `core_website` SET website_id = 0 WHERE code='admin';
UPDATE `customer_group` SET customer_group_id = 0 WHERE customer_group_code='NOT LOGGED IN';
SET FOREIGN_KEY_CHECKS=1;
I have written about this problem and solution over here:-
Magento: Solution to "Error: 404 Not Found" in Admin Login Page
InetAddress.getLocalHost().getHostName() is the best way out of the two as this is the best abstraction at the developer level.
In the package explorer, right-click on the package and select New -> File, then enter the filename including the ".properties" suffix.
Just add layout_weight="1" to in your linearLayout which having Buttons.
Edit :- let me make it simple
follow something like below, tags name may not be correct, it is just an Idea
<LL>// Top Parrent LinearLayout
<LL1 height="fill_parent" weight="1" "other tags as requirement"> <TV /><Butons /></LL1> // this layout will fill your screen.
<LL2 height="wrap_content" weight="1" orientation="Horizontal" "other tags as requirement"> <BT1 /><BT2/ ></LL2> // this layout gonna take lower part of button height of your screen
<LL/> TOP PARENT CLOSED
JS does not have a sleep function, it has setTimeout() or setInterval() functions.
If you can move the code that you need to run after the pause into the setTimeout()
callback, you can do something like this:
//code before the pause
setTimeout(function(){
//do what you need here
}, 2000);
see example here : http://jsfiddle.net/9LZQp/
This won't halt the execution of your script, but due to the fact that setTimeout()
is an asynchronous function, this code
console.log("HELLO");
setTimeout(function(){
console.log("THIS IS");
}, 2000);
console.log("DOG");
will print this in the console:
HELLO
DOG
THIS IS
(note that DOG is printed before THIS IS)
You can use the following code to simulate a sleep for short periods of time:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
now, if you want to sleep for 1 second, just use:
sleep(1000);
example: http://jsfiddle.net/HrJku/1/
please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.
In laymen's terms an unsigned int is an integer that can not be negative and thus has a higher range of positive values that it can assume. A signed int is an integer that can be negative but has a lower positive range in exchange for more negative values it can assume.
Bootstrap 4+ has made changes to the utility classes for this. From the documentation:
Added
.float-{sm,md,lg,xl}-{left,right,none}
classes for responsive floats and removed.pull-left
and.pull-right
since they’re redundant to.float-left
and.float-right
.
So use the .float-right
(or a size equivalent such as .float-lg-right
) instead of .pull-right
for your right alignment if you're using a newer Bootstrap version.
I ran into the same problem when I have update data while the RecyclerView is scrolling. And I fixed it with the following solution:
The Math.round function is overloaded When it receives a float value, it will give you an int. For example this would work.
int a=Math.round(1.7f);
When it receives a double value, it will give you a long, therefore you have to typecast it to int.
int a=(int)Math.round(1.7);
This is done to prevent loss of precision. Your double value is 64bit, but then your int variable can only store 32bit so it just converts it to long, which is 64bit but you can typecast it to 32bit as explained above.
Perl solutions:
perl -lpe 'print "Project_Name=sowstest" if $. == 8' file
-l
strips newlines and adds them back in, eliminating the need for "\n"-p
loops over the input file, printing every line-e
executes the code in single quotes$.
is the line number
perl -slpe 'print $s if $. == $n' -- -n=8 -s="Project_Name=sowstest" file
-s
enables a rudimentary argument parser--
prevents -n and -s from being parsed by the standard perl argument parserperl -lpe 'BEGIN{$n=shift; $s=shift}; print $s if $. == $n' 8 "Project_Name=sowstest" file
setenv n 8 ; setenv s "Project_Name=sowstest"
echo $n ; echo $s
perl -slpe 'print $ENV{s} if $. == $ENV{n}' file
ENV
is the hash which contains all environment variables
perl -MGetopt::Std -lpe 'BEGIN{getopt("ns",\%o)}; print $o{s} if $. == $o{n}' -- -n 8 -s "Project_Name=sowstest" file
perl -MGetopt::Long -lpe 'BEGIN{GetOptions(\%o,"line=i","string=s")}; print $o{string} if $. == $o{line}' -- --line 8 --string "Project_Name=sowstest" file
Getopt is the recommended standard-library solution.
This may be overkill for one-line perl scripts, but it can be done
localStorage.clear()
That'll clear the stored data. Then refresh and things should start to work.
Download the C++17 International Standard final draft here.
Aggregates
C++17 expands and enhances aggregates and aggregate initialization. The standard library also now includes an std::is_aggregate
type trait class. Here is the formal definition from section 11.6.1.1 and 11.6.1.2 (internal references elided):
An aggregate is an array or a class with
— no user-provided, explicit, or inherited constructors,
— no private or protected non-static data members,
— no virtual functions, and
— no virtual, private, or protected base classes.
[ Note: Aggregate initialization does not allow accessing protected and private base class’ members or constructors. —end note ]
The elements of an aggregate are:
— for an array, the array elements in increasing subscript order, or
— for a class, the direct base classes in declaration order, followed by the direct non-static data members that are not members of an anonymous union, in declaration order.
What changed?
struct B1 // not a aggregate
{
int i1;
B1(int a) : i1(a) { }
};
struct B2
{
int i2;
B2() = default;
};
struct M // not an aggregate
{
int m;
M(int a) : m(a) { }
};
struct C : B1, B2
{
int j;
M m;
C() = default;
};
C c { { 1 }, { 2 }, 3, { 4 } };
cout
<< "is C aggregate?: " << (std::is_aggregate<C>::value ? 'Y' : 'N')
<< " i1: " << c.i1 << " i2: " << c.i2
<< " j: " << c.j << " m.m: " << c.m.m << endl;
//stdout: is C aggregate?: Y, i1=1 i2=2 j=3 m.m=4
struct D // not an aggregate
{
int i = 0;
D() = default;
explicit D(D const&) = default;
};
struct B1
{
int i1;
B1() : i1(0) { }
};
struct C : B1 // not an aggregate
{
using B1::B1;
};
Trivial Classes
The definition of trivial class was reworked in C++17 to address several defects that were not addressed in C++14. The changes were technical in nature. Here is the new definition at 12.0.6 (internal references elided):
A trivially copyable class is a class:
— where each copy constructor, move constructor, copy assignment operator, and move assignment operator is either deleted or trivial,
— that has at least one non-deleted copy constructor, move constructor, copy assignment operator, or move assignment operator, and
— that has a trivial, non-deleted destructor.
A trivial class is a class that is trivially copyable and has one or more default constructors, all of which are either trivial or deleted and at least one of which is not deleted. [ Note: In particular, a trivially copyable or trivial class does not have virtual functions or virtual base classes.—end note ]
Changes:
std::memcpy
. This was a semantic contradiction, because, by defining as deleted all constructor/assignment operators, the creator of the class clearly intended that the class could not be copied/moved, yet the class still met the definition of a trivially copyable class. Hence in C++17 we have a new clause stating that trivially copyable class must have at least one trivial, non-deleted (though not necessarily publicly accessible) copy/move constructor/assignment operator. See N4148, DR1734Standard-layout Classes
The definition of standard-layout was also reworked to address defect reports. Again the changes were technical in nature. Here is the text from the standard (12.0.7). As before, internal references are elided:
A class S is a standard-layout class if it:
— has no non-static data members of type non-standard-layout class (or array of such types) or reference,
— has no virtual functions and no virtual base classes,
— has the same access control for all non-static data members,
— has no non-standard-layout base classes,
— has at most one base class subobject of any given type,
— has all non-static data members and bit-fields in the class and its base classes first declared in the same class, and
— has no element of the set M(S) of types (defined below) as a base class.108
M(X) is defined as follows:
— If X is a non-union class type with no (possibly inherited) non-static data members, the set M(X) is empty.
— If X is a non-union class type whose first non-static data member has type X0 (where said member may be an anonymous union), the set M(X) consists of X0 and the elements of M(X0).
— If X is a union type, the set M(X) is the union of all M(Ui) and the set containing all Ui, where each Ui is the type of the ith non-static data member of X.
— If X is an array type with element type Xe, the set M(X) consists of Xe and the elements of M(Xe).
— If X is a non-class, non-array type, the set M(X) is empty.
[ Note: M(X) is the set of the types of all non-base-class subobjects that are guaranteed in a standard-layout class to be at a zero offset in X. —end note ]
[ Example:
—end example ]struct B { int i; }; // standard-layout class struct C : B { }; // standard-layout class struct D : C { }; // standard-layout class struct E : D { char : 4; }; // not a standard-layout class struct Q {}; struct S : Q { }; struct T : Q { }; struct U : S, T { }; // not a standard-layout class
108) This ensures that two subobjects that have the same class type and that belong to the same most derived object are not allocated at the same address.
Changes:
Note: The C++ standards committee intended the above changes based on defect reports to apply to C++14, though the new language is not in the published C++14 standard. It is in the C++17 standard.
You've just published that private key, so now the whole world knows what it is. Hopefully that was just for testing.
EDIT: Others have noted that the openssl text header of the published key, -----BEGIN RSA PRIVATE KEY-----, indicates that it is PKCS#1. However, the actual Base64 contents of the key in question is PKCS#8. Evidently the OP copy and pasted the header and trailer of a PKCS#1 key onto the PKCS#8 key for some unknown reason. The sample code I've provided below works with PKCS#8 private keys.
Here is some code that will create the private key from that data. You'll have to replace the Base64 decoding with your IBM Base64 decoder.
public class RSAToy {
private static final String BEGIN_RSA_PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\n"
+ "MIIEuwIBADAN ...skipped the rest\n"
// + ...
// + ... skipped the rest
// + ...
+ "-----END RSA PRIVATE KEY-----";
public static void main(String[] args) throws Exception {
// Remove the first and last lines
String privKeyPEM = BEGIN_RSA_PRIVATE_KEY.replace("-----BEGIN RSA PRIVATE KEY-----\n", "");
privKeyPEM = privKeyPEM.replace("-----END RSA PRIVATE KEY-----", "");
System.out.println(privKeyPEM);
// Base64 decode the data
byte [] encoded = Base64.decode(privKeyPEM);
// PKCS8 decode the encoded RSA private key
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privKey = kf.generatePrivate(keySpec);
// Display the results
System.out.println(privKey);
}
}
This code is using the new React context API:
import React, { PureComponent, createContext } from 'react';
const { Provider, Consumer } = createContext({ width: 0, height: 0 });
class WindowProvider extends PureComponent {
state = this.getDimensions();
componentDidMount() {
window.addEventListener('resize', this.updateDimensions);
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateDimensions);
}
getDimensions() {
const w = window;
const d = document;
const documentElement = d.documentElement;
const body = d.getElementsByTagName('body')[0];
const width = w.innerWidth || documentElement.clientWidth || body.clientWidth;
const height = w.innerHeight || documentElement.clientHeight || body.clientHeight;
return { width, height };
}
updateDimensions = () => {
this.setState(this.getDimensions());
};
render() {
return <Provider value={this.state}>{this.props.children}</Provider>;
}
}
Then you can use it wherever you want in your code like this:
<WindowConsumer>
{({ width, height }) => //do what you want}
</WindowConsumer>
$mystring = "this is the text I would like to truncate";
// Pass your variable to the function
$mystring = truncate($mystring);
// Truncated tring printed out;
echo $mystring;
//truncate text function
public function truncate($text) {
//specify number fo characters to shorten by
$chars = 25;
$text = $text." ";
$text = substr($text,0,$chars);
$text = substr($text,0,strrpos($text,' '));
$text = $text."...";
return $text;
}
Ctrl+shift+L opens the Quick text search window
(This is for the benefit of others who may refer)
You can simply use cin and a char array. The cin input is delimited by the first whitespace it encounters.
#include<iostream>
using namespace std;
main()
{
char word[50];
cin>>word;
while(word){
//Do stuff with word[]
cin>>word;
}
}
Dim sFileName As String
Dim iFileNum As Integer
Dim sBuf As String
Dim Fields as String
Dim TempStr as String
sFileName = "c:\fields.ini"
''//Does the file exist?
If Len(Dir$(sFileName)) = 0 Then
MsgBox ("Cannot find fields.ini")
End If
iFileNum = FreeFile()
Open sFileName For Input As iFileNum
''//This part skips the first two lines
if not(EOF(iFileNum)) Then Line Input #iFilenum, TempStr
if not(EOF(iFileNum)) Then Line Input #iFilenum, TempStr
Do While Not EOF(iFileNum)
Line Input #iFileNum, Fields
MsgBox (Fields)
Loop
The file you read in must have exactly the file name you specify: "10_random"
not "10_random.txt" not "10_random.blah", it must exactly match what you are asking for. You can change either one to match so that they line up, but just be sure they do. It may help to show the file extensions in whatever OS you're using.
Also, for file location, it must be located in the working directory (same level) as the final executable (the .class file) that is the result of compilation.
ListBox will try to expand in height that is available.. When you set the Height property of ListBox you get a scrollviewer that actually works...
If you wish your ListBox to accodate the height available, you might want to try to regulate the Height from your parent controls.. In a Grid for example, setting the Height to Auto in your RowDefinition might do the trick...
HTH
If you want a random number, use a random number library. If you want a unique identifier with effectively 0.00...many more 0s here...001% chance of collision, you should use UUIDv1. See Nick's post for UUIDv3 and v5.
UUIDv1 is NOT secure. It isn't meant to be. It is meant to be UNIQUE, not un-guessable. UUIDv1 uses the current timestamp, plus a machine identifier, plus some random-ish stuff to make a number that will never be generated by that algorithm again. This is appropriate for a transaction ID (even if everyone is doing millions of transactions/s).
To be honest, I don't understand why UUIDv4 exists... from reading RFC4122, it looks like that version does NOT eliminate possibility of collisions. It is just a random number generator. If that is true, than you have a very GOOD chance of two machines in the world eventually creating the same "UUID"v4 (quotes because there isn't a mechanism for guaranteeing U.niversal U.niqueness). In that situation, I don't think that algorithm belongs in a RFC describing methods for generating unique values. It would belong in a RFC about generating randomness. For a set of random numbers:
chance_of_collision = 1 - (set_size! / (set_size - tries)!) / (set_size ^ tries)
Do you mean like this?
import string
astr='a(b[c])d'
deleter=string.maketrans('()[]',' ')
print(astr.translate(deleter))
# a b c d
print(astr.translate(deleter).split())
# ['a', 'b', 'c', 'd']
print(list(reversed(astr.translate(deleter).split())))
# ['d', 'c', 'b', 'a']
print(' '.join(reversed(astr.translate(deleter).split())))
# d c b a
If Ruby is installed, then
ruby yourfile.rb
where yourfile.rb
is the file containing the ruby code.
Or
irb
to start the interactive Ruby environment, where you can type lines of code and see the results immediately.
I've solved a similar problem with an easier solution:
import codecs
csvReader = csv.reader(codecs.open('file.csv', 'rU', 'utf-16'))
The key was using the codecs module to open the file with the UTF-16 encoding, there are a lot more of encodings, check the documentation.
<item name="android:statusBarColor" tools:targetApi="lollipop">@android:color/transparent</item>
<!--<item name="android:windowLightStatusBar" tools:targetApi="m">true</item>-->
Dont use windowLightStatusBar
use instead statusBarColor = @android:color/transparent
The pattern yyyy-MM-dd
isn't an officially supported format for Date
constructor. Firefox seems to support it, but don't count on other browsers doing the same.
Here are some supported strings:
DateJS seems like a good library for parsing non standard date formats.
Edit: just checked ECMA-262 standard. Quoting from section 15.9.1.15:
Date Time String Format
ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ Where the fields are as follows:
- YYYY is the decimal digits of the year in the Gregorian calendar.
- "-" (hyphon) appears literally twice in the string.
- MM is the month of the year from 01 (January) to 12 (December).
- DD is the day of the month from 01 to 31.
- "T" appears literally in the string, to indicate the beginning of the time element.
- HH is the number of complete hours that have passed since midnight as two decimal digits.
- ":" (colon) appears literally twice in the string.
- mm is the number of complete minutes since the start of the hour as two decimal digits.
- ss is the number of complete seconds since the start of the minute as two decimal digits.
- "." (dot) appears literally in the string.
- sss is the number of complete milliseconds since the start of the second as three decimal digits. Both the "." and the milliseconds field may be omitted.
- Z is the time zone offset specified as "Z" (for UTC) or either "+" or "-" followed by a time expression hh:mm
This format includes date-only forms:
- YYYY
- YYYY-MM
- YYYY-MM-DD
It also includes time-only forms with an optional time zone offset appended:
- THH:mm
- THH:mm:ss
- THH:mm:ss.sss
Also included are "date-times" which may be any combination of the above.
So, it seems that YYYY-MM-DD is included in the standard, but for some reason, Safari doesn't support it.
Update: after looking at datejs documentation, using it, your problem should be solved using code like this:
var myDate1 = Date.parseExact("29-11-2010", "dd-MM-yyyy");
var myDate2 = Date.parseExact("11-29-2010", "MM-dd-yyyy");
var myDate3 = Date.parseExact("2010-11-29", "yyyy-MM-dd");
var myDate4 = Date.parseExact("2010-29-11", "yyyy-dd-MM");
I am a fan of Cmder, a package including clink, conemu, msysgit, and some cosmetic enhancements.
https://github.com/cmderdev/cmder
Updated the script to check the start position:
function float_horizontal_scroll(id) {
var el = jQuery(id);
var isLeft = el.css('left') !== 'auto';
var start =((isLeft ? el.css('left') : el.css('right')).replace("px", ""));
jQuery(window).scroll(function () {
var leftScroll = jQuery(this).scrollLeft();
if (isLeft)
el.css({ 'left': (start + leftScroll) + 'px' });
else
el.css({ 'right': (start - leftScroll) + 'px' });
});
}
I would be careful when using Guava's ComparisonChain
because it creates an instance of it per element been compared so you would be looking at a creation of N x Log N
comparison chains just to compare if you are sorting, or N
instances if you are iterating and checking for equality.
I would instead create a static Comparator
using the newest Java 8 API if possible or Guava's Ordering
API which allows you to do that, here is an example with Java 8:
import java.util.Comparator;
import static java.util.Comparator.naturalOrder;
import static java.util.Comparator.nullsLast;
private static final Comparator<Person> COMPARATOR = Comparator
.comparing(Person::getName, nullsLast(naturalOrder()))
.thenComparingInt(Person::getAge);
@Override
public int compareTo(@NotNull Person other) {
return COMPARATOR.compare(this, other);
}
Here is how to use the Guava's Ordering
API: https://github.com/google/guava/wiki/OrderingExplained
Create a foreign key to the existing SQLLite table:
There is no direct way to do that for SQL LITE. Run the below query to recreate STUDENTS table with foreign keys. Run the query after creating initial STUDENTS table and inserting data into the table.
CREATE TABLE STUDENTS (
STUDENT_ID INT NOT NULL,
FIRST_NAME VARCHAR(50) NOT NULL,
LAST_NAME VARCHAR(50) NOT NULL,
CITY VARCHAR(50) DEFAULT NULL,
BADGE_NO INT DEFAULT NULL
PRIMARY KEY(STUDENT_ID)
);
Insert data into STUDENTS table.
Then Add FOREIGN KEY : making BADGE_NO as the foreign key of same STUDENTS table
BEGIN;
CREATE TABLE STUDENTS_new (
STUDENT_ID INT NOT NULL,
FIRST_NAME VARCHAR(50) NOT NULL,
LAST_NAME VARCHAR(50) NOT NULL,
CITY VARCHAR(50) DEFAULT NULL,
BADGE_NO INT DEFAULT NULL,
PRIMARY KEY(STUDENT_ID) ,
FOREIGN KEY(BADGE_NO) REFERENCES STUDENTS(STUDENT_ID)
);
INSERT INTO STUDENTS_new SELECT * FROM STUDENTS;
DROP TABLE STUDENTS;
ALTER TABLE STUDENTS_new RENAME TO STUDENTS;
COMMIT;
we can add the foreign key from any other table as well.
If you are planning to load an external javascript file's functions or objects, load on this context using the following code – note the runInThisContext method:
var vm = require("vm");
var fs = require("fs");
var data = fs.readFileSync('./externalfile.js');
const script = new vm.Script(data);
script.runInThisContext();
// here you can use externalfile's functions or objects as if they were instantiated here. They have been added to this context.
The answer by Jones Agyemang is probably sufficient for most use cases and was a great starting point for my solution. For scripting in Git Bent, the git wrapper library I made, I needed something a bit more robust. I'm posting the prototype I've written which is not yet totally script-friendly
<<<<<<< HEAD
which doesn't work for merge conflicts from using git stash apply
which has <<<<<<< Updated Upstream
=======
& >>>>>>>
You need the str_split_line
function from below.
# Root git directory
dir="$(git rev-parse --show-toplevel)"
# Put the grep output into an array (see below)
str_split_line "$(grep -r "^<<<<<<< " "${dir})" files
bn="$(basename "${dir}")"
for i in "${files[@]}"; do
# Remove the matched string, so we're left with the file name
file="$(sed -e "s/:<<<<<<< .*//" <<< "${i}")"
# Remove the path, keep the project dir's name
fileShort="${file#"${dir}"}"
fileShort="${bn}${fileShort}"
# Confirm merge divider & closer are present
c1=$(grep -c "^=======" "${file}")
c2=$(grep -c "^>>>>>>> " "${file}")
if [[ c1 -gt 0 && c2 -gt 0 ]]; then
echo "${fileShort} has a merge conflict"
fi
done
projectdir/file-name
projectdir/subdir/file-name
You can just copy the block of code if you don't want this as a separate function
function str_split_line(){
# for IFS, see https://stackoverflow.com/questions/16831429/when-setting-ifs-to-split-on-newlines-why-is-it-necessary-to-include-a-backspac
IFS="
"
declare -n lines=$2
while read line; do
lines+=("${line}")
done <<< "${1}"
}
In my case, I just had to disconnect and connect the SSMS. I profiled the query and the duration of execution was showing 1 minute even though the query itself runs under 2 seconds. Restarted the connection and ran again, this time the duration showed the correct execution time.
You can use jquery.form.js plugin to upload image via ajax to the server.
http://malsup.com/jquery/form/
Here is the sample jQuery ajax image upload script
(function() {
$('form').ajaxForm({
beforeSubmit: function() {
//do validation here
},
beforeSend:function(){
$('#loader').show();
$('#image_upload').hide();
},
success: function(msg) {
///on success do some here
}
}); })();
If you have any doubt, please refer following ajax image upload tutorial here
http://www.smarttutorials.net/ajax-image-upload-using-jquery-php-mysql/
I tried various javascript/jQuery-based strategies, but I kept having issues. The latest issue to arise involved accidental submission when the user uses the enter key to select from the browser's built-in auto-complete list. I finally switched to this strategy, which seems to work on all the browsers my company supports:
<div class="hidden-submit"><input type="submit" tabindex="-1"/></div>
.hidden-submit {
border: 0 none;
height: 0;
width: 0;
padding: 0;
margin: 0;
overflow: hidden;
}
This is similar to the currently-accepted answer by Chris Marasti-Georg, but by avoiding display: none
, it appears to work correctly on all browsers.
I edited the code above to include a negative tabindex
so it doesn't capture the tab key. While this technically won't validate in HTML 4, the HTML5 spec includes language to make it work the way most browsers were already implementing it anyway.
Use this code:
driver.manage().window().maximize()
works well,
Please make sure that you give enough time for the window to load before you declare this statement.
If you are finding any element to input some data then provide reasonable delay between this and the input statement.
I've got the same error. I have been trying to fixing this by setting higher permission to account running SQL Client service, however it didnt help. The problem was that I run MS Sql Management studio just within my account. So, next time... assure that you are running it as Run as Administrator, if using Win7 with UAC enabled.
By default, Ctrl+Tab in Visual Studio Code cycles through tabs in order of most recently used. This is confusing because it depends on hidden state.
Web browsers cycle through tabs in visible order. This is much more intuitive.
To achieve this in Visual Studio Code, you have to edit keybindings.json
. Use the Command Palette with CTRL+SHIFT+P, enter "Preferences: Open Keyboard Shortcuts (JSON)", and hit Enter.
Then add to the end of the file:
[
// ...
{
"key": "ctrl+tab",
"command": "workbench.action.nextEditor"
},
{
"key": "ctrl+shift+tab",
"command": "workbench.action.previousEditor"
}
]
Alternatively, to only cycle through tabs of the current window/split view, you can use:
[
{
"key": "ctrl+tab",
"command": "workbench.action.nextEditorInGroup"
},
{
"key": "ctrl+shift+tab",
"command": "workbench.action.previousEditorInGroup"
}
]
Alternatively, you can use Ctrl+PageDown (Windows) or Cmd+Option+Right (Mac).
Using accumulators is the way to compute means and standard deviations in Boost.
accumulator_set<double, stats<tag::variance> > acc;
for_each(a_vec.begin(), a_vec.end(), bind<void>(ref(acc), _1));
cout << mean(acc) << endl;
cout << sqrt(variance(acc)) << endl;
You can use String.Format:
DateTime d = DateTime.Now;
string str = String.Format("{0:00}/{1:00}/{2:0000} {3:00}:{4:00}:{5:00}.{6:000}", d.Month, d.Day, d.Year, d.Hour, d.Minute, d.Second, d.Millisecond);
// I got this result: "02/23/2015 16:42:38.234"
You can access the values in a vector just as you access any other array.
for (int i = 0; i < v.size(); i++)
{
v[i] -= 1;
}
I have not seen this mentioned in the previous issues, so let me throw out another possibility. It could be that IFItest
is not reachable or simply does not exist. For example, if one has a number of configurations, each with its own database, it could be that the database name was not changed to the correct one for the current configuration.
This seems a weird request and deserves a weird solution:
string[] sizes = new string[] { "105", "101", "102", "103", "90" };
foreach (var size in sizes.OrderBy(x => {
double sum = 0;
int position = 0;
foreach (char c in x.ToCharArray().Reverse()) {
sum += (c - 48) * (int)(Math.Pow(10,position));
position++;
}
return sum;
}))
{
Console.WriteLine(size);
}
In the general case, the answer is No.
However, you can set the debugger to break at the point where the exception is first thrown. At that time, the key which was not present will be accessible as a value in the call stack.
In Visual Studio, this option is located here:
Debug → Exceptions... → Common Language Runtime Exceptions → System.Collections.Generic
There, you can check the Thrown box.
For more specific instances where information is needed at runtime, provided your code uses IDictionary<TKey, TValue>
and not tied directly to Dictionary<TKey, TValue>
, you can implement your own dictionary class which provides this behavior.
I found this to be a better solution
$(".alert-dismissible").fadeTo(2000, 500).slideUp(500, function(){
$(".alert-dismissible").alert('close');
});
Please check out my gist where I have made a category for UILabel
for something very similar, my category lets a UILabel
stretch it's height to show all the content: https://gist.github.com/1005520
Or check out this post: https://stackoverflow.com/a/7242981/662605
This would stretch the height, but you can change it around easily to work the other way and stretch the width with something like this, which is I believe what you want to do:
@implementation UILabel (dynamicSizeMeWidth)
- (void)resizeToStretch{
float width = [self expectedWidth];
CGRect newFrame = [self frame];
newFrame.size.width = width;
[self setFrame:newFrame];
}
- (float)expectedWidth{
[self setNumberOfLines:1];
CGSize maximumLabelSize = CGSizeMake(CGRectGetWidth(self.bounds), CGFLOAT_MAX);
CGSize expectedLabelSize = [[self text] sizeWithFont:[self font]
constrainedToSize:maximumLabelSize
lineBreakMode:[self lineBreakMode]];
return expectedLabelSize.width;
}
@end
You could more simply use the sizeToFit
method available from the UIView
class, but set the number of lines to 1 to be safe.
If you are using AutoLayout, then you have a built in solution. By setting the number of lines to 0, the framework will resize your label appropriately (adding more height) to fit your text.
sizeWithFont:
is deprecated so use sizeWithAttributes:
instead:
- (float)expectedWidth{
[self setNumberOfLines:1];
CGSize expectedLabelSize = [[self text] sizeWithAttributes:@{NSFontAttributeName:self.font}];
return expectedLabelSize.width;
}
From the javadocs..http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
Path p1 = Paths.get("/tmp/foo");
is the same as
Path p4 = FileSystems.getDefault().getPath("/tmp/foo");
Path p3 = Paths.get(URI.create("file:///Users/joe/FileTest.java"));
Path p5 = Paths.get(System.getProperty("user.home"),"logs", "foo.log");
In Windows, creates file C:\joe\logs\foo.log (assuming user home as C:\joe)
In Unix, creates file /u/joe/logs/foo.log (assuming user home as /u/joe)
You can use
String hex = String.format("#%02x%02x%02x", r, g, b);
Use capital X's if you want your resulting hex-digits to be capitalized (#FFFFFF
vs. #ffffff
).
Delete the most recent commit, keeping the work you've done:
git reset --soft HEAD~1
Delete the most recent commit, destroying the work you've done:
git reset --hard HEAD~1
You are comparing doc_val_check
with an empty string. You want to assign the empty string to doc_val_check
so it should be this:
doc_val_check = "";
We dont need redux-persist we can simply use redux for persistance.
react-redux + AsyncStorage = redux-persist
so inside createsotre file simply add these lines
store.subscribe(async()=> await AsyncStorage.setItem("store", JSON.stringify(store.getState())))
this will update the AsyncStorage whenever there are some changes in the redux store.
Then load the json converted store. when ever the app loads. and set the store again.
Because redux-persist creates issues when using wix react-native-navigation. If that's the case then I prefer to use simple redux with above subscriber function
To complete a bit more previous great answers, you need to be aware that forms leverage observables to detect and handle value changes. It's something really important and powerful. Both Mark and dfsq described this aspect in their answers.
Observables allow not only to use the subscribe
method (something similar to the then
method of promises in Angular 1). You can go further if needed to implement some processing chains for updated data in forms.
I mean you can specify at this level the debounce time with the debounceTime
method. This allows you to wait for an amount of time before handling the change and correctly handle several inputs:
this.form.valueChanges
.debounceTime(500)
.subscribe(data => console.log('form changes', data));
You can also directly plug the processing you want to trigger (some asynchronous one for example) when values are updated. For example, if you want to handle a text value to filter a list based on an AJAX request, you can leverage the switchMap
method:
this.textValue.valueChanges
.debounceTime(500)
.switchMap(data => this.httpService.getListValues(data))
.subscribe(data => console.log('new list values', data));
You even go further by linking the returned observable directly to a property of your component:
this.list = this.textValue.valueChanges
.debounceTime(500)
.switchMap(data => this.httpService.getListValues(data))
.subscribe(data => console.log('new list values', data));
and display it using the async
pipe:
<ul>
<li *ngFor="#elt of (list | async)">{{elt.name}}</li>
</ul>
Just to say that you need to think the way to handle forms differently in Angular2 (a much more powerful way ;-)).
Hope it helps you, Thierry
Using the example posted by Brock, I modified it so that it is a category of UIView instead UIViewController and made it recursive so that any subview can (hopefully) find the parent UIViewController.
@interface UIView (FindUIViewController)
- (UIViewController *) firstAvailableUIViewController;
- (id) traverseResponderChainForUIViewController;
@end
@implementation UIView (FindUIViewController)
- (UIViewController *) firstAvailableUIViewController {
// convenience function for casting and to "mask" the recursive function
return (UIViewController *)[self traverseResponderChainForUIViewController];
}
- (id) traverseResponderChainForUIViewController {
id nextResponder = [self nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]]) {
return nextResponder;
} else if ([nextResponder isKindOfClass:[UIView class]]) {
return [nextResponder traverseResponderChainForUIViewController];
} else {
return nil;
}
}
@end
To use this code, add it into an new class file (I named mine "UIKitCategories") and remove the class data... copy the @interface into the header, and the @implementation into the .m file. Then in your project, #import "UIKitCategories.h" and use within the UIView code:
// from a UIView subclass... returns nil if UIViewController not available
UIViewController * myController = [self firstAvailableUIViewController];
I faced the same issue and the complete solution is to set to false(uncheck) the "Automatically detect settings" checkbox from Lan Area Network( the same window as for Bypass proxy server for local address )
Assuming timestamp is the index of the data frame, you can just do the following:
hours = sales.index.hour
If you want to add that to your sales data frame, just do:
import pandas as pd
pd.concat([sales, pd.DataFrame(hours, index=sales.index)], axis = 1)
Edit: If you have several columns of datetime objects, it's the same process. If you have a column ['date'] in your data frame, and assuming that 'date' has datetime values, you can access the hour from the 'date' as:
hours = sales['date'].hour
Edit2:
If you want to adjust a column in your data frame you have to include dt
:
sales['datehour'] = sales['date'].dt.hour
You can use this site: https://cachedviews.com/ . Cache View or Cached Pages of Any Website - Google Cached Pages of Any Website
Missing ;
after var_dump($row)
Isn't it this simple?
var result = _(data)
.groupBy(x => x.color)
.map((value, key) => ({color: key, users: value}))
.value();
In addition to the answer of BalusC, use the following Java RegExp to replace &&
with and
:
Search: (#\{[^\}]*)(&&)([^\}]*\})
Replace: $1and$3
You have run this regular expression replacement multiple times to find all occurences in case you are using >2 literals in your EL expressions. Mind to replace the leading # by $ if your EL expression syntax differs.
Sometimes using only the line below throws me an Exception,
String text = listView1.SelectedItems[0].Text;
so I use this code below:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedIndices.Count <= 0)
{
return;
}
int intselectedindex = listView1.SelectedIndices[0];
if (intselectedindex >= 0)
{
String text = listView1.Items[intselectedindex].Text;
//do something
//MessageBox.Show(listView1.Items[intselectedindex].Text);
}
}
Use the #
syntax for comments
From: https://docs.docker.com/engine/reference/builder/#format
# My comment here
RUN echo 'we are running some cool things'
Additionally, if you want the flexibility of choosing the width
, you can choose between one of the following two formats (with or without truncation):
int width = 30;
// No truncation uses %-*s
printf( "%-*s %s\n", width, "Starting initialization...", "Ok." );
// Output is "Starting initialization... Ok."
// Truncated to the specified width uses %-.*s
printf( "%-.*s %s\n", width, "Starting initialization...", "Ok." );
// Output is "Starting initialization... Ok."
Step 1: There is only one thing to import on top:
import {Route} from 'react-router-dom';
Step 2: In your Route, pass the history:
<Route
exact
path='/posts/add'
render={({history}) => (
<PostAdd history={history} />
)}
/>
Step 3: history gets accepted as part of props in the next Component, so you can simply:
this.props.history.push('/');
That was easy and really powerful.
Likely, your problem is that you parsed it okay, and now you're trying to print the contents of the XML and you can't because theres some foreign Unicode characters. Try to encode your unicode string as ascii first:
unicodeData.encode('ascii', 'ignore')
the 'ignore' part will tell it to just skip those characters. From the python docs:
>>> # Python 2: u = unichr(40960) + u'abcd' + unichr(1972)
>>> u = chr(40960) + u'abcd' + chr(1972)
>>> u.encode('utf-8')
'\xea\x80\x80abcd\xde\xb4'
>>> u.encode('ascii')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode character '\ua000' in position 0: ordinal not in range(128)
>>> u.encode('ascii', 'ignore')
'abcd'
>>> u.encode('ascii', 'replace')
'?abcd?'
>>> u.encode('ascii', 'xmlcharrefreplace')
'ꀀabcd޴'
You might want to read this article: http://www.joelonsoftware.com/articles/Unicode.html, which I found very useful as a basic tutorial on what's going on. After the read, you'll stop feeling like you're just guessing what commands to use (or at least that happened to me).