Translate all characters into their hex-entity equivalents. In this case, Null
would be converted into E;KC;C;
The answers above are correct, and what I'd consider the "best" answers. But just to be as complete as possible, you can also do this directly in CF using queryAddColumn.
See http://www.cfquickdocs.com/cf9/#queryaddcolumn
Again, it's more efficient to do it at the database level... but it's good to be aware of as many alternatives as possible (IMO, of course) :)
Execute following command:
set PATH="C:\Program Files (x86)\Java\jre7"
(whichever JRE
exists in case of 64bit).
Because your Java Path is not set so you can just do this at command line and then execute the keytool
import command.
You're almost correct, just misplaced a few quotes. Wrapping the whole thing in regular quotes will literally give you the string #demo + {this.state.id}
- you need to indicate which are variables and which are string literals. Since anything inside {}
is an inline JSX expression, you can do:
href={"#demo" + this.state.id}
This will use the string literal #demo
and concatenate it to the value of this.state.id
. This can then be applied to all strings. Consider this:
var text = "world";
And this:
{"Hello " + text + " Andrew"}
This will yield:
Hello world Andrew
You can also use ES6 string interpolation/template literals with ` (backticks) and ${expr}
(interpolated expression), which is closer to what you seem to be trying to do:
href={`#demo${this.state.id}`}
This will basically substitute the value of this.state.id
, concatenating it to #demo
. It is equivalent to doing: "#demo" + this.state.id
.
You can use the expandable list view explained in API demos to show groups
To animate the list items motion, you will have to override the getView method and apply translate animation on each list item. The values for animation depend on the position of each list item. This was something which i tried on a simple list view long time back.
Void refers to the type. Basically the type of data that it points to is unknown.
Null refers to the value. It's essentially a pointer to nothing, and is invalid to use.
You can make virtualenvwrapper use a custom Python binary instead of the one virtualenvwrapper is run with. To do that you need to use VIRTUALENV_PYTHON variable which is utilized by virtualenv:
$ export VIRTUALENV_PYTHON=/usr/bin/python3
$ mkvirtualenv -a myproject myenv
Running virtualenv with interpreter /usr/bin/python3
New python executable in myenv/bin/python3
Also creating executable in myenv/bin/python
(myenv)$ python
Python 3.2.3 (default, Oct 19 2012, 19:53:16)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
If you want both of EnsureCreated and Migrate use this code:
using (var context = new YourDbContext())
{
if (context.Database.EnsureCreated())
{
//auto migration when database created first time
//add migration history table
string createEFMigrationsHistoryCommand = $@"
USE [{context.Database.GetDbConnection().Database}];
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
CREATE TABLE [dbo].[__EFMigrationsHistory](
[MigrationId] [nvarchar](150) NOT NULL,
[ProductVersion] [nvarchar](32) NOT NULL,
CONSTRAINT [PK___EFMigrationsHistory] PRIMARY KEY CLUSTERED
(
[MigrationId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY];
";
context.Database.ExecuteSqlRaw(createEFMigrationsHistoryCommand);
//insert all of migrations
var dbAssebmly = context.GetType().GetAssembly();
foreach (var item in dbAssebmly.GetTypes())
{
if (item.BaseType == typeof(Migration))
{
string migrationName = item.GetCustomAttributes<MigrationAttribute>().First().Id;
var version = typeof(Migration).Assembly.GetName().Version;
string efVersion = $"{version.Major}.{version.Minor}.{version.Build}";
context.Database.ExecuteSqlRaw("INSERT INTO __EFMigrationsHistory(MigrationId,ProductVersion) VALUES ({0},{1})", migrationName, efVersion);
}
}
}
context.Database.Migrate();
}
It seems to me, that it is by design that this file is empty.
A similar question has been asked here: https://stackoverflow.com/questions/2567432/ubuntu-apache-httpd-conf-or-apache2-conf
So, you should have a look for /etc/apache2/apache2.conf
Came across this issue when using Bootstrap 3.
My solution was to add the carousel-fade
class to the carousel main DIV and slot the following CSS in, somewhere after the Bootstrap CSS is included:
.carousel-fade .item {
opacity: 0;
-webkit-transition: opacity 2s ease-in-out;
-moz-transition: opacity 2s ease-in-out;
-ms-transition: opacity 2s ease-in-out;
-o-transition: opacity 2s ease-in-out;
transition: opacity 2s ease-in-out;
left: 0 !important;
}
.carousel-fade .active {
opacity: 1 !important;
}
.carousel-fade .left {
opacity: 0 !important;
-webkit-transition: opacity 0.5s ease-in-out !important;
-moz-transition: opacity 0.5s ease-in-out !important;
-ms-transition: opacity 0.5s ease-in-out !important;
-o-transition: opacity 0.5s ease-in-out !important;
transition: opacity 0.5s ease-in-out !important;
}
.carousel-fade .carousel-control {
opacity: 1 !important;
}
The style transitions that Bootstrap applies mean that you have to have the mid-stride transitions (active left, next left) quickly, otherwise the item just ends up disappearing (hence the 1/2 second transition time).
I haven't experimented with adjusting the .item
and .left
transition times, but they will probably need adjusting proportionally to keep the effect looking nice.
What works for me was with one dot. Mine Office is 365. =HYPERLINK(".\Name_of_folder\","DisplayLinkName") =HYPERLINK(".\Name_of_file","DisplayLinkName")
I managed to work around it by reverting back to the last version that I had the mysql directory in, then deleting the contents of the directory, putting the new contents in it, and checking the new information back in. Although I'm curious if anyone has a better explanation for what the heck was going on there.
Another option is using eval
. This is only suitable if the strings are trusted. The first script can echo the variable assignments:
echo "VAR=myvalue"
Then:
eval $(./first.sh) ./second.sh
This approach is of particular interest when the second script you want to set environment variables for is not in bash and you also don't want to export
the variables, perhaps because they are sensitive and you don't want them to persist.
With the global configuration that you have defined for the exec-maven-plugin:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.4.0</version>
<configuration>
<mainClass>org.dhappy.test.NeoTraverse</mainClass>
</configuration>
</plugin>
invoking mvn exec:java
on the command line will invoke the plugin which is configured to execute the class org.dhappy.test.NeoTraverse
.
So, to trigger the plugin from the command line, just run:
mvn exec:java
Now, if you want to execute the exec:java
goal as part of your standard build, you'll need to bind the goal to a particular phase of the default lifecycle. To do this, declare the phase
to which you want to bind the goal in the execution
element:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<id>my-execution</id>
<phase>package</phase>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>org.dhappy.test.NeoTraverse</mainClass>
</configuration>
</plugin>
With this example, your class would be executed during the package
phase. This is just an example, adapt it to suit your needs. Works also with plugin version 1.1.
This answer can be a possible solution from many. This answer is for the people who are facing this error while working with File Upload..
We were using middleware for token based encryption - decryption and we encountered same error.
Following was our code in route file:
router.route("/uploadVideoMessage")
.post(
middleware.checkToken,
upload.single("video_file"),
videoMessageController.uploadVideoMessage
);
here we were calling middleware before upload function and that was causing the error. So when we changed it to this, it worked.
router.route("/uploadVideoMessage")
.post(
upload.single("video_file"),
middleware.checkToken,
videoMessageController.uploadVideoMessage
);
function abc(){
var form = $('#form_name')[0];
var formData = new FormData(form);
for (var [key, value] of formData.entries()) {
console.log(key, value);
}
$.ajax({
type: "POST",
url: " ",
data: formData,
contentType: false,
cache: false,
processData:false,
beforeSend: function() {
},
success: function(data) {
},
});
}
In case of NULL
columns it is better to use IF
clause like this which combine the two functions of : CONCAT
and COALESCE
and uses special chars between the columns in result like space or '_'
SELECT FirstName , LastName ,
IF(FirstName IS NULL AND LastName IS NULL, NULL,' _ ',CONCAT(COALESCE(FirstName ,''), COALESCE(LastName ,'')))
AS Contact_Phone FROM TABLE1
selects the documents where the value of the field is not equal to the specified value. This includes documents that do not contain the field.
User.find({ "username": { "$ne": 'admin' } })
$nin selects the documents where: the field value is not in the specified array or the field does not exist.
User.find({ "groups": { "$nin": ['admin', 'user'] } })
Messing with mapping is borderline moving into real ORM land. Instead of fighting with it and keeping Dapper in its true simple (fast) form, just modify your SQL slightly like so:
var sql = @"select top 1 person_id as PersonId,FirstName,LastName from Person";
Try
var ts = TimeSpan.Parse(stringTime);
With a newer .NET you also have
TimeSpan ts;
if(!TimeSpan.TryParse(stringTime, out ts)){
// throw exception or whatnot
}
// ts now has a valid format
This is the general idiom for parsing strings in .NET with the first version handling erroneous string by throwing FormatException and the latter letting the Boolean TryParse give you the information directly.
Simply git checkout have 2 uses
git checkout <existing_local_branch_name>
git checkout -b <new_feature_branch_name>
will create a new branch with the contents of master and switch to newly created branchYou can find more options at the official site
Above answers are correct. This version is easy to follow:
Because "Schema export directory is not provided to the annotation processor", So we need to provide the directory for schema export:
Step [1] In your file which extends the RoomDatabase, change the line to:
`@Database(entities = ???.class,version = 1, exportSchema = true)`
Or
`@Database(entities = ???.class,version = 1)`
(because the default value is always true)
Step [2] In your build.gradle(project:????) file, inside the defaultConfig{ } (which is inside android{ } big section), add the javaCompileOptions{ } section, it will be like:
android{
defaultConfig{
//javaComplieOptions SECTION
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation":"$projectDir/schemas".toString()]
}
}
//Other SECTION
...
}
}
$projectDir:is a variable name, you cannot change it. it will get your own project directory
schemas:is a string, you can change it to any you like. For example:
"$projectDir/MyOwnSchemas".toString()
This is a simple and clean solution - You add an event to the ViewModel and instruct the Window to close itself when that event is fired.
For more details see my blog post, Close window from ViewModel.
XAML:
<Window
x:Name="this"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions">
<i:Interaction.Triggers>
<i:EventTrigger SourceObject="{Binding}" EventName="Closed">
<ei:CallMethodAction
TargetObject="{Binding ElementName=this}"
MethodName="Close"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<Window>
ViewModel:
private ICommand _SaveAndCloseCommand;
public ICommand SaveAndCloseCommand
{
get
{
return _SaveAndCloseCommand ??
(_SaveAndCloseCommand = new DelegateCommand(SaveAndClose));
}
}
private void SaveAndClose()
{
Save();
Close();
}
public event EventHandler Closed;
private void Close()
{
if (Closed != null) Closed(this, EventArgs.Empty);
}
Note: The example uses Prism's DelegateCommand
(see Prism: Commanding), but any ICommand
implementation can be used for that matter.
You can use behaviors from this official package.
To run one project at a time in same solution
Open Solution explorer window -> Open Solution for Project -> Right click on it -> Select Properties from drop down list (Alt+Enter)-> Common Properties -> select Startup Project you will see "current selection,single selection and multiple selection from that select "Current Selection" this will help you to run one project at a time in same solution workspace having different coding.
If you are getting this error with a Java configuration, it is usually because you forget to pass in the application context to the DispatcherServlet
constructor:
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);
ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher",
new DispatcherServlet()); // <-- no constructor args!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
Fix it by adding the context as the constructor arg:
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);
ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher",
new DispatcherServlet(ctx)); // <-- hooray! Spring doesn't look for XML files!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
See the below code (taken from this post)
Put this code in a Module in VBA (Developer Tab -> Visual Basic)
Dim TimerActive As Boolean
Sub StartTimer()
Start_Timer
End Sub
Private Sub Start_Timer()
TimerActive = True
Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End Sub
Private Sub Stop_Timer()
TimerActive = False
End Sub
Private Sub Timer()
If TimerActive Then
ActiveSheet.Cells(1, 1).Value = Time
Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End If
End Sub
You can invoke the "StartTimer" function when the workbook opens and have it repeat every minute by adding the below code to your workbooks Visual Basic "This.Workbook" class in the Visual Basic editor.
Private Sub Workbook_Open()
Module1.StartTimer
End Sub
Now, every time 1 minute passes the Timer procedure will be invoked, and set cell A1 equal to the current time.
The specific way to run it depends on whether you gave the image a tag/name or not.
$ docker images
REPOSITORY TAG ID CREATED SIZE
ubuntu 12.04 8dbd9e392a96 4 months ago 131.5 MB (virtual 131.5 MB)
With a name (let's use Ubuntu):
$ docker run -i -t ubuntu:12.04 /bin/bash
Without a name, just using the ID:
$ docker run -i -t 8dbd9e392a96 /bin/bash
Please see Docker run reference for more information.
It is not possible to programmatically open the permission screen. Instead, we can open the app settings screen.
Code
Intent i = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + BuildConfig.APPLICATION_ID));
startActivity(i);
Sample Output
Unfortunately none of these solutions provided really solve the problem because at the end of the day the APIs are seriously lacking when it comes to providing the pertinent information. You can make a few guesses however using currentUserNotificationSettings
(iOS8+) just isn't sufficient in its current form to really answer the question. Although a lot of the solutions here seem to suggest that either that or isRegisteredForRemoteNotifications
is more of a definitive answer it really is not.
Consider this:
with isRegisteredForRemoteNotifications
documentation states:
Returns YES if the application is currently registered for remote notifications, taking into account any systemwide settings...
However if you throw a simply NSLog
into your app delegate to observe the behavior it is clear this does not behave the way we are anticipating it will work. It actually pertains directly to remote notifications having been activated for this app/device. Once activated for the first time this will always return YES
. Even turning them off in settings (notifications) will still result in this returning YES
this is because, as of iOS8, an app may register for remote notifications and even send to a device without the user having notifications enabled, they just may not do Alerts, Badges and Sound without the user turning that on. Silent notifications are a good example of something you may continue to do even with notifications turned off.
As far as currentUserNotificationSettings
it indicates one of four things:
Alerts are on Badges are on Sound is on None are on.
This gives you absolutely no indication whatsoever about the other factors or the Notification switch itself.
A user may in fact turn off badges, sound and alerts but still have show on lockscreen or in notification center. This user should still be receiving push notifications and be able to see them both on the lock screen and in the notification center. They have the notification switch on. BUT currentUserNotificationSettings
will return: UIUserNotificationTypeNone
in that case. This is not truly indicative of the users actual settings.
A few guesses one can make:
isRegisteredForRemoteNotifications
is NO
then you can assume that this device has never successfully registered for remote notifications.application:didRegisterUserNotificationSettings:
is made containing user notification settings at this time since this is the first time a user has been registered the settings should indicate what the user selected in terms of the permission request. If the settings equate to anything other than: UIUserNotificationTypeNone
then push permission was granted, otherwise it was declined. The reason for this is that from the moment you begin the remote registration process the user only has the ability to accept or decline, with the initial settings of an acceptance being the settings you setup during the registration process.For Windows 7 using the Git found here (it uses MinGW, not Cygwin):
Make sure it's referenced in your web.config:
Unfortunately, as noted in several answers and comments, Write-Host
can be dangerous and cannot be piped to other processes and Write-Output
does not have the -NoNewline
flag.
But those methods are the "*nix" ways to display progression, the "PowerShell" way to do that seems to be Write-Progress
: it displays a bar at the top of the PowerShell window with progress information, available from PowerShell 3.0 onward, see manual for details.
# Total time to sleep
$start_sleep = 120
# Time to sleep between each notification
$sleep_iteration = 30
Write-Output ( "Sleeping {0} seconds ... " -f ($start_sleep) )
for ($i=1 ; $i -le ([int]$start_sleep/$sleep_iteration) ; $i++) {
Start-Sleep -Seconds $sleep_iteration
Write-Progress -CurrentOperation ("Sleep {0}s" -f ($start_sleep)) ( " {0}s ..." -f ($i*$sleep_iteration) )
}
Write-Progress -CurrentOperation ("Sleep {0}s" -f ($start_sleep)) -Completed "Done waiting for X to finish"
And to take the OP's example:
# For the file log
Write-Output "Enabling feature XYZ"
# For the operator
Write-Progress -CurrentOperation "EnablingFeatureXYZ" ( "Enabling feature XYZ ... " )
Enable-SPFeature...
# For the operator
Write-Progress -CurrentOperation "EnablingFeatureXYZ" ( "Enabling feature XYZ ... Done" )
# For the log file
Write-Output "Feature XYZ enabled"
Another cause of this could be if you don't use the default variable name for the "id" which is actually: id.
The other answers didn't work for me, this is what ended up doing the trick for apache2:
1) Enable the headers mod:
sudo a2enmod headers
2) Create the /etc/apache2/mods-enabled/headers.conf
file and insert:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
3) Restart your server:
sudo service apache2 restart
I just got this problem today, since it showed up after Norton requested reboot I blamed Norton.
But it wasn't Norton, I removed Norton, rebooted -> problem still there.
netstat -nao was showing that PID 4 owned my port 80 connection.
I then went to control panel,
then "Turn Windows features on or off"
then unchecked Internet Information Services.
Rebooted, the problem went away.
My xampp server is running ok now.
I don't ever remembering turning IIS on in the first place. I had been running many months before this happened. I still don't know what caused it in the first place. Maybe a previous windows updated enabled iis and my reboot turned it on, I don't know.
Obviously this is a late answer, but I have a better option if you can use .NET 4.5 or newer:
internal static void WriteInformation<T>(string text, [CallerMemberName]string method = "")
{
Console.WriteLine(DateTime.Now.ToString() + " => " + typeof(T).FullName + "." + method + ": " + text);
}
This will print the current Date and Time, followed by "Namespace.ClassName.MethodName" and ending with ": text".
Sample output:
6/17/2016 12:41:49 PM => WpfApplication.MainWindow..ctor: MainWindow initialized
Sample use:
Logger.WriteInformation<MainWindow>("MainWindow initialized");
The given answer is far from complete. In fact, it is so far from complete that it tends to lead the reader to believe that this answer is OS dependent when it isn't. It also isn't something which is programming language dependent (as some commentators have suggested). I'm going to add more information in order to make this more clear. First, lets give the list of current new line variations (as in, what they've been since 1999):
\r\n
is only used on Windows Notepad, the DOS command line, most of the Windows API and in some (older) Windows apps.\n
is used for all other systems, applications and the Internet.You'll notice that I've put most Windows apps in the \n
group which may be slightly controversial but before you disagree with this statement, please grab a UNIX formatted text file and try it in 10 web friendly Windows applications of your choice (which aren't listed in my exceptions above). What percentage of them handled it just fine? You'll find that they (practically) all implement auto detection of line endings or just use \n
because, while Windows may use \r\n
, the Internet uses \n
. Therefore, it is best practice for applications to use \n
alone if you want your output to be Internet friendly.
PHP also defines a newline character called PHP_EOL
. This constant is set to the OS specific newline string for the machine PHP is running on (\r\n
for Windows and \n
for everything else). This constant is not very useful for webpages and should be avoided for HTML output or for writing most text to files. It becomes VERY useful when we move to command line output from PHP applications because it will allow your application to output to a terminal Window in a consistent manner across all supported OSes.
If you want your PHP applications to work from any server they are placed on, the two biggest things to remember are that you should always just use \n
unless it is terminal output (in which case you use PHP_EOL) and you should also ALWAYS use /
for your path separator (not \
).
The even longer explanation:
An application may choose to use whatever line endings it likes regardless of the default OS line ending style. If I want my text editor to print a newline every time it encounters a period that is no harder than using the \n
to represent a newline because I'm interpreting the text as I display it anyway. IOW, I'm fiddling around with measuring the width of each character so it knows where to display the next so it is very simple to add a statement saying that if the current char is a period then perform a newline action (or if it is a \n
then display a period).
Aside from the null terminator, no character code is sacred and when you write a text editor or viewer you are in charge of translating the bits in your file into glyphs (or carriage returns) on the screen. The only thing that distinguishes a control character such as the newline from other characters is that most font sets don't include them (meaning they don't have a visual representation available).
That being said, if you are working at a higher level of abstraction then you probably aren't making your own textbox controls. If this is the case then you're stuck with whatever line ending that control makes available to you. Even in this case it is a simple matter to automatically detect the line ending style of any string and make the conversion before you load your text into the control and then undo it when you read from that control. Meaning, that if you're a desktop application dev and your application doesn't recognize \n
as a newline then it isn't a very friendly application and you really have no excuse because it isn't hard to make it the right way. It also means that whomever wrote Notepad should be ashamed of himself because it really is very easy to do much better and so many people suffer through using it every day.
Query to count the number of columns in a table:
select count(*) from user_tab_columns where table_name = 'tablename';
Replace tablename with the name of the table whose total number of columns you want returned.
On Linux and other UNIX / UNIX-like platforms, the OS places a limit on the number of open file descriptors that a process may have at any given time. In the old days, this limit used to be hardwired1, and relatively small. These days it is much larger (hundreds / thousands), and subject to a "soft" per-process configurable resource limit. (Look up the ulimit
shell builtin ...)
Your Java application must be exceeding the per-process file descriptor limit.
You say that you have 19 files open, and that after a few hundred times you get an IOException saying "too many files open". Now this particular exception can ONLY happen when a new file descriptor is requested; i.e. when you are opening a file (or a pipe or a socket). You can verify this by printing the stacktrace for the IOException.
Unless your application is being run with a small resource limit (which seems unlikely), it follows that it must be repeatedly opening files / sockets / pipes, and failing to close them. Find out why that is happening and you should be able to figure out what to do about it.
FYI, the following pattern is a safe way to write to files that is guaranteed not to leak file descriptors.
Writer w = new FileWriter(...);
try {
// write stuff to the file
} finally {
try {
w.close();
} catch (IOException ex) {
// Log error writing file and bail out.
}
}
1 - Hardwired, as in compiled into the kernel. Changing the number of available fd slots required a recompilation ... and could result in less memory being available for other things. In the days when Unix commonly ran on 16-bit machines, these things really mattered.
UPDATE
The Java 7 way is more concise:
try (Writer w = new FileWriter(...)) {
// write stuff to the file
} // the `w` resource is automatically closed
UPDATE 2
Apparently you can also encounter a "too many files open" while attempting to run an external program. The basic cause is as described above. However, the reason that you encounter this in exec(...)
is that the JVM is attempting to create "pipe" file descriptors that will be connected to the external application's standard input / output / error.
You may catch multiple exceptions in single catch block.
try{
// somecode throwing multiple exceptions;
} catch (Exception1 | Exception2 | Exception3 exception){
// handle exception.
}
@outis's answer is good: concise and correct as regards relations.
However, the situation is slightly more complicated as regards SQL.
Consider the usual suppliers and parts database but implemented in SQL:
SELECT * FROM S NATURAL JOIN SP;
would return a resultset** with columns
SNO, SNAME, STATUS, CITY, PNO, QTY
The join is performed on the column with the same name in both tables, SNO
. Note that the resultset has six columns and only contains one column for SNO
.
Now consider a theta eqijoin, where the column names for the join must be explicitly specified (plus range variables S
and SP
are required):
SELECT * FROM S JOIN SP ON S.SNO = SP.SNO;
The resultset will have seven columns, including two columns for SNO
. The names of the resultset are what the SQL Standard refers to as "implementation dependent" but could look like this:
SNO, SNAME, STATUS, CITY, SNO, PNO, QTY
or perhaps this
S.SNO, SNAME, STATUS, CITY, SP.SNO, PNO, QTY
In other words, NATURAL JOIN
in SQL can be considered to remove columns with duplicated names from the resultset (but alas will not remove duplicate rows - you must remember to change SELECT
to SELECT DISTINCT
yourself).
** I don't quite know what the result of SELECT * FROM table_expression;
is. I know it is not a relation because, among other reasons, it can have columns with duplicate names or a column with no name. I know it is not a set because, among other reasons, the column order is significant. It's not even a SQL table or SQL table expression. I call it a resultset.
UPDATE totals
SET total = total + 1
WHERE name = 'bill';
If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:
UPDATE totals
SET total = total + 1
WHERE name = 'bill'
AND total = 203;
Use setExtendedState(int state)
, where state would be JFrame.MAXIMIZED_BOTH
.
I find that the "solution" of just increasing the timeouts obscures what's really going on here, which is either
You usually encounter #2 when Mocha doesn't receive assertion errors from a callback. This is caused by some other code swallowing the exception further up the stack. The right way of dealing with this is to fix the code and not swallow the error.
When external code swallows your errors
In case it's a library function that you are unable to modify, you need to catch the assertion error and pass it onto Mocha yourself. You do this by wrapping your assertion callback in a try/catch block and pass any exceptions to the done handler.
it('should not fail', function (done) { // Pass reference here!
i_swallow_errors(function (err, result) {
try { // boilerplate to be able to get the assert failures
assert.ok(true);
assert.equal(result, 'bar');
done();
} catch (error) {
done(error);
}
});
});
This boilerplate can of course be extracted into some utility function to make the test a little more pleasing to the eye:
it('should not fail', function (done) { // Pass reference here!
i_swallow_errors(handleError(done, function (err, result) {
assert.equal(result, 'bar');
}));
});
// reusable boilerplate to be able to get the assert failures
function handleError(done, fn) {
try {
fn();
done();
} catch (error) {
done(error);
}
}
Speeding up network tests
Other than that I suggest you pick up the advice on starting to use test stubs for network calls to make tests pass without having to rely on a functioning network. Using Mocha, Chai and Sinon the tests might look something like this
describe('api tests normally involving network calls', function() {
beforeEach: function () {
this.xhr = sinon.useFakeXMLHttpRequest();
var requests = this.requests = [];
this.xhr.onCreate = function (xhr) {
requests.push(xhr);
};
},
afterEach: function () {
this.xhr.restore();
}
it("should fetch comments from server", function () {
var callback = sinon.spy();
myLib.getCommentsFor("/some/article", callback);
assertEquals(1, this.requests.length);
this.requests[0].respond(200, { "Content-Type": "application/json" },
'[{ "id": 12, "comment": "Hey there" }]');
expect(callback.calledWith([{ id: 12, comment: "Hey there" }])).to.be.true;
});
});
See Sinon's nise
docs for more info.
I think what you originally meant to do was to make an array only of characters, not of pointers:
char options[2][100];
options[0][0]='t';
options[0][1]='e';
options[0][2]='s';
options[0][3]='t';
options[0][4]='1';
options[0][5]='\0'; /* NUL termination of C string */
/* A standard C library function which copies strings. */
strcpy(options[1], "test2");
The code above shows two distinct methods of setting the character values in memory you have set aside to contain characters.
Enable GPU Hardware Acceleration (in addition to Intel's HAXM), if you are using API 15 v3 or newer and SDK Tools v17+. Graphics acceleration for the emulator takes advantage of your development computer's graphics hardware, specifically its graphics processing unit (GPU), to make screen drawing faster. This gives a noticeable boost in speed.
To enable graphics acceleration enabled by default on your emulator: when creating the AVD, in the Hardware section, click New, select GPU emulation and set the value to Yes.
To enable acceleration only at runtime: use the -gpu flag while starting the emulator like this:
emulator -avd <avd_name> -gpu on
Source: Google's Using the Emulator tutorial.
Here is a quick and dirty version that uses the local systems settings to work out the time difference. NOTE: This will not work if you need to convert to a timezone that your current system is not running in. I have tested this with UK settings under BST timezone
from datetime import datetime
def ConvertP4DateTimeToLocal(timestampValue):
assert isinstance(timestampValue, int)
# get the UTC time from the timestamp integer value.
d = datetime.utcfromtimestamp( timestampValue )
# calculate time difference from utcnow and the local system time reported by OS
offset = datetime.now() - datetime.utcnow()
# Add offset to UTC time and return it
return d + offset
You can change your target's launch settings in "Manage Scheme" to Wait for <app>.app to be launched manually
, which allows you debug by setting a breakpoint in application: didReceiveRemoteNotification: fetchCompletionHandler:
and sending the push notification to trigger the background launch.
I'm not sure it'll solve the issue, but it may assist you with debugging for now.
Toastr is a very nice component, and you can show messages with theses commands:
// for success - green box
toastr.success('Success messages');
// for errors - red box
toastr.error('errors messages');
// for warning - orange box
toastr.warning('warning messages');
// for info - blue box
toastr.info('info messages');
If you want to provide a title on the toastr message, just add a second argument:
// for info - blue box
toastr.success('The process has been saved.', 'Success');
you also can change the default behaviour using something like this:
toastr.options.timeOut = 3000; // 3s
See more on the github of the project.
A sample of use:
$(document).ready(function() {
// show when page load
toastr.info('Page Loaded!');
$('#linkButton').click(function() {
// show when the button is clicked
toastr.success('Click Button');
});
});
and a html:
<a id='linkButton'>Show Message</a>
I have another solution since the STR() function would result some blank spaces, so I use the FORMAT() function as folowing example:
SELECT ':' + STR(1000.2324422), ':' + FORMAT(1000.2324422,'##.#######'), ':' + FORMAT(1000.2324422,'##')
The result of above code would be:
: 1000 :1000.2324422 :1000
After adding new item to persons
add:
myGrid.DataSource = null;
myGrid.DataSource = persons;
$.getJSON
is an asynchronous request, meaning the code will continue to run even though the request is not yet done. You should trigger the second request when the first one is done, one of the choices you seen already in ComFreek's answer.
Alternatively you could use jQuery's $.when/.then(), similar to this:
var input = "netuetamundis"; var sID; $(document).ready(function () { $.when($.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/" + input + "?api_key=API_KEY_HERE", function () { obj = name; sID = obj.id; console.log(sID); })).then(function () { $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function (stats) { console.log(stats); }); }); });
This would be more open for future modification and separates out the responsibility for the first call to know about the second call.
The first call can simply complete and do it's own thing not having to be aware of any other logic you may want to add, leaving the coupling of the logic separated.
change the background color of cell B5 based on the value of another cell - C5. If C5 is greater than 80% then the background color is green but if it's below, it will be amber/red.
There is no mention that B5 contains any value so assuming 80%
is .8
formatted as percentage without decimals and blank counts as "below":
Select B5, colour "amber/red" with standard fill then Format - Conditional formatting..., Custom formula is and:
=C5>0.8
with green fill and Done.
If you don't mind using gVim, you can launch a single instance, so that when a new file is opened with it it's automatically opened in a new tab in the currently running instance.
to do this you can write: gVim --remote-tab-silent file
You could always make an alias to this command so that you don't have to type so many words.
For example I use linux and bash and in my ~/.bashrc
file I have:
alias g='gvim --remote-tab-silent'
so instead of doing $ mate file
I do: $ g file
I have used both R and MATLAB to solve problems and construct models related to Environmental Engineering and there is a lot of overlap between the two systems. In my opinion, the advantages of MATLAB lie in specialized domain-specific applications. Some examples are:
Functions such as streamline that aid in fluid dynamics investigations.
Toolboxes such as the image processing toolset. I have not found a R package that provides an equivalent implementation of tools like the watershed algorithm.
In my opinion MATLAB provides far better interactive graphics capabilities. However, I think R produces better static print-quality graphics, depending on the application. MATLAB's symbolic math toolbox is also better integrated and more capable than R equivalents such as Ryacas or rSymPy. The existence of the MATLAB compiler also allows systems based on MATLAB code to be deployed independently of the MATLAB environment-- although it's availability will depend on how much money you have to throw around.
Another thing I should note is that the MATLAB debugger is one of the best I have worked with.
The principle advantage I see with R is the openness of the system and the ease with which it can be extended. This has resulted in an incredible diversity of packages on CRAN. I know Mathworks also maintains a repository of user-contributed toolboxes and I can't make a fair comparison as I have not used it that much.
The openness of R also extends to linking in compiled code. A while back I had a model written in Fortran and I was trying to decide between using R or MATLAB as a front-end to help prepare input and process results. I spent an hour reading about the MEX interface to compiled code. When I found that I would have to write and maintain a separate Fortran routine that did some intricate pointer juggling in order to manage the interface, I shelved MATLAB.
The R interface consists of calling .Fortran( [subroutine name], [argument list]) and is simply quicker and cleaner.
Off the top of my cat's head, make sure the div
you're trying to center is not set to width: 100%
.
If it is, then the rules set on the child divs are what will matter.
You can disable need to run Internet Explorer's first launch configuration by running this PowerShell script, it will adjust corresponding registry property:
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Internet Explorer\Main" -Name "DisableFirstRunCustomize" -Value 2
After this, WebClient will work without problems
I use exactly the same sass mixin placeholder as NoDirection wrote. I find it in sass mixins collection here and I'm very satisfied with it. There's a text that explains a mixins option more.
You can try to do what you're doing by manually loading the images, but I would very very strongly recommend taking a look at Universal Image Loader.
I recently integrated it into my project and I have to say its fantastic. Does all the worrying about making things asynchronous, resizing, caching images for you. It's really easy to integrate and set up. Within 5 minutes you can probably get it doing what you want.
Example code:
//ImageLoader config
DisplayImageOptions displayimageOptions = new DisplayImageOptions.Builder().showStubImage(R.drawable.downloadplaceholder).cacheInMemory().cacheOnDisc().showImageOnFail(R.drawable.loading).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()).
defaultDisplayImageOptions(displayimageOptions).memoryCache(new WeakMemoryCache()).discCache(new UnlimitedDiscCache(cacheDir)).build();
if (ImageLoader.getInstance().isInited()) {
ImageLoader.getInstance().destroy();
}
ImageLoader.getInstance().init(config);
imageLoadingListener = new ImageLoadingListener() {
@Override
public void onLoadingStarted(String s, View view) {
}
@Override
public void onLoadingFailed(String s, View view, FailReason failReason) {
ImageView imageView = (ImageView) view;
imageView.setImageResource(R.drawable.android);
Log.i("Failed to Load " + s, failReason.toString());
}
@Override
public void onLoadingComplete(String s, View view, Bitmap bitmap) {
}
@Override
public void onLoadingCancelled(String s, View view) {
}
};
//Imageloader usage
ImageView imageView = new ImageView(getApplicationContext());
if (orientation == 1) {
imageView.setLayoutParams(new LinearLayout.LayoutParams(width / 6, width / 6));
} else {
imageView.setLayoutParams(new LinearLayout.LayoutParams(height / 6, height / 6));
}
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageLoader.displayImage(SERVER_HOSTNAME + "demos" + demo.getPathRoot() + demo.getRootName() + ".png", imageView, imageLoadingListener);
This can lazy load the images, fit them correctly to the size of the imageView showing a placeholder image while it loads, and showing a default icon if loading fails and caching the resources.
-- I should also add that this current config keeps the image aspect ratio, hence applicable to your original question
for(j = 0; j<=90; j++){}
j++ means j=j+1, j value already 0 now we are adding 1 so now the sum value of j+1 became 1, finally we are overriding the j value(0) with the sum value(1) so here we are overriding the j value by j+1. So each iteration j value will be incremented by 1.
for(j = 0; j<=90; j+3){}
Here j+3 means j value already 0 now we are adding 3 so now the sum value of j+3 became 3 but we are not overriding the existing j value. So that JVM asking the programmer, you are calculating the new value but where you are assigning that value to a variable(i.e j). That's why we are getting the compile-time error " invalid AssignmentOperator ".
If we want to increment j value by 3 then we can use any one of the following way.
for (int j=0; j<=90; j+=3) --> here each iteration j value will be incremented by 3.
for (int j=0; j<=90; j=j+3) --> here each iteration j value will be incremented by 3.
I've only ever seen this error on Windows and what it seems to mean is that something blocked git from modifying a file at the moment when it tried to a apply a patch.
Windows tends to give processes exclusive access to files when it shouldn't really be necessary, in the past virus checkers have been one source of suspicion but I've never proved this conclusively.
Probably the easiest thing to do is to abort and try again, hoping that it doesn't happen the next time.
git rebase --abort
You can attempt to use git apply
and knowledge of what commit git was actually trying to do before doing a git rebase --continue
but in all honesty I wouldn't recommend this. Most of the times I've seen this tried there's been a better than evens chance that something gets accidentally missed or messed up.
If your user has a local folder e.g. Linux, in your users home folder you could create a .my.cnf file and provide the credentials to access the server there. for example:-
[client]
host=localhost
user=yourusername
password=yourpassword or exclude to force entry
database=mygotodb
Mysql would then open this file for each user account read the credentials and open the selected database.
Not sure on Windows, I upgraded from Windows because I needed the whole house not just the windows (aka Linux) a while back.
This is used in several apps to clean user-generated content removing extra spacing/returns etc but retains the meaning of spaces.
text.replace(/[\n\r\s\t]+/g, ' ')
You have to use image
.listStyle {
list-style: none;
background: url(bullet.jpg) no-repeat left center;
padding-left: 40px;
}
Use document.title
:
console.log(document.title)
_x000D_
<title>Title test</title>
_x000D_
Expanding on the bitset
answer:
#include <iostream>
#include <bitset>
#include <string>
using namespace std;
int main() {
bitset<8> byte(std::string("10010011");
// Set Bit
byte.set(3); // 10010111
// Clear Bit
byte.reset(2); // 10010101
// Toggle Bit
byte.flip(7); // 00010101
cout << byte << endl;
return 0;
}
To check if variable is null or empty use this:
IF LEN(ISNULL(@var, '')) = 0
-- Is empty or NULL
ELSE
-- Is not empty and is not NULL
Alternate way.
If you don't want to add the PATH as the previous well written answers pointed out,
but you want to execute pip as your command then you can do that with py -m
as prefix.
Given that you have to do it again and again.
eg.
py -m <command>
as in
py -m pip install --upgrade pip setuptools
Also make sure to have pip
and py
installed
Boost contains cstdint.hpp header file with the types you are looking for: http://www.boost.org/doc/libs/1_36_0/boost/cstdint.hpp
Made this new helper function in TypeScript, maybe someone will appreciate it. If you remove type declaration from script parameter it will just be plain JS.
const evalPageScripts = () => {
const scripts = document.querySelectorAll('script');
scripts.forEach((script: HTMLScriptElement) => {
const newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = script.src;
if (script.parentNode) {
script.parentNode.removeChild(script);
}
return document.body.appendChild(newScript);
})
};
export default evalPageScripts;
_x000D_
I would read into a ByteArrayOutputStream and then call toByteArray() to get the resultant byte array. You don't need to define the size in advance (although it's possibly an optimisation if you know it. In many cases you won't)
One way to achieve this is with a custom directive. Here's an example using a custom directive (ng-match
in this case):
<p>Email:<input type="email" name="email1" ng-model="emailReg">
Repeat Email:<input type="email" name="email2" ng-model="emailReg2" ng-match="emailReg"></p>
<span data-ng-show="myForm.emailReg2.$error.match">Emails have to match!</span>
NOTE: It's not generally recommended to use ng-
as a prefix for a custom directive because it may conflict with an official AngularJS directive.
It's also possible to get this functionality without using a custom directive:
HTML
<button ng-click="add()></button>
<span ng-show="IsMatch">Emails have to match!</span>
Controller
$scope.add = function() {
if ($scope.emailReg != $scope.emailReg2) {
$scope.IsMatch=true;
return false;
}
$scope.IsMatch=false;
}
If you don't want to include any extra CSS you can just use the button color classes into the nav-link element, it will format the pill just the same as a regular button.
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>_x000D_
_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>_x000D_
_x000D_
<ul class="nav nav-pills p-3">_x000D_
<li class="nav-item">_x000D_
<a class="nav-link active" href="#">Normal</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link active btn-primary" href="#">Primary</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link active btn-secondary" href="#">Secondary</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link active btn-success" href="#">Success</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link active btn-warning" href="#">Warning</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link active btn-danger" href="#">Danger</a>_x000D_
</li>_x000D_
_x000D_
</ul>
_x000D_
You need to compile the bibtex file.
Suppose you have article.tex
and article.bib
. You need to run:
latex article.tex
(this will generate a document with question marks in place of unknown references)bibtex article
(this will parse all the .bib files that were included in the article and generate metainformation regarding references)latex article.tex
(this will generate document with all the references in the correct places)latex article.tex
(just in case if adding references broke page numbering somewhere)Leaving aside the fact that they are private
, since a
and b
are members of A
, they are meant to be initialized by A
's constructors, not by some other class's constructors (derived or not).
Try:
class A
{
int a, b;
protected: // or public:
A(int a, int b): a(a), b(b) {}
};
class B : public A
{
B() : A(0, 0) {}
};
Yes, it is possible as follows. These colours can be used in a console application to view some errors in red, etc.
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;//after this line every text will be white on blue background
Console.WriteLine("White on blue.");
Console.WriteLine("Another line.");
Console.ResetColor();//reset to the defoult colour
In modern browsers you can use Object.getOwnPropertyNames
to get all properties (both enumerable and non-enumerable) on an object. For instance:
function Person ( age, name ) {
this.age = age;
this.name = name;
}
Person.prototype.greet = function () {
return "My name is " + this.name;
};
Person.prototype.age = function () {
this.age = this.age + 1;
};
// ["constructor", "greet", "age"]
Object.getOwnPropertyNames( Person.prototype );
Note that this only retrieves own-properties, so it will not return properties found elsewhere on the prototype chain. That, however, doesn't appear to be your request so I will assume this approach is sufficient.
If you would only like to see enumerable properties, you can instead use Object.keys
. This would return the same collection, minus the non-enumerable constructor
property.
COMMAND: python --version && python3 --version
OUTPUT:
Python 2.7.10
Python 3.7.1
ALIAS COMMAND: pyver
OUTPUT:
Python 2.7.10
Python 3.7.1
You can make an alias like "pyver" in your .bashrc file or else using a text accelerator like AText maybe.
You can find clear difference between interface and abstract class.
Interface
Abstract class
Abstract class contains abstract and non-abstract methods.
Does not force users to implement all methods when inherited the abstract class.
Contains all kinds of variables including primitive and non-primitive
Declare using abstract keyword.
Methods and members of an abstract class can be defined with any visibility.
A child class can only extend a single class (abstract or concrete).
JFrame and JApplet are top level containers. If you wish to create a desktop application, you will use JFrame and if you plan to host your application in browser you will use JApplet.
JComponent is an abstract class for all Swing components and you can use it as the base class for your new component. JPanel is a simple usable component you can use for almost anything.
Since this is for a fun project, the simplest way for you is to work with JPanel and then host it inside JFrame or JApplet. Netbeans has a visual designer for Swing with simple examples.
for Lat,Long in zip(Latitudes, Longitudes):
Java has two kind of Variables
a)
Class Level (Static) :
They are one per Class.Say you have Student Class and defined name as static variable.Now no matter how many student object you create all will have same name.
Object Level :
They belong to per Object.If name is non-static ,then all student can have different name.
b)
Class Level :
This variables are initialized on Class load.So even if no student object is created you can still access and use static name variable.
Object Level:
They will get initialized when you create a new object ,say by new();
C)
Your Problem :
Your class is Just loaded in JVM and you have called its main (static) method : Legally allowed.
Now from that you want to call an Object varibale : Where is the object ??
You have to create a Object and then only you can access Object level varibales.
Try This write after
initcomponents();
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("Your image address")));
select *
from blah
where DatetimeField between '22/02/2009 09:00:00.000' and '23/05/2009 10:30:00.000'
Depending on the country setting for the login, the month/day may need to be swapped around.
List the packages by:
adb shell su 0 pm list packages
Review which package you want to uninstall and copy the package name from there. For example:
com.android.calculator2
Lastly type in:
adb uninstall com.android.calculator2
and you are done.
I solve the problem. So simple. Syntax error.
But I also want to know how to pass a function with parameters to view....
You might want colored output with this.
I use this one-liner for listing the tracked files and directories in the current directory of the current branch:
ls --group-directories-first --color=auto -d $(git ls-tree $(git branch | grep \* | cut -d " " -f2) --name-only)
You might want to add it as an alias:
alias gl='ls --group-directories-first --color=auto -d $(git ls-tree $(git branch | grep \* | cut -d " " -f2) --name-only)'
If you want to recursively list files:
'ls' --color=auto -d $(git ls-tree -rt $(git branch | grep \* | cut -d " " -f2) --name-only)
And an alias:
alias glr="'ls' --color=auto -d \$(git ls-tree -rt \$(git branch | grep \\* | cut -d \" \" -f2) --name-only)"
The shape
method requires that a
be a Numpy ndarray. But Numpy can also calculate the shape of iterables of pure python objects:
np.shape([[1,2],[1,2]])
That's my way:
$lines = preg_split('/[\r\n]+/', $db_text, NULL, PREG_SPLIT_NO_EMPTY);
This also will skip all empty lines too.
<script type="text/JavaScript">
setTimeout("location.href = 'http://www.your_site.com';",1500);
</script>
Use dict() on a list of tuples, this solution will allow you to have arbitrary values in each list, so long as they are the same length
i_s = range(1, 11)
x_s = range(1, 11)
# x_s = range(11, 1, -1) # Also works
d = dict([(i_s[index], x_s[index], ) for index in range(len(i_s))])
This may sound like the long way around, but you may want to look at using Excel to generate INSERT SQL code that you can past into Query Analyzer to create your table.
Works well if you cant use the wizards because the excel file isn't on the server
This just happened to me in a foreach loop. I had inadvertently typed ($array as $key as $value)
and PHP objected to the first as
.
As others stated, it's likely failing because the requested key doesn't exist in the array. I have a helper function here that takes the array, the suspected key, as well as a default return in the event the key does not exist.
protected function _getArrayValue($array, $key, $default = null)
{
if (isset($array[$key])) return $array[$key];
return $default;
}
hope it helps.
The code was most likely compiled with a later JDK (without using cross-compilation options) and is being run on an earlier JRE. While upgrading the JRE is one solution, it would be better to use the cross-compilation options to ensure the code will run on whatever JRE is intended as the minimum version for the app.
Don't forget that there is a difference between bash's builtin time
(which should be called by default when you do time command
) and /usr/bin/time
(which should require you to call it by its full path).
The builtin time
always prints to stderr, but /usr/bin/time
will allow you to send time's output to a specific file, so you do not interfere with the executed command's stderr stream. Also, /usr/bin/time
's format is configurable on the command line or by the environment variable TIME
, whereas bash's builtin time
format is only configured by the TIMEFORMAT
environment variable.
$ time factor 1234567889234567891 # builtin
1234567889234567891: 142662263 8653780357
real 0m3.194s
user 0m1.596s
sys 0m0.004s
$ /usr/bin/time factor 1234567889234567891
1234567889234567891: 142662263 8653780357
1.54user 0.00system 0:02.69elapsed 57%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (0major+215minor)pagefaults 0swaps
$ /usr/bin/time -o timed factor 1234567889234567891 # log to file `timed`
1234567889234567891: 142662263 8653780357
$ cat timed
1.56user 0.02system 0:02.49elapsed 63%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (0major+217minor)pagefaults 0swaps
(INNER) JOIN: Returns records that have matching values in both tables.
LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right table.
RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left table.
FULL (OUTER) JOIN: Return all records when there is a match in either left or right table
For example, lets suppose we have two table with following records:
Table A
id firstname lastname
___________________________
1 Ram Thapa
2 sam Koirala
3 abc xyz
6 sruthy abc
Table B
id2 place
_____________
1 Nepal
2 USA
3 Lumbini
5 Kathmandu
Inner Join
Note: It give the intersection of two table.
Syntax
SELECT column_name FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name;
Apply it in your sample table:
SELECT TableA.firstName,TableA.lastName,TableB.Place FROM TableA INNER JOIN TableB ON TableA.id = TableB.id2;
Result will be:
firstName lastName Place
_____________________________________
Ram Thapa Nepal
sam Koirala USA
abc xyz Lumbini
Left Join
Note : will give all selected rows in TableA, plus any common selected rows in TableB.
SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;
Apply it in your sample table
SELECT TableA.firstName,TableA.lastName,TableB.Place FROM TableA LEFT JOIN TableB ON TableA.id = TableB.id2;
Result will be:
firstName lastName Place
______________________________
Ram Thapa Nepal
sam Koirala USA
abc xyz Lumbini
sruthy abc Null
Right Join
Note:will give all selected rows in TableB, plus any common selected rows in TableA.
Syntax:
SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name;
Apply it in your samole table:
SELECT TableA.firstName,TableA.lastName,TableB.Place FROM TableA RIGHT JOIN TableB ON TableA.id = TableB.id2;
Result will bw:
firstName lastName Place
______________________________
Ram Thapa Nepal
sam Koirala USA
abc xyz Lumbini
Null Null Kathmandu
Full Join
Note : It is same as union operation, it will return all selected values from both tables.
Syntax:
SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name = table2.column_name;
Apply it in your samp[le table:
SELECT TableA.firstName,TableA.lastName,TableB.Place FROM TableA FULL JOIN TableB ON TableA.id = TableB.id2;
Result will be:
firstName lastName Place
______________________________
Ram Thapa Nepal
sam Koirala USA
abc xyz Lumbini
sruthy abc Null
Null Null Kathmandu
Some facts
For INNER joins the order doesn't matter
For (LEFT, RIGHT or FULL) OUTER joins,the order matter
Find More at w3schools
For those that like to work with small numbers
const today = new Date();
const endDate = new Date(startDate.setDate(startDate.getDate() + 7));
const days = parseInt((endDate - today) / (1000 * 60 * 60 * 24));
const hours = parseInt(Math.abs(endDate - today) / (1000 * 60 * 60) % 24);
const minutes = parseInt(Math.abs(endDate.getTime() - today.getTime()) / (1000 * 60) % 60);
const seconds = parseInt(Math.abs(endDate.getTime() - today.getTime()) / (1000) % 60);
const times = 4;
new Array(times).fill().map(() => console.log('test'));
This snippet will console.log
test
4 times.
If Khanh TO's solution caused UI issues for you (like it did for me) try using $timeout
to not update the attribute until it has been unchanged for 500ms.
var oldWidth = window.innerWidth;
$(window).on('resize.doResize', function () {
var newWidth = window.innerWidth,
updateStuffTimer;
if (newWidth !== oldWidth) {
$timeout.cancel(updateStuffTimer);
}
updateStuffTimer = $timeout(function() {
updateStuff(newWidth); // Update the attribute based on window.innerWidth
}, 500);
});
$scope.$on('$destroy',function (){
$(window).off('resize.doResize'); // remove the handler added earlier
});
Reference: https://gist.github.com/tommaitland/7579618
git config --global http.postBuffer 524288000
Work in my case - AWS code commit
I suggest to use construction like
<style>
.hr { height:0; border-top:1px solid _anycolor_; }
.hr hr { display:none }
</style>
<div class="hr"><hr /></div>
Figuring out package dependencies is really not that hard. You rarely do it anyway. Probably once during project setup and few more during upgrades. With maven you'll end up fixing mismatched dependencies, badly written poms, and doing package exclusions anyway.
Not that hard... for toy projects. But the projects I work on have many, really many, of them, and I'm very glad to get them transitively, to have a standardized naming scheme for them. Managing all this manually by hand would be a nightmare.
And yes, sometimes you have to work on the convergence of dependencies. But think about it twice, this is not inherent to Maven, this is inherent to any system using dependencies (and I am talking about Java dependencies in general here).
So with Ant, you have to do the same work except that you have to do everything manually: grabbing some version of project A and its dependencies, grabbing some version of project B and its dependencies, figuring out yourself what exact versions they use, checking that they don't overlap, checking that they are not incompatible, etc. Welcome to hell.
On the other hand, Maven supports dependency management and will retrieve them transitively for me and gives me the tooling I need to manage the complexity inherent to dependency management: I can analyze a dependency tree, control the versions used in transitive dependencies, exclude some of them if required, control the converge across modules, etc. There is no magic. But at least you have support.
And don't forget that dependency management is only a small part of what Maven offers, there is much more (not even mentioning the other tools that integrates nicely with Maven, e.g. Sonar).
Slow FIX-COMPILE-DEPLOY-DEBUG cycle, which kills productivity. This is my main gripe. You make a change, the you have to wait for maven build to kick in and wait for it to deploy. No hot deployment whatsoever.
First, why do you use Maven like this? I don't. I use my IDE to write tests, code until they pass, refactor, deploy, hot deploy and run a local Maven build when I'm done, before to commit, to make sure I will not break the continuous build.
Second, I'm not sure using Ant would make things much better. And to my experience, modular Maven builds using binary dependencies gives me faster build time than typical monolithic Ant builds. Anyway, have a look at Maven Shell for a ready to (re)use Maven environment (which is awesome by the way).
So at end, and I'm sorry to say so, it's not really Maven that is killing your productivity, it's you misusing your tools. And if you're not happy with it, well, what can I say, don't use it. Personally, I'm using Maven since 2003 and I never looked back.
We can say like DispatcherServlet
taking care of everything in Spring MVC.
At web container start up:
DispatcherServlet
will be loaded and initialized by calling
init()
methodinit()
of DispatcherServlet
will try to identify the Spring
Configuration Document with naming conventions like
"servlet_name-servlet.xml"
then all beans can be identified.Example:
public class DispatcherServlet extends HttpServlet {
ApplicationContext ctx = null;
public void init(ServletConfig cfg){
// 1. try to get the spring configuration document with default naming conventions
String xml = "servlet_name" + "-servlet.xml";
//if it was found then creates the ApplicationContext object
ctx = new XmlWebApplicationContext(xml);
}
...
}
So, in generally DispatcherServlet
capture request URI and hand over to HandlerMapping
. HandlerMapping
search mapping bean with method of controller, where controller returning logical name(view). Then this logical name is send to DispatcherServlet
by HandlerMapping
. Then DispatcherServlet
tell ViewResolver
to give full location of view by appending prefix and suffix, then DispatcherServlet
give view to the client.
scrollintoview()
increases usabilityInstead of default DOM implementation you can use a plugin that animates movement and doesn't have any unwanted effects. Here's the simplest way of using it with defaults:
$("yourTargetLiSelector").scrollintoview();
Anyway head over to this blog post where you can read all the details and will eventually get you to GitHub source codeof the plugin.
This plugin automatically searches for the closest scrollable ancestor element and scrolls it so that selected element is inside its visible view port. If the element is already in the view port it doesn't do anything of course.
aspirinemaga, just replace:
$this->db->set('time', 'NOW()', FALSE);
$this->db->insert('mytable', $data);
for it:
$this->db->set('time', 'NOW() + INTERVAL 1 DAY', FALSE);
$this->db->insert('mytable', $data);
test open the termenal or cmd. go to the [tomcat-home]\bin directory. ex: c:\tomcat8\bin write the following command: Tomcat8W //ES//Tomcat8 will open dialog, select the java tap(top tap). change the Java virtual Machine value.
These all do {1..8}
and should all be POSIX. They also will not break if you
put a conditional continue
in the loop. The canonical way:
f=
while [ $((f+=1)) -le 8 ]
do
echo $f
done
Another way:
g=
while
g=${g}1
[ ${#g} -le 8 ]
do
echo ${#g}
done
and another:
set --
while
set $* .
[ ${#} -le 8 ]
do
echo ${#}
done
While you can do
value = d.values()[index]
It should be faster to do
value = next( v for i, v in enumerate(d.itervalues()) if i == index )
edit: I just timed it using a dict of len 100,000,000 checking for the index at the very end, and the 1st/values() version took 169 seconds whereas the 2nd/next() version took 32 seconds.
Also, note that this assumes that your index is not negative
I'd like explain the different alter table syntaxes - See the MySQL documentation
For adding/removing defaults on a column:
ALTER TABLE table_name
ALTER COLUMN col_name {SET DEFAULT literal | DROP DEFAULT}
For renaming a column, changing it's data type and optionally changing the column order:
ALTER TABLE table_name
CHANGE [COLUMN] old_col_name new_col_name column_definition
[FIRST|AFTER col_name]
For changing a column's data type and optionally changing the column order:
ALTER TABLE table_name
MODIFY [COLUMN] col_name column_definition
[FIRST | AFTER col_name]
Chain
You can now use the chain
feature in packed
mode as describe in Eugene's answer.
Guideline
You can use a horizontal guideline at 50% position and add bottom and top (8dp) constraints to edittext and button:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<android.support.design.widget.TextInputLayout
android:id="@+id/client_id_input_layout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="@+id/guideline"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent">
<android.support.design.widget.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/login_client_id"
android:inputType="textEmailAddress"/>
</android.support.design.widget.TextInputLayout>
<android.support.v7.widget.AppCompatButton
android:id="@+id/authenticate"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@string/login_auth"
app:layout_constraintTop_toTopOf="@+id/guideline"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"/>
<android.support.constraint.Guideline
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/guideline"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5"/>
</android.support.constraint.ConstraintLayout>
The concise version:
String dateStr = "06/27/2007";
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = (Date)formatter.parse(dateStr);
Add a try/catch block for a ParseException to ensure the format is a valid date.
DO NOT use git push origin --mirror UNDER ALMOST ANY CIRCUMSTANCE.
It does not ask if you're sure you want to do this, and you'd better be sure, because it will erase all of your remote branches that are not on your local box.
For Python >= 2.7, use subprocess.check_output()
.
http://docs.python.org/2/library/subprocess.html#subprocess.check_output
The answer your question: the correct way to refer to a different sheet is by appropriately qualifying each Range
you use.
Please read this explanation and its conclusion, which I guess will give essential information.
The error you are getting is likely due to the sought-for value Sheet2!D2
not being found in the searched range Sheet1!A1:A65536
. This may stem from two cases:
The value is actually not present (pointed out by chris nielsen).
You are searching the wrong Range. If the ActiveSheet
is Sheet1
, then using Range("D2")
without qualifying it will be searching for Sheet1!D2
, and it will throw the same error even if the sought-for value is present in the correct Range.
Code accounting for this (and items below) follows:
Sub srch()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim srchres As Variant
Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
On Error Resume Next
srchres = Application.WorksheetFunction.VLookup(ws2.Range("D2"), ws1.Range("A1:C65536"), 1, False)
On Error GoTo 0
If (IsEmpty(srchres)) Then
ws2.Range("E2").Formula = CVErr(xlErrNA) ' Use whatever you want
Else
ws2.Range("E2").Value = srchres
End If
End Sub
I will point out a few additional notable points:
Catching the error as done by chris nielsen is a good practice, probably mandatory if using Application.WorksheetFunction.VLookup
(although it will not suitably handle case 2 above).
This catching is actually performed by the function VLOOKUP
as entered in a cell (and, if the sought-for value is not found, the result of the error is presented as #N/A
in the result). That is why the first soluton by L42 does not need any extra error handling (it is taken care by =VLOOKUP...
).
Using =VLOOKUP...
is fundamentally different from Application.WorksheetFunction.VLookup
: the first leaves a formula, whose result may change if the cells referenced change; the second writes a fixed value.
Both solutions by L42 qualify Ranges suitably.
You are searching the first column of the range, and returning the value in that same column. Other functions are available for that (although yours works fine).
Least amount of markup possible (you only need one span):
<p>This text is left. <span>This text is right.</span></p>
How you want to achieve the left/right styles is up to you, but I would recommend an external style on an ID or a class.
The full HTML:
<p class="split-para">This text is left. <span>This text is right.</span></p>
And the CSS:
.split-para { display:block;margin:10px;}
.split-para span { display:block;float:right;width:50%;margin-left:10px;}
Use .toInt()
for int .toFloat()
for float and .toDouble()
for double
I was reciving some date from my arduino uno (0-1023 numbers). Using code from 1337holiday, jwygralak67 and some tips from other sources:
import serial
import time
ser = serial.Serial(
port='COM4',\
baudrate=9600,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout=0)
print("connected to: " + ser.portstr)
#this will store the line
seq = []
count = 1
while True:
for c in ser.read():
seq.append(chr(c)) #convert from ANSII
joined_seq = ''.join(str(v) for v in seq) #Make a string from array
if chr(c) == '\n':
print("Line " + str(count) + ': ' + joined_seq)
seq = []
count += 1
break
ser.close()
Install it by running
python setup.py install
Better yet, you can download from github. Install git via apt-get install git
and then follow this steps:
git clone https://github.com/mwaskom/seaborn.git
cd seaborn
python setup.py install
You can also use a regular expression as a field separator. The following will print "bar" by using a regular expression to set the number "10" as a separator.
echo "foo 10 bar" | awk -F'[0-9][0-9]' '{print $2}'
Late answer, but I figured I should add a link to my site because I have written a tutorial how to make an image cache for android: http://squarewolf.nl/2010/11/android-image-cache/ Update: the page has been taken offline as the source was outdated. I join @elenasys in her advice to use Ignition.
So to all the people who stumble upon this question and haven't found a solution: hope you enjoy! =D
You can use this variant:
import lombok.Getter;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonProperty;
//...
@JsonProperty(value = "rr") // for deserialization
@Getter(onMethod_ = {@JsonGetter(value = "r")}) // for serialization
private String rrrr;
with Lombok getter
This is likely caused by your application's connection pool; not an Oracle DBMS issue. Most connection pools have a validate statement that can execute before giving you the connection. In oracle you would want "Select 1 from dual".
The reason it started occurring after you restarted the server is that the connection pool was probably added without a restart and you are just now experiencing the use of the connection pool for the first time. What is the modification dates on your resource files that deal with database connections?
Validate Query example:
<Resource name="jdbc/EmployeeDB" auth="Container"
validationQuery="Select 1 from dual" type="javax.sql.DataSource" username="dbusername" password="dbpassword"
driverClassName="org.hsql.jdbcDriver" url="jdbc:HypersonicSQL:database"
maxActive="8" maxIdle="4"/>
EDIT: In the case of Grails, there are similar configuration options for the grails pool. Example for Grails 1.2 (see release notes for Grails 1.2)
dataSource {
pooled = true
dbCreate = "update"
url = "jdbc:mysql://localhost/yourDB"
driverClassName = "com.mysql.jdbc.Driver"
username = "yourUser"
password = "yourPassword"
properties {
maxActive = 50
maxIdle = 25
minIdle = 5
initialSize = 5
minEvictableIdleTimeMillis = 60000
timeBetweenEvictionRunsMillis = 60000
maxWait = 10000
}
}
This is my .env mail settings
MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=hello27
MAIL_ENCRYPTION=tls
i was getting thesame error as stated in the question but by using
php artisan config:cache
Everything worked fine
You could use the following code, it does a recursive call into the function in order to properly wait for the desired time.
function exportar(page,miliseconds,totalpages)
{
if (page <= totalpages)
{
nextpage = page + 1;
console.log('fnExcelReport('+ page +'); nextpage = '+ nextpage + '; miliseconds = '+ miliseconds + '; totalpages = '+ totalpages );
fnExcelReport(page);
setTimeout(function(){
exportar(nextpage,miliseconds,totalpages);
},miliseconds);
};
}
One of the way you can achieve this is:
Now your java program can be opened in a fancy way just like any other MSWindows apps.! :)
# Make sure only root can run our script
if [ "$(id -u)" != "0" ]; then
echo "This script must be run as root" 1>&2
exit 1
fi
This code will execute two commands.bat that exist in the path C:/folders/folder.
Runtime.getRuntime().exec("cd C:/folders/folder & call commands.bat");
Take This as an alternate to startActivityforResult.But keep in mind that for such cases this approach can be expensive in terms of performance but in some cases you might need to use.
In Activity2,
@Override
public void onBackPressed() {
String data = mEditText.getText();
SharedPreferences sp = getSharedPreferences("LoginInfos", 0);
Editor editor = sp.edit();
editor.putString("email",data);
editor.commit();
}
In Activity1,
@Override
public void onResume() {
SharedPreferences sp = getSharedPreferences("LoginInfos", 0);
String dataFromOtherAct= sp.getString("email", "no email");
}
To hide Navigation bar :
[self.navigationController setNavigationBarHidden:YES animated:YES];
To show Navigation bar :
[self.navigationController setNavigationBarHidden:NO animated:YES];
I was just faced with a similar problem. I exported the contents of the db into one sql file and used TextEdit to find and replace everything I needed. Simplicity ftw!
In my case I am working in a container and unfortuantely pytest has the tendency to use python2.7 rather than my python3 interpreter of choice.
In my case this worked:
python3 -m pytest
My folder structure
/
app/
-module1.py
-module2.py
-tests/
--test_module1.py
--test_module2.py
requirements.txt
README.md
A simple solution that works for me, to work with console ability(ReadKey, String with Format and arg etc) and to see and save the output:
I write TextWriter that write to Console
and to Trace
and replace the Console.Out
with it.
if you use Dialog -> Debugging -> Check the "Redirect All Output Window Text to the Immediate Window" you get it in the Immediate Window and pretty clean.
my code: in start of my code:
Console.SetOut(new TextHelper());
and the class:
public class TextHelper : TextWriter
{
TextWriter console;
public TextHelper() {
console = Console.Out;
}
public override Encoding Encoding => this.console.Encoding;
public override void WriteLine(string format, params object[] arg)
{
string s = string.Format(format, arg);
WriteLine(s);
}
public override void Write(object value)
{
console.Write(value);
System.Diagnostics.Trace.Write(value);
}
public override void WriteLine(object value)
{
Write(value);
Write("\n");
}
public override void WriteLine(string value)
{
console.WriteLine(value);
System.Diagnostics.Trace.WriteLine(value);
}
}
Note: I override just what I needed so if you write other types you should override more
The below example is self explainatory. where refs and events can be used to call function from and to parent and child.
// PARENT
<template>
<parent>
<child
@onChange="childCallBack"
ref="childRef"
:data="moduleData"
/>
<button @click="callChild">Call Method in child</button>
</parent>
</template>
<script>
export default {
methods: {
callChild() {
this.$refs.childRef.childMethod('Hi from parent');
},
childCallBack(message) {
console.log('message from child', message);
}
}
};
</script>
// CHILD
<template>
<child>
<button @click="callParent">Call Parent</button>
</child>
</template>
<script>
export default {
methods: {
callParent() {
this.$emit('onChange', 'hi from child');
},
childMethod(message) {
console.log('message from parent', message);
}
}
}
</script>
@ian this is not 100% accurate. If you have several iframes in a page you will have multiple onPageFinished (and onPageStarted). And if you have several redirects it may also fail. This approach solves (almost) all the problems:
boolean loadingFinished = true;
boolean redirect = false;
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
if (!loadingFinished) {
redirect = true;
}
loadingFinished = false;
webView.loadUrl(urlNewString);
return true;
}
@Override
public void onPageStarted(WebView view, String url) {
loadingFinished = false;
//SHOW LOADING IF IT ISNT ALREADY VISIBLE
}
@Override
public void onPageFinished(WebView view, String url) {
if (!redirect) {
loadingFinished = true;
//HIDE LOADING IT HAS FINISHED
} else {
redirect = false;
}
}
});
UPDATE:
According to the documentation: onPageStarted will NOT be called when the contents of an embedded frame changes, i.e. clicking a link whose target is an iframe.
I found a specific case like that on Twitter where only a pageFinished was called and messed the logic a bit. To solve that I added a scheduled task to remove loading after X seconds. This is not needed in all the other cases.
UPDATE 2:
Now with current Android WebView implementation:
boolean loadingFinished = true;
boolean redirect = false;
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(
WebView view, WebResourceRequest request) {
if (!loadingFinished) {
redirect = true;
}
loadingFinished = false;
webView.loadUrl(request.getUrl().toString());
return true;
}
@Override
public void onPageStarted(
WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
loadingFinished = false;
//SHOW LOADING IF IT ISNT ALREADY VISIBLE
}
@Override
public void onPageFinished(WebView view, String url) {
if (!redirect) {
loadingFinished = true;
//HIDE LOADING IT HAS FINISHED
} else {
redirect = false;
}
}
});
I use this query to get it:
SELECT name FROM sqlite_master WHERE type='table'
And to use in iOS:
NSString *aStrQuery=[NSString stringWithFormat:@"SELECT name FROM sqlite_master WHERE type='table'"];
Everything you write in your own stylesheet is overwriting the user agent styles - that's the point of writing your own stylesheet.
You can just concatenate them.
SET ABS_PATH=%~dp0
SET REL_PATH=..\SomeFile.txt
SET COMBINED_PATH=%ABS_PATH%%REL_PATH%
it looks odd with \..\ in the middle of your path but it works. No need to do anything crazy :)
you cant change the background of checkbox but some how you can do a trick try this :)
.divBox {_x000D_
width: 20px;_x000D_
height: 20px;_x000D_
background: #ddd;_x000D_
margin: 20px 90px;_x000D_
position: relative;_x000D_
-webkit-box-shadow: 0px 1px 3px rgba(0,0,0,0.5);_x000D_
-moz-box-shadow: 0px 1px 3px rgba(0,0,0,0.5);_x000D_
box-shadow: 0px 1px 3px rgba(0,0,0,0.5);_x000D_
}_x000D_
_x000D_
.divBox label {_x000D_
display: block;_x000D_
width: 20px;_x000D_
height: 20px;_x000D_
-webkit-transition: all .5s ease;_x000D_
-moz-transition: all .5s ease;_x000D_
-o-transition: all .5s ease;_x000D_
-ms-transition: all .5s ease;_x000D_
transition: all .5s ease;_x000D_
cursor: pointer;_x000D_
position: absolute;_x000D_
top: 1px;_x000D_
z-index: 1;_x000D_
/* _x000D_
use this background transparent to check the value of checkbox _x000D_
background: transparent;_x000D_
*/_x000D_
background: Black;_x000D_
-webkit-box-shadow:inset 0px 1px 3px rgba(0,0,0,0.5);_x000D_
-moz-box-shadow:inset 0px 1px 3px rgba(0,0,0,0.5);_x000D_
box-shadow:inset 0px 1px 3px rgba(0,0,0,0.5);_x000D_
}_x000D_
_x000D_
.divBox input[type=checkbox]:checked + label {_x000D_
background: green;_x000D_
}
_x000D_
<div class="divBox">_x000D_
<input type="checkbox" value="1" id="checkboxFourInput"name="" />_x000D_
<label for="checkboxFourInput"></label>_x000D_
</div>
_x000D_
class BooleanTester
{
boolean primitive;
Boolean object;
public static void main(String[] args) {
BooleanTester booleanTester = new BooleanTester();
System.out.println("primitive: " + booleanTester.getPrimitive());
System.out.println("object: " + booleanTester.getObject());
}
public boolean getPrimitive() {
return primitive;
}
public Boolean getObject() {
return object;
}
}
output:
primitive: false
object: null
This seems obvious but I had a situation where Jackson, while serializing an object to JSON, was throwing an NPE after calling a getter, just like this one, that returns a primitive boolean which was not assigned. This led me to believe that Jackson was receiving a null and trying to call a method on it, hence the NPE. I was wrong.
Moral of the story is that when Java allocates memory for a primitive, that memory has a value even if not initialized, which Java equates to false for a boolean. By contrast, when allocating memory for an uninitialized complex object like a Boolean, it allocates only space for a reference to that object, not the object itself - there is no object in memory to refer to - so resolving that reference results in null.
I think that strictly speaking, "defaults to false" is a little off the mark. I think Java does not allocate the memory and assign it a value of false until it is explicitly set; I think Java allocates the memory and whatever value that memory happens to have is the same as the value of 'false'. But for practical purpose they are the same thing.
In Python 3.8+ you can do
import hashlib
with open("your_filename.png", "rb") as f:
file_hash = hashlib.md5()
while chunk := f.read(8192):
file_hash.update(chunk)
print(file_hash.digest())
print(file_hash.hexdigest()) # to get a printable str instead of bytes
On Python 3.7 and below:
with open("your_filename.png", "rb") as f:
file_hash = hashlib.md5()
chunk = f.read(8192)
while chunk:
file_hash.update(chunk)
chunk = f.read(8192)
print(file_hash.hexdigest())
This reads the file 8192 (or 2¹³) bytes at a time instead of all at once with f.read()
to use less memory.
Consider using hashlib.blake2b
instead of md5
(just replace md5
with blake2b
in the above snippets). It's cryptographically secure and faster than MD5.
select distinct * into newtablename from oldtablename
Now, the newtablename
will have no duplicate records.
Simply change the table name(newtablename
) by pressing F2 in object explorer in sql server.
You can't do that in plain HTML, but you can do it with jQuery:
JavaScript Image Dropdown
Are you tired with your old fashion dropdown? Try this new one. Image combo box. You can add an icon with each option. It works with your existing "select" element or you can create by JSON object.
Use the attr
method of jQuery like this:
alert($('input').attr('name'));
Note that you can also use attr
to set the attribute values by specifying second argument:
$('input').attr('name', 'new_name')
Use the time.Now() and time.Format() functions (as time.LocalTime() doesn't exist anymore as of Go 1.0.3)
t := time.Now()
fmt.Println(t.Format("20060102150405"))
Online demo (with date fixed in the past in the playground, never mind)
Try shelljs to call c/c++ program or shared libraries by using node program from linux/unix . node-cmd an option in windows. Both packages basically enable us to call c/c++ program similar to the way we call from terminal/command line.
Eg in ubuntu:
const shell = require('shelljs');
shell.exec("command or script name");
In windows:
const cmd = require('node-cmd');
cmd.run('command here');
Note: shelljs and node-cmd are for running os commands, not specific to c/c++.
According to Alexis King answer, here is a plain JavaScript version.
function cleanUp(obj) {_x000D_
for (var attrKey in obj) {_x000D_
var attrValue = obj[attrKey];_x000D_
if (attrValue === null || attrValue === "") {_x000D_
delete obj[attrKey];_x000D_
} else if (Object.prototype.toString.call(attrValue) === "[object Object]") {_x000D_
cleanUp(attrValue);_x000D_
} else if (Array.isArray(attrValue)) {_x000D_
attrValue.forEach(function (arrayValue) {_x000D_
cleanUp(arrayValue);_x000D_
});_x000D_
}_x000D_
}_x000D_
}
_x000D_
Are you getting errors, or just not sure where to start?
%pylab inline
import pandas as pd
import matplotlib.pyplot as plt
df2 = df.groupby(['Name', 'Abuse/NFF'])['Name'].count().unstack('Abuse/NFF').fillna(0)
df2[['abuse','nff']].plot(kind='bar', stacked=True)
You could also use zip
import matplotlib.pyplot as plt
l = [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
(2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
(4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
x, y = zip(*l)
plt.plot(x, y)
Try itext
. Add dependency to your build.gradle
for latest as of this post
Note: special version for android, trailing "g":
dependencies {
compile 'com.itextpdf:itextg:5.5.9'
}
class Pin(models.Model):
"""Pin Class"""
image_link = models.CharField(max_length=255, null=True, blank=True)
image = models.ImageField(upload_to='images/', blank=True)
title = models.CharField(max_length=255, null=True, blank=True)
source_name = models.CharField(max_length=255, null=True, blank=True)
source_link = models.CharField(max_length=255, null=True, blank=True)
description = models.TextField(null=True, blank=True)
tags = models.ForeignKey(Tag, blank=True, null=True)
def __unicode__(self):
"""Unicode class."""
return unicode(self.image_link)
def save(self, *args, **kwargs):
"""Store image locally if we have a URL"""
if self.image_link and not self.image:
result = urllib.urlretrieve(self.image_link)
self.image.save(os.path.basename(self.image_link), File(open(result[0], 'r')))
self.save()
super(Pin, self).save()
I create now the log-css.js https://codepen.io/luis7lobo9b/pen/QWyobwY
// log-css.js v1
const log = console.log.bind();
const css = function(item, color = '#fff', background = 'none', fontSize = '12px', fontWeight = 700, fontFamily) {
return ['%c ' + item + ' ', 'color:' + color + ';background:' + background + ';font-size:' + fontSize + ';font-weight:' + fontWeight + (fontFamily ? ';font-family:' + fontFamily : '')];
};
// example
log(...css('Lorem ipsum dolor sit amet, consectetur adipisicing elit.', 'rebeccapurple', '#000', '14px'));
In a new Php 5.6, you can use ... operator
instead of using func_get_args()
.
So, using this, you can get all the parameters you pass:
function manyVars(...$params) {
var_dump($params);
}
My understanding of marshalling is different to the other answers.
Serialization:
To Produce or rehydrate a wire-format version of an object graph utilizing a convention.
Marshalling:
To Produce or rehydrate a wire-format version of an object graph by utilizing a mapping file, so that the results can be customized. The tool may start by adhering to a convention, but the important difference is the ability to customize results.
Contract First Development:
Marshalling is important within the context of contract first development.
A great summary by @addyosmani
Shamelessly copied from https://addyosmani.com/blog/script-priorities/
The solution above does not work in all InputBox-Cancel cases. Most notably, it does not work if you have to InputBox a Range.
For example, try the following InputBox for defining a custom range ('sRange', type:=8, requires Set + Application.InputBox) and you will get an error upon pressing Cancel:
Sub Cancel_Handler_WRONG()
Set sRange = Application.InputBox("Input custom range", _
"Cancel-press test", Selection.Address, Type:=8)
If StrPtr(sRange) = 0 Then 'I also tried with sRange.address and vbNullString
MsgBox ("Cancel pressed!")
Exit Sub
End If
MsgBox ("Your custom range is " & sRange.Address)
End Sub
The only thing that works, in this case, is an "On Error GoTo ErrorHandler" statement before the InputBox + ErrorHandler at the end:
Sub Cancel_Handler_OK()
On Error GoTo ErrorHandler
Set sRange = Application.InputBox("Input custom range", _
"Cancel-press test", Selection.Address, Type:=8)
MsgBox ("Your custom range is " & sRange.Address)
Exit Sub
ErrorHandler:
MsgBox ("Cancel pressed")
End Sub
So, the question is how to detect either an error or StrPtr()=0 with an If statement?
I see many answers suggesting itertools.tee, but that's ignoring one crucial warning in the docs for it:
This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use
list()
instead oftee()
.
Basically, tee
is designed for those situation where two (or more) clones of one iterator, while "getting out of sync" with each other, don't do so by much -- rather, they say in the same "vicinity" (a few items behind or ahead of each other). Not suitable for the OP's problem of "redo from the start".
L = list(DictReader(...))
on the other hand is perfectly suitable, as long as the list of dicts can fit comfortably in memory. A new "iterator from the start" (very lightweight and low-overhead) can be made at any time with iter(L)
, and used in part or in whole without affecting new or existing ones; other access patterns are also easily available.
As several answers rightly remarked, in the specific case of csv
you can also .seek(0)
the underlying file object (a rather special case). I'm not sure that's documented and guaranteed, though it does currently work; it would probably be worth considering only for truly huge csv files, in which the list
I recommmend as the general approach would have too large a memory footprint.
This prints all elements that contain sub:
for s in filter (lambda x: sub in x, list): print (s)
This should fulfill your requirements.
ABC:\s*(\(\D+\)\s*.*?)\\n
Here it is with some tests http://www.regexplanet.com/cookbook/ahJzfnJlZ2V4cGxhbmV0LWhyZHNyDgsSBlJlY2lwZRiEjiUM/index.html
Futher reading on regular expressions: http://www.regular-expressions.info/characters.html
If you want to never expire a session use 0
or negative value -1
.
<session-config>
<session-timeout>0</session-timeout>
</session-config>
or mention 1440
it indicates 1440 minutes
[24hours * 60 minutes
]
<session-config>
<session-timeout>1440</session-timeout><!-- 24hours -->
</session-config>
Session will be expire after 24hours
.
An analysis of the various options available, and the pros and cons of each is available here.
The suggested options are:
SELECT my_column FROM my_table WHERE search_column = ?
, execute it for each value and UNION the results client-side. Requires only one prepared statement. Slow and painful.SELECT my_column FROM my_table WHERE search_column IN (?,?,?)
and execute it. Requires one prepared statement per size-of-IN-list. Fast and obvious.SELECT my_column FROM my_table WHERE search_column = ? ; SELECT my_column FROM my_table WHERE search_column = ? ; ...
and execute it. [Or use UNION ALL
in place of those semicolons. --ed] Requires one prepared statement per size-of-IN-list. Stupidly slow, strictly worse than WHERE search_column IN (?,?,?)
, so I don't know why the blogger even suggested it.SELECT my_column FROM my_table WHERE search_column IN (1,2,3,4,5,6,6,6,6,6)
. Any decent server will optimize out the duplicate values before running the query.None of these options are super great, though.
Duplicate questions have been answered in these places with equally sane alternatives, still none of them super great:
The Right Answer, if you are using JDBC4 and a server that supports x = ANY(y)
, is to use PreparedStatement.setArray
as described here:
There doesn't seem to be any way to make setArray
work with IN-lists, though.
Sometimes SQL statements are loaded at runtime (e.g., from a properties file) but require a variable number of parameters. In such cases, first define the query:
query=SELECT * FROM table t WHERE t.column IN (?)
Next, load the query. Then determine the number of parameters prior to running it. Once the parameter count is known, run:
sql = any( sql, count );
For example:
/**
* Converts a SQL statement containing exactly one IN clause to an IN clause
* using multiple comma-delimited parameters.
*
* @param sql The SQL statement string with one IN clause.
* @param params The number of parameters the SQL statement requires.
* @return The SQL statement with (?) replaced with multiple parameter
* placeholders.
*/
public static String any(String sql, final int params) {
// Create a comma-delimited list based on the number of parameters.
final StringBuilder sb = new StringBuilder(
String.join(", ", Collections.nCopies(possibleValue.size(), "?")));
// For more than 1 parameter, replace the single parameter with
// multiple parameter placeholders.
if (sb.length() > 1) {
sql = sql.replace("(?)", "(" + sb + ")");
}
// Return the modified comma-delimited list of parameters.
return sql;
}
For certain databases where passing an array via the JDBC 4 specification is unsupported, this method can facilitate transforming the slow = ?
into the faster IN (?)
clause condition, which can then be expanded by calling the any
method.
This has been covered quite a bit, but there's a crucial piece of information that's missing. Hopefully, I can help to clear up how this works and give some relief to weary travellers. :-)
Delete From Current Process
Obviously, everyone knows that you just do this to delete an environment variable from your current process:
set FOO=
Persistent Delete
There are two sets of environment variables, system-wide and user.
Delete User Environment Variable:
reg delete "HKCU\Environment" /v FOO /f
Delete System-Wide Environment Variable:
REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOO
Apply Value Without Rebooting
Here's the magic information that's missing! You're wondering why after you do this, when you launch a new command window, the environment variable is still there. The reason is because explorer.exe has not updated its environment. When one process launches another, the new process inherits the environment from the process that launched it.
There are two ways to fix this without rebooting. The most brute-force way is to kill your explorer.exe process and start it again. You can do that from Task Manager. I don't recommend this method, however.
The other way is by telling explorer.exe that the environment has changed and that it should reread it. This is done by broadcasting a Windows message (WM_SETTINGCHANGE). This can be accomplished with a simple PowerShell script. You could easily write one to do this, but I found one in Update Window Settings After Scripted Changes:
if (-not ("win32.nativemethods" -as [type])) {
add-type -Namespace Win32 -Name NativeMethods -MemberDefinition @"
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr SendMessageTimeout(
IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam,
uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);
"@
}
$HWND_BROADCAST = [intptr]0xffff;
$WM_SETTINGCHANGE = 0x1a;
$result = [uintptr]::zero
[win32.nativemethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE,[uintptr]::Zero, "Environment", 2, 5000, [ref]$result);
Summary
So to delete a user environment variable named "FOO" and have the change reflected in processes you launch afterwards, do the following.
Note, you'll probably have to update your PowerShell settings to allow you to run this script, but I'll leave that as a Google-fu exercise for you.
I ran into a similar problem where I have a dependency property that I wanted the class to listen to change events to grab related data from a service.
public static readonly DependencyProperty CustomerProperty =
DependencyProperty.Register("Customer", typeof(Customer),
typeof(CustomerDetailView),
new PropertyMetadata(OnCustomerChangedCallBack));
public Customer Customer {
get { return (Customer)GetValue(CustomerProperty); }
set { SetValue(CustomerProperty, value); }
}
private static void OnCustomerChangedCallBack(
DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
CustomerDetailView c = sender as CustomerDetailView;
if (c != null) {
c.OnCustomerChanged();
}
}
protected virtual void OnCustomerChanged() {
// Grab related data.
// Raises INotifyPropertyChanged.PropertyChanged
OnPropertyChanged("Customer");
}
I am not sure,how you are opening popup or say model in your code. But you can try something like this..
<html ng-app="MyApp">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<script type="text/javascript">
var myApp = angular.module("MyApp", []);
myApp.controller('MyController', function ($scope) {
$scope.open = function(){
var modalInstance = $modal.open({
templateUrl: '/assets/yourOpupTemplatename.html',
backdrop:'static',
keyboard:false,
controller: function($scope, $modalInstance) {
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
$scope.ok = function () {
$modalInstance.close();
};
}
});
}
});
</script>
</head>
<body ng-controller="MyController">
<button class="btn btn-primary" ng-click="open()">Test Modal</button>
<!-- Confirmation Dialog -->
<div class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Delete confirmation</h4>
</div>
<div class="modal-body">
<p>Are you sure?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="cancel()">No</button>
<button type="button" class="btn btn-primary" ng-click="ok()">Yes</button>
</div>
</div>
</div>
</div>
<!-- End of Confirmation Dialog -->
</body>
</html>
Did you try adding the self prefix to the fileName and replacing the method above the Button ? With the self, it becomes visible between methods.
...
def load_file(self):
self.fileName = filedialog.askopenfilename(filetypes = (("Template files", "*.tplate")
,("HTML files", "*.html;*.htm")
,("All files", "*.*") ))
...
In my case, the error was because I had not declared the field in my $fillable array in the model. Well, it seems to be something basic, but for us who started with laravel it could work.
If there are people like me out there: If you want to call the cloud function from the same project as the cloud function it self, you can init the firebase sdk and use onCall method. It will handle everything for you:
exports.newRequest = functions.https.onCall((data, context) => {
console.log(`This is the received data: ${data}.`);
return data;
})
Call this function like this:
// Init the firebase SDK first
const functions = firebase.functions();
const addMessage = functions.httpsCallable(`newRequest`);
Firebase docs: https://firebase.google.com/docs/functions/callable
If you can't init the SDK here is the essence from the other suggestions:
In python 3.6 I got the value of last key from the following code
list(dict.keys())[-1]
cat CMakeLists.txt
project (hello)
set(CMAKE_BINARY_DIR "/bin")
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR})
add_executable (hello hello.c)
I would first suggest that you step back and look at organizing your plays to not require such complexity, but if you really really do, use the following:
vars:
myvariable: "{{[param1|default(''), param2|default(''), param3|default('')]|join(',')}}"
You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:
cursor.execute('INSERT INTO images VALUES(?)', (img,))
Without the comma, (img)
is just a grouped expression, not a tuple, and thus the img
string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.
>>> len(img)
74
>>> len((img,))
1
If you find it easier to read, you can also use a list literal:
cursor.execute('INSERT INTO images VALUES(?)', [img])
Easy and safe - make new stream from original source:
MemoryStream source = new MemoryStream(byteArray);
MemoryStream copy = new MemoryStream(byteArray);
Well, guys for me it was only remove the :method => :delete
<%= link_to('Sign out', destroy_user_session_path) %>
Install the NuGet package called SevenZipSharp.Interop
Then:
SevenZipBase.SetLibraryPath(@".\x86\7z.dll");
var compressor = new SevenZip.SevenZipCompressor();
var filesToCompress = Directory.GetFiles(@"D:\data\");
compressor.CompressFiles(@"C:\archive\abc.7z", filesToCompress);
In excel, hide the workbooks, and save them as hidden. When your app loads them they will not be shown.
Edit: upon re-reading, it became clear that these workbooks are not part of your application. Such a solution would be inappropriate for user workbooks.
Not answering the question directly, but it might help someone else.
I have a column called Volume
, having both -
(invalid/NaN) and numbers formatted with ,
df['Volume'] = df['Volume'].astype('str')
df['Volume'] = df['Volume'].str.replace(',', '')
df['Volume'] = pd.to_numeric(df['Volume'], errors='coerce')
Casting to string is required for it to apply to str.replace
As others said, class variables are shared between a given class and its subclasses. Class instance variables belong to exactly one class; its subclasses are separate.
Why does this behavior exist? Well, everything in Ruby is an object—even classes. That means that each class has an object of the class Class
(or rather, a subclass of Class
) corresponding to it. (When you say class Foo
, you're really declaring a constant Foo
and assigning a class object to it.) And every Ruby object can have instance variables, so class objects can have instance variables, too.
The trouble is, instance variables on class objects don't really behave the way you usually want class variables to behave. You usually want a class variable defined in a superclass to be shared with its subclasses, but that's not how instance variables work—the subclass has its own class object, and that class object has its own instance variables. So they introduced separate class variables with the behavior you're more likely to want.
In other words, class instance variables are sort of an accident of Ruby's design. You probably shouldn't use them unless you specifically know they're what you're looking for.
I had a situation when variables went missing from POST and all of the above answers didn't help. It turned out that
max_input_vars=1000
was set by default and POST in question had more than that. This may be a problem.
Your /home/gnu/bin/c++
seem to require additional flag to link things properly and CMake doesn't know about that.
To use /usr/bin/c++
as your compiler run cmake
with -DCMAKE_CXX_COMPILER=/usr/bin/c++
.
Also, CMAKE_PREFIX_PATH
variable sets destination dir where your project' files should be installed. It has nothing to do with CMake installation prefix and CMake itself already know this.
If your app is a system app,you can use PowerManager.goToSleep() to turn screen off,you requires a special permission
before you use goToSleep(), you need use reflection just like:
public static void goToSleep(Context context) {
PowerManager powerManager= (PowerManager)context.getSystemService(Context.POWER_SERVICE);
try {
powerManager.getClass().getMethod("goToSleep", new Class[]{long.class}).invoke(powerManager, SystemClock.uptimeMillis());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
Now,you can use goToSleep() to turn screen off.
This is what happens when the power key is pressed to turn off the screen.
Check out this fiddle:
http://jsfiddle.net/G6N5T/1574/
.wrap {_x000D_
width: 100%;_x000D_
overflow:auto;_x000D_
}_x000D_
_x000D_
.fleft {_x000D_
float:left; _x000D_
width: 33%;_x000D_
background:lightblue;_x000D_
height: 400px;_x000D_
}_x000D_
_x000D_
.fcenter{_x000D_
float:left;_x000D_
width: 33%;_x000D_
background:lightgreen;_x000D_
height:400px;_x000D_
margin-left:0.25%;_x000D_
}_x000D_
_x000D_
.fright {_x000D_
float: right;_x000D_
background:pink;_x000D_
height: 400px;_x000D_
width: 33.5%;_x000D_
_x000D_
}
_x000D_
<div class="wrap">_x000D_
<!--Updated on 10/8/2016; fixed center alignment percentage-->_x000D_
<div class="fleft">Left</div>_x000D_
<div class="fcenter">Center</div>_x000D_
<div class="fright">Right</div>_x000D_
</div>
_x000D_
This uses the CSS float
property for left, right, and center alignments of div
s on a page.
You can use -b to specify a cookie file to read the cookies from as well.
In many situations using -c and -b to the same file is what you want:
curl -b cookies.txt -c cookies.txt http://example.com
Further
Using only -c will make curl start with no cookies but still parse and understand cookies and if redirects or multiple URLs are used, it will then use the received cookies within the single invoke before it writes them all to the output file in the end.
The -b option feeds a set of initial cookies into curl so that it knows about them at start, and it activates curl's cookie parser so that it'll parse and use incoming cookies as well.
See Also
The cookies chapter in the Everything curl book.
To overcome the null
/ undefined
issue, try using the ?
operator to check existence:
<p ng-if="post?.capabilities?.items?.length > 0">
Sidenote, if anyone got to this page looking for an Ionic Framework answer, ensure you use *ngIf
:
<p *ngIf="post?.capabilities?.items?.length > 0">
About CharsetFilter
mentioned in @kosoant answer ....
There is a build in Filter
in tomcat web.xml
(located at conf/web.xml
). The filter is named setCharacterEncodingFilter
and is commented by default. You can uncomment this ( Please remember to uncomment its filter-mapping
too )
Also there is no need to set jsp-config
in your web.xml
(I have test it for Tomcat 7+ )
The information you want can be found by running
mysql --help
or
mysqld --help --verbose
I tried this :
mysql --help | grep Default -A 1
And the output:
(Defaults to on; use --skip-auto-rehash to disable.)
-A, --no-auto-rehash
--
(Defaults to on; use --skip-line-numbers to disable.)
-L, --skip-line-numbers
--
(Defaults to on; use --skip-column-names to disable.)
-N, --skip-column-names
--
(Defaults to on; use --skip-reconnect to disable.)
-s, --silent Be more silent. Print results with a tab as separator,
--
--default-auth=name Default authentication client-side plugin to use.
--binary-mode By default, ASCII '\0' is disallowed and '\r\n' is
--
Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/etc/my.cnf ~/.my.cnf
The answer from Judah did not work for me (or is not complete) as the application was exiting after the first BeginOutputReadLine();
This works for me as a complete snippet, reading the constant output of a ping:
var process = new Process();
process.StartInfo.FileName = "ping";
process.StartInfo.Arguments = "google.com -t";
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.OutputDataReceived += (sender, a) => Console.WriteLine(a.Data);
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
function my_url (base, opt)
{
var retval = ["" + base];
retval.push( opt.page_name ? "&page_name=" + opt.page_name : "");
retval.push( opt.table_name ? "&table_name=" + opt.table_name : "");
retval.push( opt.optionResult ? "&optionResult=" + opt.optionResult : "");
return retval.join("");
}
my_url("?z=z", { page_name : "pageX" /* no table_name and optionResult */ } );
/* Returns:
?z=z&page_name=pageX
*/
This avoids using typeof whatever === "undefined"
. (Also, there isn't any string concatenation.)
from random import random
my_list = range(10)
shuffled_list = sorted(my_list, key=lambda x: random())
This alternative may be useful for some applications where you want to swap the ordering function.
There are two methods in super class as java.lang.Object. We need to override them to custom object.
public boolean equals(Object obj)
public int hashCode()
Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.
public class Test
{
private int num;
private String data;
public boolean equals(Object obj)
{
if(this == obj)
return true;
if((obj == null) || (obj.getClass() != this.getClass()))
return false;
// object must be Test at this point
Test test = (Test)obj;
return num == test.num &&
(data == test.data || (data != null && data.equals(test.data)));
}
public int hashCode()
{
int hash = 7;
hash = 31 * hash + num;
hash = 31 * hash + (null == data ? 0 : data.hashCode());
return hash;
}
// other methods
}
If you want get more, please check this link as http://www.javaranch.com/journal/2002/10/equalhash.html
This is another example, http://java67.blogspot.com/2013/04/example-of-overriding-equals-hashcode-compareTo-java-method.html
Have Fun! @.@
This is very good question but not as wanting as question. There is difference between 'self' and 'cls' used method though analogically they are at same place
def moon(self, moon_name):
self.MName = moon_name
#but here cls method its use is different
@classmethod
def moon(cls, moon_name):
instance = cls()
instance.MName = moon_name
Now you can see both are moon function but one can be used inside class while other function name moon can be used for any class.
For practical programming approach :
While designing circle class we use area method as cls instead of self because we don't want area to be limited to particular class of circle only .
The length property returns the length of a string (number of characters).
The length of an empty string is 0.
var str = "Hello World!";
var n = str.length;
The result of n will be: 12
var str = "";
var n = str.length;
The result of n will be: 0
Array length Property:
The length property sets or returns the number of elements in an array.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length;
The result will be: 4
Syntax:
Return the length of an array:
array.length
Set the length of an array:
array.length=number
You can change project facet from Project --> Properties --> Project Facet --> Java --> {required JDK version}
A filter argument with a trailing * can be evaluated almost instantaneously via an index lookup. A leading * implies a sequential search through the index, so it is O(N). It will take ages.
I suggest you reconsider the requirement.
Rename your file, commit the changes including the "deleted" file, and don't include the new (renamed) file.
Rename your file back.
I was facing same problem but accidentlty I sorted this problem. 1) Login in github 2) Click on Fork Button at Top Right. 3) After above step you can see Clone or download in Green color under <> Code Tab.
Have you tried:
SELECT Cast( 2.555 as decimal(53,8))
This would return 2.55500000
. Is that what you want?
UPDATE:
Apparently you can also use SQL_VARIANT_PROPERTY to find the precision and scale of a value. Example:
SELECT SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Precision'),
SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Scale')
returns 8|7
You may be able to use this in your conversion process...
In addition to what the other answers have said, note that the '/' character in "dd/MM/yyyy" is not a literal character: it represents the date separator of the current user's culture. Therefore, if the current culture uses yyyy-MM-dd dates, then when you call toString it will give you a date such as "31-12-2016" (using dashes instead of slashes). To force it to use slashes, you need to escape that character:
DateTime.Now.ToString("dd/MM/yyyy") --> "19-12-2016" for a Japanese user
DateTime.Now.ToString("dd/MM/yyyy") --> "19/12/2016" for a UK user
DateTime.Now.ToString("dd\\/MM\\/yyyy") --> "19/12/2016" independent of region