Swift 4 This is just awesome
self.imgViewPreview.transform = CGAffineTransform(scaleX: 0, y: 0)
UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0, options: .curveEaseOut, animations: {
self.imgViewPreview.image = newImage
self.imgViewPreview.transform = .identity
}, completion: nil)
This answer has be updated and so the comments below no longer apply.
2018-05-18 STOP PRESS.
UPSERT support in SQLite! UPSERT syntax was added to SQLite with version 3.24.0 (pending) !
UPSERT is a special syntax addition to INSERT that causes the INSERT to behave as an UPDATE or a no-op if the INSERT would violate a uniqueness constraint. UPSERT is not standard SQL. UPSERT in SQLite follows the syntax established by PostgreSQL.
alternatively:
Another completely different way of doing this is: In my application I set my in memory rowID to be long.MaxValue when I create the row in memory. (MaxValue will never be used as an ID you will won't live long enough.... Then if rowID is not that value then it must already be in the database so needs an UPDATE if it is MaxValue then it needs an insert. This is only useful if you can track the rowIDs in your app.
What personally me fount usable for me is:
(mousedown)="callEvent()" (keyup.enter)="$event.preventDefault()
keyup.enter
prevents the event from triggering on keyup, but it still occurs for keydown, that works for me.
Yes it is possible. Just call it:
class Foo(object):
def method1(self):
pass
def method2(self, method):
return method()
foo = Foo()
foo.method2(foo.method1)
Using Collections#addAll()
String[] words = {"ace","boom","crew","dog","eon"};
List<String> arrayList = new ArrayList<>();
Collections.addAll(arrayList, words);
Yes, fork is a clone. It emerged because, you cannot push to others' copies without their permission. They make a copy of it for you (fork), where you will have write permission as well.
In the future if the actual owner or others users with a fork like your changes they can pull it back to their own repository. Alternatively you can send them a "pull-request".
Another way created by eGerman that uses PE numbers of compiled executables (does not rely on registry records or environment variables):
@echo off &setlocal
call :getPETarget "%SystemRoot%\explorer.exe"
if "%=ExitCode%" EQU "00008664" (
echo x64
) else (
if "%=ExitCode%" EQU "0000014C" (
echo x32
) else (
echo undefined
)
)
goto :eof
:getPETarget FilePath
:: ~~~~~~~~~~~~~~~~~~~~~~
:: Errorlevel
:: 0 Success
:: 1 File Not Found
:: 2 Wrong Magic Number
:: 3 Out Of Scope
:: 4 No PE File
:: ~~~~~~~~~~~~~~~~~~~~~~
:: =ExitCode
:: CPU identifier
setlocal DisableDelayedExpansion
set "File=%~1"
set Cmp="%temp%\%random%.%random%.1KB"
set Dmp="%temp%\%random%.%random%.dmp"
REM write 1024 times 'A' into a temporary file
if exist "%File%" (
>%Cmp% (
for /l %%i in (1 1 32) do <nul set /p "=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
)
setlocal EnableDelayedExpansion
) else (endlocal &cmd /c exit 0 &exit /b 1)
REM generate a HEX dump of the executable file (first 1024 Bytes)
set "X=1"
>!Dmp! (
for /f "skip=1 tokens=1,2 delims=: " %%i in ('fc /b "!File!" !Cmp!^|findstr /vbi "FC:"') do (
set /a "Y=0x%%i"
for /l %%k in (!X! 1 !Y!) do echo 41
set /a "X=Y+2"
echo %%j
)
)
del !Cmp!
REM read certain values out of the HEX dump
set "err="
<!Dmp! (
set /p "A="
set /p "B="
REM magic number has to be "MZ"
if "!A!!B!" neq "4D5A" (set "err=2") else (
REM skip next 58 bytes
for /l %%i in (3 1 60) do set /p "="
REM bytes 61-64 contain the offset to the PE header in little endian order
set /p "C="
set /p "D="
set /p "E="
set /p "F="
REM check if the beginning of the PE header is part of the HEX dump
if 0x!F!!E!!D!!C! lss 1 (set "err=3") else (
if 0x!F!!E!!D!!C! gtr 1018 (set "err=3") else (
REM skip the offset to the PE header
for /l %%i in (65 1 0x!F!!E!!D!!C!) do set /p "="
REM next 4 bytes have to contain the signature of the PE header
set /p "G="
set /p "H="
set /p "I="
set /p "J="
REM next 2 bytes contain the CPU identifier in little endian order
set /p "K="
set /p "L="
)
)
)
)
del !Dmp!
if defined err (endlocal &endlocal &cmd /c exit 0 &exit /b %err%)
REM was the signature ("PE\0\0") of the PE header found
if "%G%%H%%I%%J%"=="50450000" (
REM calculate the decimal value of the CPU identifier
set /a "CPUID=0x%L%%K%"
) else (endlocal &endlocal &cmd /c exit 0 &exit /b 4)
endlocal &endlocal &cmd /c exit %CPUID% &exit /b 0
You can use numpy's slicing, simply start:stop:step
.
>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])
This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:
>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2] # O(1), constant time
>>> b[:] = 0 # modifying the view changes original array
>>> a # original array is modified
array([0, 2, 0, 4, 0])
so if either of the above things are a problem, you can make a copy explicitly:
>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy() # explicit copy, O(n)
>>> b[:] = 0 # modifying the copy
>>> a # original is intact
array([1, 2, 3, 4, 5])
This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.
It's frowned upon because it's a platform-specific hack that has nothing to do with actually learning programming, but instead to get around a feature of the IDE/OS - the console window launched from Visual Studio closes when the program has finished execution, and so the new user doesn't get to see the output of his new program.
Bodging in System("pause") runs the Windows command-line "pause" program and waits for that to terminate before it continues execution of the program - the console window stays open so you can read the output.
A better idea would be to put a breakpoint at the end and debug it, but that again has problems.
Add the below declarations to your class:
public const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
public const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
After:
var client = new HttpClient();
And:
ServicePointManager.SecurityProtocol = Tls12;
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 /*| SecurityProtocolType.Tls */| Tls12;
Happy? :)
indices = [i for i, s in enumerate(mylist) if 'aa' in s]
I'd like to provide an abstract, high-level perspective.
I/O operations interact with the environment. The environment is not part of your program, and not under your control. The environment truly exists "concurrently" with your program. As with all things concurrent, questions about the "current state" don't make sense: There is no concept of "simultaneity" across concurrent events. Many properties of state simply don't exist concurrently.
Let me make this more precise: Suppose you want to ask, "do you have more data". You could ask this of a concurrent container, or of your I/O system. But the answer is generally unactionable, and thus meaningless. So what if the container says "yes" – by the time you try reading, it may no longer have data. Similarly, if the answer is "no", by the time you try reading, data may have arrived. The conclusion is that there simply is no property like "I have data", since you cannot act meaningfully in response to any possible answer. (The situation is slightly better with buffered input, where you might conceivably get a "yes, I have data" that constitutes some kind of guarantee, but you would still have to be able to deal with the opposite case. And with output the situation is certainly just as bad as I described: you never know if that disk or that network buffer is full.)
So we conclude that it is impossible, and in fact unreasonable, to ask an I/O system whether it will be able to perform an I/O operation. The only possible way we can interact with it (just as with a concurrent container) is to attempt the operation and check whether it succeeded or failed. At that moment where you interact with the environment, then and only then can you know whether the interaction was actually possible, and at that point you must commit to performing the interaction. (This is a "synchronisation point", if you will.)
Now we get to EOF. EOF is the response you get from an attempted I/O operation. It means that you were trying to read or write something, but when doing so you failed to read or write any data, and instead the end of the input or output was encountered. This is true for essentially all the I/O APIs, whether it be the C standard library, C++ iostreams, or other libraries. As long as the I/O operations succeed, you simply cannot know whether further, future operations will succeed. You must always first try the operation and then respond to success or failure.
In each of the examples, note carefully that we first attempt the I/O operation and then consume the result if it is valid. Note further that we always must use the result of the I/O operation, though the result takes different shapes and forms in each example.
C stdio, read from a file:
for (;;) {
size_t n = fread(buf, 1, bufsize, infile);
consume(buf, n);
if (n == 0) { break; }
}
The result we must use is n
, the number of elements that were read (which may be as little as zero).
C stdio, scanf
:
for (int a, b, c; scanf("%d %d %d", &a, &b, &c) == 3; ) {
consume(a, b, c);
}
The result we must use is the return value of scanf
, the number of elements converted.
C++, iostreams formatted extraction:
for (int n; std::cin >> n; ) {
consume(n);
}
The result we must use is std::cin
itself, which can be evaluated in a boolean context and tells us whether the stream is still in the good()
state.
C++, iostreams getline:
for (std::string line; std::getline(std::cin, line); ) {
consume(line);
}
The result we must use is again std::cin
, just as before.
POSIX, write(2)
to flush a buffer:
char const * p = buf;
ssize_t n = bufsize;
for (ssize_t k = bufsize; (k = write(fd, p, n)) > 0; p += k, n -= k) {}
if (n != 0) { /* error, failed to write complete buffer */ }
The result we use here is k
, the number of bytes written. The point here is that we can only know how many bytes were written after the write operation.
POSIX getline()
char *buffer = NULL;
size_t bufsiz = 0;
ssize_t nbytes;
while ((nbytes = getline(&buffer, &bufsiz, fp)) != -1)
{
/* Use nbytes of data in buffer */
}
free(buffer);
The result we must use is nbytes
, the number of bytes up to and including the newline (or EOF if the file did not end with a newline).
Note that the function explicitly returns -1
(and not EOF!) when an error occurs or it reaches EOF.
You may notice that we very rarely spell out the actual word "EOF". We usually detect the error condition in some other way that is more immediately interesting to us (e.g. failure to perform as much I/O as we had desired). In every example there is some API feature that could tell us explicitly that the EOF state has been encountered, but this is in fact not a terribly useful piece of information. It is much more of a detail than we often care about. What matters is whether the I/O succeeded, more-so than how it failed.
A final example that actually queries the EOF state: Suppose you have a string and want to test that it represents an integer in its entirety, with no extra bits at the end except whitespace. Using C++ iostreams, it goes like this:
std::string input = " 123 "; // example
std::istringstream iss(input);
int value;
if (iss >> value >> std::ws && iss.get() == EOF) {
consume(value);
} else {
// error, "input" is not parsable as an integer
}
We use two results here. The first is iss
, the stream object itself, to check that the formatted extraction to value
succeeded. But then, after also consuming whitespace, we perform another I/O/ operation, iss.get()
, and expect it to fail as EOF, which is the case if the entire string has already been consumed by the formatted extraction.
In the C standard library you can achieve something similar with the strto*l
functions by checking that the end pointer has reached the end of the input string.
while(!feof)
is wrong because it tests for something that is irrelevant and fails to test for something that you need to know. The result is that you are erroneously executing code that assumes that it is accessing data that was read successfully, when in fact this never happened.
vertical-align
is only supposed to work on elements that are rendered as inline
. <span>
is rendered as inline by default, but not all elements are. The paragraph block element, <p>
, is rendered as a block by default. Table render types (e.g. table-cell
) will allow you to use vertical-align as well.
Some browsers may allow you to use the vertical-align
CSS property on items such as the paragraph block, but they are not supposed to. Text denoted as a paragraph should be filled with written-language content or the mark-up is incorrect and should be using one of a number of other options instead.
I hope this helps!
You can do:
$("#submittername").text("testing");
or
$("#submittername").html("testing <b>1 2 3</b>");
In my case, I just had to do
It all then went fine. I still have no clue what happened.
The default date format depends on the language setting for the database server. You can also change it per session, like:
set language french
select cast(getdate() as varchar(50))
-->
févr 8 2013 9:45AM
I have also used a non-generic version, using the new
keyword:
public interface IMetadata
{
Type DataType { get; }
object Data { get; }
}
public interface IMetadata<TData> : IMetadata
{
new TData Data { get; }
}
Explicit interface implementation is used to allow both Data
members:
public class Metadata<TData> : IMetadata<TData>
{
public Metadata(TData data)
{
Data = data;
}
public Type DataType
{
get { return typeof(TData); }
}
object IMetadata.Data
{
get { return Data; }
}
public TData Data { get; private set; }
}
You could derive a version targeting value types:
public interface IValueTypeMetadata : IMetadata
{
}
public interface IValueTypeMetadata<TData> : IMetadata<TData>, IValueTypeMetadata where TData : struct
{
}
public class ValueTypeMetadata<TData> : Metadata<TData>, IValueTypeMetadata<TData> where TData : struct
{
public ValueTypeMetadata(TData data) : base(data)
{}
}
This can be extended to any kind of generic constraints.
I have always used
git reset --merge
I can't remember it ever failing.
Create the symlink to latest version
ln -s -f /usr/local/bin/python3.8 /usr/local/bin/python
Close and open a new terminal
and try
python --version
Perhaps add the number of days in the current month using calendar.monthrange()?
import calendar, datetime
def increment_month(when):
days = calendar.monthrange(when.year, when.month)[1]
return when + datetime.timedelta(days=days)
now = datetime.datetime.now()
print 'It is now %s' % now
print 'In a month, it will be %s' % increment_month(now)
string[] lines = File.ReadAllLines("sample.txt"); List<string> list1 = new List<string>(); List<string> list2 = new List<string>(); foreach (var line in lines) { string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); list1.Add(values[0]); list2.Add(values[1]); }
Instead of constantly generating project metadata via import->maven command, you can generate your project metadata once and the place it in your git repository along with the rest of your source code. After than, using import->git command will import a proper maven-enabled project, assuming you have maven tools installed.
Make sure to place into the source control system all files in project dir that start with '.' such as .classpath and .project along with the entire contents of the .settings directory.
Not directly. But you can use extensions such as LESS to help you achieve the same.
Got to this answer ? probably the answers above are to long ...
just type in :
echo "setenv M2_HOME $M2_HOME" | sudo tee -a /etc/launchd.conf
and restart your mac (thats it!)
restarting is annoying ? just use the command :
grep -E "^setenv" /etc/launchd.conf | xargs -t -L 1 launchctl
and restart IntelliJ IDEA
I've been using something like this. Just set up a simple HTML page with an textinput. Make sure that the textinput always has focus. When you scan a barcode with your barcode scanner you will receive the code and after that a 'enter'. Realy simple then; just capture the incoming keystrokes and when the 'enter' comes in you can use AJAX to handle your code.
This is not specific to sqlite but you can just do
SELECT * FROM ... WHERE UPPER(name) = UPPER('someone')
Thanks to this question (and answers), I discovered an easy way to get at the exact NumberFormat string for virtually any format that Excel has to offer.
Step 1: In the user interface, set a cell to the NumberFormat you want to use.
In my example, I selected the Chinese (PRC) Currency from the options contained in the "Account Numbers Format" combo box.
Step 2: Expand the Number Format dropdown and select "More Number Formats...".
Step 3: In the Number tab, in Category, click "Custom".
The "Sample" section shows the Chinese (PRC) currency formatting that I applied.
The "Type" input box contains the NumberFormat string that you can use programmatically.
So, in this example, the NumberFormat of my Chinese (PRC) Currency cell is as follows:
_ [$¥-804]* #,##0.00_ ;_ [$¥-804]* -#,##0.00_ ;_ [$¥-804]* "-"??_ ;_ @_
If you do these steps for each NumberFormat that you desire, then the world is yours.
I hope this helps.
Combining matty-j suggestion with the snippet of the question, I ended up with this code focusing on resizing the grid after the data was loaded.
The HTML:
<div ng-grid="gridOptions" class="gridStyle"></div>
The directive:
angular.module('myApp.directives', [])
.directive('resize', function ($window) {
return function (scope, element) {
var w = angular.element($window);
scope.getWindowDimensions = function () {
return { 'h': w.height(), 'w': w.width() };
};
scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
// resize Grid to optimize height
$('.gridStyle').height(newValue.h - 250);
}, true);
w.bind('resize', function () {
scope.$apply();
});
}
});
The controller:
angular.module('myApp').controller('Admin/SurveyCtrl', function ($scope, $routeParams, $location, $window, $timeout, Survey) {
// Retrieve data from the server
$scope.surveys = Survey.query(function(data) {
// Trigger resize event informing elements to resize according to the height of the window.
$timeout(function () {
angular.element($window).resize();
}, 0)
});
// Configure ng-grid.
$scope.gridOptions = {
data: 'surveys',
...
};
}
Cudos accepted answer is great. However, the Draggable module also has a "drag" event that tells you the position while your dragging. So, in addition to the 'start' and 'stop' you could add the following event within your Draggable object:
// Drag current position of dragged image.
drag: function(event, ui) {
// Show the current dragged position of image
var currentPos = $(this).position();
$("div#xpos").text("CURRENT: \nLeft: " + currentPos.left + "\nTop: " + currentPos.top);
}
First you have to check if FileZilla is running on xampp control panel Than such error can occur You have to stop the FileZilla service from Xampp control panel
A simple way :
select * from hockey_stats
where game_date >= '2012-03-11' and game_date <= '2012-05-11'
Both lines you posted are fine, but you can do it purely in integers, and it will be the most efficient:
def sum_digits(n):
s = 0
while n:
s += n % 10
n //= 10
return s
or with divmod
:
def sum_digits2(n):
s = 0
while n:
n, remainder = divmod(n, 10)
s += remainder
return s
Even faster is the version without augmented assignments:
def sum_digits3(n):
r = 0
while n:
r, n = r + n % 10, n // 10
return r
> %timeit sum_digits(n)
1000000 loops, best of 3: 574 ns per loop
> %timeit sum_digits2(n)
1000000 loops, best of 3: 716 ns per loop
> %timeit sum_digits3(n)
1000000 loops, best of 3: 479 ns per loop
> %timeit sum(map(int, str(n)))
1000000 loops, best of 3: 1.42 us per loop
> %timeit sum([int(digit) for digit in str(n)])
100000 loops, best of 3: 1.52 us per loop
> %timeit sum(int(digit) for digit in str(n))
100000 loops, best of 3: 2.04 us per loop
The Classloader API doesn't have an "enumerate" method, because class loading is an "on-demand" activity -- you usually have thousands of classes in your classpath, only a fraction of which will ever be needed (the rt.jar alone is 48MB nowadays!).
So, even if you could enumerate all classes, this would be very time- and memory-consuming.
The simple approach is to list the concerned classes in a setup file (xml or whatever suits your fancy); if you want to do this automatically, restrict yourself to one JAR or one class directory.
The easiest way to do it directly in the list is
HashSet<Object> seen=new HashSet<>();
employee.removeIf(e->!seen.add(e.getID()));
removeIf
will remove an element if it meets the specified criteriaSet.add
will return false
if it did not modify the Set
, i.e. already contains the valueOf course, it only works if the list supports removal of elements.
var wrapper = $(document.body);
strings = [
"19 51 2.108997",
"20 47 2.1089"
];
$.each(strings, function(key, value) {
var tmp = value.split(" ");
$.each([
tmp[0] + " " + tmp[1],
tmp[2]
], function(key, value) {
$("<span>" + value + "</span>").appendTo(wrapper);
});
});
There is a similar question in the Stackoverflow. You need to override EditText
in order to get access to InputConnection
object which contains deleteSurroundingText
method. It will help you to detect deletion (backspace) event. Please, take a look at a solution I provided there Android - cannot capture backspace/delete press in soft. keyboard
This is a lot simpler with .slideToggle():
jQuery('.class1 a').click( function() {
$(this).next('.class2').slideToggle();
});
EDIT: made it .next instead of .siblings
http://www.mredesign.com/demos/jquery-effects-1/
You can also add cookie's to remember where you're at...
http://c.hadcoleman.com/2008/09/jquery-slide-toggle-with-cookie/
The re-install fixed it because the installer created a new MySQL instance and the symbolic link to /usr/local/mysql now points to a data directory that does not have an existing pid.
It's worth noting that the mysql prefpane and mysql.server script use the hostname for the pid, so changing the hostname may cause issues with the this.
While the prefpane is out of date, it's a nice GUI for someone to start/stop MySQL even if the auto-start function doesn't work.
I've taken a hybrid approach where I've adapted my MySQL install script to use Launchd to auto-start MySQL, but the plist actually calls the mysql.server script. This way the prefpane can still be used to start/stop MySQL on demand, and trying to do a simple MySQL restart won't be too confusing.
Here is script that just enables this Launchd behavior on Yosemite with MySQL already installed: https://raw.githubusercontent.com/MacMiniVault/Mac-Scripts/master/mmvMySQL/YosemiteLaunchd.sh
Here is the script that handles the entire automated installation of MySQL: https://raw.githubusercontent.com/MacMiniVault/Mac-Scripts/master/mmvMySQL/mmvmysql.sh
You can get a list of invalid characters from Path.GetInvalidPathChars
and GetInvalidFileNameChars
.
UPD: See Steve Cooper's suggestion on how to use these in a regular expression.
UPD2: Note that according to the Remarks section in MSDN "The array returned from this method is not guaranteed to contain the complete set of characters that are invalid in file and directory names." The answer provided by sixlettervaliables goes into more details.
Actually, you have it down pat, there's nothing more you need to know :-)
I would just add the following bits:
&
takes a variable and gives you the address, *
takes an address and gives you the variable (or contents).char **p
means that p
is a pointer to a pointer to a char
.As to things working differently, not really:
\0
) character.The Python approach to "main" is almost unique to the language(*).
The semantics are a bit subtle. The __name__
identifier is bound to the name of any module as it's being imported. However, when a file is being executed then __name__
is set to "__main__"
(the literal string: __main__
).
This is almost always used to separate the portion of code which should be executed from the portions of code which define functionality. So Python code often contains a line like:
#!/usr/bin/env python
from __future__ import print_function
import this, that, other, stuff
class SomeObject(object):
pass
def some_function(*args,**kwargs):
pass
if __name__ == '__main__':
print("This only executes when %s is executed rather than imported" % __file__)
Using this convention one can have a file define classes and functions for use in other programs, and also include code to evaluate only when the file is called as a standalone script.
It's important to understand that all of the code above the if __name__
line is being executed, evaluated, in both cases. It's evaluated by the interpreter when the file is imported or when it's executed. If you put a print
statement before the if __name__
line then it will print output every time any other code attempts to import that as a module. (Of course, this would be anti-social. Don't do that).
I, personally, like these semantics. It encourages programmers to separate functionality (definitions) from function (execution) and encourages re-use.
Ideally almost every Python module can do something useful if called from the command line. In many cases this is used for managing unit tests. If a particular file defines functionality which is only useful in the context of other components of a system then one can still use __name__ == "__main__"
to isolate a block of code which calls a suite of unit tests that apply to this module.
(If you're not going to have any such functionality nor unit tests than it's best to ensure that the file mode is NOT executable).
Summary: if __name__ == '__main__':
has two primary use cases:
It's fairly common to def main(*args)
and have if __name__ == '__main__':
simply call main(*sys.argv[1:])
if you want to define main in a manner that's similar to some other programming languages. If your .py file is primarily intended to be used as a module in other code then you might def test_module()
and calling test_module()
in your if __name__ == '__main__:'
suite.
if __file__ == $0
).Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000
or Access-Control-Allow-Origin: *
on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true
on the POST response as well.
Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept
to match the requested header.
Below procedure worked for me to resolve all the escaping issues and have the procedure more a generic utility.
CREATE PROCEDURE `export_table`(
IN tab_name varchar(50),
IN select_columns varchar(1000),
IN filename varchar(100),
IN where_clause varchar(1000),
IN header_row varchar(2000))
BEGIN
INSERT INTO impl_log_activities(TABLE_NAME, LOG_MESSAGE,CREATED_TS) values(tab_name, where_clause,sysdate());
COMMIT;
SELECT CONCAT( "SELECT ", header_row,
" UNION ALL ",
"SELECT ", select_columns,
" INTO OUTFILE ", "'",filename,"'"
" FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '""' ",
" LINES TERMINATED BY '\n'"
" FROM ", tab_name, " ",
(case when where_clause is null then "" else where_clause end)
) INTO @SQL_QUERY;
INSERT INTO impl_log_activities(TABLE_NAME, LOG_MESSAGE,CREATED_TS) values(tab_name, @SQL_QUERY, sysdate());
COMMIT;
PREPARE stmt FROM @SQL_QUERY;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
Deleting nodes from XML
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']");
for (int i = nodes.Count - 1; i >= 0; i--)
{
nodes[i].ParentNode.RemoveChild(nodes[i]);
}
doc.Save(path);
Adding attribute to Nodes in XML
XmlDocument originalXml = new XmlDocument();
originalXml.Load(path);
XmlNode menu = originalXml.SelectSingleNode("//Settings");
XmlNode newSub = originalXml.CreateNode(XmlNodeType.Element, "Setting", null);
XmlAttribute xa = originalXml.CreateAttribute("name");
xa.Value = "qwerty";
XmlAttribute xb = originalXml.CreateAttribute("value");
xb.Value = "555";
newSub.Attributes.Append(xa);
newSub.Attributes.Append(xb);
menu.AppendChild(newSub);
originalXml.Save(path);
ggplot2
and scales
packages can do that:
y <- c(12, 20)/100
x <- c(1, 2)
library(ggplot2)
library(scales)
myplot <- qplot(as.factor(x), y, geom="bar")
myplot + scale_y_continuous(labels=percent)
It seems like the stat()
option has been taken off, causing the error message. Try this:
library(scales)
myplot <- ggplot(mtcars, aes(factor(cyl))) +
geom_bar(aes(y = (..count..)/sum(..count..))) +
scale_y_continuous(labels=percent)
myplot
public void CreateCSVFile(DataTable dt, string strFilePath,string separator)
{
#region Export Grid to CSV
// Create the CSV file to which grid data will be exported.
StreamWriter sw = new StreamWriter(strFilePath, false);
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(separator);
}
}
sw.Write(sw.NewLine);
// Now write all the rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < iColCount - 1)
{
sw.Write(separator);
}
}
sw.Write(sw.NewLine);
}
sw.Close();
#endregion
}
With so many great answers, I thought I would toss one more into the mix. This one, unlike the others, would permit you to cycle through any number of messages with ease:
var index = 0,
messg = [
"PUSH ME",
"DON'T PUSH ME",
"I'M SO CONFUSED!"
];
$(".pushme").on("click", function() {
$(this).text(function(index, text){
index = $.inArray(text, messg);
return messg[++index % messg.length];
});
}??????????????????????????????????????????????);?
try
raw_input('Enter your input:') # If you use Python 2
input('Enter your input:') # If you use Python 3
and if you want to have a numeric value just convert it:
try:
mode=int(raw_input('Input:'))
except ValueError:
print "Not a number"
To convert seconds time stamp to millisecond time stamp. You could use the TimeUnit API and neat like this.
long milliSecondTimeStamp = MILLISECONDS.convert(secondsTimeStamp, SECONDS)
I guess the answer you need is referenced here Python sets are not json serializable
Not all datatypes can be json serialized . I guess pickle module will serve your purpose.
For Mac only:
echo "Hello World" | pbcopy
pbpaste
These are located /usr/bin/pbcopy
and /usr/bin/pbpaste
.
try like this (no pun intended btw)
script {
try {
sh 'do your stuff'
} catch (Exception e) {
echo 'Exception occurred: ' + e.toString()
sh 'Handle the exception!'
}
}
The key is to put try...catch in a script block in declarative pipeline syntax. Then it will work. This might be useful if you want to say continue pipeline execution despite failure (eg: test failed, still you need reports..)
Solution with ActiveRoute (if you want pass object by route - use JSON.stringfy/JSON.parse):
Prepare object before sending:
export class AdminUserListComponent {
users : User[];
constructor( private router : Router) { }
modifyUser(i) {
let navigationExtras: NavigationExtras = {
queryParams: {
"user": JSON.stringify(this.users[i])
}
};
this.router.navigate(["admin/user/edit"], navigationExtras);
}
}
Receive your object in destination component:
export class AdminUserEditComponent {
userWithRole: UserWithRole;
constructor( private route: ActivatedRoute) {}
ngOnInit(): void {
super.ngOnInit();
this.route.queryParams.subscribe(params => {
this.userWithRole.user = JSON.parse(params["user"]);
});
}
}
set @r = 0;
select
case when mod(c,2)=0 then round(sum(lat_N),4)
else round(sum(lat_N)/2,4)
end as Med
from
(select lat_N, @r := @r+1, @r as id from station order by lat_N) A
cross join
(select (count(1)+1)/2 as c from station) B
where id >= floor(c) and id <=ceil(c)
Pre-ES6
Always 2 bytes per character. UTF-16 is not allowed because the spec says "values must be 16-bit unsigned integers". Since UTF-16 strings can use 3 or 4 byte characters, it would violate 2 byte requirement. Crucially, while UTF-16 cannot be fully supported, the standard does require that the two byte characters used are valid UTF-16 characters. In other words, Pre-ES6 JavaScript strings support a subset of UTF-16 characters.
ES6 and later
2 bytes per character, or 5 or more bytes per character. The additional sizes come into play because ES6 (ECMAScript 6) adds support for Unicode code point escapes. Using a unicode escape looks like this: \u{1D306}
Practical notes
This doesn't relate to the internal implemention of a particular engine. For example, some engines use data structures and libraries with full UTF-16 support, but what they provide externally doesn't have to be full UTF-16 support. Also an engine may provide external UTF-16 support as well but is not mandated to do so.
For ES6, practically speaking characters will never be more than 5 bytes long (2 bytes for the escape point + 3 bytes for the Unicode code point) because the latest version of Unicode only has 136,755 possible characters, which fits easily into 3 bytes. However this is technically not limited by the standard so in principal a single character could use say, 4 bytes for the code point and 6 bytes total.
Most of the code examples here for calculating byte size don't seem to take into account ES6 Unicode code point escapes, so the results could be incorrect in some cases.
You can still do this in top. While top is running, press '1' on your keyboard, it will then show CPU usage per core.
Limit the processes shown by having that specific process run under a specific user account and use Type 'u' to limit to that user
This happened to me after adding a new page to an asp.net project.
What I did was exclude the page, get it to build again successfully.
Then I added back the page with all the code commented out. Success.
Then I uncommented the code bit by bit and then it all worked.
As I understand , all of previous answers , does not make an Array output, In my case : I have a model with parent-children structure (simplified code here):
public function parent(){
return $this->belongsTo('App\Models\Accounting\accounting_coding', 'parent_id');
}
public function children()
{
return $this->hasMany('App\Models\Accounting\accounting_coding', 'parent_id');
}
and if you want to have all of children IDs as an Array , This approach is fine and working for me :
public function allChildren()
{
$allChildren = [];
if ($this->has_branch) {
foreach ($this->children as $child) {
$subChildren = $child->allChildren();
if (count($subChildren) == 1) {
$allChildren [] = $subChildren[0];
} else if (count($subChildren) > 1) {
$allChildren += $subChildren;
}
}
}
$allChildren [] = $this->id;//adds self Id to children Id list
return $allChildren;
}
the allChildren() returns , all of childrens as a simple Array .
This is how I come up with the IP
func ReadUserIP(r *http.Request) string {
IPAddress := r.Header.Get("X-Real-Ip")
if IPAddress == "" {
IPAddress = r.Header.Get("X-Forwarded-For")
}
if IPAddress == "" {
IPAddress = r.RemoteAddr
}
return IPAddress
}
X-Real-Ip - fetches first true IP (if the requests sits behind multiple NAT sources/load balancer)
X-Forwarded-For - if for some reason X-Real-Ip is blank and does not return response, get from X-Forwarded-For
Be aware, that your code is quite noisy. I know the thread is old, but a lot of people will read it anyway. You could do the same thing using the guava library with:
if ("POST".equalsIgnoreCase(request.getMethod())) {
test = CharStreams.toString(request.getReader());
}
You now can do this with Flexbox justify-content: flex-end
now:
div {_x000D_
display: flex;_x000D_
justify-content: flex-end;_x000D_
align-items: flex-end;_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
border: solid 1px red;_x000D_
}_x000D_
_x000D_
<div>_x000D_
Something to align_x000D_
</div>
_x000D_
Consult your Caniuse to see if Flexbox is right for you.
I would use submodules (as Pat Notz) or two distinct repositories. If you modify your binary files too often, then I would try to minimize the impact of the huge repository cleaning the history:
I had a very similar problem several months ago: ~21 GB of MP3 files, unclassified (bad names, bad id3's, don't know if I like that MP3 file or not...), and replicated on three computers.
I used an external hard disk drive with the main Git repository, and I cloned it into each computer. Then, I started to classify them in the habitual way (pushing, pulling, merging... deleting and renaming many times).
At the end, I had only ~6 GB of MP3 files and ~83 GB in the .git directory. I used git-write-tree
and git-commit-tree
to create a new commit, without commit ancestors, and started a new branch pointing to that commit. The "git log" for that branch only showed one commit.
Then, I deleted the old branch, kept only the new branch, deleted the ref-logs, and run "git prune": after that, my .git folders weighted only ~6 GB...
You could "purge" the huge repository from time to time in the same way: Your "git clone"'s will be faster.
You can use ngModel
like
<input type="checkbox" [ngModel]="checkboxValue" (ngModelChange)="addProp($event)" data-md-icheck/>
To update the checkbox state by updating the property checkboxValue
in your code and when the checkbox is changed by the user addProp()
is called.
Taking some answers one step further - if you do the following you can check if any element within the radio group has been checked:
if ($('input[name="yourRadioNames"]:checked').val()){
(checked) or if (!$('input[name="yourRadioNames"]:checked').val()){
(not checked)
I like Kango_V's answer, but I think it's too complex. I think this is simpler - maybe too simple. If inclined, you could replace String with a Generic marker, and make it work for any Key type.
public static <E> Map<String, E> convertListToMap(Collection<E> sourceList, ListToMapConverterInterface<E> converterInterface) {
Map<String, E> newMap = new HashMap<String, E>();
for( E item : sourceList ) {
newMap.put( converterInterface.getKeyForItem( item ), item );
}
return newMap;
}
public interface ListToMapConverterInterface<E> {
public String getKeyForItem(E item);
}
Used like this:
Map<String, PricingPlanAttribute> pricingPlanAttributeMap = convertListToMap( pricingPlanAttributeList,
new ListToMapConverterInterface<PricingPlanAttribute>() {
@Override
public String getKeyForItem(PricingPlanAttribute item) {
return item.getFullName();
}
} );
If all else fails, you can always submit a query, limiting the return rows to none:
select * from MYTABLENAME limit 0
At least with Miniconda (I assume it's the same for Anaconda), within the environment folder, the packages are installed in a folder called \conda-meta.
i.e.
C:\Users\username\Miniconda3\envs\environmentname\conda-meta
If you install on the base environment, the location is:
C:\Users\username\Miniconda3\pkgs
In most contexts where double
values are used, calculations will have a certain amount of uncertainty. The difference between 1.33333333333333300 and 1.33333333333333399 may be less than the amount of uncertainty that exists in the calculations. Displaying the value of "2/3 + 2/3" as "1.33333333333333" is apt to be more meaningful than displaying it as "1.33333333333333319", since the latter display implies a level of precision that doesn't really exist.
In the debugger, however, it is important to uniquely indicate the value held by a variable, including essentially-meaningless bits of precision. It would be very confusing if a debugger displayed two variables as holding the value "1.333333333333333" when one of them actually held 1.33333333333333319 and the other held 1.33333333333333294 (meaning that, while they looked the same, they weren't equal). The extra precision shown by the debugger isn't apt to represent a numerically-correct calculation result, but indicates how the code will interpret the values held by the variables.
You can use the onkeydown Property of the TextBox for limiting its value to numbers only.
<asp:TextBox ID="TextBox1" runat="server" onkeydown = "return (!(event.keyCode>=65) && event.keyCode!=32);"></asp:TextBox>
!(keyCode>=65) check is for excludng Alphabets.
keyCode!=32 check is for excluding Space character inbetween the numbers.
If you want to exclude Symbols also from entering into the textbox, then include the below condition also in the 'onkeydown' property.
!(event.shiftKey && (event.keyCode >= 48 && event.keyCode <= 57))
Thus the TextBox will finally become
<asp:TextBox ID="TextBox1" runat="server" onkeydown = "return (!(event.keyCode>=65) && event.keyCode!=32 && !(event.shiftKey && (event.keyCode >= 48 && event.keyCode <= 57)));"></asp:TextBox>
Explanation:
KeyCode for 'a' is '65' and 'z' is '90'.
KeyCodes from '90' to '222' which are other symbols are also not needed.
KeyCode for 'Space' Key is '32' which is also not needed.
Then a combination of 'Shift' key and 'Number' keys (which denotes Symbols) also not needed. KeyCode for '0' is '48' and '9' is '57'.
Hence all these are included in the TextBox declaration itself which produces the desired result.
Try and see.
def recursive_copy_files(source_path, destination_path, override=False):
"""
Recursive copies files from source to destination directory.
:param source_path: source directory
:param destination_path: destination directory
:param override if True all files will be overridden otherwise skip if file exist
:return: count of copied files
"""
files_count = 0
if not os.path.exists(destination_path):
os.mkdir(destination_path)
items = glob.glob(source_path + '/*')
for item in items:
if os.path.isdir(item):
path = os.path.join(destination_path, item.split('/')[-1])
files_count += recursive_copy_files(source_path=item, destination_path=path, override=override)
else:
file = os.path.join(destination_path, item.split('/')[-1])
if not os.path.exists(file) or override:
shutil.copyfile(item, file)
files_count += 1
return files_count
To kill process on a specific port, you can try this
npx kill-port [port-number]
char[] characters;
...
string s = new string(characters);
In .NET 4.0 you can use the Take
method:
string.Concat(myString.Take(maxLength));
Not tested for efficiency!
In case you want to match multiple words to your magic word, you can pass the words to match as a tuple:
>>> magicWord = 'zzzTest'
>>> magicWord.startswith(('zzz', 'yyy', 'rrr'))
True
startswith
takes a string or a tuple of strings.
<create-report-card-form [currentReportCardCount]="providerData.reportCards.length" ...
^^^^^^^^^^^^^^^^^^^^^^^^
In your HomeComponent template, you are trying to bind to an input on the CreateReportCardForm component that doesn't exist.
In CreateReportCardForm, these are your only three inputs:
@Input() public reportCardDataSourcesItems: SelectItem[];
@Input() public reportCardYearItems: SelectItem[];
@Input() errorMessages: Message[];
Add one for currentReportCardCount and you should be good to go.
i think that special characters are # and @ only... query will list both.
DECLARE @str VARCHAR(50)
SET @str = '[azAB09ram#reddy@wer45' + CHAR(5) + 'a~b$'
SELECT DISTINCT poschar
FROM MASTER..spt_values S
CROSS APPLY (SELECT SUBSTRING(@str,NUMBER,1) AS poschar) t
WHERE NUMBER > 0
AND NUMBER <= LEN(@str)
AND NOT (ASCII(t.poschar) BETWEEN 65 AND 90
OR ASCII(t.poschar) BETWEEN 97 AND 122
OR ASCII(t.poschar) BETWEEN 48 AND 57)
Try this sed
version:
ls -l | sed '2 ! d'
It says "delete all the lines that aren't the second one".
Environment.NewLine
will return the newline character for the corresponding platform in which your code is running
you will find this very useful when you deploy your code in linux on the Mono framework
Can you use date as a factor?
Yes, but you probably shouldn't.
...or should you use
as.Date
on a date column?
Yes.
Which leads us to this:
library(scales)
df$Month <- as.Date(df$Month)
ggplot(df, aes(x = Month, y = AvgVisits)) +
geom_bar(stat = "identity") +
theme_bw() +
labs(x = "Month", y = "Average Visits per User") +
scale_x_date(labels = date_format("%m-%Y"))
in which I've added stat = "identity"
to your geom_bar
call.
In addition, the message about the binwidth wasn't an error. An error will actually say "Error" in it, and similarly a warning will always say "Warning" in it. Otherwise it's just a message.
The fastest way is to do a*a
or a**2
or np.square(a)
whereas np.power(a, 2)
showed to be considerably slower.
np.power()
allows you to use different exponents for each element if instead of 2
you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2
or a*a
, which become important in cases where you have small tolerances.
I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:
In [29]: a = np.random.random((1000, 1000))
In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop
In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop
In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop
I would recommend to use date->diff function, as in example below:
$dStart = new DateTime('2012-07-26');
$dEnd = new DateTime('2012-08-26');
$dDiff = $dStart->diff($dEnd);
echo $dDiff->format('%r%a'); // use for point out relation: smaller/greater
Try this
function checkForm($fields){
foreach($fields as $field){
if($field['required'] && strlen($_POST[$field['name']]) <= 0){
$field['value'] = "Some error";
}
}
return $field;
}
One more to thing to think about when daemonizing in python:
If your are using python logging and you want to continue using it after daemonizing, make sure to call close()
on the handlers (particularly the file handlers).
If you don't do this the handler can still think it has files open, and your messages will simply disappear - in other words make sure the logger knows its files are closed!
This assumes when you daemonise you are closing ALL the open file descriptors indiscriminatingly - instead you could try closing all but the log files (but it's usually simpler to close all then reopen the ones you want).
For me looks better like this:
Some text, Some text, Some text
br {_x000D_
display: inline;_x000D_
content: '';_x000D_
}_x000D_
_x000D_
br:after {_x000D_
content: ', ';_x000D_
display: inline-block;_x000D_
}
_x000D_
<div style="display:block">_x000D_
<span>Some text</span>_x000D_
<br>_x000D_
<span>Some text</span>_x000D_
<br>_x000D_
<span>Some text</span>_x000D_
</div>
_x000D_
It's probably not anywhere approaching a best practice, but I usually call a SIZE
on the collection to load the children in the same transaction, like you have suggested. It's clean, immune to any changes in the structure of the child elements, and yields SQL with low overhead.
I worked it around through this "hiding" div ...
<div STYLE="position:absolute;display:none;"><INPUT type='file' id='file1' name='files[]'></div>
AArch64 is the 64-bit state introduced in the Armv8-A architecture (https://en.wikipedia.org/wiki/ARM_architecture#ARMv8-A). The 32-bit state which is backwards compatible with Armv7-A and previous 32-bit Arm architectures is referred to as AArch32. Therefore the GNU triplet for the 64-bit ISA is aarch64. The Linux kernel community chose to call their port of the kernel to this architecture arm64 rather than aarch64, so that's where some of the arm64 usage comes from.
As far as I know the Apple backend for aarch64 was called arm64 whereas the LLVM community-developed backend was called aarch64 (as it is the canonical name for the 64-bit ISA) and later the two were merged and the backend now is called aarch64.
So AArch64 and ARM64 refer to the same thing.
Using c++11/c++0x compile flags, you can
auto it = max_element(std::begin(cloud), std::end(cloud)); // c++11
Otherwise, write your own:
template <typename T, size_t N> const T* mybegin(const T (&a)[N]) { return a; }
template <typename T, size_t N> const T* myend (const T (&a)[N]) { return a+N; }
See it live at http://ideone.com/aDkhW:
#include <iostream>
#include <algorithm>
template <typename T, size_t N> const T* mybegin(const T (&a)[N]) { return a; }
template <typename T, size_t N> const T* myend (const T (&a)[N]) { return a+N; }
int main()
{
const int cloud[] = { 1,2,3,4,-7,999,5,6 };
std::cout << *std::max_element(mybegin(cloud), myend(cloud)) << '\n';
std::cout << *std::min_element(mybegin(cloud), myend(cloud)) << '\n';
}
Oh, and use std::minmax_element(...)
if you need both at once :/
You need to specify the format:
DateTime date = DateTime.ParseExact(
"Tue, 1 Jan 2008 00:00:00 UTC",
"ddd, d MMM yyyy HH:mm:ss UTC",
CultureInfo.InvariantCulture);
A .war
file is a Web Application Archive which runs inside an application server while a .jar
is Java Application Archive that runs a desktop application on a user's machine.
A nice Java 7+ answer from Benoit Blanchon can be found here:
With Java 7, you can use
Files.createDirectories()
.For instance:
Files.createDirectories(Paths.get("/path/to/directory"));
I made one that you can access with any textarea element you like:
function textControl (element, event)
{
if(event.keyCode==9 || event.which==9)
{
event.preventDefault();
var s = element.selectionStart;
element.value = element.value.substring(0,element.selectionStart) + "\t" + element.value.substring(element.selectionEnd);
element.selectionEnd = s+1;
}
}
And the element would look like this:
<textarea onkeydown="textControl(this,event)"></textarea>
You can also use an express framework
app.get("/:id",function(req,res)
{
var id = req.params.id;
res.render("home.ejs",{identity : id});
});
Express file, which receives a JS variable identity from node.js
<a href = "/any_route/<%=identity%>
includes identity JS variable into your href
without a trouble enter
Change encoding in notepad++ UTF-8 with BOM. That is how it worked for me
You can do this by providing in class numbers
:
By the way, there is a strong convention that Java class names are uppercased.
Case 1 (simple getter):
public class Numbers {
private List<Integer> list;
public List<Integer> getList() { return list; }
...
}
Case 2 (non-modifiable wrapper):
public class Numbers {
private List<Integer> list;
public List<Integer> getList() { return Collections.unmodifiableList( list ); }
...
}
Case 3 (specific methods):
public class Numbers {
private List<Integer> list;
public void addToList( int i ) { list.add(i); }
public int getValueAtIndex( int index ) { return list.get( index ); }
...
}
I was getting this error in a local Docker environment. I solved it by simply restarting Docker.
If the favicon is a png type image, it'll not work in older versions of Chrome. However it'll work just fine in FireFox. Also, don't forget to clear your browser cache while working on such things. Many a times, code is just fine, but cache is the real culprit.
Won't running this in the background do it?
#!/bin/sh
while [ 1 ]; do
echo "Hell yeah!" &
sleep 15
done
This is about as efficient as it gets. The important part only gets executed every 15 seconds and the script sleeps the rest of the time (thus not wasting cycles).
RedirectToAction("actionName", "controllerName");
It has other overloads as well, please check up!
Also, If you are new and you are not using T4MVC, then I would recommend you to use it!
It gives you intellisence for actions,Controllers,views etc (no more magic strings)
Try
document.location.host
or
document.location.hostname
One of the possible implementations:
File file = new File("userdata.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
String usr = document.getElementsByTagName("user").item(0).getTextContent();
String pwd = document.getElementsByTagName("password").item(0).getTextContent();
when used with the XML content:
<credentials>
<user>testusr</user>
<password>testpwd</password>
</credentials>
results in "testusr"
and "testpwd"
getting assigned to the usr
and pwd
references above.
i use as following for over come this matter
edittext_style.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:thickness="0dp"
android:shape="rectangle">
<stroke android:width="1dp"
android:color="#c8c8c8"/>
<corners android:radius="0dp" />
And applied as bellow
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/editTextName"
android:background="@drawable/edit_text_style"/>
try like this..
List last updated on December 1, 2020:
As of November 30, 2020, AWS now has EC2 Mac instances:
We previously used and had good experiences with:
Here are some other sites that I am aware of:
When we were with MacStadium, we loved them. We had great connectivity/uptime. When I've needed hands-on support to plug in a Time Machine backup, they've been great. They performed a seamless upgrade to better hardware for us over one weekend (when we could afford a bit of downtime), and that went off without a hitch. Highly recommended. (Not affiliated - just happy).
In April of 2020, we stopped using MacStadium, simply because we no longer needed a Mac server. If I need another Mac host, I would be happy to go back to them.
java.util.UUID
: toString() method
Instead of using a %, the units vh set it to a percent of the viewport (browser window) size.
I was able to set a modal with an image and text beneath to be responsive to the browser window size using vh.
If you just want the content to scroll, you could leave out the part that limits the size of the modal body.
/*When the modal fills the screen it has an even 2.5% on top and bottom*/
/*Centers the modal*/
.modal-dialog {
margin: 2.5vh auto;
}
/*Sets the maximum height of the entire modal to 95% of the screen height*/
.modal-content {
max-height: 95vh;
overflow: scroll;
}
/*Sets the maximum height of the modal body to 90% of the screen height*/
.modal-body {
max-height: 90vh;
}
/*Sets the maximum height of the modal image to 69% of the screen height*/
.modal-body img {
max-height: 69vh;
}
OP here (I am answering this question after two years, the post made by Daniel Cerecedo was not bad at a time, but the web services are developing very fast)
After three years of full-time software development (with focus also on software architecture, project management and microservice architecture) I definitely choose the second way (but with one general endpoint) as the best one.
If you have a special endpoint for images, it gives you much more power over handling those images.
We have the same REST API (Node.js) for both - mobile apps (iOS/android) and frontend (using React). This is 2017, therefore you don't want to store images locally, you want to upload them to some cloud storage (Google cloud, s3, cloudinary, ...), therefore you want some general handling over them.
Our typical flow is, that as soon as you select an image, it starts uploading on background (usually POST on /images endpoint), returning you the ID after uploading. This is really user-friendly, because user choose an image and then typically proceed with some other fields (i.e. address, name, ...), therefore when he hits "send" button, the image is usually already uploaded. He does not wait and watching the screen saying "uploading...".
The same goes for getting images. Especially thanks to mobile phones and limited mobile data, you don't want to send original images, you want to send resized images, so they do not take that much bandwidth (and to make your mobile apps faster, you often don't want to resize it at all, you want the image that fits perfectly into your view). For this reason, good apps are using something like cloudinary (or we do have our own image server for resizing).
Also, if the data are not private, then you send back to app/frontend just URL and it downloads it from cloud storage directly, which is huge saving of bandwidth and processing time for your server. In our bigger apps there are a lot of terabytes downloaded every month, you don't want to handle that directly on each of your REST API server, which is focused on CRUD operation. You want to handle that at one place (our Imageserver, which have caching etc.) or let cloud services handle all of it.
Cons : The only "cons" which you should think of is "not assigned images". User select images and continue with filling other fields, but then he says "nah" and turn off the app or tab, but meanwhile you successfully uploaded the image. This means you have uploaded an image which is not assigned anywhere.
There are several ways of handling this. The most easiest one is "I don't care", which is a relevant one, if this is not happening very often or you even have desire to store every image user send you (for any reason) and you don't want any deletion.
Another one is easy too - you have CRON and i.e. every week and you delete all unassigned images older than one week.
Be careful to check if
display_errors
or
error_reporting
is active (not a comment) somewhere else in the ini file.
My development server refused to display errors after upgrade to Kubuntu 16.04 - I had checked php.ini numerous times ... turned out that there was a diplay_errors = off; about 100 lines below my
display_errors = on;
So remember the last one counts!
If you are looking for a way to import all your images from the image
// Import all images in image folder
function importAll(r) {
let images = {};
r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
return images;
}
const images = importAll(require.context('../images', false, /\.(gif|jpe?g|svg)$/));
Then:
<img src={images['image-01.jpg']}/>
You can find the original thread here: Dynamically import images from a directory using webpack
Answer : I found this and wants to share it with you.
Sub Copier4()
Dim x As Integer
For x = 1 To ActiveWorkbook.Sheets.Count
'Loop through each of the sheets in the workbook
'by using x as the sheet index number.
ActiveWorkbook.Sheets(x).Copy _
After:=ActiveWorkbook.Sheets(ActiveWorkbook.Sheets.Count)
'Puts all copies after the last existing sheet.
Next
End Sub
But the question, can we use it with following code to rename the sheets, if yes, how can we do so?
Sub CreateSheetsFromAList()
Dim MyCell As Range, MyRange As Range
Set MyRange = Sheets("Summary").Range("A10")
Set MyRange = Range(MyRange, MyRange.End(xlDown))
For Each MyCell In MyRange
Sheets.Add After:=Sheets(Sheets.Count) 'creates a new worksheet
Sheets(Sheets.Count).Name = MyCell.Value ' renames the new worksheet
Next MyCell
End Sub
Beware: leaving calls to console in your production code will cause your site to break in Internet Explorer. Never keep it unwrapped. See: https://web.archive.org/web/20150908041020/blog.patspam.com/2009/the-curse-of-consolelog
If you want to clean your database named "example_db":
1) Login to another db(for example 'postgres'):
psql postgres
2) Remove your database:
DROP DATABASE example_db;
3) Recreate your database:
CREATE DATABASE example_db;
2k20 update: use Josh's solution with URLSearchParams.toString().
Old answer:
Without jQuery
var params = {
parameter1: 'value_1',
parameter2: 'value 2',
parameter3: 'value&3'
};
var esc = encodeURIComponent;
var query = Object.keys(params)
.map(k => esc(k) + '=' + esc(params[k]))
.join('&');
For browsers that don't support arrow function syntax which requires ES5, change the .map...
line to
.map(function(k) {return esc(k) + '=' + esc(params[k]);})
Are you tied to this library? Google Gson is very popular. I have myself not used it with Generics but their front page says Gson considers support for Generics very important.
You can use a function that accepts a array and finds the max value in it. i made it generic so it could also accept other data types
public static <T extends Comparable<T>> T findMax(T[] array){
T max = array[0];
for(T data: array){
if(data.compareTo(max)>0)
max =data;
}
return max;
}
As @HarlemSquirrel posted, it is the best and I think the correct solution.
But, to answer the OP specific problem, it should be something like the following command, as he doesn't want to recreate ALL services in the docker-compose.yml
file, but only the nginx
one:
docker-compose up -d --force-recreate --no-deps --build nginx
Options description:
Options:
-d Detached mode: Run containers in the background,
print new container names. Incompatible with
--abort-on-container-exit.
--force-recreate Recreate containers even if their configuration
and image haven't changed.
--build Build images before starting containers.
--no-deps Don't start linked services.
Although the tricky solution @tbaxter120 advised is good but I use this function and work like a charm, pString is a delimited string and pDelimiter is a delimiter character:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[DelimitedSplit]
--===== Define I/O parameters
(@pString NVARCHAR(MAX), @pDelimiter CHAR(1))
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 0 up to 10,000...
-- enough to cover VARCHAR(8000)
WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
-- for both a performance gain and prevention of accidental "overruns"
SELECT TOP (ISNULL(DATALENGTH(@pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
SELECT 1 UNION ALL -- does away with 0 base CTE, and the OR condition in one go!
SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(@pString,t.N,1) = @pDelimiter
),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
SELECT s.N1,
---ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000)
ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,50000)
FROM cteStart s
)
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
Item = SUBSTRING(@pString, l.N1, l.L1)
FROM cteLen l
;
Then for example you can call it in where clause as below:
WHERE [fieldname] IN (SELECT LTRIM(RTRIM(Item)) FROM [dbo].[DelimitedSplit]('2,5,11', ','))
Hope this help.
I have a minor improvement on Ross Drew's answer.
For a small array, a simple loop is faster than the System.arraycopy approach, because of the overhead associated with setting up System.arraycopy. Therefore, it's better to fill the first few bytes of the array using a simple loop, and only move to System.arraycopy when the filled array has a certain size.
The optimal size of the initial loop will be JVM specific and system specific of course.
private static final int SMALL = 16;
public static void arrayFill(byte[] array, byte value) {
int len = array.length;
int lenB = len < SMALL ? len : SMALL;
for (int i = 0; i < lenB; i++) {
array[i] = value;
}
for (int i = SMALL; i < len; i += i) {
System.arraycopy(array, 0, array, i, len < i + i ? len - i : i);
}
}
You are just supposed to provide the predict
method with the same 2D array, but with one value that you want to process (or more). In short, you can just replace
[0.58,0.76]
With
[[0.58,0.76]]
And it should work.
EDIT: This answer became popular so I thought I'd add a little more explanation about ML. The short version: we can only use predict
on data that is of the same dimensionality as the training data (X
) was.
In the example in question, we give the computer a bunch of rows in X
(with 2 values each) and we show it the correct responses in y
. When we want to predict
using new values, our program expects the same - a bunch of rows. Even if we want to do it to just one row (with two values), that row has to be part of another array.
The selected answer makes it sound slightly more complex than it is, the following is what you need (install npm first on your system).
npm install -g elasticdump
elasticdump --input=http://mysrc.com:9200/my_index --output=http://mydest.com:9200/my_index --type=mapping
elasticdump --input=http://mysrc.com:9200/my_index --output=http://mydest.com:9200/my_index --type=data
You can skip the first elasticdump command for subsequent copies if the mappings remain constant.
I have just done a migration from AWS to Qbox.io with the above without any problems.
More details over at:
https://www.npmjs.com/package/elasticdump
Help page (as of Feb 2016) included for completeness:
elasticdump: Import and export tools for elasticsearch
Usage: elasticdump --input SOURCE --output DESTINATION [OPTIONS]
--input
Source location (required)
--input-index
Source index and type
(default: all, example: index/type)
--output
Destination location (required)
--output-index
Destination index and type
(default: all, example: index/type)
--limit
How many objects to move in bulk per operation
limit is approximate for file streams
(default: 100)
--debug
Display the elasticsearch commands being used
(default: false)
--type
What are we exporting?
(default: data, options: [data, mapping])
--delete
Delete documents one-by-one from the input as they are
moved. Will not delete the source index
(default: false)
--searchBody
Preform a partial extract based on search results
(when ES is the input,
(default: '{"query": { "match_all": {} } }'))
--sourceOnly
Output only the json contained within the document _source
Normal: {"_index":"","_type":"","_id":"", "_source":{SOURCE}}
sourceOnly: {SOURCE}
(default: false)
--all
Load/store documents from ALL indexes
(default: false)
--bulk
Leverage elasticsearch Bulk API when writing documents
(default: false)
--ignore-errors
Will continue the read/write loop on write error
(default: false)
--scrollTime
Time the nodes will hold the requested search in order.
(default: 10m)
--maxSockets
How many simultaneous HTTP requests can we process make?
(default:
5 [node <= v0.10.x] /
Infinity [node >= v0.11.x] )
--bulk-mode
The mode can be index, delete or update.
'index': Add or replace documents on the destination index.
'delete': Delete documents on destination index.
'update': Use 'doc_as_upsert' option with bulk update API to do partial update.
(default: index)
--bulk-use-output-index-name
Force use of destination index name (the actual output URL)
as destination while bulk writing to ES. Allows
leveraging Bulk API copying data inside the same
elasticsearch instance.
(default: false)
--timeout
Integer containing the number of milliseconds to wait for
a request to respond before aborting the request. Passed
directly to the request library. If used in bulk writing,
it will result in the entire batch not being written.
Mostly used when you don't care too much if you lose some
data when importing but rather have speed.
--skip
Integer containing the number of rows you wish to skip
ahead from the input transport. When importing a large
index, things can go wrong, be it connectivity, crashes,
someone forgetting to `screen`, etc. This allows you
to start the dump again from the last known line written
(as logged by the `offset` in the output). Please be
advised that since no sorting is specified when the
dump is initially created, there's no real way to
guarantee that the skipped rows have already been
written/parsed. This is more of an option for when
you want to get most data as possible in the index
without concern for losing some rows in the process,
similar to the `timeout` option.
--inputTransport
Provide a custom js file to us as the input transport
--outputTransport
Provide a custom js file to us as the output transport
--toLog
When using a custom outputTransport, should log lines
be appended to the output stream?
(default: true, except for `$`)
--help
This page
Examples:
# Copy an index from production to staging with mappings:
elasticdump \
--input=http://production.es.com:9200/my_index \
--output=http://staging.es.com:9200/my_index \
--type=mapping
elasticdump \
--input=http://production.es.com:9200/my_index \
--output=http://staging.es.com:9200/my_index \
--type=data
# Backup index data to a file:
elasticdump \
--input=http://production.es.com:9200/my_index \
--output=/data/my_index_mapping.json \
--type=mapping
elasticdump \
--input=http://production.es.com:9200/my_index \
--output=/data/my_index.json \
--type=data
# Backup and index to a gzip using stdout:
elasticdump \
--input=http://production.es.com:9200/my_index \
--output=$ \
| gzip > /data/my_index.json.gz
# Backup ALL indices, then use Bulk API to populate another ES cluster:
elasticdump \
--all=true \
--input=http://production-a.es.com:9200/ \
--output=/data/production.json
elasticdump \
--bulk=true \
--input=/data/production.json \
--output=http://production-b.es.com:9200/
# Backup the results of a query to a file
elasticdump \
--input=http://production.es.com:9200/my_index \
--output=query.json \
--searchBody '{"query":{"term":{"username": "admin"}}}'
------------------------------------------------------------------------------
Learn more @ https://github.com/taskrabbit/elasticsearch-dump`enter code here`
On Windows you can have in your PATH
PATH = ...;C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\; ...
remove it from PATH env, then
npm install -g typescript@latest
it worked for me to solve the
"TypeScript error TS1005: ';' expected"
See also how to update TypeScript to latest version with npm?
I had the exact same error message doing a database export via Sequel Pro on a mac. I was the root user so i knew it wasn't permissions. Then i tried it with mysqldump and got a different error message: Got error: 1449: The user specified as a definer ('joey'@'127.0.0.1') does not exist when using LOCK TABLES
Ahh, I had restored this database from a backup on the dev site and I hadn't created that user on this machine. "grant all on . to 'joey'@'127.0.0.1' identified by 'joeypass'; " did the trick.
hth
Try the maven-exec-plugin. From there:
mvn exec:java -Dexec.mainClass="com.example.Main"
This will run your class in the JVM. You can use -Dexec.args="arg0 arg1"
to pass arguments.
If you're on Windows, apply quotes for
exec.mainClass
andexec.args
:mvn exec:java -D"exec.mainClass"="com.example.Main"
If you're doing this regularly, you can add the parameters into the pom.xml as well:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>com.example.Main</mainClass>
<arguments>
<argument>foo</argument>
<argument>bar</argument>
</arguments>
</configuration>
</plugin>
I recommend use /(?=.*...)/g
Example
const text1 = 'I am using regex';
/(?=.*regex)/g.test(text1) // true
const text2 = 'regex is awesome';
/(?=.*regex)/g.test(text2) // true
const text3 = 'regex is util';
/(?=.*util)(?=.*regex)/g.test(text3) // true
const text4 = 'util is necessary';
/(?=.*util)(?=.*regex)/g.test(text4) // false because need regex in text
Use regex101 to test
With a FrameLayout you can place a text on top of an image view, the frame layout holding both an imageView and a textView.
If that's not enough and you want something more fancy like 'drawing' text, you need to draw text on a canvas - a sample is here: How to draw RTL text (Arabic) onto a Bitmap and have it ordered properly?
There is a sample from google, which lists the existing google accounts and generates an access token upon selection , you can send that access token to server to retrieve the related details from it to identify the user.
You can also get the email id from access token , for that you need to modify the SCOPE
Please go through My Post
Using ONLY css is impossbile. In fact, all form elements are impossible to customize to look in the same way on all browsers only with css. You can try niceforms though ;)
Short answer for the code in question is:
UPDATE `table` SET test=number
Here table
is the table name and it's surrounded by grave accent (aka back-ticks `) as this is MySQL convention to escape keywords (and TABLE
is a keyword in that case).
BEWARE, that this is pretty dangerous query which will wipe everything in column test
in every row of your table replacing it by the number
(regardless of it's value)
It is more common to use WHERE
clause to limit your query to only specific set of rows:
UPDATE `products` SET `in_stock` = true WHERE `supplier_id` = 10
It's happening because the @valerio-vaudi said.
Your problem is the dependency of spring batch spring-boot-starter-batch that has a spring-boot-starter-jdbc transitive maven dependency.
But you can resolve it set the primary datasource with your configuration
@Primary
@Bean(name = "dataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource getDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
width, height = map(int, input().split())
def rectanglePerimeter(width, height):
return ((width + height)*2)
print(rectanglePerimeter(width, height))
Running it like this produces:
% echo "1 2" | test.py
6
I suspect IDLE is simply passing a single string to your script. The first input()
is slurping the entire string. Notice what happens if you put some print statements in after the calls to input()
:
width = input()
print(width)
height = input()
print(height)
Running echo "1 2" | test.py
produces
1 2
Traceback (most recent call last):
File "/home/unutbu/pybin/test.py", line 5, in <module>
height = input()
EOFError: EOF when reading a line
Notice the first print statement prints the entire string '1 2'
. The second call to input()
raises the EOFError
(end-of-file error).
So a simple pipe such as the one I used only allows you to pass one string. Thus you can only call input()
once. You must then process this string, split it on whitespace, and convert the string fragments to ints yourself. That is what
width, height = map(int, input().split())
does.
Note, there are other ways to pass input to your program. If you had run test.py
in a terminal, then you could have typed 1
and 2
separately with no problem. Or, you could have written a program with pexpect to simulate a terminal, passing 1
and 2
programmatically. Or, you could use argparse to pass arguments on the command line, allowing you to call your program with
test.py 1 2
Illegal offset type errors occur when you attempt to access an array index using an object or an array as the index key.
Example:
$x = new stdClass();
$arr = array();
echo $arr[$x];
//illegal offset type
Your $xml
array contains an object or array at $xml->entry[$i]->source
for some value of $i
, and when you try to use that as an index key for $s
, you get that warning. You'll have to make sure $xml
contains what you want it to and that you're accessing it correctly.
[Try this solution it's simple] You can create a static variable in a Swift class then call it from any Objective-C class.
You can specify the latest version of ruby by looking at https://www.ruby-lang.org/en/downloads/
Fetch the latest version:
curl -sSL https://get.rvm.io | bash -s stable --ruby
Install it:
rvm install 2.2
Use it as default:
rvm use 2.2 --default
Or run the latest command from ruby:
rvm install ruby --latest
rvm use 2.2 --default
in my case there was a copy or replace window for that particular file open and hence the unlink error. i closed it and there is no unlink error
See this table.
A 101x101 QR code, with high level error correction, can hold 3248 bits, or 406 bytes. Probably not enough for any meaningful SVG/XML data.
A 177x177 grid, depending on desired level of error correction, can store between 1273 and 2953 bytes. Maybe enough to store something small.
I could do this (demo):
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
</head>
<body>
<form >
<input type="file" id="f" data-max-size="32154" />
<input type="submit" />
</form>
<script>
$(function(){
$('form').submit(function(){
var isOk = true;
$('input[type=file][data-max-size]').each(function(){
if(typeof this.files[0] !== 'undefined'){
var maxSize = parseInt($(this).attr('max-size'),10),
size = this.files[0].size;
isOk = maxSize > size;
return isOk;
}
});
return isOk;
});
});
</script>
</body>
</html>
My problem was slightly different.
By default Eclipse saved my manifest.json as an ANSI encoded text file.
Solution:
To push branches and tags (but not remotes):
git push origin 'refs/tags/*' 'refs/heads/*'
This would be equivalent to combining the --tags
and --all
options for git push
, which git does not seem to allow.
You might want to try the full login command:
mysql -h host -u root -p
where host would be 127.0.0.1
.
Do this just to make sure cooperation exists.
Using mysql -u root -p
allows me to do a a lot of database searching, but refuses any database creation due to a path setting.
A Re-Introduction to Javascript by the Mozilla team (they make Firefox) should explain it.
I have created the batch file and put it to the Cygwin's /bin directory. This script was developed so it allows to install/uninstall the registry entries for opening selected folders and drives in Cygwin. For details see the link http://with-love-from-siberia.blogspot.com/2013/12/cygwin-here.html.
update: This solution does the same as early suggestions but all manipulations with Windows Registry are hidden within the script.
Perform the command to install
cyghere.bat /install
Perform the command to uninstall
cyghere.bat /uninstall
You can achieve with following way
this.projectService.create(project)
.subscribe(
result => {
console.log(result);
},
error => {
console.log(error);
this.errors = error
}
);
}
if (!this.errors) {
//route to new page
}
You can use array_intersect()
.
$result = !empty(array_intersect($people, $criminals));
$('input[name="testing"]').val(theValue);
$("#datepicker").datepicker("getDate")
returns a date object, not a string.
var dateObject = $("#datepicker").datepicker("getDate"); // get the date object
var dateString = dateObject.getFullYear() + '-' + (dateObject.getMonth() + 1) + '-' + dateObject.getDate();// Y-n-j in php date() format
Will you ever need to join this table to other tables? Do you need a way to uniquely identify a record? If the answer is yes, you need a primary key. Assume your data is something like a customer table that has the names of the people who are customers. There may be no natural key because you need the addresses, emails, phone numbers, etc. to determine if this Sally Smith is different from that Sally Smith and you will be storing that information in related tables as the person can have mulitple phones, addesses, emails, etc. Suppose Sally Smith marries John Jones and becomes Sally Jones. If you don't have an artifical key onthe table, when you update the name, you just changed 7 Sally Smiths to Sally Jones even though only one of them got married and changed her name. And of course in this case withouth an artificial key how do you know which Sally Smith lives in Chicago and which one lives in LA?
You say you have no natural key, therefore you don't have any combinations of field to make unique either, this makes the artficial key critical.
I have found anytime I don't have a natural key, an artifical key is an absolute must for maintaining data integrity. If you do have a natural key, you can use that as the key field instead. But personally unless the natural key is one field, I still prefer an artifical key and unique index on the natural key. You will regret it later if you don't put one in.
You will have an if-check no matter how efficient you try to optimize this not-so-intensive computation :) You can subtract the upper bound from the number and if it's positive you know you are out of range. You can perhaps perform some boolean bit-shift logic to figure it out and you can even use Fermat's theorem if you want (kidding :) But the point is "why" do you need to optimize this comparison? What's the purpose?
The relevant build.gradle file will then update automatically.
Open your build.gradle file and add a new build rule to the dependencies closure. For example, if you wanted to add Google Play Services, your project's dependencies section would look something like this:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.android.gms:play-services:6.5.+'
}
In the Project panel, Control + click the module you want to add the dependency to and select Open Module Settings.
Select the Dependencies tab, followed by the + button in the bottom-left corner. You can choose from the following list of options:
You can then enter more information about the dependency you want to add to your project. For example, if you choose Library Dependency, Android Studio displays a list of libraries for you to choose from.
Once you've added your dependency, check your module-level build.gradle file. It should have automatically updated to include the new dependency.
What you could do is use ng-repeat
passing in the value of whatever you're iterating on to the ng-checked
and from there utilising ng-class
to apply your styles depending on the result.
I did something similar recently and it worked for me.
now Application-Level Rate Limiting 200 calls per hour !
I too needed a rounded ImageView, I used the below code, you can modify it accordingly:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class RoundedImageView extends ImageView {
public RoundedImageView(Context context) {
super(context);
}
public RoundedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = ((BitmapDrawable) drawable).getBitmap();
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
int w = getWidth();
@SuppressWarnings("unused")
int h = getHeight();
Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
canvas.drawBitmap(roundBitmap, 0, 0, null);
}
public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap sbmp;
if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
float factor = smallest / radius;
sbmp = Bitmap.createScaledBitmap(bmp,
(int) (bmp.getWidth() / factor),
(int) (bmp.getHeight() / factor), false);
} else {
sbmp = bmp;
}
Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final String color = "#BAB399";
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, radius, radius);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor(color));
canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
radius / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(sbmp, rect, rect, paint);
return output;
}
}
Running a direct build APK will work. But make sure you uninstall any previously installed package of the same name.
Note that if the problem is being caused by appearing scrollbars, putting
body {
overflow: hidden;
}
in your CSS might be an easy fix (if you don't need the page to scroll).
It is possible to set both labels together with axis.set
function. Look for the example:
import pandas as pd
import matplotlib.pyplot as plt
values = [[1,2], [2,5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], index=['Index 1','Index 2'])
ax = df2.plot(lw=2,colormap='jet',marker='.',markersize=10,title='Video streaming dropout by category')
# set labels for both axes
ax.set(xlabel='x axis', ylabel='y axis')
plt.show()
or select Edit Scheme
from Product
> Scheme
Menu
select Enable Zombie Objects
form the Diagnostics
tab
As alternative, if you prefer .xcconfig
files you can read this article https://therealbnut.wordpress.com/2012/01/01/setting-xcode-4-0-environment-variables-from-a-script/
If you are seeing this issue with IIS hosting, but not when F5 debugging, try creating a new application in IIS.
This fixed it for me. (windows 10) In the end i deleted the "bad" IIS application and re-created an identical one with the same name.
Also, It can be done with LINQ
var str = "Hello@Hello&Hello(Hello)";
var characters = str.Select(c => char.IsLetter(c) ? c : ',')).ToArray();
var output = new string(characters);
Console.WriteLine(output);
You could make your blue div
position: relative
and then give the div.title
position:absolute;
and bottom: 0px
Here is a working demo.. http://jsfiddle.net/gLaG6/
The correct way in .NET 4.0 is:
if (String.IsNullOrWhiteSpace(strSearch))
The String.IsNullOrWhiteSpace
method used above is equivalent to:
if (strSearch == null || strSearch == String.Empty || strSearch.Trim().Length == 0)
// String.Empty is the same as ""
Reference for IsNullOrWhiteSpace method
http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx
Indicates whether a specified string is Nothing, empty, or consists only of white-space characters.
In earlier versions, you could do something like this:
if (String.IsNullOrEmpty(strSearch) || strSearch.Trim().Length == 0)
The String.IsNullOrEmpty
method used above is equivalent to:
if (strSearch == null || strSearch == String.Empty)
Which means you still need to check for your "IsWhiteSpace" case with the .Trim().Length == 0
as per the example.
Reference for IsNullOrEmpty method
http://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx
Indicates whether the specified string is Nothing or an Empty string.
Explanation:
You need to ensure strSearch
(or any variable for that matter) is not null
before you dereference it using the dot character (.
) - i.e. before you do strSearch.SomeMethod()
or strSearch.SomeProperty
you need to check that strSearch != null
.
In your example you want to make sure your string has a value, which means you want to ensure the string:
String.Empty
/ ""
)In the cases above, you must put the "Is it null?" case first, so it doesn't go on to check the other cases (and error) when the string is null
.
please pay attention this code for upload image only. I use HTMLHelper for upload image. in cshtml file put this code
@using (Html.BeginForm("UploadImageAction", "Admin", FormMethod.Post, new { enctype = "multipart/form-data", id = "myUploadForm" }))
{
<div class="controls">
@Html.UploadFile("UploadImage")
</div>
<button class="button">Upload Image</button>
}
then create a HTMLHelper for Upload tag
public static class UploadHelper
{
public static MvcHtmlString UploadFile(this HtmlHelper helper, string name, object htmlAttributes = null)
{
TagBuilder input = new TagBuilder("input");
input.Attributes.Add("type", "file");
input.Attributes.Add("id", helper.ViewData.TemplateInfo.GetFullHtmlFieldId(name));
input.Attributes.Add("name", helper.ViewData.TemplateInfo.GetFullHtmlFieldName(name));
if (htmlAttributes != null)
{
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
input.MergeAttributes(attributes);
}
return new MvcHtmlString(input.ToString());
}
}
and finally in Action Upload your file
[AjaxOnly]
[HttpPost]
public ActionResult UploadImageAction(HttpPostedFileBase UploadImage)
{
string path = Server.MapPath("~") + "Files\\UploadImages\\" + UploadImage.FileName;
System.Drawing.Image img = new Bitmap(UploadImage.InputStream);
img.Save(path);
return View();
}
By using sscanf we can convert string to float.
#include<stdio.h>
#include<string.h>
int main()
{
char str[100] ="4.0800" ;
const char s[2] = "-";
char *token;
double x;
/* get the first token */
token = strtok(str, s);
sscanf(token,"%f",&x);
printf( " %f",x );
return 0;
}
If it "doesn't care about the output", couldn't the exec to the script be called with the &
to background the process?
EDIT - incorporating what @AdamTheHut commented to this post, you can add this to a call to exec
:
" > /dev/null 2>/dev/null &"
That will redirect both stdio
(first >
) and stderr
(2>
) to /dev/null
and run in the background.
There are other ways to do the same thing, but this is the simplest to read.
An alternative to the above double-redirect:
" &> /dev/null &"
Suppose STUDENTID contains some characters or numbers that you already know i.e. 'searchstring' then below query will work for you.
You could try this:
select * from STUDENTS where CHARINDEX('searchstring',STUDENTID)>0
I think this one is the fastest and easiest one.
With question 3, this article states that RESTful Services are appropiate in this scenarios:
While SOAP is the way to go when:
Your __init__.py
should have a docstring.
Although all the functionality is implemented in modules and subpackages, your package docstring is the place to document where to start. For example, consider the python email
package. The package documentation is an introduction describing the purpose, background, and how the various components within the package work together. If you automatically generate documentation from docstrings using sphinx or another package, the package docstring is exactly the right place to describe such an introduction.
For any other content, see the excellent answers by firecrow and Alex Martelli.
For Android 3+:
In the Project window, select the Android view.
Right-click the res folder and select New > Image Asset.
If your app supports Android 8.0, create adaptive and legacy launcher icons.
If your app supports versions no higher than Android 7.1, create a legacy launcher icon only.
In the Icon Type field, select Launcher Icons (Legacy Only) .
Select an Asset Type, and then specify the asset in the field underneath.
You can use this very trial PowerShell Command to get the MSBuildToolsPath
from the registry.
Resolve-Path HKLM:\SOFTWARE\Microsoft\MSBuild\ToolsVersions\* |
Get-ItemProperty -Name MSBuildToolsPath
MSBuildToolsPath : C:\Program Files (x86)\MSBuild\12.0\bin\amd64\
PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\12.0
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions
PSChildName : 12.0
PSDrive : HKLM
PSProvider : Microsoft.PowerShell.Core\Registry
MSBuildToolsPath : C:\Program Files (x86)\MSBuild\14.0\bin\amd64\
PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\14.0
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions
PSChildName : 14.0
PSDrive : HKLM
PSProvider : Microsoft.PowerShell.Core\Registry
MSBuildToolsPath : C:\Windows\Microsoft.NET\Framework64\v2.0.50727\
PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\2.0
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions
PSChildName : 2.0
PSDrive : HKLM
PSProvider : Microsoft.PowerShell.Core\Registry
MSBuildToolsPath : C:\Windows\Microsoft.NET\Framework64\v3.5\
PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\3.5
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions
PSChildName : 3.5
PSDrive : HKLM
PSProvider : Microsoft.PowerShell.Core\Registry
MSBuildToolsPath : C:\Windows\Microsoft.NET\Framework64\v4.0.30319\
PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions
PSChildName : 4.0
PSDrive : HKLM
PSProvider : Microsoft.PowerShell.Core\Registry
or from the filesystem
Resolve-Path "C:\Program Files (x86)\MSBuild\*\Bin\amd64\MSBuild.exe"
Resolve-Path "C:\Program Files (x86)\MSBuild\*\Bin\MSBuild.exe"
Path
----
C:\Program Files (x86)\MSBuild\12.0\Bin\amd64\MSBuild.exe
C:\Program Files (x86)\MSBuild\14.0\Bin\amd64\MSBuild.exe
C:\Program Files (x86)\MSBuild\12.0\Bin\MSBuild.exe
C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe
$("#elementName option").text();
This will give selected text of Combo-Box.
$("#elementName option").val();
This will give selected value associated selected item in Combo-Box.
$("#elementName option").length;
It will give the multi-select combobox values in the array and length will give number of element of the array.
Note:#elementName is id the Combo-box.
What you might like to do is look up CSS grid based layouts. This layout method involves specifying some CSS classes to align the page contents to a grid structure. It's more closely related to print-bsed layout than web-based, but it's a technique used on a lot of websites to layout the content into a structure without having to resort to tables.
Try this for starters from Smashing Magazine.
I would do it like this:
SELECT top(100)* into #tmpFerdeen
FROM Customers
Insert into #tmpFerdeen
SELECT top(100)*
FROM CustomerEurope
Insert into #tmpFerdeen
SELECT top(100)*
FROM CustomerAsia
Insert into #tmpFerdeen
SELECT top(100)*
FROM CustomerAmericas
I think you are looking for:
$result->isEmpty()
This is different from empty($result)
, which will not be true because the result will be an empty collection. Your suggestion of count($result)
is also a good solution. I cannot find any reference in the docs
array=[0,10,20,40]
for e in reversed(array):
print e
This are just php notice messages,it seems php.ini configurations are not according vtiger standards,
you can disable this message by setting error reporting to E_ALL & ~E_NOTICE in php.ini
For example error_reporting(E_ALL&~E_NOTICE)
and then restart apache to reflect changes.
In your product.service.ts you are using stringify method in a wrong way..
Just use
JSON.stringify(product)
instead of
JSON.stringify({product})
i have checked your problem and after this it's working absolutely fine.
I came across this error message through a silly mistake. A classic example of Python giving you plenty of room to make a fool of yourself. Observe:
class DOH(object):
def __init__(self, property=None):
self.property=property
def property():
return property
x = DOH(1)
print(x.property())
Results
$ python3 t.py
Traceback (most recent call last):
File "t.py", line 9, in <module>
print(x.property())
TypeError: 'int' object is not callable
The problem here of course is that the function is overwritten with a property.
Yes, as of May 29, 2015 this functionality is now provided in the Android Design Support Library
This library includes support for
You can use SSMS's "Generate Scripts..." function to script out whatever you need to transfer. Right-click on the source database in SSMS, choose "Generate Scripts...", and follow the wizard along. Then run your resultant script that will now contain the stored procedure create statements.
Guidelines from MSDN: Using decimal, float, and real Data
The default maximum precision of numeric and decimal data types is 38. In Transact-SQL, numeric is functionally equivalent to the decimal data type. Use the decimal data type to store numbers with decimals when the data values must be stored exactly as specified.
The behavior of float and real follows the IEEE 754 specification on approximate numeric data types. Because of the approximate nature of the float and real data types, do not use these data types when exact numeric behavior is required, such as in financial applications, in operations involving rounding, or in equality checks. Instead, use the integer, decimal, money, or smallmoney data types. Avoid using float or real columns in WHERE clause search conditions, especially the = and <> operators. It is best to limit float and real columns to > or < comparisons.
This is pretty simple with numpy
, just subtract the arrays:
diffs = array1 - array2
I get:
diffs == array([ 0.1, 0.2, 0.3])
You can also use button click event like this:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="MyButtonClick" />
</ItemTemplate>
</asp:TemplateField>
protected void MyButtonClick(object sender, System.EventArgs e)
{
//Get the button that raised the event
Button btn = (Button)sender;
//Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}
You can do like this to get data:
void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple ButtonField column fields are used, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Select")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Get the last name of the selected author from the appropriate
// cell in the GridView control.
GridViewRow selectedRow = CustomersGridView.Rows[index];
}
}
and Button in gridview should have command like this and handle rowcommand event:
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="false"
onrowcommand="CustomersGridView_RowCommand"
runat="server">
<columns>
<asp:buttonfield buttontype="Button"
commandname="Select"
headertext="Select Customer"
text="Select"/>
</columns>
</asp:gridview>
You can replace database value in date_default_timezone_set function, date_default_timezone_set(SOME_PHP_VARIABLE); but just needs to take care of exact values relevant to the timezones.
I was facing a similar issue with the DropDownButton when i was trying to display a dynamic list of strings in the dropdown. I ended up creating a plugin : flutter_search_panel. Not a dropdown plugin, but you can display the items with the search functionality.
Use the following code for using the widget :
FlutterSearchPanel(
padding: EdgeInsets.all(10.0),
selected: 'a',
title: 'Demo Search Page',
data: ['This', 'is', 'a', 'test', 'array'],
icon: new Icon(Icons.label, color: Colors.black),
color: Colors.white,
textStyle: new TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 20.0, decorationStyle: TextDecorationStyle.dotted),
onChanged: (value) {
print(value);
},
),
dep and clg alphabets validation is not working
var selectedRow = null;
function validateform() {
var table = document.getElementById("mytable");
var rowCount = table.rows.length;
console.log(rowCount);
var x = document.forms["myform"]["usrname"].value;
if (x == "") {
alert("name must be filled out");
return false;
}
var y = document.forms["myform"]["usremail"].value;
if (y == "") {
alert("email must be filled out");
return false;
}
var mail = /[^@]+@[a-zA-Z]+\.[a-zA-Z]{2,6}/
if (mail.test(y)) {
//alert("email must be a valid format");
//return false ;
} else {
alert("not a mail id")
return false;
}
var z = document.forms["myform"]["usrage"].value;
if (z == "") {
alert("age must be filled out");
return false;
}
if (isNaN(z) || z < 1 || z > 100) {
alert("The age must be a number between 1 and 100");
return false;
}
var a = document.forms["myform"]["usrdpt"].value;
if (a == "") {
alert("Dept must be filled out");
return false;
}
var dept = "`@#$%^&*()+=-[]\\\';,./{}|\":<>?~_";
if (dept.match(a)) {
alert("special charachers found");
return false;
}
var b = document.forms["myform"]["usrclg"].value;
if (b == "") {
alert("College must be filled out");
return false;
}
console.log(table);
var row = table.insertRow(rowCount);
row.setAttribute('id', rowCount);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
var cell5 = row.insertCell(5);
var cell6 = row.insertCell(6);
var cell7 = row.insertCell(7);
cell0.innerHTML = rowCount;
cell1.innerHTML = x;
cell2.innerHTML = y;
cell3.innerHTML = z;
cell4.innerHTML = a;
cell5.innerHTML = b;
cell6.innerHTML = '<Button type="button" onclick=onEdit("' + x + '","' + y + '","' + z + '","' + a + '","' + b + '","' + rowCount + '")>Edit</BUTTON>';
cell7.innerHTML = '<Button type="button" onclick=deletefunction(' + rowCount + ')>Delete</BUTTON>';
}
function emptyfunction() {
document.getElementById("usrname").value = "";
document.getElementById("usremail").value = "";
document.getElementById("usrage").value = "";
document.getElementById("usrdpt").value = "";
document.getElementById("usrclg").value = "";
}
function onEdit(x, y, z, a, b, rowCount) {
selectedRow = rowCount;
console.log(selectedRow);
document.forms["myform"]["usrname"].value = x;
document.forms["myform"]["usremail"].value = y;
document.forms["myform"]["usrage"].value = z;
document.forms["myform"]["usrdpt"].value = a;
document.forms["myform"]["usrclg"].value = b;
document.getElementById('Add').style.display = 'none';
document.getElementById('update').style.display = 'block';
}
function deletefunction(rowCount) {
document.getElementById("mytable").deleteRow(rowCount);
}
function onUpdatefunction() {
var row = document.getElementById(selectedRow);
console.log(row);
var x = document.forms["myform"]["usrname"].value;
if (x == "") {
alert("name must be filled out");
document.myForm.x.focus();
return false;
}
var y = document.forms["myform"]["usremail"].value;
if (y == "") {
alert("email must be filled out");
document.myForm.y.focus();
return false;
}
var mail = /[^@]+@[a-zA-Z]+\.[a-zA-Z]{2,6}/
if (mail.test(y)) {
//alert("email must be a valid format");
//return false ;
} else {
alert("not a mail id");
return false;
}
var z = document.forms["myform"]["usrage"].value;
if (z == "") {
alert("age must be filled out");
document.myForm.z.focus();
return false;
}
if (isNaN(z) || z < 1 || z > 100) {
alert("The age must be a number between 1 and 100");
return false;
}
var a = document.forms["myform"]["usrdpt"].value;
if (a == "") {
alert("Dept must be filled out");
return false;
}
var letters = /^[A-Za-z]+$/;
if (a.test(letters)) {
//Your logice will be here.
} else {
alert("Please enter only alphabets");
return false;
}
var b = document.forms["myform"]["usrclg"].value;
if (b == "") {
alert("College must be filled out");
return false;
}
var letters = /^[A-Za-z]+$/;
if (b.test(letters)) {
//Your logice will be here.
} else {
alert("Please enter only alphabets");
return false;
}
row.cells[1].innerHTML = x;
row.cells[2].innerHTML = y;
row.cells[3].innerHTML = z;
row.cells[4].innerHTML = a;
row.cells[5].innerHTML = b;
}
_x000D_
<html>
<head>
</head>
<body>
<form name="myform">
<h1>
<center> Admission form </center>
</h1>
<center>
<tr>
<td>Name :</td>
<td><input type="text" name="usrname" PlaceHolder="Enter Your First Name" required></td>
</tr>
<tr>
<td> Email ID :</td>
<td><input type="text" name="usremail" PlaceHolder="Enter Your email address" pattern="[^@]+@[a-zA-Z]+\.[a-zA-Z]{2,6}" required></td>
</tr>
<tr>
<td>Age :</td>
<td><input type="number" name="usrage" PlaceHolder="Enter Your Age" required></td>
</tr>
<tr>
<td>Dept :</td>
<td><input type="text" name="usrdpt" PlaceHolder="Enter Dept"></td>
</tr>
<tr>
<td>College :</td>
<td><input type="text" name="usrclg" PlaceHolder="Enter college"></td>
</tr>
</center>
<center>
<br>
<br>
<tr>
<td>
<Button type="button" onclick="validateform()" id="Add">Add</button>
</td>
<td>
<Button type="button" onclick="onUpdatefunction()" style="display:none;" id="update">update</button>
</td>
<td><button type="reset">Reset</button></td>
</tr>
</center>
<br><br>
<center>
<table id="mytable" border="1">
<tr>
<th>SNO</th>
<th>Name</th>
<th>Email ID</th>
<th>Age</th>
<th>Dept</th>
<th>College</th>
</tr>
</center>
</table>
</form>
</body>
</html>
_x000D_
I think you need quotes around your {$row['null_field']}
, so '{$row['null_field']}'
If you don't have the quotes, you'll occasionally end up with an insert statement that looks like this: insert into table2 (f1, f2) values ('val1',)
which is a syntax error.
If that is a numeric field, you will have to do some testing above it, and if there is no value in null_field, explicitly set it to null..
I've started a project to help people making their first GitHub pull request. You can do the hands-on tutorial to make your first PR here
The workflow is simple as
git clone <clone url you copied earlier>
git checkout -b branch-name
git commit
git push origin branch-name
Compare and pull request
buttonYou can describe your css selection like cascading style sheet dows:
protected override void When()
{
SUT.Browser.FindElements(By.CssSelector("#carousel > a.tiny.button"))
}
That was much more painful than it ought to have been.
It turns out there are two concepts, the format of the data and the format of the axis. You need to format the data series as a time, then you format the graph's display axis as date and time.
Highlight all columns and insert your graph
Select the column, right click, format cells. Select time so that the data is in time format.
Now right click on the axis text and change it to display whatever format you want
One option is to use altertify, this gives a nice looking alert box.
Simply include the required libraries from here, and use the following piece of code to display the alert box.
alertify.confirm("This is a confirm dialog.",
function(){
alertify.success('Ok');
},
function(){
alertify.error('Cancel');
});
The output will look like this. To see it in action here is the demo
if you have not restarted your computer after installing jdk just restart your computer.
if you want to make a portable java and set path before using java, just make a batch file i explained below.
if you want to run this batch file when your computer start just put your batch file shortcut in startup folder. In windows 7 startup folder is "C:\Users\user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
make a batch file like this:
set Java_Home=C:\Program Files\Java\jdk1.8.0_11
set PATH=%PATH%;C:\Program Files\Java\jdk1.8.0_11\bin
note:
java_home
and path
are variables. you can make any variable as you wish.
for example set amir=good_boy
and you can see amir by %amir%
or you can see java_home by %java_home%
For now I took @Gian's advice & limited the number of records per Workbook to 500k and rolled over the rest to the next Workbook. Seems to be working decent. For the above configuration, it took me about 10 mins per workbook.
textarea {
white-space: pre;
overflow-wrap: normal;
overflow-x: scroll;
}
white-space: nowrap
also works if you don't care about whitespace, but of course you don't want that if you're working with code (or indented paragraphs or any content where there might deliberately be multiple spaces) ... so i prefer pre
.
overflow-wrap: normal
(was word-wrap
in older browsers) is needed in case some parent has changed that setting; it can cause wrapping even if pre
is set.
also -- contrary to the currently accepted answer -- textareas do often wrap by default. pre-wrap
seems to be the default on my browser.
You can use the following script if you don't wish to use Wizard;
RESTORE DATABASE myDB
FROM DISK = N'C:\BackupDB.bak'
WITH REPLACE,RECOVERY,
MOVE N'HRNET' TO N'C:\MSSQL\Data\myDB.mdf',
MOVE N'HRNET_LOG' TO N'C:\MSSQL\Data\myDB.ldf'
The difference between an operating system and a kernel:
The kernel is a part of an operating system. The operating system is the software package that communicates directly to the hardware and our application. The kernel is the lowest level of the operating system. The kernel is the main part of the operating system and is responsible for translating the command into something that can be understood by the computer. The main functions of the kernel are:
By using the following code you can find name, path, size as like this all kind of information of all audio song files
String[] STAR = { "*" };
Uri allaudiosong = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String audioselection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
Cursor cursor;
cursor = managedQuery(allaudiosong, STAR, audioselection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String song_name = cursor
.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
System.out.println("Audio Song Name= "+song_name);
int song_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media._ID));
System.out.println("Audio Song ID= "+song_id);
String fullpath = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DATA));
System.out.println("Audio Song FullPath= "+fullpath);
String album_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM));
System.out.println("Audio Album Name= "+album_name);
int album_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
System.out.println("Audio Album Id= "+album_id);
String artist_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST));
System.out.println("Audio Artist Name= "+artist_name);
int artist_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
System.out.println("Audio Artist ID= "+artist_id);
} while (cursor.moveToNext());
#!/bin/sh
# http://www.tldp.org/LDP/abs/html/io-redirection.html
echo "Hello World"
exec > script.log 2>&1
echo "Start logging out from here to a file"
bad command
echo "End logging out from here to a file"
exec > /dev/tty 2>&1 #redirects out to controlling terminal
echo "Logged in the terminal"
Output:
> ./above_script.sh
Hello World
Not logged in the file
> cat script.log
Start logging out from here to a file
./logging_sample.sh: line 6: bad: command not found
End logging out from here to a file
Read more here: http://www.tldp.org/LDP/abs/html/io-redirection.html
Add this to html:
<svg id="mySVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"/>
Try this function and adapt for you program:
var svgNS = "http://www.w3.org/2000/svg";
function createCircle()
{
var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle. for rectangle use "rectangle"
myCircle.setAttributeNS(null,"id","mycircle");
myCircle.setAttributeNS(null,"cx",100);
myCircle.setAttributeNS(null,"cy",100);
myCircle.setAttributeNS(null,"r",50);
myCircle.setAttributeNS(null,"fill","black");
myCircle.setAttributeNS(null,"stroke","none");
document.getElementById("mySVG").appendChild(myCircle);
}
The sanctioned way of creating and using child processes is through the subprocess module.
import subprocess
pl = subprocess.Popen(['ps', '-U', '0'], stdout=subprocess.PIPE).communicate()[0]
print pl
The command is broken down into a python list of arguments so that it does not need to be run in a shell (By default the subprocess.Popen does not use any kind of a shell environment it just execs it). Because of this we cant simply supply 'ps -U 0' to Popen.
In my understanding, Get-Content eliminates ALL newlines/carriage returns when it rolls your text file through the pipeline. To do multiline regexes, you have to re-combine your string array into one giant string. I do something like:
$text = [string]::Join("`n", (Get-Content test.txt))
[regex]::Replace($text, "t`n", "ting`na ", "Singleline")
Clarification: small files only folks! Please don't try this on your 40 GB log file :)
@user187291 code works and only fails when + is not encoded.
I know this is very old post. But this worked to me.
$is_encoded = preg_match('~%[0-9A-F]{2}~i', $string);
if($is_encoded) {
$string = urlencode(urldecode(str_replace(['+','='], ['%2B','%3D'], $string)));
} else {
$string = urlencode($string);
}
for who looks for more options here is a one
// Set text within a `TextView`
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("Hey @sarah, where did @jim go? #lost");
// Style clickable spans based on pattern
new PatternEditableBuilder().
addPattern(Pattern.compile("\\@(\\w+)"), Color.BLUE,
new PatternEditableBuilder.SpannableClickedListener() {
@Override
public void onSpanClicked(String text) {
Toast.makeText(MainActivity.this, "Clicked username: " + text,
Toast.LENGTH_SHORT).show();
}
}).into(textView);
RESOURCE : CodePath
\t
in a string marks an escape sequence for a tab character. For a literal \
, use \\
.