Since the question was asked the Angular team has solved this issue by making it possible to dynamically create input names.
With Angular version 1.3 and later you can now do this:
<form name="vm.myForm" novalidate>
<div ng-repeat="p in vm.persons">
<input type="text" name="person_{{$index}}" ng-model="p" required>
<span ng-show="vm.myForm['person_' + $index].$invalid">Enter a name</span>
</div>
</form>
Angular 1.3 also introduced ngMessages, a more powerful tool for form validation. You can use the same technique with ngMessages:
<form name="vm.myFormNgMsg" novalidate>
<div ng-repeat="p in vm.persons">
<input type="text" name="person_{{$index}}" ng-model="p" required>
<span ng-messages="vm.myFormNgMsg['person_' + $index].$error">
<span ng-message="required">Enter a name</span>
</span>
</div>
</form>
Bundler allows you to use gems directly from git repositories. In your Gemfile:
# Use the http(s), ssh, or git protocol
gem 'foo', git: 'https://github.com/dideler/foo.git'
gem 'foo', git: '[email protected]:dideler/foo.git'
gem 'foo', git: 'git://github.com/dideler/foo.git'
# Specify a tag, ref, or branch to use
gem 'foo', git: '[email protected]:dideler/foo.git', tag: 'v2.1.0'
gem 'foo', git: '[email protected]:dideler/foo.git', ref: '4aded'
gem 'foo', git: '[email protected]:dideler/foo.git', branch: 'development'
# Shorthand for public repos on GitHub (supports all the :git options)
gem 'foo', github: 'dideler/foo'
For more info, see https://bundler.io/v2.0/guides/git.html
request.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(
System.Text.Encoding.UTF8.GetBytes(
$"{yourusername}:{yourpwd}")));
Take a look at DecimalFormat. You can easily use it to take a number and give it a set number of decimal places.
Edit: Example
If you want to disable ctrl+f5 , ctrl+R , f5 ,backspace then you can use this simple code. This code is working in Mozila as well as Chrome . Add this code inside your body tag:
<body onkeydown="return (event.keyCode == 154)">
To handle eliminating duplicates, implement an IEqualityComparer<Person>
that can be used in the Distinct()
method, and then getting your dictionary will be easy.
Given:
class PersonComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
return x.FirstAndLastName.Equals(y.FirstAndLastName, StringComparison.OrdinalIgnoreCase);
}
public int GetHashCode(Person obj)
{
return obj.FirstAndLastName.ToUpper().GetHashCode();
}
}
class Person
{
public string FirstAndLastName { get; set; }
}
Get your dictionary:
List<Person> people = new List<Person>()
{
new Person() { FirstAndLastName = "Bob Sanders" },
new Person() { FirstAndLastName = "Bob Sanders" },
new Person() { FirstAndLastName = "Jane Thomas" }
};
Dictionary<string, Person> dictionary =
people.Distinct(new PersonComparer()).ToDictionary(p => p.FirstAndLastName, p => p);
There are hardware and software watchpoints. They are for reading and for writing a variable. You need to consult a tutorial:
http://www.unknownroad.com/rtfm/gdbtut/gdbwatch.html
To set a watchpoint, first you need to break the code into a place where the varianle i is present in the environment, and set the watchpoint.
watch
command is used to set a watchpoit for writing, while rwatch
for reading, and awatch
for reading/writing.
My Dark Color scheme for QtCreator is at:
https://github.com/borzh/qt-creator-css/blob/master/qt-creator.css
To use with Vim (dark) scheme.
Hope it is useful for someone.
Logging is very configurable in Linux, and you might want to look into your /etc/syslog.conf
(or perhaps under /etc/rsyslog.d/
). Details depend upon the logging subsystem, and the distribution.
Look also into files under /var/log/
(and perhaps run dmesg
for kernel logs).
and always remember this venerable explanation of Spaces + Tabs:
I think you mean to use map
instead of filter
:
>>> from string import upper
>>> mylis=['this is test', 'another test']
>>> map(upper, mylis)
['THIS IS TEST', 'ANOTHER TEST']
Even simpler, you could use str.upper
instead of importing from string
(thanks to @alecxe):
>>> map(str.upper, mylis)
['THIS IS TEST', 'ANOTHER TEST']
In Python 2.x, map
constructs a new list by applying a given function to every element in a list. filter
constructs a new list by restricting to elements that evaluate to True
with a given function.
In Python 3.x, map
and filter
construct iterators instead of lists, so if you are using Python 3.x and require a list the list comprehension approach would be better suited.
Your project has to have a builder set for it. If there is not one Eclipse will default to Ant. Which you can use you have to create an Ant build file, which you can Google how to do. It is rather involved though. This is not required to run locally in Eclipse though. If your class is run-able. It looks like yours is, but we can not see all of it.
If you look at your project build path do you have an output folder selected? If you check that folder have the compiled class files been put there? If not the something is not set in Eclpise for it to know to compile. You might check to see if auto build is set for your project.
If you're using jQuery 1.5, then statusCode
will work.
If you're using jQuery 1.4, try this:
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
alert(textStatus);
alert(errorThrown);
}
You should see the status code from the first alert.
The No input file specified is a message you are presented with because of the implementation of PHP on your server, which in this case indicates a CGI implementation (can be verified with phpinfo()
).
Now, to properly explain this, you need to have some basic understanding on how your system works with URL's. Based on your .htaccess file, it seems that your CMS expects the URL to passed along as a PATH_INFO
variable. CGI and FastCGI implementations do not have PATH_INFO
available, so when trying to pass the URI along, PHP fails with that message.
We need to find an alternative.
One option is to try and fix this. Looking into the documentation for core php.ini directives you can see that you can change the workings for your implementation. Although, GoDaddy probably won't allow you to change PHP settings on a shared enviroment.
We need to find an alternative to modifying PHP settings
Looking into system/uri.php
on line 40, you will see that the CMS attempts two types of URI detection - the first being PATH_INFO
, which we just learned won't work - the other being the REQUEST_URI
.
This should basically, be enough - but the parsing of the URI passed, will cause you more trouble, as the URI, which you could pass to REQUEST_URI
variable, forces parse_url()
to only return the URL path - which basically puts you back to zero.
Now, there's actually only one possibilty left - and that's changing the core of the CMS. The URI detection part is insufficient.
Add QUERY_STRING
to the array on line 40 as the first element in system/uri.php
and change your .htaccess to look like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
This will pass the URI you request to index.php
as QUERY_STRING
and have the URI detection to find it.
This, on the other hand, makes it impossible to update the CMS without changing core files till this have been fixed. That sucks...
Need a better option?
Find a better CMS.
the discussion has yet to mention the difference in scope of mutable and immutable default arguments, when they are previously declared vars.
the default arguments' values, which are previously declared vars, becomes accessible as if they were stated as global.
however, if the function tries to mutate them (even later in the function) they are no longer global. as already mentioned, you can freely change them as long as you don't mutate them.
it is based on the same logic as the regular least astonishment, however it also affects scope and it is important to familiarize with it.
a function that does not change the default arguments value can access them freely:
global_list = [1]
global_int = 1
def foo2(a=global_list,b=global_int):
print('global_list:')
print(global_list) # implicity global
print('global_int:')
print(global_int) # implicity global
>>> foo2()
global_list:
[1]
global_int:
1
>>> global_list = [2]
>>> global_int = 2
>>> foo2()
global_list:
[2]
global_int:
2
however the function cannot change them from within and the error message might be confusing, as it acts as if it doesn't know this var at all:
def foo3(a=global_list,b=global_int):
print('global_list:')
print(global_list) # implicity global
global_list.remove(2) # yes, i'm "cheating"
global_list.append(3)
print(global_list) # implicity global
print('global_int:')
print(global_int) # local
print('the error is in the previous line is because this next line assignment makes global_int a local var')
global_int = 3
print(global_int)
>>> foo3()
global_list:
[1]
global_int:
Traceback (most recent call last)...
UnboundLocalError: local variable 'global_int' referenced before assignment
code example: https://onlinegdb.com/BkB1Unb1u
implements
means implementation, when interface
is meant to declare just to provide interface
not for implementation.
A 100% abstract class
is functionally equivalent to an interface
but it can also have implementation if you wish (in this case it won't remain 100% abstract
), so from the JVM's perspective they are different things.
Also the member variable in a 100% abstract class can have any access qualifier, where in an interface they are implicitly public static final
.
''.join(c for c in myString if not c in badTokens)
There are predefined macros that are used by most compilers, you can find the list here. GCC compiler predefined macros can be found here. Here is an example for gcc:
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
//define something for Windows (32-bit and 64-bit, this part is common)
#ifdef _WIN64
//define something for Windows (64-bit only)
#else
//define something for Windows (32-bit only)
#endif
#elif __APPLE__
#include <TargetConditionals.h>
#if TARGET_IPHONE_SIMULATOR
// iOS Simulator
#elif TARGET_OS_IPHONE
// iOS device
#elif TARGET_OS_MAC
// Other kinds of Mac OS
#else
# error "Unknown Apple platform"
#endif
#elif __linux__
// linux
#elif __unix__ // all unices not caught above
// Unix
#elif defined(_POSIX_VERSION)
// POSIX
#else
# error "Unknown compiler"
#endif
The defined macros depend on the compiler that you are going to use.
The _WIN64
#ifdef
can be nested into the _WIN32
#ifdef
because _WIN32
is even defined when targeting the Windows x64 version. This prevents code duplication if some header includes are common to both
(also WIN32
without underscore allows IDE to highlight the right partition of code).
You have two approaches to this:
I would suggest the second method because its less irritating. Remember to also check onpaste
. If you use only keypress Then We Can Copy and paste special characters so use onpaste
also to restrict Pasting special characters
Additionally, I will also suggest that you reconsider if you really want to prevent users from entering special characters. Because many people have $, #, @ and * in their passwords.
I presume that this might be in order to prevent SQL injection; if so: its better that you handle the checks server-side. Or better still, escape the values and store them in the database.
Your delete code looks like this
Gridview1.DeleteRow(e.RowIndex);
Gridview1.DataBind();
When you call Gridview1.DataBind() you will populate your gridview with the current datasource. So, it will delete all the existent rows, and it will add all the rows from CustomersSqlDataSource.
What you need to do is delete the row from the table that CustomersSqlDataSource querying.
You can do this very easy by setting a delete command to CustomersSqlDataSource, add a delete parameter, and then execute the delete command.
CustomersSqlDataSource.DeleteCommand = "DELETE FROM Customer Where CustomerID=@CustomerID"; // Customer is the name of the table where you take your data from. Maybe you named it different
CustomersSqlDataSource.DeleteParameters.Add("CustomerID", Gridview1.DataKeys[e.RowIndex].Values["CustomerID"].ToString());
CustomersSqlDataSource.Delete();
Gridview1.DataBind();
But take into account that this will delete the data from the database.
In matplotlib 2.0 there is a parameter called fillstyle
which allows better control on the way markers are filled.
In my case I have used it with errorbars but it works for markers in general
http://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.errorbar.html
fillstyle
accepts the following values: [‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]
There are two important things to keep in mind when using fillstyle
,
1) If mfc is set to any kind of value it will take priority, hence, if you did set fillstyle to 'none' it would not take effect. So avoid using mfc in conjuntion with fillstyle
2) You might want to control the marker edge width (using markeredgewidth
or mew
) because if the marker is relatively small and the edge width is thick, the markers will look like filled even though they are not.
Following is an example using errorbars:
myplot.errorbar(x=myXval, y=myYval, yerr=myYerrVal, fmt='o', fillstyle='none', ecolor='blue', mec='blue')
There is a method addAll() which will serve the purpose of copying One ArrayList to another.
For example you have two Array Lists: sourceList and targetList, use below code.
targetList.addAll(sourceList);
$monthname = date("F", strtotime($month));
F
means full month name
Unset is a function. Therefore you have to submit which variable has to be destroyed.
unset($var);
In your case
unset ($_SESSION["products"]);
If you need to reset whole session variable just call
session_destroy ();
Traversing the string is probably the most efficient, though using Regex to do this might yield cleaner looking code (though you can always hide your traverse code in a function).
This should get you for starting with two letters and ending with two numbers.
[A-Za-z]{2}(.*)[0-9]{2}
If you know it will always be just two and two you can
[A-Za-z]{2}[0-9]{2}
Satisfies all your requirements if you use the trick told below
/^(\+\d{1,3}[- ]?)?\d{10}$/
^
start of line+
followed by \d+
followed by a
or -
which are optional.0
s do not follow.\d+
10 times.DEMO Added m
ultiline flag in demo to check for all cases
P.S. You really need to specify which language you use so as to use an if
condition something like below:
// true if above regex is satisfied and (&&) it does not (`!`) match `0`s `5` or more times
if(number.match(/^(\+\d{1,3}[- ]?)?\d{10}$/) && ! (number.match(/0{5,}/)) )
meshgrid helps in creating a rectangular grid from two 1-D arrays of all pairs of points from the two arrays.
x = np.array([0, 1, 2, 3, 4])
y = np.array([0, 1, 2, 3, 4])
Now, if you have defined a function f(x,y) and you wanna apply this function to all the possible combination of points from the arrays 'x' and 'y', then you can do this:
f(*np.meshgrid(x, y))
Say, if your function just produces the product of two elements, then this is how a cartesian product can be achieved, efficiently for large arrays.
Referred from here
If you revise your regular expression like this:
drupal-6.14/(?=sites(?!/all|/default)).*
^^
...then it will match all inputs that contain drupal-6.14/
followed by sites
followed by anything other than /all
or /default
. For example:
drupal-6.14/sites/foo
drupal-6.14/sites/bar
drupal-6.14/sitesfoo42
drupal-6.14/sitesall
Changing ?=
to ?!
to match your original regex simply negates those matches:
drupal-6.14/(?!sites(?!/all|/default)).*
^^
So, this simply means that drupal-6.14/
now cannot be followed by sites
followed by anything other than /all
or /default
. So now, these inputs will satisfy the regex:
drupal-6.14/sites/all
drupal-6.14/sites/default
drupal-6.14/sites/all42
But, what may not be obvious from some of the other answers (and possibly your question) is that your regex will also permit other inputs where drupal-6.14/
is followed by anything other than sites
as well. For example:
drupal-6.14/foo
drupal-6.14/xsites
Conclusion: So, your regex basically says to include all subdirectories of drupal-6.14
except those subdirectories of sites
whose name begins with anything other than all
or default
.
It really depends what you mean by "improved":
Clearer?
boolean twoOrMoreAreTrue(boolean a, boolean b, boolean c)
{
return (a && b) || (a && c) || (b && c);
}
Terser?
boolean moreThanTwo(boolean a, boolean b, boolean c)
{
return a == b ? a : c;
}
More general?
boolean moreThanXTrue(int x, boolean[] bs)
{
int count = 0;
for(boolean b : bs)
{
count += b ? 1 : 0;
if(count > x) return true;
}
return false;
}
More scalable?
boolean moreThanXTrue(int x, boolean[] bs)
{
int count = 0;
for(int i < 0; i < bs.length; i++)
{
count += bs[i] ? 1 : 0;
if(count > x) return true;
int needed = x - count;
int remaining = bs.length - i;
if(needed >= remaining) return false;
}
return false;
}
Faster?
// Only profiling can answer this.
Which one is "improved" depends heavily on the situation.
There are couple of way which can be used.
const stations = [
{call:'station one',frequency:'000'},
{call:'station two',frequency:'001'}
];
const callList = stations.map(({call}) => call)
Solution 1
<p>{callList.join(', ')}</p>
Solution 2
<ol>
{ callList && callList.map(item => <li>{item}</li>) }
</ol>
Of course there are other ways also available.
and here the fork of the toolkit wich contains the port to 4.O,
https://github.com/jogibear9988/wpftoolkit
it's worked very well to me .
Use split
method:
entry = prompt("Enter your name");
entryArray = entry.split("");
Refer String.prototype.split()
for more info.
If you would like to ignore case you could use the following:
String s = "yip";
String best = "yodel";
int compare = s.compareToIgnoreCase(best);
if(compare < 0){
//-1, --> s is less than best. ( s comes alphabetically first)
}
else if(compare > 0 ){
// best comes alphabetically first.
}
else{
// strings are equal.
}
Instead of playing with tags, I took different approach. Made delegate for my subclass of UITableViewCell(OptionButtonsCell) and added an indexPath var. From my button in storyboard I connected @IBAction to the OptionButtonsCell and there I send delegate method with the right indexPath to anyone interested. In cell for index path I set current indexPath and it works :)
Let the code speak for itself:
Swift 3 Xcode 8
OptionButtonsTableViewCell.swift
import UIKit
protocol OptionButtonsDelegate{
func closeFriendsTapped(at index:IndexPath)
}
class OptionButtonsTableViewCell: UITableViewCell {
var delegate:OptionButtonsDelegate!
@IBOutlet weak var closeFriendsBtn: UIButton!
var indexPath:IndexPath!
@IBAction func closeFriendsAction(_ sender: UIButton) {
self.delegate?.closeFriendsTapped(at: indexPath)
}
}
MyTableViewController.swift
class MyTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, OptionButtonsDelegate {...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "optionCell") as! OptionButtonsTableViewCell
cell.delegate = self
cell.indexPath = indexPath
return cell
}
func closeFriendsTapped(at index: IndexPath) {
print("button tapped at index:\(index)")
}
Assuming all of these columns are int
, then the first thing to sort out is converting one or more of them to a better data type - int
division performs truncation, so anything less than 100% would give you a result of 0:
select (100.0 * (SPGI09_EARLY_OVER_T – SPGI09_OVER_WK_EARLY_ADJUST_T)) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T + SPGR99_ON_TIME_Q)
from
CSPGI09_OVERSHIPMENT
Here, I've mutiplied one of the numbers by 100.0
which will force the result of the calculation to be done with float
s rather than int
s. By choosing 100
, I'm also getting it ready to be treated as a %
.
I was also a little confused by your bracketing - I think I've got it correct - but you had brackets around single values, and then in other places you had a mix of operators (-
and /
) at the same level, and so were relying on the precedence rules to define which operator applied first.
@Test(expected = Exception.class)
Tells Junit that exception is the expected result so test will be passed (marked as green) when exception is thrown.
For
@Test
Junit will consider test as failed if exception is thrown, provided it's an unchecked exception. If the exception is checked it won't compile and you will need to use other methods. This link might help.
Here I'm just doing the difference between today, and a CREATED_DATE
DATE
field in a table, which obviously is a date in the past:
SELECT
((FLOOR(ABS(MONTHS_BETWEEN(CREATED_DATE, SYSDATE))) / 12) * 12) || ' months, ' AS MONTHS,
-- we take total days - years(as days) - months(as days) to get remaining days
FLOOR((SYSDATE - CREATED_DATE) - -- total days
(FLOOR((SYSDATE - CREATED_DATE)/365)*12)*(365/12) - -- years, as days
-- this is total months - years (as months), to get number of months,
-- then multiplied by 30.416667 to get months as days (and remove it from total days)
FLOOR(((SYSDATE - CREATED_DATE)/365)*12 - (FLOOR((SYSDATE - CREATED_DATE)/365)*12)) * (365/12))
|| ' days ' AS DAYS
FROM MyTable
I use (365/12), or 30.416667, as my conversion factor because I'm using total days and removing years and months (as days) to get the remainder number of days. It was good enough for my purposes, anyway.
Portability between Linux and Windows is a big headache, since Linux is a POSIX-conformant system with - generally - a proper, high quality toolchain for C, whereas Windows doesn't even provide a lot of functions in the C standard library.
However, if you want to stick to the standard, you can write something like this:
#include <stdio.h>
#include <stdlib.h>
FILE *f = fopen("textfile.txt", "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET); /* same as rewind(f); */
char *string = malloc(fsize + 1);
fread(string, 1, fsize, f);
fclose(f);
string[fsize] = 0;
Here string
will contain the contents of the text file as a properly 0-terminated C string. This code is just standard C, it's not POSIX-specific (although that it doesn't guarantee it will work/compile on Windows...)
This was the method which worked best for me and didn't open up new tabs, but just downloaded the files/images I required:
var filesForDownload = [];
filesForDownload( { path: "/path/file1.txt", name: "file1.txt" } );
filesForDownload( { path: "/path/file2.jpg", name: "file2.jpg" } );
filesForDownload( { path: "/path/file3.png", name: "file3.png" } );
filesForDownload( { path: "/path/file4.txt", name: "file4.txt" } );
$jq('input.downloadAll').click( function( e )
{
e.preventDefault();
var temporaryDownloadLink = document.createElement("a");
temporaryDownloadLink.style.display = 'none';
document.body.appendChild( temporaryDownloadLink );
for( var n = 0; n < filesForDownload.length; n++ )
{
var download = filesForDownload[n];
temporaryDownloadLink.setAttribute( 'href', download.path );
temporaryDownloadLink.setAttribute( 'download', download.name );
temporaryDownloadLink.click();
}
document.body.removeChild( temporaryDownloadLink );
} );
As of AngularJS 1.2 there's a directive called ng-repeat-start
that does exactly what you ask for. See my answer in this question for a description of how to use it.
With bootstrap 4 just use col-auto
<div class="container-fluid">
<div class="row">
<div class="col-sm-auto">
Fixed content
</div>
<div class="col-sm">
Normal scrollable content
</div>
</div>
</div>
Sorry but I don't understand why too many people even think a string was something that could be evaluated. You must change your mindset, really. Forget all connections between strings on one side and expressions, calls, evaluation on the other side.
The (possibly) only connection is via parse(text = ....)
and all good R programmers should know that this is rarely an efficient or safe means to construct expressions (or calls). Rather learn more about substitute()
, quote()
, and possibly the power of using do.call(substitute, ......)
.
fortunes::fortune("answer is parse")
# If the answer is parse() you should usually rethink the question.
# -- Thomas Lumley
# R-help (February 2005)
Dec.2017: Ok, here is an example (in comments, there's no nice formatting):
q5 <- quote(5+5)
str(q5)
# language 5 + 5
e5 <- expression(5+5)
str(e5)
# expression(5 + 5)
and if you get more experienced you'll learn that q5
is a "call"
whereas e5
is an "expression"
, and even that e5[[1]]
is identical to q5
:
identical(q5, e5[[1]])
# [1] TRUE
For Java < 7 you can use if-else along with Exception:
try {
// common logic to handle both exceptions
} catch (Exception ex) {
if (ex instanceof Exception1 || ex instanceof Exception2) {
}
else {
throw ex;
// or if you don't want to have to declare Exception use
// throw new RuntimeException(ex);
}
}
Edited and replaced Throwable with Exception.
I would like to augment to Stephen C's answer, my case was on the first dot. So since we have DHCP to allocate IP addresses in the company, DHCP changed my machine's address without of course asking neither me nor Oracle. So out of the blue oracle refused to do anything and gave the minus one dreaded exception. So if you want to workaround this once and for ever, and since TCP.INVITED_NODES of SQLNET.ora file does not accept wildcards as stated here, you can add you machine's hostname instead of the IP address.
Query to show a 3-variable boolean expression truth table :
;WITH cteData AS
(SELECT 0 AS A, 0 AS B, 0 AS C
UNION ALL SELECT 0,0,1
UNION ALL SELECT 0,1,0
UNION ALL SELECT 0,1,1
UNION ALL SELECT 1,0,0
UNION ALL SELECT 1,0,1
UNION ALL SELECT 1,1,0
UNION ALL SELECT 1,1,1
)
SELECT cteData.*,
CASE WHEN
(A=1) OR (B=1) AND (C=1)
THEN 'True' ELSE 'False' END AS Result
FROM cteData
Results for (A=1) OR (B=1) AND (C=1)
:
A B C Result
0 0 0 False
0 0 1 False
0 1 0 False
0 1 1 True
1 0 0 True
1 0 1 True
1 1 0 True
1 1 1 True
Results for (A=1) OR ( (B=1) AND (C=1) )
are the same.
Results for ( (A=1) OR (B=1) ) AND (C=1)
:
A B C Result
0 0 0 False
0 0 1 False
0 1 0 False
0 1 1 True
1 0 0 False
1 0 1 True
1 1 0 False
1 1 1 True
In Python 2.6+, you could use io.open()
that is default (builtin open()
) on Python 3:
import io
with io.open(filename, 'w', encoding=character_encoding) as file:
file.write(unicode_text)
It might be more convenient if you need to write the text incrementally (you don't need to call unicode_text.encode(character_encoding)
multiple times). Unlike codecs
module, io
module has a proper universal newlines support.
Under Trace properties > Events Selection tab > select show all columns. Now under column filters, you should see the database name. Enter the database name for the Like section and you should see traces only for that database.
Use this one, I've written this to my app,
<?xml version="1.0" encoding="utf-8"?>
<!-- res/drawable/rounded_edittext.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<solid android:color="#882C383E"/>
<corners
android:bottomRightRadius="5dp"
android:bottomLeftRadius="5dp"
android:topLeftRadius="5dp"
android:topRightRadius="5dp"/>
</shape>
SELECT
OBJECT_NAME(parent_object_id) 'Parent table',
c.NAME 'Parent column name',
OBJECT_NAME(referenced_object_id) 'Referenced table',
cref.NAME 'Referenced column name'
FROM
sys.foreign_key_columns fkc
INNER JOIN
sys.columns c
ON fkc.parent_column_id = c.column_id
AND fkc.parent_object_id = c.object_id
INNER JOIN
sys.columns cref
ON fkc.referenced_column_id = cref.column_id
AND fkc.referenced_object_id = cref.object_id where OBJECT_NAME(parent_object_id) = 'tablename'
If you want to get the foreign key relation of all the tables exclude the where
clause else write your tablename instead of tablename
It means the CPU attempted to execute an instruction it didn't understand. This could be caused by corruption I guess, or maybe it's been compiled for the wrong architecture (in which case I would have thought the O/S would refuse to run the executable). Not entirely sure what the root issue is.
For Eclipse in Macbook it is just 2 click process:
It also happens if the startup project is changed to the one, which does not have the connection strings.
SELECT user_id
FROM user_logs
WHERE login_date BETWEEN '2014-02-01' AND '2014-03-01'
Between keyword works exceptionally for a date. it assumes the time is at 00:00:00 (i.e. midnight) for dates.
Even better:
DataTable DTable = new DataTable();
BindingSource SBind = new BindingSource();
SBind.DataSource = DTable;
DataGridView ServersTable = new DataGridView();
ServersTable.AutoGenerateColumns = false;
ServersTable.DataSource = DTable;
ServersTable.DataSource = SBind;
ServersTable.Refresh();
You're telling the bindable source that it's bound to the DataTable, in-turn you need to tell your DataGridView not to auto-generate columns, so it will only pull the data in for the columns you've manually input into the control... lastly refresh the control to update the databind.
I installed ArcGIS Pro 1.4 and it didn't register the Python 3.5.2 it installed which prevented me from installing any add-ons. I resolved this by using the "reg" command in an Administrator PowerShell session to manually create and populate the necessary registry keys/values (where Python is installed in C:\Python35):
reg add "HKLM\Software\Python\PythonCore\3.5\Help\Main Python Documentation" /reg:64 /ve /t REG_SZ /d "C:\Python35\Doc\Python352.chm"
reg add "HKLM\Software\Python\PythonCore\3.5\InstallPath" /reg:64 /ve /t REG_SZ /d "C:\Python35\"
reg add "HKLM\Software\Python\PythonCore\3.5\InstallPath\InstallGroup" /reg:64 /ve /t REG_SZ /d "Python 3.5"
reg add "HKLM\Software\Python\PythonCore\3.5\PythonPath" /reg:64 /ve /t REG_SZ /d "C:\Python35\Lib;C:\Python35\DLLs;C:\Python35\Lib\lib-tk"
I find this easier than using Registry Editor but that's solely a personal preference.
The same commands can be executed in CMD.EXE session if you prefer; just make sure you run it as Administrator.
I have the same issue where I want a single script to work with a table that has columns added periodically by other developers. Not only that, but I am supporting many different versions of our database as customers may not all be up-to-date with the current version.
I took the solution by Jonas and modified it slightly. This allows me to make a copy of the row and then change the primary key before adding it back into the original source table. This is also really handy for working with tables that do not allow NULL values in columns and you don't want to have to specify each column name in the INSERT.
This code copies the row for 'ABC' to 'XYZ'
SELECT * INTO #TempRow FROM SourceTable WHERE KeyColumn = 'ABC';
UPDATE #TempRow SET KeyColumn = 'XYZ';
INSERT INTO SourceTable SELECT * FROM #TempRow;
DELETE #TempRow;
Once you have finished the drop the temp table.
DROP TABLE #TempRow;
At here:
cmd.exe /k "<SomePath>\<My Batch File>.bat" & pause
Take a look what are you doing:
How to resolve it? well,using the correct syntax, enclosing the argument for the new CMD instance:
cmd.exe /k ""<SomePath>\<My Batch File>.bat" & pause"
you have to import Microsoft.AspNetCore.Identity & System.Security.Claims
// to get current user ID
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
// to get current user info
var user = await _userManager.FindByIdAsync(userId);
When deciding whether to make a class static or non-static you need to look at what information you are trying to represent. This entails a more 'bottom-up' style of programming where you focus on the data you are representing first. Is the class you are writing a real-world object like a rock, or a chair? These things are physical and have physical attributes such as color, weight which tells you that you may want to instantiate multiple objects with different properties. I may want a black chair AND a red chair at the same time. If you ever need two configurations at the same time then you instantly know you will want to instantiate it as an object so each object can be unique and exist at the same time.
On the other end, static functions tend to lend more to actions which do not belong to a real-world object or an object that you can easily represent. Remember that C#'s predecessors are C++ and C where you can just define global functions that do not exist in a class. This lends more to 'top-down' programming. Static methods can be used for these cases where it doesn't make sense that an 'object' performs the task. By forcing you to use classes this just makes it easier to group related functionality which helps you create more maintainable code.
Most classes can be represented by either static or non-static, but when you are in doubt just go back to your OOP roots and try to think about what you are representing. Is this an object that is performing an action (a car that can speed up, slow down, turn) or something more abstract (like displaying output).
Get in touch with your inner OOP and you can never go wrong!
I had a similar error but with different context when I uploaded a *.p file to Google Drive. I tried to use it later in a Google Colab session, and got this error:
1 with open("/tmp/train.p", mode='rb') as training_data:
----> 2 train = pickle.load(training_data)
UnpicklingError: invalid load key, '<'.
I solved it by compressing the file, upload it and then unzip on the session. It looks like the pickle file is not saved correctly when you upload/download it so it gets corrupted.
As an addendum, if you are using this technique to define strings in your target, this is how I had to define and use them:
In Build Settings -> Preprocessor Macros, and yes backslashes are critical in the definition:
APPURL_NSString=\@\"www.foobar.org\"
And in the source code:
objectManager.client.baseURL = APPURL_NSString;
For folks who are stumbling across Victor Stoddard's answer above in 2019, and become hopeful and doe eyed, note that:
a) Support for X-Content-Duration was removed in Firefox 41: https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/41#HTTP
b) I think it was only supported in Firefox for .ogg audio and .ogv video, not for any other types.
c) I can't see that it was ever supported at all in Chrome, but that may just be a lack of research on my part. But its presence or absence seems to have no effect one way or another for webm or ogv videos as of today in Chrome 71.
d) I can't find anywhere where 'Content-Duration' replaced 'X-Content-Duration' for anything, I don't think 'X-Content-Duration' lived long enough for there to be a successor header name.
I think this means that, as of today if you want to serve webm or ogv containers that contain streams that don't know their duration (e.g. the output of an ffpeg pipe) to Chrome or FF, and you want them to be scrubbable in an HTML 5 video element, you are probably out of luck. Firefox 64.0 makes a half hearted attempt to make these scrubbable whether or not you serve via range requests, but it gets confused and throws up a spinning wheel until the stream is completely downloaded if you seek a few times more than it thinks is appropriate. Chrome doesn't even try, it just nopes out and won't let you scrub at all until the entire stream is finished playing.
Important:
I'm sorry to say that the response from "Borealid" is imprecise and somewhat incorrect - firstly there is no relation to statefulness or statelessness to answer this question, and most importantly the definition of the tuple for a socket is incorrect.
First remember below two rules:
Primary key of a socket: A socket is identified by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT, PROTOCOL}
not by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT}
- Protocol is an important part of a socket's definition.
OS Process & Socket mapping: A process can be associated with (can open/can listen to) multiple sockets which might be obvious to many readers.
Example 1: Two clients connecting to same server port means: socket1 {SRC-A, 100, DEST-X,80, TCP}
and socket2{SRC-B, 100, DEST-X,80, TCP}
. This means host A connects to server X's port 80 and another host B also connects to same server X to the same port 80. Now, how the server handles these two sockets depends on if the server is single threaded or multiple threaded (I'll explain this later). What is important is that one server can listen to multiple sockets simultaneously.
To answer the original question of the post:
Irrespective of stateful or stateless protocols, two clients can connect to same server port because for each client we can assign a different socket (as client IP will definitely differ). Same client can also have two sockets connecting to same server port - since such sockets differ by SRC-PORT
. With all fairness, "Borealid" essentially mentioned the same correct answer but the reference to state-less/full was kind of unnecessary/confusing.
To answer the second part of the question on how a server knows which socket to answer. First understand that for a single server process that is listening to same port, there could be more than one sockets (may be from same client or from different clients). Now as long as a server knows which request is associated with which socket, it can always respond to appropriate client using the same socket. Thus a server never needs to open another port in its own node than the original one on which client initially tried to connect. If any server allocates different server-ports after a socket is bound, then in my opinion the server is wasting its resource and it must be needing the client to connect again to the new port assigned.
A bit more for completeness:
Example 2: It's a very interesting question: "can two different processes on a server listen to the same port". If you do not consider protocol as one of parameter defining socket then the answer is no. This is so because we can say that in such case, a single client trying to connect to a server-port will not have any mechanism to mention which of the two listening processes the client intends to connect to. This is the same theme asserted by rule (2). However this is WRONG answer because 'protocol' is also a part of the socket definition. Thus two processes in same node can listen to same port only if they are using different protocol. For example two unrelated clients (say one is using TCP and another is using UDP) can connect and communicate to the same server node and to the same port but they must be served by two different server-processes.
Server Types - single & multiple:
When a server's processes listening to a port that means multiple sockets can simultaneously connect and communicate with the same server-process. If a server uses only a single child-process to serve all the sockets then the server is called single-process/threaded and if the server uses many sub-processes to serve each socket by one sub-process then the server is called multi-process/threaded server. Note that irrespective of the server's type a server can/should always uses the same initial socket to respond back (no need to allocate another server-port).
Suggested Books and rest of the two volumes if you can.
A Note on Parent/Child Process (in response to query/comment of 'Ioan Alexandru Cucu')
Wherever I mentioned any concept in relation to two processes say A and B, consider that they are not related by parent child relationship. OS's (especially UNIX) by design allow a child process to inherit all File-descriptors (FD) from parents. Thus all the sockets (in UNIX like OS are also part of FD) that a process A listening to, can be listened by many more processes A1, A2, .. as long as they are related by parent-child relation to A. But an independent process B (i.e. having no parent-child relation to A) cannot listen to same socket. In addition, also note that this rule of disallowing two independent processes to listen to same socket lies on an OS (or its network libraries) and by far it's obeyed by most OS's. However, one can create own OS which can very well violate this restrictions.
Use a non-consuming regular expression.
The typical (i.e. Perl/Java) notation is:
(?=
expr)
This means "match expr but after that continue matching at the original match-point."
You can do as many of these as you want, and this will be an "and." Example:
(?=match this expression)(?=match this too)(?=oh, and this)
You can even add capture groups inside the non-consuming expressions if you need to save some of the data therein.
For those who don't want to use HTML agility pack and want to get HtmlDocument from string using native .net code only here is a good article on how to convert string to HtmlDocument
Here is the code block to use
public System.Windows.Forms.HtmlDocument GetHtmlDocument(string html)
{
WebBrowser browser = new WebBrowser();
browser.ScriptErrorsSuppressed = true;
browser.DocumentText = html;
browser.Document.OpenNew(true);
browser.Document.Write(html);
browser.Refresh();
return browser.Document;
}
Remove dotted outline from links, button and input element.
a:focus, a:active,
button::-moz-focus-inner,
input[type="reset"]::-moz-focus-inner,
input[type="button"]::-moz-focus-inner,
input[type="submit"]::-moz-focus-inner {
border: 0;
outline : 0;
}
You can import json as simplejson like this:
import json as simplejson
and keep backward compatibility.
I got this problem today while installing SugarCRM (a free CRM).
The system was not able to connect to the database using the root user. I could definitively log in as root from the console... so what was the problem?
I found out that in my situation, I was getting exactly the same error, but that was because the password was sent to mysql directly from the $_POST
data, in other words, the <
character from my password was sent to mysql as <
which means the password was wrong.
Everything else did not help a bit. The list of users in mysql were correct, including the anonymous user (which appears after the root entries.)
That clearly depends on the particular implementation of the interpreter/compiler of the specific language.
That said, theoretically, any sane implementation is likely to be able to implement one in terms of the other if it was faster so the difference should be negligible at most.
Of course, I assumed while
and for
behave as they do in C and similar languages. You could create a language with completely different semantics for while
and for
You can use Get-Member
if(Get-Member -inputobject $var -name "Property" -Membertype Properties){
#Property exists
}
Window > Preferences, go to the Run/Debug > Console section >> "Limit console output.>>Console buffer size(characters):" (This option can be seen in Eclipse Indigo ,but it limits buffer size at 1,000,000 )
NullPointerException
s are among the easier exceptions to diagnose, frequently. Whenever you get an exception in Java and you see the stack trace ( that's what your second quote-block is called, by the way ), you read from top to bottom. Often, you will see exceptions that start in Java library code or in native implementations methods, for diagnosis you can just skip past those until you see a code file that you wrote.
Then you like at the line indicated and look at each of the objects ( instantiated classes ) on that line -- one of them was not created and you tried to use it. You can start by looking up in your code to see if you called the constructor on that object. If you didn't, then that's your problem, you need to instantiate that object by calling new Classname( arguments ). Another frequent cause of NullPointerException
s is accidentally declaring an object with local scope when there is an instance variable with the same name.
In your case, the exception occurred in your constructor for Workshop on line 75. <init>
means the constructor for a class. If you look on that line in your code, you'll see the line
denimjeansButton.addItemListener(this);
There are fairly clearly two objects on this line: denimjeansButton
and this
. this
is synonymous with the class instance you are currently in and you're in the constructor, so it can't be this
. denimjeansButton
is your culprit. You never instantiated that object. Either remove the reference to the instance variable denimjeansButton
or instantiate it.
Iterable is a generic interface. A problem you might be having (you haven't actually said what problem you're having, if any) is that if you use a generic interface/class without specifying the type argument(s) you can erase the types of unrelated generic types within the class. An example of this is in Non-generic reference to generic class results in non-generic return types.
So I would at least change it to:
public class ProfileCollection implements Iterable<Profile> {
private ArrayList<Profile> m_Profiles;
public Iterator<Profile> iterator() {
Iterator<Profile> iprof = m_Profiles.iterator();
return iprof;
}
...
public Profile GetActiveProfile() {
return (Profile)m_Profiles.get(m_ActiveProfile);
}
}
and this should work:
for (Profile profile : m_PC) {
// do stuff
}
Without the type argument on Iterable, the iterator may be reduced to being type Object so only this will work:
for (Object profile : m_PC) {
// do stuff
}
This is a pretty obscure corner case of Java generics.
If not, please provide some more info about what's going on.
You can load an XML document into an XMLType, then query it, e.g.:
DECLARE
x XMLType := XMLType(
'<?xml version="1.0" ?>
<person>
<row>
<name>Tom</name>
<Address>
<State>California</State>
<City>Los angeles</City>
</Address>
</row>
<row>
<name>Jim</name>
<Address>
<State>California</State>
<City>Los angeles</City>
</Address>
</row>
</person>');
BEGIN
FOR r IN (
SELECT ExtractValue(Value(p),'/row/name/text()') as name
,ExtractValue(Value(p),'/row/Address/State/text()') as state
,ExtractValue(Value(p),'/row/Address/City/text()') as city
FROM TABLE(XMLSequence(Extract(x,'/person/row'))) p
) LOOP
-- do whatever you want with r.name, r.state, r.city
END LOOP;
END;
One nice thing about logging.exception
that SiggyF's answer doesn't show is that you can pass in an arbitrary message, and logging will still show the full traceback with all the exception details:
import logging
try:
1/0
except ZeroDivisionError:
logging.exception("Deliberate divide by zero traceback")
With the default (in recent versions) logging behaviour of just printing errors to sys.stderr
, it looks like this:
>>> import logging
>>> try:
... 1/0
... except ZeroDivisionError:
... logging.exception("Deliberate divide by zero traceback")
...
ERROR:root:Deliberate divide by zero traceback
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero
Thanks bhavya's solution.There have been two answers about swift, but those are not very intact. I have do that in the swift3.Below is the main code.
In AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// seclect the mainStoryBoard entry by whthere user is login.
let userDefaults = UserDefaults.standard
if let isLogin: Bool = userDefaults.value(forKey:Common.isLoginKey) as! Bool? {
if (!isLogin) {
self.window?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LogIn")
}
}else {
self.window?.rootViewController = mainStoryboard.instantiateViewController(withIdentifier: "LogIn")
}
return true
}
In SignUpViewController.swift
@IBAction func userLogin(_ sender: UIButton) {
//handle your login work
UserDefaults.standard.setValue(true, forKey: Common.isLoginKey)
let delegateTemp = UIApplication.shared.delegate
delegateTemp?.window!?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Main")
}
In logOutAction function
@IBAction func logOutAction(_ sender: UIButton) {
UserDefaults.standard.setValue(false, forKey: Common.isLoginKey)
UIApplication.shared.delegate?.window!?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
}
Once again, please wait for a while, sometimes you missed that it actually worked but you are feeling really stressed and could not wait(I was).
Not sure why I fixed the same issue that happened on my Macbook, however, choose Nexus 5X API R would work somehow. OR below
Wipe Data: Tools->Open AVD Manager and click ? the emu "Wipe Data"
Cold Boots Now: Tools->Open AVD Manager and click ? the emu "Cold Boots Now"
Uninstall & Reinstall Android Emulator from SDK: Tools->Open SDK Manager->Android SDK(left-side menu)->SDK tools(middle in the main screen), then click "Android Emulator" and APPLY, then again click "Android Emulator" apply to reinstall, so finish
SELECT name, GROUP_CONCAT( section )
FROM `tmp`
GROUP BY name
If you are using Docker toolkit on window 10 home you will need to access the webpage through docker-machine ip command. It is generally 192.168.99.100:
It is assumed that you are running with publish command like below.
docker run -it -p 8080:8080 demo
With Window 10 pro version you can access with localhost or corresponding loopback 127.0.0.1:8080 etc (Tomcat or whatever you wish). This is because you don't have a virtual box there and docker is running directly on Window Hyper V and loopback is directly accessible.
Verify the hosts file in window for any digression. It should have 127.0.0.1 mapped to localhost
The problem is only when last digit is 5. Eg. 0.045 is internally stored as 0.044999999999999... You could simply increment last digit to 6 and round off. This will give you the desired results.
import re
def custom_round(num, precision=0):
# Get the type of given number
type_num = type(num)
# If the given type is not a valid number type, raise TypeError
if type_num not in [int, float, Decimal]:
raise TypeError("type {} doesn't define __round__ method".format(type_num.__name__))
# If passed number is int, there is no rounding off.
if type_num == int:
return num
# Convert number to string.
str_num = str(num).lower()
# We will remove negative context from the number and add it back in the end
negative_number = False
if num < 0:
negative_number = True
str_num = str_num[1:]
# If number is in format 1e-12 or 2e+13, we have to convert it to
# to a string in standard decimal notation.
if 'e-' in str_num:
# For 1.23e-7, e_power = 7
e_power = int(re.findall('e-[0-9]+', str_num)[0][2:])
# For 1.23e-7, number = 123
number = ''.join(str_num.split('e-')[0].split('.'))
zeros = ''
# Number of zeros = e_power - 1 = 6
for i in range(e_power - 1):
zeros = zeros + '0'
# Scientific notation 1.23e-7 in regular decimal = 0.000000123
str_num = '0.' + zeros + number
if 'e+' in str_num:
# For 1.23e+7, e_power = 7
e_power = int(re.findall('e\+[0-9]+', str_num)[0][2:])
# For 1.23e+7, number_characteristic = 1
# characteristic is number left of decimal point.
number_characteristic = str_num.split('e+')[0].split('.')[0]
# For 1.23e+7, number_mantissa = 23
# mantissa is number right of decimal point.
number_mantissa = str_num.split('e+')[0].split('.')[1]
# For 1.23e+7, number = 123
number = number_characteristic + number_mantissa
zeros = ''
# Eg: for this condition = 1.23e+7
if e_power >= len(number_mantissa):
# Number of zeros = e_power - mantissa length = 5
for i in range(e_power - len(number_mantissa)):
zeros = zeros + '0'
# Scientific notation 1.23e+7 in regular decimal = 12300000.0
str_num = number + zeros + '.0'
# Eg: for this condition = 1.23e+1
if e_power < len(number_mantissa):
# In this case, we only need to shift the decimal e_power digits to the right
# So we just copy the digits from mantissa to characteristic and then remove
# them from mantissa.
for i in range(e_power):
number_characteristic = number_characteristic + number_mantissa[i]
number_mantissa = number_mantissa[i:]
# Scientific notation 1.23e+1 in regular decimal = 12.3
str_num = number_characteristic + '.' + number_mantissa
# characteristic is number left of decimal point.
characteristic_part = str_num.split('.')[0]
# mantissa is number right of decimal point.
mantissa_part = str_num.split('.')[1]
# If number is supposed to be rounded to whole number,
# check first decimal digit. If more than 5, return
# characteristic + 1 else return characteristic
if precision == 0:
if mantissa_part and int(mantissa_part[0]) >= 5:
return type_num(int(characteristic_part) + 1)
return type_num(characteristic_part)
# Get the precision of the given number.
num_precision = len(mantissa_part)
# Rounding off is done only if number precision is
# greater than requested precision
if num_precision <= precision:
return num
# Replace the last '5' with 6 so that rounding off returns desired results
if str_num[-1] == '5':
str_num = re.sub('5$', '6', str_num)
result = round(type_num(str_num), precision)
# If the number was negative, add negative context back
if negative_number:
result = result * -1
return result
The problem you're having, is that you are using a Group Selector
, whereas you should be using a Multiples selector
! To be more specific, you're using $('.a, .b')
whereas you should be using $('.a.b')
.
For more information, see the overview of the different ways to combine selectors herebelow!
Select all <h1>
elements AND all <p>
elements AND all <a>
elements :
$('h1, p, a')
Select all <input>
elements of type
text
, with classes code
and red
:
$('input[type="text"].code.red')
Select all <i>
elements inside <p>
elements:
$('p i')
Select all <ul>
elements that are immediate children of a <li>
element:
$('li > ul')
Select all <a>
elements that are placed immediately after <h2>
elements:
$('h2 + a')
Select all <span>
elements that are siblings of <div>
elements:
$('div ~ span')
I'm not sure the default hashcode is the address - I read the OpenJDK source for hashcode generation a while ago, and I remember it being something a bit more complicated. Still not something that guarantees a good distribution, perhaps. However, that is to some extent moot, as few classes you'd use as keys in a hashmap use the default hashcode - they supply their own implementations, which ought to be good.
On top of that, what you may not know (again, this is based in reading source - it's not guaranteed) is that HashMap stirs the hash before using it, to mix entropy from throughout the word into the bottom bits, which is where it's needed for all but the hugest hashmaps. That helps deal with hashes that specifically don't do that themselves, although i can't think of any common cases where you'd see that.
Finally, what happens when the table is overloaded is that it degenerates into a set of parallel linked lists - performance becomes O(n). Specifically, the number of links traversed will on average be half the load factor.
To add to those who have mentioned the implicit rules, it's best to see what make has defined implicitly and for your env using:
make -p
For instance:
%.o: %.c
$(COMPILE.c) $(OUTPUT_OPTION) $<
which expands
COMPILE.c = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c
This will also print # environment
data. Here, you will find GCC's include path among other useful info.
C_INCLUDE_PATH=/usr/include
In make, when it comes to search, the paths are many, the light is one... or something to that effect.
C_INCLUDE_PATH
is system-wide, set it in your shell's *.rc
.$(CPPFLAGS)
is for the preprocessor include path.VPATH = my_dir_to_search
... or even more specific
vpath %.c src
vpath %.h include
make uses VPATH as a general search path so use cautiously. If a file exists in more than one location listed in VPATH, make will take the first occurrence in the list.
Or no JavaScript load function at all...
<html>
<head></head>
<body>
<canvas id="canvas" width="150" height="150"></canvas>
</body>
<script type="text/javascript">
var draw = function() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (30, 30, 55, 50);
}
}
draw();
//or self executing...
(function(){
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (50, 50, 55, 50);
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (70, 70, 55, 50);
}
})();
</script>
</html>
You can try the enable/disable methods instead of using the option method:
$("#txtSearch").datepicker("enable");
$("#txtSearch").datepicker("disable");
This disables the entire textbox. So may be you can use datepicker.destroy()
instead:
$(document).ready(function() {
$("#ddlSearchType").change(function() {
if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date") {
$("#txtSearch").datepicker();
}
else {
$("#txtSearch").datepicker("destroy");
}
}).change();
});
I was in a situation where we have a master branch, and then another branch called 17.0 and inside this 17.0 there was a commit hash no say "XYZ". And customer is given a build till that XYZ revision. Now we came across a bug and that needs to be solved for that customer. So we need to create separate branch for that customer till that "xyz" hash. So here is how I did it.
First I created a folder with that customer name on my local machine. Say customer name is "AAA" once that folder is created issue following command inside this folder:
This works for me.
Request.Url.OriginalString.Replace(Request.Url.PathAndQuery, "") + Request.ApplicationPath;
So if you want to access your domain name do consider to include the application name in case of:
====================================
For the dev.x.us/web
it return this strong text
From the description of material design specs:
Grid Lists are an alternative to standard list views. Grid lists are distinct from grids used for layouts and other visual presentations.
If you are looking for a much lightweight Grid component library, I'm using React-Flexbox-Grid, the implementation of flexboxgrid.css
in React.
On top of that, React-Flexbox-Grid played nicely with both material-ui, and react-toolbox (the alternative material design implementation).
sudo apt-get update
OpenGL: sudo apt-get install libglu1-mesa-dev freeglut3-dev mesa-common-dev
Locate your Visual Studio folder for where it puts libraries and also header files, download and copy lib files to lib folder and header files to header. Then copy dll files to system32. Then your code will 100% run.
Also Windows: For all of those includes you just need to download glut32.lib
, glut.h
, glut32.dll
.
If you are using Anaconda for package management, following should do:
conda install -c anaconda beautifulsoup4
This might not directly answer your question but for the sake of those that come with states like the below
state = {
currentstate:[
{
id: 1 ,
firstname: 'zinani',
sex: 'male'
}
]
}
Solution
const new_value = {
id: 2 ,
firstname: 'san',
sex: 'male'
}
Replace the current state with the new value
this.setState({ currentState: [...this.state.currentState, new_array] })
Your code is absolutely fine. It just needs "exit 0" for a cleaner exit.
tncserver.exe C:\Work -p4 -b57600 -r -cFE -tTNC426B
exit 0
I've been dealing with 01 - which is a numeric.
string(number($v)) != string($v)
makes the segregation
If it is just "access in other controller" then you can use angular constants for that, the benefit is; you can add some global settings or other things that you want to access throughout application
app.constant(‘appGlobals’, {
defaultTemplatePath: '/assets/html/template/',
appName: 'My Awesome App'
});
and then access it like:
app.controller(‘SomeController’, [‘appGlobals’, function SomeController(config) {
console.log(appGlobals);
console.log(‘default path’, appGlobals.defaultTemplatePath);
}]);
(didn't test)
more info: http://ilikekillnerds.com/2014/11/constants-values-global-variables-in-angularjs-the-right-way/
From the man read:
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
Input parameters:
int fd
file descriptor is an integer and not a file pointer. The file descriptor for stdin
is 0
void *buf
pointer to buffer to store characters read by the read
function
size_t count
maximum number of characters to read
So you can read character by character with the following code:
char buf[1];
while(read(0, buf, sizeof(buf))>0) {
// read() here read from stdin charachter by character
// the buf[0] contains the character got by read()
....
}
This works with Windows 10, 8.x, 7, and possibly further back:
@echo Started: %date% %time%
.
.
.
@echo Completed: %date% %time%
Step-1: Your Model class
public class RechargeMobileViewModel
{
public string CustomerFullName { get; set; }
public string TelecomSubscriber { get; set; }
public int TotalAmount { get; set; }
public string MobileNumber { get; set; }
public int Month { get; set; }
public List<SelectListItem> getAllDaysList { get; set; }
// Define the list which you have to show in Drop down List
public List<SelectListItem> getAllWeekDaysList()
{
List<SelectListItem> myList = new List<SelectListItem>();
var data = new[]{
new SelectListItem{ Value="1",Text="Monday"},
new SelectListItem{ Value="2",Text="Tuesday"},
new SelectListItem{ Value="3",Text="Wednesday"},
new SelectListItem{ Value="4",Text="Thrusday"},
new SelectListItem{ Value="5",Text="Friday"},
new SelectListItem{ Value="6",Text="Saturday"},
new SelectListItem{ Value="7",Text="Sunday"},
};
myList = data.ToList();
return myList;
}
}
Step-2: Call this method to fill Drop down in your controller Action
namespace MvcVariousApplication.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
RechargeMobileViewModel objModel = new RechargeMobileViewModel();
objModel.getAllDaysList = objModel.getAllWeekDaysList();
return View(objModel);
}
}
}
Step-3: Fill your Drop-Down List of View as follows
@model MvcVariousApplication.Models.RechargeMobileViewModel
@{
ViewBag.Title = "Contact";
}
@Html.LabelFor(model=> model.CustomerFullName)
@Html.TextBoxFor(model => model.CustomerFullName)
@Html.LabelFor(model => model.MobileNumber)
@Html.TextBoxFor(model => model.MobileNumber)
@Html.LabelFor(model => model.TelecomSubscriber)
@Html.TextBoxFor(model => model.TelecomSubscriber)
@Html.LabelFor(model => model.TotalAmount)
@Html.TextBoxFor(model => model.TotalAmount)
@Html.LabelFor(model => model.Month)
@Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")
How about:
c = os.getcwd().split('\\')
print '\\'.join(c[0:-2])
basically LINQ join operator provides no benefit for SQL. I.e. the following query
var r = from dealer in db.Dealers
from contact in db.DealerContact
where dealer.DealerID == contact.DealerID
select dealerContact;
will result in INNER JOIN in SQL
join is useful for IEnumerable<> because it is more efficient:
from contact in db.DealerContact
clause would be re-executed for every dealer But for IQueryable<> it is not the case. Also join is less flexible.
Have you tried any of these?
onMouseDown onMouseEnter onMouseLeave
onMouseMove onMouseOut onMouseOver onMouseUp
it also mentions the following:
React normalizes events so that they have consistent properties across different browsers.
The event handlers below are triggered by an event in the bubbling phase. To register an event handler for the capture phase, append Capture to the event name; for example, instead of using onClick, you would use onClickCapture to handle the click event in the capture phase.
HTML:
<input id="id_ok" class="btn btn-space" value="OK" type="button">
<input id="id_cancel" class="btn btn-space" value="Cancel" type="button">
CSS:
.btn-space {
margin-right: 5px;
}
Error:Execution failed for task com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException:
finished with non-zero exit value 1
One reason for this error to occure is that the file path to a resource file is to long:
Error: File path too long on Windows, keep below 240 characters
Fix: Move your project folder closer to the root of your disk
Don't:// folder/folder/folder/folder/very_long_folder_name/MyProject...
Do://folder/short_name/MyProject
Another reason could be duplicated resources or name spaces
Example:
<style name="MyButton" parent="android:Widget.Button">
<item name="android:textColor">@color/accent_color</item>
<item name="android:textColor">#000000</item>
</style>
And make sure all file names and extensions are in lowercase
Wrong
myimage.PNG
myImage.png
Correct
my_image.png
Make sure to Clean/Rebuild project
(delete the 'build' folder)
This method is deprecated now from now starting with Android Q.
Try This will really help.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {// if build version is less than Q try the old traditional method
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
btnOnOff.setText("Wifi ONN");
} else {
wifiManager.setWifiEnabled(false);
btnOnOff.setText("Wifi OFF");
}
} else {// if it is Android Q and above go for the newer way NOTE: You can also use this code for less than android Q also
Intent panelIntent = new Intent(Settings.Panel.ACTION_WIFI);
startActivityForResult(panelIntent, 1);
}
I have gone through all the answers as at this date (2020-07-24), and there has to be a simpler more familiar way to solve this problem, which is the following.
Two scenarios... One is if the XML string is well-formed, i.e. it begins with something like <?xml version="1.0" encoding="utf-16"?>
or its likes, before encountering the root element, which is <msg>
in the question. The other is if it is NOT well-formed, i.e. just the root element (e.g. <msg>
in the question) and its child nodes only.
Firstly, just a simple class that contains the properties that match, in case-insensitive names, the child nodes of the root node in the XML. So, from the question, it would be something like...
public class TheModel
{
public int Id { get; set; }
public string Action { get; set; }
}
The following is the rest of the code...
// These are the key using statements to add.
using Newtonsoft.Json;
using System.Xml;
bool isWellFormed = false;
string xml = = @"
<msg>
<id>1</id>
<action>stop</action>
</msg>
";
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
if (isWellFormed)
{
xmlDocument.RemoveChild(xmlDocument.FirstChild);
/* i.e. removing the first node, which is the declaration part.
Also, if there are other unwanted parts in the XML,
write another similar code to locate the nodes
and remove them to only leave the desired root node
(and its child nodes).*/
}
var serializedXmlNode = JsonConvert.SerializeXmlNode(
xmlDocument,
Newtonsoft.Json.Formatting.Indented,
true
);
var theDesiredObject = JsonConvert.DeserializeObject<TheModel>(serializedXmlNode);
var dictionary = (from x in y
select new SomeClass
{
prop1 = value1,
prop2 = value2
}
).ToDictionary(item => item.prop1);
That's assuming that SomeClass.prop1
is the desired Key
for the dictionary.
If you've installed with the dmg, you can also go to the Mac "System Preferences" menu, click on "MySql" and then on the configuration tab to see the location of all MySql directories.
Reference: https://dev.mysql.com/doc/refman/8.0/en/osx-installation-prefpane.html
Sometimes the .gz
extension is wrongfully appended to the filename.
file foo.csv.gz
to know the actual file type.foo.csv
or whatever the actual file type is.The answer above is causing an error in my build environment.
This doesn't work in Swift 4.0:
attributedText.addAttribute(NSUnderlineStyleAttributeName,
value: NSUnderlineStyle.styleSingle.rawValue,
range: textRange)
Try this instead:
attributedText.addAttribute(NSAttributedStringKey.underlineStyle,
value: NSUnderlineStyle.styleSingle.rawValue,
range: textRange)
hope this helps someone.
From MSDN:
A
String
object is a sequential collection ofSystem.Char
objects that represent a string.
So you can use this:
var howManyBytes = yourString.Length * sizeof(Char);
You can use ArgbEvaluatorCompat class above API 11.
implementation 'com.google.android.material:material:1.0.0'
ValueAnimator colorAnim = ValueAnimator.ofObject(new ArgbEvaluatorCompat(), startColor, endColor);
colorAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mTargetColor = (int) animation.getAnimatedValue();
}
});
colorAnim.start();
I'll just try to answer the question but my examples very simple because I'm new at mvc. Hope this help somebody.
[HttpPost] ///This function is in my controller class
public ActionResult Delete(string txtDelete)
{
int _id = Convert.ToInt32(txtDelete); // put your code
}
This code is in my controller's cshtml
> @using (Html.BeginForm("Delete", "LibraryManagement"))
{
<button>Delete</button>
@Html.Label("Enter an ID number");
@Html.TextBox("txtDelete") }
Just make sure the textbox name and your controller's function input are the same name and type(string).This way, your function get the textbox input.
you can try setting the padding instead of the height/width.
You can do it in one sql statement for existing customers, 3 statements for new ones. All you have to do is be an optimist and act as though the customer already exists:
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);
If the customer does not exist, you'll get an sql exception which text will be something like:
null value in column "customer_id" violates not-null constraint
(providing you made customer_id non-nullable, which I'm sure you did). When that exception occurs, insert the customer into the customer table and redo the insert into the order table:
insert into customer(name) values ('John');
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);
Unless your business is growing at a rate that will make "where to put all the money" your only real problem, most of your inserts will be for existing customers. So, most of the time, the exception won't occur and you'll be done in one statement.
To vote on this issue, here is one active suggestion of how this could be added to the language. I'm not saying this is the best way to do this (at all), feel free to put out your own suggestion. But allowing properties to be passed by ref like Visual Basic already can do would hugely help simplify some code, and quite often!
One more point I want to add. In spring-servlet.xml
we include component scan for Controller package.
In following example we include filter annotation for controller package.
<!-- Scans for annotated @Controllers in the classpath -->
<context:component-scan base-package="org.test.web" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
In applicationcontext.xml
we add filter for remaining package excluding controller.
<context:component-scan base-package="org.test">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
A simple fix that I use to add space in horizontal legends, simply add spaces in the labels (see extract below):
scale_fill_manual(values=c("red","blue","white"),
labels=c("Label of category 1 ",
"Label of category 2 ",
"Label of category 3"))
export a=$(script.sh)
Hope this helps. Note there are no spaces between variable and =. To echo the output
echo $a
To get the negation, do this ...
df.filter(not( ..expression.. ))
eg
df.filter(not($"state" === "TX"))
If the above solution does not work for you it is may be possible to obtain the same result with the following pure nodejs code. The above did not work for me and resulted in a compilation exception when running 'npm install iconv' on OSX:
npm install iconv
npm WARN package.json [email protected] No README.md file found!
npm http GET https://registry.npmjs.org/iconv
npm http 200 https://registry.npmjs.org/iconv
npm http GET https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz
npm http 200 https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz
> [email protected] install /Users/markboyd/git/portal/app/node_modules/iconv
> node-gyp rebuild
gyp http GET http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
gyp http 200 http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
xcode-select: Error: No Xcode is selected. Use xcode-select -switch <path-to-xcode>, or see the xcode-select manpage (man xcode-select) for further information.
fs.readFileSync() returns a Buffer if no encoding is specified. And Buffer has a toString() method that will convert to UTF8 if no encoding is specified giving you the file's contents. See the nodejs documentation. This worked for me.
I made a procedure that execute a FOREACH
with CURSOR
for any table.
Example of use:
CREATE TABLE #A (I INT, J INT)
INSERT INTO #A VALUES (1, 2), (2, 3)
EXEC PRC_FOREACH
#A --Table we want to do the FOREACH
, 'SELECT @I, @J' --The execute command, each column becomes a variable in the same type, so DON'T USE SPACES IN NAMES
--The third variable is the database, it's optional because a table in TEMPB or the DB of the proc will be discovered in code
The result is 2 selects for each row.
The syntax of UPDATE
and break the FOREACH
are written in the hints.
This is the proc code:
CREATE PROC [dbo].[PRC_FOREACH] (@TBL VARCHAR(100) = NULL, @EXECUTE NVARCHAR(MAX)=NULL, @DB VARCHAR(100) = NULL) AS BEGIN
--LOOP BETWEEN EACH TABLE LINE
IF @TBL + @EXECUTE IS NULL BEGIN
PRINT '@TBL: A TABLE TO MAKE OUT EACH LINE'
PRINT '@EXECUTE: COMMAND TO BE PERFORMED ON EACH FOREACH TRANSACTION'
PRINT '@DB: BANK WHERE THIS TABLE IS (IF NOT INFORMED IT WILL BE DB_NAME () OR TEMPDB)' + CHAR(13)
PRINT 'ROW COLUMNS WILL VARIABLE WITH THE SAME NAME (COL_A = @COL_A)'
PRINT 'THEREFORE THE COLUMNS CANT CONTAIN SPACES!' + CHAR(13)
PRINT 'SYNTAX UPDATE:
UPDATE TABLE
SET COL = NEW_VALUE
WHERE CURRENT OF MY_CURSOR
CLOSE CURSOR (BEFORE ALL LINES):
IF 1 = 1 GOTO FIM_CURSOR'
RETURN
END
SET @DB = ISNULL(@DB, CASE WHEN LEFT(@TBL, 1) = '#' THEN 'TEMPDB' ELSE DB_NAME() END)
--Identifies the columns for the variables (DECLARE and INTO (Next cursor line))
DECLARE @Q NVARCHAR(MAX)
SET @Q = '
WITH X AS (
SELECT
A = '', @'' + NAME
, B = '' '' + type_name(system_type_id)
, C = CASE
WHEN type_name(system_type_id) IN (''VARCHAR'', ''CHAR'', ''NCHAR'', ''NVARCHAR'') THEN ''('' + REPLACE(CONVERT(VARCHAR(10), max_length), ''-1'', ''MAX'') + '')''
WHEN type_name(system_type_id) IN (''DECIMAL'', ''NUMERIC'') THEN ''('' + CONVERT(VARCHAR(10), precision) + '', '' + CONVERT(VARCHAR(10), scale) + '')''
ELSE ''''
END
FROM [' + @DB + '].SYS.COLUMNS C WITH(NOLOCK)
WHERE OBJECT_ID = OBJECT_ID(''[' + @DB + '].DBO.[' + @TBL + ']'')
)
SELECT
@DECLARE = STUFF((SELECT A + B + C FROM X FOR XML PATH('''')), 1, 1, '''')
, @INTO = ''--Read the next line
FETCH NEXT FROM MY_CURSOR INTO '' + STUFF((SELECT A + '''' FROM X FOR XML PATH('''')), 1, 1, '''')'
DECLARE @DECLARE NVARCHAR(MAX), @INTO NVARCHAR(MAX)
EXEC SP_EXECUTESQL @Q, N'@DECLARE NVARCHAR(MAX) OUTPUT, @INTO NVARCHAR(MAX) OUTPUT', @DECLARE OUTPUT, @INTO OUTPUT
--PREPARE TO QUERY
SELECT
@Q = '
DECLARE ' + @DECLARE + '
-- Cursor to scroll through object names
DECLARE MY_CURSOR CURSOR FOR
SELECT *
FROM [' + @DB + '].DBO.[' + @TBL + ']
-- Opening Cursor for Reading
OPEN MY_CURSOR
' + @INTO + '
-- Traversing Cursor Lines (While There)
WHILE @@FETCH_STATUS = 0
BEGIN
' + @EXECUTE + '
-- Reading the next line
' + @INTO + '
END
FIM_CURSOR:
-- Closing Cursor for Reading
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR'
EXEC SP_EXECUTESQL @Q --MAGIA
END
class MyActivity{
private final Handler handler = new Handler();
private Runnable yourRunnable;
protected void onCreate(@Nullable Bundle savedInstanceState) {
// ....
this.yourRunnable = new Runnable() {
@Override
public void run() {
//code
}
};
this.handler.postDelayed(this.yourRunnable, 2000);
}
@Override
protected void onDestroy() {
// to avoid memory leaks
this.handler.removeCallbacks(this.yourRunnable);
}
}
And to be double sure you can be combined it with the "static class" method as described in the tronman answer
Typically, you need a server side scripting language like PHP to connect to MySQL, however, if you're just doing a quick mockup, then you can use http://www.mysqljs.com to connect to MySQL from Javascript using code as follows:
MySql.Execute(
"mysql.yourhost.com",
"username",
"password",
"database",
"select * from Users",
function (data) {
console.log(data)
});
It has to be mentioned that this is not a secure way of accessing MySql, and is only suitable for private demos, or scenarios where the source code cannot be accessed by end users, such as within Phonegap iOS apps.
You can try opening the wsdl in web browser and saving with .wsdl extension. And set the WSDL in SOAP UI project to this .wsdl file. This really works.
I would use itertools.chain
- this will also cater for > 1 element in each sublist:
from itertools import chain
list(chain.from_iterable([[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]))
While you can call exit()
(and may need to do so if your application encounters some fatal error), the cleanest way to exit a program is to return from main()
:
int main()
{
// do whatever your program does
} // function returns and exits program
When you call exit()
, objects with automatic storage duration (local variables) are not destroyed before the program terminates, so you don't get proper cleanup. Those objects might need to clean up any resources they own, persist any pending state changes, terminate any running threads, or perform other actions in order for the program to terminate cleanly.
An other way of CASE:
SELECT *
FROM MyTable
WHERE 1 = CASE WHEN @myParm = value1 AND MyColumn IS NULL THEN 1
WHEN @myParm = value2 AND MyColumn IS NOT NULL THEN 1
WHEN @myParm = value3 THEN 1
END
https://www.typescriptlang.org/docs/handbook/advanced-types.html
One difference is that interfaces create a new name that is used everywhere. Type aliases don’t create a new name — for instance, error messages won’t use the alias name.
You need to take a copy of the list and iterate over it first, or the iteration will fail with what may be unexpected results.
For example (depends on what type of list):
for tup in somelist[:]:
etc....
An example:
>>> somelist = range(10)
>>> for x in somelist:
... somelist.remove(x)
>>> somelist
[1, 3, 5, 7, 9]
>>> somelist = range(10)
>>> for x in somelist[:]:
... somelist.remove(x)
>>> somelist
[]
Install a cross compiler, like mingw64 from your package manager.
Then compile in the following way: instead of simply calling gcc
call i686-w64-mingw32-gcc
for 32-bit Windows or x86_64-w64-mingw32-gcc"
for 64-bit Windows. I would also use the --static
option, as the target system may not have all the libraries.
If you want to compile other language, like Fortran, replace -gcc
with -gfortran
in the previous commands.
Double quotes can be achieved using VBA in one of two ways
First one is often the best
"...text..." & Chr(34) & "...text..."
Or the second one, which is more literal
"...text..." & """" & "...text..."
in python the operators should be in quotes: db.ProductData.update({'fromAddress':'http://localhost:7000/'}, {"$set": {'fromAddress': 'http://localhost:5000/'}},{"multi": True})
var pause_menu = {
pause_button : { someProperty : "prop1", someOther : "prop2" },
resume_button : { resumeProp : "prop", resumeProp2 : false },
quit_button : false
};
then:
pause_menu.pause_button.someProperty //evaluates to "prop1"
etc etc.
It works with
this.Width = System.Windows.SystemParameters.VirtualScreenWidth;
this.Height = System.Windows.SystemParameters.VirtualScreenHeight;
Tested on 2 monitors.
The following is my configuration:
cmake_minimum_required(VERSION 2.8)
set(Boost_INCLUDE_DIR /usr/local/src/boost_1_46_1)
set(Boost_LIBRARY_DIR /usr/local/src/boost_1_46_1/stage/lib)
find_package(Boost COMPONENTS system filesystem REQUIRED)
include_directories(${Boost_INCLUDE_DIR})
link_directories(${Boost_LIBRARY_DIR})
add_executable(main main.cpp)
target_link_libraries( main ${Boost_LIBRARIES} )
SELECT @var = col1,
@var2 = col2
FROM Table
Here is some interesting information about SET / SELECT
- SET is the ANSI standard for variable assignment, SELECT is not.
- SET can only assign one variable at a time, SELECT can make multiple assignments at once.
- If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
- When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
- As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.
I was facing the same problem, unable to create directory on Galaxy S but was able to create it successfully on Nexus and Samsung Droid. How I fixed it was by adding following line of code:
File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+getPackageName()+"/");
dir.mkdirs();
The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc
A set of simple examples:
Using Gson:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class Gson {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
com.google.gson.Gson gson = new com.google.gson.Gson();
Response respuesta = gson.fromJson(json, Response.class);
System.out.println(respuesta.getExample());
System.out.println(respuesta.getFr());
} catch (IOException ex) {
}
return null;
}
public class Response{
private String example;
private String fr;
public String getExample() {
return example;
}
public void setExample(String example) {
this.example = example;
}
public String getFr() {
return fr;
}
public void setFr(String fr) {
this.fr = fr;
}
}
}
Using json-simple:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonSimple {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
try {
JSONParser parser = new JSONParser();
Object resultObject = parser.parse(json);
if (resultObject instanceof JSONArray) {
JSONArray array=(JSONArray)resultObject;
for (Object object : array) {
JSONObject obj =(JSONObject)object;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
}else if (resultObject instanceof JSONObject) {
JSONObject obj =(JSONObject)resultObject;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
} catch (Exception e) {
// TODO: handle exception
}
} catch (IOException ex) {
}
return null;
}
}
etc...
Try with this
Response.Clear();
Response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.pptx;", getLegalFileName(CurrentPresentation.Presentation_NM)));
Response.Flush();
Response.BinaryWrite(masterPresentation.ToArray());
Response.End();
You can, under certain circumstances.
But the fact that you consider this is a strong sign that there is something wrong with your architecture: Primary keys should be pure technical and carry no business meaning whatsoever. So there should never be the need to change them.
Thomas
The XOR definition is well known to be the odd-parity function. For two inputs:
A XOR B = (A AND NOT B) OR (B AND NOT A)
The complement of XOR is XNOR
A XNOR B = (A AND B) OR (NOT A AND NOT B)
Henceforth, the normal two-input XAND defined as
A XAND B = A AND NOT B
The complement is XNAND:
A XNAND B = B OR NOT A
A nice result from this XAND definition is that any dual-input binary function can be expressed concisely using no more than one logical function or gate.
+---+---+---+---+
If A is: | 1 | 0 | 1 | 0 |
and B is: | 1 | 1 | 0 | 0 |
+---+---+---+---+
Then: yields:
+-----------+---+---+---+---+
| FALSE | 0 | 0 | 0 | 0 |
| A NOR B | 0 | 0 | 0 | 1 |
| A XAND B | 0 | 0 | 1 | 0 |
| NOT B | 0 | 0 | 1 | 1 |
| B XAND A | 0 | 1 | 0 | 0 |
| NOT A | 0 | 1 | 0 | 1 |
| A XOR B | 0 | 1 | 1 | 0 |
| A NAND B | 0 | 1 | 1 | 1 |
| A AND B | 1 | 0 | 0 | 0 |
| A XNOR B | 1 | 0 | 0 | 1 |
| A | 1 | 0 | 1 | 0 |
| B XNAND A | 1 | 0 | 1 | 1 |
| B | 1 | 1 | 0 | 0 |
| A XNAND B | 1 | 1 | 0 | 1 |
| A OR B | 1 | 1 | 1 | 0 |
| TRUE | 1 | 1 | 1 | 1 |
+-----------+---+---+---+---+
Note that XAND and XNAND lack reflexivity.
This XNAND definition is extensible if we add numbered kinds of exclusive-ANDs to correspond to their corresponding minterms. Then XAND must have ceil(lg(n)) or more inputs, with the unused msbs all zeroes. The normal kind of XAND is written without a number unless used in the context of other kinds.
The various kinds of XAND or XNAND gates are useful for decoding.
XOR is also extensible to any number of bits. The result is one if the number of ones is odd, and zero if even. If you complement any input or output bit of an XOR, the function becomes XNOR, and vice versa.
I have seen no definition for XNOT, I will propose a definition:
Let it to relate to high-impedance (Z, no signal, or perhaps null valued Boolean type Object).
0xnot 0 = Z
0xnot 1 = Z
1xnot 0 = 1
1xnot 1 = 0
You can also try with /usr/local/bin/git
it worked for me
For what its worth, in Pycharm it is: Right click on the root folder->Mark Directory as-> Sources Root
pip install --user package-name
Seems to work, but the package is install the the path of user. such as :
"c:\users\***\appdata\local\temp\pip-req-tracker-_akmzo\42a6c7d627641b148564ff35597ec30fd5543aa1cf6e41118b98d7a3"
I want to install the package in python folder such c:\Python27. I install the module into the expected folder by:
pip install package-name --no-cache-dir
You can try to use the runner in atom Hit Ctrl+R (Alt+R on Win/Linux) to launch the runner for the active window. Hit Ctrl+Shift+R (Alt+Shift+R on Win/Linux) to run the currently selected text in the active window. Hit Ctrl+Shift+C to kill a currently running process. Hit Escape to close the runner window
Many problems here
I've set up a fiddle that works for you: http://jsfiddle.net/w9kSU/
$('.majorpointslegend').click(function(){
if($(this).text()=='Expand'){
$('#mylist').show();
$(this).text('Colapse');
}else{
$('#mylist').hide();
$(this).text('Expand');
}
});
Since Spring 4.2 you can use @EventListener
(documentation)
@Component
class MyClassWithEventListeners {
@EventListener({ContextRefreshedEvent.class})
void contextRefreshedEvent() {
System.out.println("a context refreshed event happened");
}
}
Take a look at the Event Log API. Case a) (bluescreen, user cut the power cord or system hang) causes a note ('system did not shutdown correctly' or something like that) to be left in the 'System' event log the next time the system is rebooted properly. You should be able to access it programmatically using the above API (honestly, I've never used it but it should work).
You may be able to keep multiple tabs and more formatting information if you export to an OpenDocument Spreadsheet file (ods) or an older Excel format and import it with the ODS reader or the Excel reader you mentioned above.
open bash profile in textEdit
open -e .bash_profile
Edit file or paste in front of PATH export PATH=/usr/bin:/usr/sbin:/bin:/sbin:/usr/local/bin:/usr/local/sbin:~/bin
save & close the file
*To open .bash_profile directly open textEdit > file > recent
If you are after performance, try to avoid using AngularJS filters as they are applied twice per each expression to check for their stability.
A better way would be to use CSS ::first-letter
pseudo-element with text-transform: uppercase;
. That can't be used on inline elements such as span
, though, so the next best thing would be to use text-transform: capitalize;
on the whole block, which capitalizes every word.
Example:
var app = angular.module('app', []);_x000D_
_x000D_
app.controller('Ctrl', function ($scope) {_x000D_
$scope.msg = 'hello, world.';_x000D_
});
_x000D_
.capitalize {_x000D_
display: inline-block; _x000D_
}_x000D_
_x000D_
.capitalize::first-letter {_x000D_
text-transform: uppercase;_x000D_
}_x000D_
_x000D_
.capitalize2 {_x000D_
text-transform: capitalize;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="app">_x000D_
<div ng-controller="Ctrl">_x000D_
<b>My text:</b> <div class="capitalize">{{msg}}</div>_x000D_
<p><b>My text:</b> <span class="capitalize2">{{msg}}</span></p>_x000D_
</div>_x000D_
</div>
_x000D_
This is exactly what ajax is for. See here:
Basically, you ajax/test.php and put the returned HTML code to the element which has the result id.
$('#result').load('ajax/test.php');
Of course, you will need to put the functionality which takes time to a new php file (or call the old one with a GET parameter which will activate that functionality only).
There are two ways to do this. First is like this:
while True: # Loop continuously
inp = raw_input() # Get the input
if inp == "": # If it is a blank line...
break # ...break the loop
The second is like this:
inp = raw_input() # Get the input
while inp != "": # Loop until it is a blank line
inp = raw_input() # Get the input again
Note that if you are on Python 3.x, you will need to replace raw_input
with input
.
I'd suggest using git rebase -i
; move the commit you want to push to the top of the commits you've made. Then use git log
to get the SHA of the rebased commit, check it out, and push it. The rebase will have ensures that all your other commits are now children of the one you pushed, so future pushes will work fine too.
Set return type to Void
instead of void
and return null
// Modify existing method
public static Void displayInt(Integer i) {
System.out.println(i);
return null;
}
OR
// Or use Lambda
myForEach(theList, i -> {System.out.println(i);return null;});
In case it helps someone, I had a similar issue and the error was because of two reasons:
Not using the app's namespace before the url name
{% url 'app_name:url_name' %}
Missing single quotes around the url name (as pointed out here by Charlie)
Last revision merged from trunk to branch can be found by running this command inside the working copy directory:
svn log -v --stop-on-copy
buildscript {
project.ext {
supportLibVersion = '27.1.1'
compileVersion = 28
minSupportedVersion = 22
}
}
and set dependencies:
implementation "com.android.support:appcompat-v7:$project.supportLibVersion"
You must ensure that the form is in the document. You can append the form to the body.
Here's more modern approach:
.parent {display: flow-root;}
No more clearfixes.
p.s. Using overflow: hidden; hides the box-shadow so...
Before 2015, using the var
keyword was the only way to declare a JavaScript variable.
After ES6 (a JavaScript version), it allows 2 new keywords let & const.
let
= can be re-assigned
const
= cannot be re-assigned ( const which comes from constant, short-form 'const' )
Example:
Suppose, declaring a Country Name / Your mother name, const
is most suitable here. because there is less chance to change a country name or your mother name soon or later.
Your age, weight, salary, speed of a bike and more like these types of data that change often or need to reassign. those situations, let
is used.
From my recent experience, JsonReader#setLenient
basically makes the parser very tolerant, even to allow malformed JSON data.
But for certain data retrieved from your trusted RESTful API(s), this error might be caused by trailing white spaces. In such cases, simply trim
the data would avoid the error:
String trimmed = result1.trim();
Then gson.fromJson(trimmed, T)
might work. Surely this only covers a special case, so YMMV.
Note that reversing the whole string (either with the rbegin()
/rend()
range constructor or with std::reverse
) and comparing it with the input would perform unnecessary work.
It's sufficient to compare the first half of the string with the latter half, in reverse:
#include <string>
#include <algorithm>
#include <iostream>
int main()
{
std::string s;
std::cin >> s;
if( equal(s.begin(), s.begin() + s.size()/2, s.rbegin()) )
std::cout << "is a palindrome.\n";
else
std::cout << "is NOT a palindrome.\n";
}
demo: http://ideone.com/mq8qK
Well... I had the same issue and it was a headache. Since I didn't care much about the namespace or the xml schema, I just deleted this data from my xml and it solved all my issues. May not be the best answer? Probably, but if you don't want to deal with all of this and you ONLY care about the data (and won't be using the xml for some other task) deleting the namespace may solve your problems.
XmlDocument vinDoc = new XmlDocument();
string vinInfo = "your xml string";
vinDoc.LoadXml(vinInfo);
vinDoc.InnerXml = vinDoc.InnerXml.Replace("xmlns=\"http://tempuri.org\/\", "");
Another possibility is to use regular expressions which is what Perl is famous for:
if ($mystring =~ /s1\.domain\.com/) {
print qq("$mystring" contains "s1.domain.com"\n);
}
The backslashes are needed because a .
can match any character. You can get around this by using the \Q
and \E
operators.
my $substring = "s1.domain.com";
if ($mystring =~ /\Q$substring\E/) {
print qq("$mystring" contains "$substring"\n);
}
Or, you can do as eugene y stated and use the index function.
Just a word of warning: Index returns a -1
when it can't find a match instead of an undef
or 0
.
Thus, this is an error:
my $substring = "s1.domain.com";
if (not index($mystring, $substr)) {
print qq("$mystring" doesn't contains "$substring"\n";
}
This will be wrong if s1.domain.com
is at the beginning of your string. I've personally been burned on this more than once.
Similar answer to above
docker images | awk '{print $1}' | grep -v 'none' | grep -iv 'repo' | xargs -n1 docker pull
Hat tip to Adam Bien if you don't want to use createQuery
with a String
and want type safety:
@PersistenceContext EntityManager em; public List<ConfigurationEntry> allEntries() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<ConfigurationEntry> cq = cb.createQuery(ConfigurationEntry.class); Root<ConfigurationEntry> rootEntry = cq.from(ConfigurationEntry.class); CriteriaQuery<ConfigurationEntry> all = cq.select(rootEntry); TypedQuery<ConfigurationEntry> allQuery = em.createQuery(all); return allQuery.getResultList(); }
http://www.adam-bien.com/roller/abien/entry/selecting_all_jpa_entities_as
You can use a simpler pre-processor trick if you are willing to list your enum
entries in an external file.
/* file: errors.def */
/* syntax: ERROR_DEF(name, value) */
ERROR_DEF(ErrorA, 0x1)
ERROR_DEF(ErrorB, 0x2)
ERROR_DEF(ErrorC, 0x4)
Then in a source file, you treat the file like an include file, but you define what you want the ERROR_DEF
to do.
enum Errors {
#define ERROR_DEF(x,y) x = y,
#include "errors.def"
#undef ERROR_DEF
};
static inline std::ostream & operator << (std::ostream &o, Errors e) {
switch (e) {
#define ERROR_DEF(x,y) case y: return o << #x"[" << y << "]";
#include "errors.def"
#undef ERROR_DEF
default: return o << "unknown[" << e << "]";
}
}
If you use some source browsing tool (like cscope), you'll have to let it know about the external file.
You can have only one default export which you declare like:
export default App;
or
export default class App extends React.Component {...
and later do import App from './App'
If you want to export something more you can use named exports which you declare without default
keyword like:
export {
About,
Contact,
}
or:
export About;
export Contact;
or:
export const About = class About extends React.Component {....
export const Contact = () => (<div> ... </div>);
and later you import them like:
import App, { About, Contact } from './App';
EDIT:
There is a mistake in the tutorial as it is not possible to make 3 default exports in the same main.js
file. Other than that why export anything if it is no used outside the file?. Correct main.js
:
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute } from 'react-router'
class App extends React.Component {
...
}
class Home extends React.Component {
...
}
class About extends React.Component {
...
}
class Contact extends React.Component {
...
}
ReactDOM.render((
<Router history = {browserHistory}>
<Route path = "/" component = {App}>
<IndexRoute component = {Home} />
<Route path = "home" component = {Home} />
<Route path = "about" component = {About} />
<Route path = "contact" component = {Contact} />
</Route>
</Router>
), document.getElementById('app'))
EDIT2:
another thing is that this tutorial is based on react-router-V3 which has different api than v4.
$host
is a variable of the Core module.
$host
This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.
This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.
$http_host
is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER
(ref).
$http_HEADER
The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;
Summarizing:
$http_host
equals always the HTTP_HOST
request header.$host
equals $http_host
, lowercase and without the port number (if present), except when HTTP_HOST
is absent or is an empty value. In that case, $host
equals the value of the server_name
directive of the server which processed the request.In VB
: This should work
ConfigurationManager.ConnectionStrings("SQLServer").ConnectionString
In C#
it would be (as per comment of Ala)
ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString
Why not use controller inheritance, all methods/properties defined in scope of HeaderCtrl are accessible in the controller inside ng-view. $scope.servHelper is accessible in all your controllers.
angular.module('fnetApp').controller('HeaderCtrl', function ($scope, MyHelperService) {
$scope.servHelper = MyHelperService;
});
<div ng-controller="HeaderCtrl">
<div ng-view=""></div>
</div>
Find the file "config.inc.php" under your phpMyAdmin directory and edit the following lines:
$cfg['Servers'][$i]['auth_type'] = 'config'; // config, http, cookie
$cfg['Servers'][$i]['user'] = 'root'; // MySQL user
$cfg['Servers'][$i]['password'] = 'TYPE_YOUR_PASSWORD_HERE'; // MySQL password
Note that the password used in the 'password' field must be the same for the MySQL root password. Also, you should check if root login is allowed in this line:
$cfg['Servers'][$i]['AllowRoot'] = TRUE; // true = allow root login
This way you have your root password set.
If portability is important you may not want to depend on a specific shell in your Makefile. Not all environments have bash available.
The permament pool contains everything that is not your application data, but rather things required for the VM: typically it contains interned strings, the byte code of defined classes, but also other "not yours" pieces of data.
According to MSDN
result is the number of lines affected, and since your query is select
no lines are affected (i.e. inserted, deleted or updated) anyhow.
If you want to return a single row of the query, use ExecuteScalar()
instead of ExecuteNonQuery()
:
int result = (int) (command.ExecuteScalar());
However, if you expect many rows to be returned, ExecuteReader()
is the only option:
using (SqlDataReader reader = command.ExecuteReader()) {
while (reader.Read()) {
int result = reader.GetInt32(0);
...
}
}
The following worked for me.
var iframe = top.frames[name].document;
var css = '' +
'<style type="text/css">' +
'body{margin:0;padding:0;background:transparent}' +
'</style>';
iframe.open();
iframe.write(css);
iframe.close();
You coud try java.net.URLClassloader with the url of the folder/jar where your updated class resides and use it instead of the default classloader when creating a new thread.
Instead of using -f or --force developers should use
--force-with-lease
Why? Because it checks the remote branch for changes which is absolutely a good idea. Let's imagine that James and Lisa are working on the same feature branch and Lisa has pushed a commit. James now rebases his local branch and is rejected when trying to push. Of course James thinks this is due to rebase and uses --force and would rewrite all Lisa's changes. If James had used --force-with-lease he would have received a warning that there are commits done by someone else. I don't see why anyone would use --force instead of --force-with-lease when pushing after a rebase.
use below code , change proper database name and user name and then take that output and execute in SSMS. FOR SQL 2005 ABOVE
USE <database_name>
select 'GRANT EXECUTE ON ['+name+'] TO [userName] '
from sys.objects
where type ='P'
and is_ms_shipped = 0
For SQL Server, from http://msdn.microsoft.com/en-us/library/ms179859.aspx :
% Any string of zero or more characters.
WHERE title LIKE '%computer%'
finds all book titles with the word 'computer' anywhere in the book title.
_ Any single character.
WHERE au_fname LIKE '_ean'
finds all four-letter first names that end with ean (Dean, Sean, and so on).
[ ] Any single character within the specified range ([a-f]) or set ([abcdef]).
WHERE au_lname LIKE '[C-P]arsen'
finds author last names ending with arsen and starting with any single character between C and P, for example Carsen, Larsen, Karsen, and so on. In range searches, the characters included in the range may vary depending on the sorting rules of the collation.
[^] Any single character not within the specified range ([^a-f]) or set ([^abcdef]).
WHERE au_lname LIKE 'de[^l]%'
all author last names starting with de and where the following letter is not l.
Well,
$xml = "l
vv";
Works.
You can also use the following:
$xml = "l\nvv";
or
$xml = <<<XML
l
vv
XML;
You can concatenate strings using the .=
operator.
$str = "Hello";
$str .= " World";
echo $str; //Will echo out "Hello World";
I'll Explain how to add an image using Android studio(2.3.3). First you need to add the image into res/drawable folder in the project. Like below
Now in go to activity_main.xml (or any activity you need to add image) and select the Design view. There you can see your Palette tool box on left side. You need to drag and drop ImageView.
It will prompt you Resources dialog box. In there select Drawable under the project section you can see your image. Like below
Select the image you want press Ok you can see the image on the Design view. If you want it configure using xml it would look like below.
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/homepage"
tools:layout_editor_absoluteX="55dp"
tools:layout_editor_absoluteY="130dp" />
You need to give image location using
app:srcCompat="@drawable/imagename"
if ($('a').on('Clicked').text().search('1') == -1)
{
//Page == 1
}
else
{
//Page != 1
}
May be this is useful to you.
//Method writes a string to a text file
-(void) writeToTextFile{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = @"One\nTwo\nThree\nFour\nFive";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSUTF8StringEncoding
error:nil];
}
//Method retrieves content from documents directory and
//displays it in an alert
-(void) displayContent{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error:nil];
//use simple alert from my library (see previous post for details)
[ASFunctions alert:content];
[content release];
}
This should work for alpha 6. The key is the class "mr-auto" on the left nav, which will push the right nav to the right. You also need to add navbar-toggleable-md or it will stack in a column instead of a row. Note I didn't add the remaining toggle items (e.g. toggle button), I added just enough to get it to formatted as requested. Here are more complete examples https://v4-alpha.getbootstrap.com/examples/navbars/.
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">
<div class="container">
<a class="navbar-brand" href="#">Navbar</a>
<ul class="nav navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
<ul class="nav navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Link on the Right</a>
</li>
</ul>
</div>
</nav>
</body>
Have you tried:
eval $cmd
For the follow-on question of how to escape *
since it has special meaning when it's naked or in double quoted strings: use single quotes.
MYSQL='mysql AMORE -u username -ppassword -h localhost -e'
QUERY="SELECT "'*'" FROM amoreconfig" ;# <-- "double"'single'"double"
eval $MYSQL "'$QUERY'"
Bonus: It also reads nice: eval mysql query ;-)
use this in style
body
{
overflow:hidden;
width:100%;
}
Use this in head tag
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes" />
Paul Dardeau answer is perfect, the only thing is, what if all the files inside those folders are not PDF files and you want to grab it all no matter the extension. Well just change it to
find . -name "*.*" -type f -exec cp {} ./pdfsfolder \;
Just to sum up!
You can try this way.
byte ptext[] = myString.getBytes("ISO-8859-1");
String value = new String(ptext, "UTF-8");
To delete all stashes older than 40 days, use:
git reflog expire --expire-unreachable=40.days refs/stash
Add --dry-run
to see which stashes are deleted.
See https://stackoverflow.com/a/44829516/946850 for an explanation and much more detail.
make it simple
private void dataGridView1_cellformatting(object sender,DataGridViewCellFormattingEventArgs e)
{
var amount = (int)e.Value;
// return if rowCount = 0
if (this.dataGridView1.Rows.Count == 0)
return;
if (amount > 0)
e.CellStyle.BackColor = Color.Green;
else
e.CellStyle.BackColor = Color.Red;
}
take a look cell formatting
Did you import it? Importing matplotlib
is not enough.
>>> import matplotlib
>>> matplotlib.pyplot
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
but
>>> import matplotlib.pyplot
>>> matplotlib.pyplot
works.
pyplot is a submodule of matplotlib and not immediately imported when you import matplotlib.
The most common form of importing pyplot is
import matplotlib.pyplot as plt
Thus, your statements won't be too long, e.g.
plt.plot([1,2,3,4,5])
instead of
matplotlib.pyplot.plot([1,2,3,4,5])
And: pyplot
is not a function, it's a module! So don't call it, use the functions defined inside this module instead. See my example above
function SetCaretEnd(tID) {
tID += "";
if (!tID.startsWith("#")) { tID = "#" + tID; }
$(tID).focus();
var t = $(tID).val();
if (t.length == 0) { return; }
$(tID).val("");
$(tID).val(t);
$(tID).scrollTop($(tID)[0].scrollHeight); }
4 suggested ways to open apk files:
1.open apk file by Android Studio (For Photo,java code and analyze size) the best way
2.open by applications winRar,7zip,etc (Just to see photos and ...)
3.use website javadecompilers (For Photo and java code)
4.use APK Tools (For Photo and java code)
Generics:
With Java generics, you don't actually get any of the execution efficiency that you get with .NET because when you compile a generic class in Java, the compiler takes away the type parameter and substitutes Object everywhere. For instance if you have a Foo<T>
class the java compiler generates Byte Code as if it was Foo<Object>
. This means casting and also boxing/unboxing will have to be done in the "background".
I've been playing with Java/C# for a while now and, in my opinion, the major difference at the language level are, as you pointed, delegates.
$num += (6-$num%6)%6;
no need for a while loop! Modulo (%) returns the remainder of a division. IE 20%6 = 2. 6-2 = 4. 20+4 = 24. 24 is divisible by 6.
When you use the input function it automatically turns it into a string. You need to go:
vote = int(input('Enter the name of the player you wish to vote for'))
which turns the input into a int type value
You could take advantage of closure
.
var i = 0;
function generateId() {
return i++;
}
If you want to enclose it:
function generator() {
var i = 0;
return function() {
return i++;
};
}
var generateId = generator();
generateId(); //1
generateId(); //2
generator
could accept a default prefix; generateId
coud accept an optional suffix:
function generator(prefix) {
var i = 0;
return function(suffix) {
return prefix + (i++) + (suffix || '');
};
}
var generateId = generator('_');
generateId('_'); //_1_
generateId('@'); //_2@
This comes in handy if you want your id to indicate a sequence, very much like new Date().getTime()
, but easier to read.
There is no way to "discard" the time component.
DateTime.Today
is the same as:
DateTime d = DateTime.Now.Date;
If you only want to display only the date portion, simply do that - use ToString
with the format string you need.
For example, using the standard format string "D" (long date format specifier):
d.ToString("D");
Class.forName(nameString).newInstance();