http://dev.mysql.com/doc/refman/5.6/en/load-data-local.html
Put this in my.cnf - the [client]
section should already be there
(if you're not too concerned about security).
[client]
loose-local-infile=1
You can go for this :
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
I had this issue and it was because of limited internet connection to source. You can use a proxy (VPN) but the better solution is download manually NodeJs from the source https://nodejs.org/download/ and Git, too.
after installation manually, aptana will check if they installed or not.
Set your PERL_UNICODE
envariable to AS
. This makes all Perl scripts decode @ARGV
as UTF-8 strings, and sets the encoding of all three of stdin, stdout, and stderr to UTF-8. Both these are global effects, not lexical ones.
At the top of your source file (program, module, library, do
hickey), prominently assert that you are running perl version 5.12 or better via:
use v5.12; # minimal for unicode string feature
use v5.14; # optimal for unicode string feature
Enable warnings, since the previous declaration only enables strictures and features, not warnings. I also suggest promoting Unicode warnings into exceptions, so use both these lines, not just one of them. Note however that under v5.14, the utf8
warning class comprises three other subwarnings which can all be separately enabled: nonchar
, surrogate
, and non_unicode
. These you may wish to exert greater control over.
use warnings;
use warnings qw( FATAL utf8 );
Declare that this source unit is encoded as UTF-8. Although once upon a time this pragma did other things, it now serves this one singular purpose alone and no other:
use utf8;
Declare that anything that opens a filehandle within this lexical scope but not elsewhere is to assume that that stream is encoded in UTF-8 unless you tell it otherwise. That way you do not affect other module’s or other program’s code.
use open qw( :encoding(UTF-8) :std );
Enable named characters via \N{CHARNAME}
.
use charnames qw( :full :short );
If you have a DATA
handle, you must explicitly set its encoding. If you want this to be UTF-8, then say:
binmode(DATA, ":encoding(UTF-8)");
There is of course no end of other matters with which you may eventually find yourself concerned, but these will suffice to approximate the state goal to “make everything just work with UTF-8”, albeit for a somewhat weakened sense of those terms.
One other pragma, although it is not Unicode related, is:
use autodie;
It is strongly recommended.
My own boilerplate these days tends to look like this:
use 5.014;
use utf8;
use strict;
use autodie;
use warnings;
use warnings qw< FATAL utf8 >;
use open qw< :std :utf8 >;
use charnames qw< :full >;
use feature qw< unicode_strings >;
use File::Basename qw< basename >;
use Carp qw< carp croak confess cluck >;
use Encode qw< encode decode >;
use Unicode::Normalize qw< NFD NFC >;
END { close STDOUT }
if (grep /\P{ASCII}/ => @ARGV) {
@ARGV = map { decode("UTF-8", $_) } @ARGV;
}
$0 = basename($0); # shorter messages
$| = 1;
binmode(DATA, ":utf8");
# give a full stack dump on any untrapped exceptions
local $SIG{__DIE__} = sub {
confess "Uncaught exception: @_" unless $^S;
};
# now promote run-time warnings into stack-dumped
# exceptions *unless* we're in an try block, in
# which case just cluck the stack dump instead
local $SIG{__WARN__} = sub {
if ($^S) { cluck "Trapped warning: @_" }
else { confess "Deadly warning: @_" }
};
while (<>) {
chomp;
$_ = NFD($_);
...
} continue {
say NFC($_);
}
__END__
Saying that “Perl should [somehow!] enable Unicode by default” doesn’t even start to begin to think about getting around to saying enough to be even marginally useful in some sort of rare and isolated case. Unicode is much much more than just a larger character repertoire; it’s also how those characters all interact in many, many ways.
Even the simple-minded minimal measures that (some) people seem to think they want are guaranteed to miserably break millions of lines of code, code that has no chance to “upgrade” to your spiffy new Brave New World modernity.
It is way way way more complicated than people pretend. I’ve thought about this a huge, whole lot over the past few years. I would love to be shown that I am wrong. But I don’t think I am. Unicode is fundamentally more complex than the model that you would like to impose on it, and there is complexity here that you can never sweep under the carpet. If you try, you’ll break either your own code or somebody else’s. At some point, you simply have to break down and learn what Unicode is about. You cannot pretend it is something it is not.
goes out of its way to make Unicode easy, far more than anything else I’ve ever used. If you think this is bad, try something else for a while. Then come back to : either you will have returned to a better world, or else you will bring knowledge of the same with you so that we can make use of your new knowledge to make better at these things.
At a minimum, here are some things that would appear to be required for to “enable Unicode by default”, as you put it:
All source code should be in UTF-8 by default. You can get that with use utf8
or export PERL5OPTS=-Mutf8
.
The DATA
handle should be UTF-8. You will have to do this on a per-package basis, as in binmode(DATA, ":encoding(UTF-8)")
.
Program arguments to scripts should be understood to be UTF-8 by default. export PERL_UNICODE=A
, or perl -CA
, or export PERL5OPTS=-CA
.
The standard input, output, and error streams should default to UTF-8. export PERL_UNICODE=S
for all of them, or I
, O
, and/or E
for just some of them. This is like perl -CS
.
Any other handles opened by should be considered UTF-8 unless declared otherwise; export PERL_UNICODE=D
or with i
and o
for particular ones of these; export PERL5OPTS=-CD
would work. That makes -CSAD
for all of them.
Cover both bases plus all the streams you open with export PERL5OPTS=-Mopen=:utf8,:std
. See uniquote.
You don’t want to miss UTF-8 encoding errors. Try export PERL5OPTS=-Mwarnings=FATAL,utf8
. And make sure your input streams are always binmode
d to :encoding(UTF-8)
, not just to :utf8
.
Code points between 128–255 should be understood by to be the corresponding Unicode code points, not just unpropertied binary values. use feature "unicode_strings"
or export PERL5OPTS=-Mfeature=unicode_strings
. That will make uc("\xDF") eq "SS"
and "\xE9" =~ /\w/
. A simple export PERL5OPTS=-Mv5.12
or better will also get that.
Named Unicode characters are not by default enabled, so add export PERL5OPTS=-Mcharnames=:full,:short,latin,greek
or some such. See uninames and tcgrep.
You almost always need access to the functions from the standard Unicode::Normalize
module various types of decompositions. export PERL5OPTS=-MUnicode::Normalize=NFD,NFKD,NFC,NFKD
, and then always run incoming stuff through NFD and outbound stuff from NFC. There’s no I/O layer for these yet that I’m aware of, but see nfc, nfd, nfkd, and nfkc.
String comparisons in using eq
, ne
, lc
, cmp
, sort
, &c&cc are always wrong. So instead of @a = sort @b
, you need @a = Unicode::Collate->new->sort(@b)
. Might as well add that to your export PERL5OPTS=-MUnicode::Collate
. You can cache the key for binary comparisons.
built-ins like printf
and write
do the wrong thing with Unicode data. You need to use the Unicode::GCString
module for the former, and both that and also the Unicode::LineBreak
module as well for the latter. See uwc and unifmt.
If you want them to count as integers, then you are going to have to run your \d+
captures through the Unicode::UCD::num
function because ’s built-in atoi(3) isn’t currently clever enough.
You are going to have filesystem issues on filesystems. Some filesystems silently enforce a conversion to NFC; others silently enforce a conversion to NFD. And others do something else still. Some even ignore the matter altogether, which leads to even greater problems. So you have to do your own NFC/NFD handling to keep sane.
All your code involving a-z
or A-Z
and such MUST BE CHANGED, including m//
, s///
, and tr///
. It’s should stand out as a screaming red flag that your code is broken. But it is not clear how it must change. Getting the right properties, and understanding their casefolds, is harder than you might think. I use unichars and uniprops every single day.
Code that uses \p{Lu}
is almost as wrong as code that uses [A-Za-z]
. You need to use \p{Upper}
instead, and know the reason why. Yes, \p{Lowercase}
and \p{Lower}
are different from \p{Ll}
and \p{Lowercase_Letter}
.
Code that uses [a-zA-Z]
is even worse. And it can’t use \pL
or \p{Letter}
; it needs to use \p{Alphabetic}
. Not all alphabetics are letters, you know!
If you are looking for variables with /[\$\@\%]\w+/
, then you have a problem. You need to look for /[\$\@\%]\p{IDS}\p{IDC}*/
, and even that isn’t thinking about the punctuation variables or package variables.
If you are checking for whitespace, then you should choose between \h
and \v
, depending. And you should never use \s
, since it DOES NOT MEAN [\h\v]
, contrary to popular belief.
If you are using \n
for a line boundary, or even \r\n
, then you are doing it wrong. You have to use \R
, which is not the same!
If you don’t know when and whether to call Unicode::Stringprep, then you had better learn.
Case-insensitive comparisons need to check for whether two things are the same letters no matter their diacritics and such. The easiest way to do that is with the standard Unicode::Collate module. Unicode::Collate->new(level => 1)->cmp($a, $b)
. There are also eq
methods and such, and you should probably learn about the match
and substr
methods, too. These are have distinct advantages over the built-ins.
Sometimes that’s still not enough, and you need the Unicode::Collate::Locale module instead, as in Unicode::Collate::Locale->new(locale => "de__phonebook", level => 1)->cmp($a, $b)
instead. Consider that Unicode::Collate::->new(level => 1)->eq("d", "ð")
is true, but Unicode::Collate::Locale->new(locale=>"is",level => 1)->eq("d", " ð")
is false. Similarly, "ae" and "æ" are eq
if you don’t use locales, or if you use the English one, but they are different in the Icelandic locale. Now what? It’s tough, I tell you. You can play with ucsort to test some of these things out.
Consider how to match the pattern CVCV (consonsant, vowel, consonant, vowel) in the string “niño”. Its NFD form — which you had darned well better have remembered to put it in — becomes “nin\x{303}o”. Now what are you going to do? Even pretending that a vowel is [aeiou]
(which is wrong, by the way), you won’t be able to do something like (?=[aeiou])\X)
either, because even in NFD a code point like ‘ø’ does not decompose! However, it will test equal to an ‘o’ using the UCA comparison I just showed you. You can’t rely on NFD, you have to rely on UCA.
And that’s not all. There are a million broken assumptions that people make about Unicode. Until they understand these things, their code will be broken.
Code that assumes it can open a text file without specifying the encoding is broken.
Code that assumes the default encoding is some sort of native platform encoding is broken.
Code that assumes that web pages in Japanese or Chinese take up less space in UTF-16 than in UTF-8 is wrong.
Code that assumes Perl uses UTF-8 internally is wrong.
Code that assumes that encoding errors will always raise an exception is wrong.
Code that assumes Perl code points are limited to 0x10_FFFF is wrong.
Code that assumes you can set $/
to something that will work with any valid line separator is wrong.
Code that assumes roundtrip equality on casefolding, like lc(uc($s)) eq $s
or uc(lc($s)) eq $s
, is completely broken and wrong. Consider that the uc("s")
and uc("?")
are both "S"
, but lc("S")
cannot possibly return both of those.
Code that assumes every lowercase code point has a distinct uppercase one, or vice versa, is broken. For example, "ª"
is a lowercase letter with no uppercase; whereas both "?"
and "?"
are letters, but they are not lowercase letters; however, they are both lowercase code points without corresponding uppercase versions. Got that? They are not \p{Lowercase_Letter}
, despite being both \p{Letter}
and \p{Lowercase}
.
Code that assumes changing the case doesn’t change the length of the string is broken.
Code that assumes there are only two cases is broken. There’s also titlecase.
Code that assumes only letters have case is broken. Beyond just letters, it turns out that numbers, symbols, and even marks have case. In fact, changing the case can even make something change its main general category, like a \p{Mark}
turning into a \p{Letter}
. It can also make it switch from one script to another.
Code that assumes that case is never locale-dependent is broken.
Code that assumes Unicode gives a fig about POSIX locales is broken.
Code that assumes you can remove diacritics to get at base ASCII letters is evil, still, broken, brain-damaged, wrong, and justification for capital punishment.
Code that assumes that diacritics \p{Diacritic}
and marks \p{Mark}
are the same thing is broken.
Code that assumes \p{GC=Dash_Punctuation}
covers as much as \p{Dash}
is broken.
Code that assumes dash, hyphens, and minuses are the same thing as each other, or that there is only one of each, is broken and wrong.
Code that assumes every code point takes up no more than one print column is broken.
Code that assumes that all \p{Mark}
characters take up zero print columns is broken.
Code that assumes that characters which look alike are alike is broken.
Code that assumes that characters which do not look alike are not alike is broken.
Code that assumes there is a limit to the number of code points in a row that just one \X
can match is wrong.
Code that assumes \X
can never start with a \p{Mark}
character is wrong.
Code that assumes that \X
can never hold two non-\p{Mark}
characters is wrong.
Code that assumes that it cannot use "\x{FFFF}"
is wrong.
Code that assumes a non-BMP code point that requires two UTF-16 (surrogate) code units will encode to two separate UTF-8 characters, one per code unit, is wrong. It doesn’t: it encodes to single code point.
Code that transcodes from UTF-16 or UTF-32 with leading BOMs into UTF-8 is broken if it puts a BOM at the start of the resulting UTF-8. This is so stupid the engineer should have their eyelids removed.
Code that assumes the CESU-8 is a valid UTF encoding is wrong. Likewise, code that thinks encoding U+0000 as "\xC0\x80"
is UTF-8 is broken and wrong. These guys also deserve the eyelid treatment.
Code that assumes characters like >
always points to the right and <
always points to the left are wrong — because they in fact do not.
Code that assumes if you first output character X
and then character Y
, that those will show up as XY
is wrong. Sometimes they don’t.
Code that assumes that ASCII is good enough for writing English properly is stupid, shortsighted, illiterate, broken, evil, and wrong. Off with their heads! If that seems too extreme, we can compromise: henceforth they may type only with their big toe from one foot. (The rest will be duct taped.)
Code that assumes that all \p{Math}
code points are visible characters is wrong.
Code that assumes \w
contains only letters, digits, and underscores is wrong.
Code that assumes that ^
and ~
are punctuation marks is wrong.
Code that assumes that ü
has an umlaut is wrong.
Code that believes things like ?
contain any letters in them is wrong.
Code that believes \p{InLatin}
is the same as \p{Latin}
is heinously broken.
Code that believe that \p{InLatin}
is almost ever useful is almost certainly wrong.
Code that believes that given $FIRST_LETTER
as the first letter in some alphabet and $LAST_LETTER
as the last letter in that same alphabet, that [${FIRST_LETTER}-${LAST_LETTER}]
has any meaning whatsoever is almost always complete broken and wrong and meaningless.
Code that believes someone’s name can only contain certain characters is stupid, offensive, and wrong.
Code that tries to reduce Unicode to ASCII is not merely wrong, its perpetrator should never be allowed to work in programming again. Period. I’m not even positive they should even be allowed to see again, since it obviously hasn’t done them much good so far.
Code that believes there’s some way to pretend textfile encodings don’t exist is broken and dangerous. Might as well poke the other eye out, too.
Code that converts unknown characters to ?
is broken, stupid, braindead, and runs contrary to the standard recommendation, which says NOT TO DO THAT! RTFM for why not.
Code that believes it can reliably guess the encoding of an unmarked textfile is guilty of a fatal mélange of hubris and naïveté that only a lightning bolt from Zeus will fix.
Code that believes you can use printf
widths to pad and justify Unicode data is broken and wrong.
Code that believes once you successfully create a file by a given name, that when you run ls
or readdir
on its enclosing directory, you’ll actually find that file with the name you created it under is buggy, broken, and wrong. Stop being surprised by this!
Code that believes UTF-16 is a fixed-width encoding is stupid, broken, and wrong. Revoke their programming licence.
Code that treats code points from one plane one whit differently than those from any other plane is ipso facto broken and wrong. Go back to school.
Code that believes that stuff like /s/i
can only match "S"
or "s"
is broken and wrong. You’d be surprised.
Code that uses \PM\pM*
to find grapheme clusters instead of using \X
is broken and wrong.
People who want to go back to the ASCII world should be whole-heartedly encouraged to do so, and in honor of their glorious upgrade they should be provided gratis with a pre-electric manual typewriter for all their data-entry needs. Messages sent to them should be sent via an ??????s telegraph at 40 characters per line and hand-delivered by a courier. STOP.
I don’t know how much more “default Unicode in ” you can get than what I’ve written. Well, yes I do: you should be using Unicode::Collate
and Unicode::LineBreak
, too. And probably more.
As you see, there are far too many Unicode things that you really do have to worry about for there to ever exist any such thing as “default to Unicode”.
What you’re going to discover, just as we did back in 5.8, that it is simply impossible to impose all these things on code that hasn’t been designed right from the beginning to account for them. Your well-meaning selfishness just broke the entire world.
And even once you do, there are still critical issues that require a great deal of thought to get right. There is no switch you can flip. Nothing but brain, and I mean real brain, will suffice here. There’s a heck of a lot of stuff you have to learn. Modulo the retreat to the manual typewriter, you simply cannot hope to sneak by in ignorance. This is the 21?? century, and you cannot wish Unicode away by willful ignorance.
You have to learn it. Period. It will never be so easy that “everything just works,” because that will guarantee that a lot of things don’t work — which invalidates the assumption that there can ever be a way to “make it all work.”
You may be able to get a few reasonable defaults for a very few and very limited operations, but not without thinking about things a whole lot more than I think you have.
As just one example, canonical ordering is going to cause some real headaches. "\x{F5}"
‘õ’, "o\x{303}"
‘õ’, "o\x{303}\x{304}"
‘?’, and "o\x{304}\x{303}"
‘o~’ should all match ‘õ’, but how in the world are you going to do that? This is harder than it looks, but it’s something you need to account for.
If there’s one thing I know about Perl, it is what its Unicode bits do and do not do, and this thing I promise you: “ _?_?_?_?_?_ _?_s_ _?_?_ _U_?_?_?_?_?_?_ _?_?_?_?_?_ _?_?_?_?_?_?_ _ ”
You cannot just change some defaults and get smooth sailing. It’s true that I run with PERL_UNICODE
set to "SA"
, but that’s all, and even that is mostly for command-line stuff. For real work, I go through all the many steps outlined above, and I do it very, ** very** carefully.
You can declare columns/variables as varchar2(n CHAR) and varchar2(n byte).
n CHAR means the variable will hold n characters. In multi byte character sets you don't always know how many bytes you want to store, but you do want to garantee the storage of a certain amount of characters.
n bytes means simply the number of bytes you want to store.
varchar is deprecated. Do not use it. What is the difference between varchar and varchar2?
Create a list with type<DataRow>
by extend the datatable
with AsEnumerable
call.
var mylist = dt.AsEnumerable().ToList();
Cheers!! Happy Coding
JMF was abandoned. VLC is more up to date and it reads everything. https://stackoverflow.com/a/5160010
I think vlc beats every other software out there yet, or at least the ones that I know...
Step 1) Create Profile and Account
You need to create a profile and account using the Configure Database Mail Wizard which can be accessed from the Configure Database Mail context menu of the Database Mail node in Management Node. This wizard is used to manage accounts, profiles, and Database Mail global settings.
Step 2)
RUN:
sp_CONFIGURE 'show advanced', 1
GO
RECONFIGURE
GO
sp_CONFIGURE 'Database Mail XPs', 1
GO
RECONFIGURE
GO
Step 3)
USE msdb
GO
EXEC sp_send_dbmail @profile_name='yourprofilename',
@recipients='[email protected]',
@subject='Test message',
@body='This is the body of the test message.
Congrates Database Mail Received By you Successfully.'
To loop through the table
DECLARE @email_id NVARCHAR(450), @id BIGINT, @max_id BIGINT, @query NVARCHAR(1000)
SELECT @id=MIN(id), @max_id=MAX(id) FROM [email_adresses]
WHILE @id<=@max_id
BEGIN
SELECT @email_id=email_id
FROM [email_adresses]
set @query='sp_send_dbmail @profile_name=''yourprofilename'',
@recipients='''+@email_id+''',
@subject=''Test message'',
@body=''This is the body of the test message.
Congrates Database Mail Received By you Successfully.'''
EXEC @query
SELECT @id=MIN(id) FROM [email_adresses] where id>@id
END
Posted this on the following link http://ms-sql-queries.blogspot.in/2012/12/how-to-send-email-from-sql-server.html
I'd like to add another method. This one uses recursive querys, something I haven't seen in the other answers. It is supported by Oracle since 11gR2.
with cte0 as (
select phone_number x
from hr.employees
), cte1(xstr,xrest,xremoved) as (
select x, x, null
from cte0
union all
select xstr,
case when instr(xrest,'.') = 0 then null else substr(xrest,instr(xrest,'.')+1) end,
case when instr(xrest,'.') = 0 then xrest else substr(xrest,1,instr(xrest,'.') - 1) end
from cte1
where xrest is not null
)
select xstr, xremoved from cte1
where xremoved is not null
order by xstr
It is quite flexible with the splitting character. Simply change it in the INSTR
calls.
Complete walkthrough of writing setup.py
scripts here. (with some examples)
If you'd like a real-world example, I could point you towards the setup.py
scripts of a couple major projects. Django's is here, pyglet's is here. You can just browse the source of other projects for a file named setup.py for more examples.
These aren't simple examples; the tutorial link I gave has those. These are more complex, but also more practical.
UPDATE 2: without seconds option
UPDATE: AM after noon corrected, tested: http://jsfiddle.net/aorcsik/xbtjE/
I created this function to do this:
function formatDate(date) {_x000D_
var d = new Date(date);_x000D_
var hh = d.getHours();_x000D_
var m = d.getMinutes();_x000D_
var s = d.getSeconds();_x000D_
var dd = "AM";_x000D_
var h = hh;_x000D_
if (h >= 12) {_x000D_
h = hh - 12;_x000D_
dd = "PM";_x000D_
}_x000D_
if (h == 0) {_x000D_
h = 12;_x000D_
}_x000D_
m = m < 10 ? "0" + m : m;_x000D_
_x000D_
s = s < 10 ? "0" + s : s;_x000D_
_x000D_
/* if you want 2 digit hours:_x000D_
h = h<10?"0"+h:h; */_x000D_
_x000D_
var pattern = new RegExp("0?" + hh + ":" + m + ":" + s);_x000D_
_x000D_
var replacement = h + ":" + m;_x000D_
/* if you want to add seconds_x000D_
replacement += ":"+s; */_x000D_
replacement += " " + dd;_x000D_
_x000D_
return date.replace(pattern, replacement);_x000D_
}_x000D_
_x000D_
alert(formatDate("February 04, 2011 12:00:00"));
_x000D_
If working on EJB client library:
You need to mention the argument for getting the initial context.
InitialContext ctx = new InitialContext();
If you do not, it will look in the project folder for properties file. Also you can include the properties credentials or values in your class file itself as follows:
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
props.put(Context.PROVIDER_URL, "jnp://localhost:1099");
InitialContext ctx = new InitialContext(props);
URL_PKG_PREFIXES: Constant that holds the name of the environment property for specifying the list of package prefixes to use when loading in URL context factories.
The EJB client library is the primary library to invoke remote EJB components.
This library can be used through the InitialContext. To invoke EJB components the library creates an EJB client context via a URL context factory. The only necessary configuration is to parse the value org.jboss.ejb.client.naming for the java.naming.factory.url.pkgs property to instantiate an InitialContext.
What about:
git reset
back to the last commit before you started making changes.git pull
to re-pull just the remote changes you threw away with the reset.Or will that explode when you try to re-merge the branch?
There is a little known feature, which makes this even better. You can use a configurable default value instead of a hard-coded one, here is an example:
config.properties:
timeout.default=30
timeout.myBean=60
context.xml:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>config.properties</value>
</property>
</bean>
<bean id="myBean" class="Test">
<property name="timeout" value="${timeout.myBean:${timeout.default}}" />
</bean>
To use the default while still being able to easily override later, do this in config.properties:
timeout.myBean = ${timeout.default}
There is nothing wrong with the example you have given. But i must say i believe it's not efficient to store function definitions in a cpp file. I only understand the need to separate the function's declaration and definition.
When used together with explicit class instantiation, the Boost Concept Check Library (BCCL) can help you generate template function code in cpp files.
this is an old post but...
just surprised that nobody talk about pg_hba file as it can be a good reason to get this error code.
Check here for those who forgot to configure it: http://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html
Changing "Build Active Architectures Only" to Yes in CordovaLib.xcodeproj -> Build Settings did the trick for me. earlier the app was running on simulator, but not on the device.
I needed this instead of using padding because I used inline-block containers to display a series of individual events in a workflow timeline. The last event in the timeline needed no arrow after it.
Ended up with something like:
.transaction-tile:after {
content: "\f105";
}
.transaction-tile:last-child:after {
content: "\00a0";
}
Used fontawesome for the gt (chevron) character. For whatever reason "content: none;" was producing alignment issues on the last tile.
Add multiple connection strings in your web.config or app.config.
Then you can get them as a string like :
System.Configuration.ConfigurationManager.
ConnectionStrings["entityFrameworkConnection"].ConnectionString;
Then use the string to set :
Provider
Metadata
ProviderConnectionString
It is better explained here :
In Windows (command prompt) you can use CertUtil, here is the syntax:
CertUtil [Options] -hashfile InFile [HashAlgorithm]
for syntax explanation type in cmd:
CertUtil -hashfile -?
example:
CertUtil -hashfile C:\myFile.txt MD5
default is SHA1 it supports: MD2, MD4, MD5, SHA1, SHA256, SHA384, SHA512. Unfortunately no CRC32 as Unix shell does.
Here is a link if you want to find out more https://technet.microsoft.com/en-us/library/cc732443.aspx#BKMK_menu
The SAMPLE clause will give you a random sample percentage of all rows in a table.
For example, here we obtain 25% of the rows:
SELECT * FROM emp SAMPLE(25)
The following SQL (using one of the analytical functions) will give you a random sample of a specific number of each occurrence of a particular value (similar to a GROUP BY) in a table.
Here we sample 10 of each:
SELECT * FROM (
SELECT job, sal, ROW_NUMBER()
OVER (
PARTITION BY job ORDER BY job
) SampleCount FROM emp
)
WHERE SampleCount <= 10
We had a problem like this some weeks before. If you set a breakpoint and have a deep look into this.Controls
, the problem reveals it's nature: you have to recurse through all child controls.
The code could look like this:
private void CleanForm()
{
traverseControlsAndSetTextEmpty(this);
}
private void traverseControlsAndSetTextEmpty(Control control)
{
foreach(var c in control.Controls)
{
if (c is TextBox) ((TextBox)c).Text = String.Empty;
traverseControlsAndSetTextEmpty(c);
}
}
Jackson has an XmlMapper which will support this out of the box, no need to write any code at all.
Here's a nice tutorial https://www.baeldung.com/jackson-xml-serialization-and-deserialization
Maven dependency:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.8</version>
</dependency>
For writing a Map
to xml:
Map<String, String> map = new HashMap<>();
map.put("SomeKey", "someValue");
XmlMapper mapper = new XmlMapper();
String xml = mapper.writeValueAsString(map);
Will give you
<HashMap><SomeKey>someValue</SomeKey></HashMap>
I was able to customise the root element by creating a HashMap
subclass
@JacksonXmlRootElement(localName = "MyRootElement")
public class XmlHashMap<K, V> extends HashMap<K, V>
{
}
So now
Map<String, String> map = new XmlHashMap<>();
map.put("SomeKey", "someValue");
XmlMapper mapper = new XmlMapper();
String xml = mapper.writeValueAsString(map);
Will give you
<MyRootElement><SomeKey>someValue</SomeKey></MyRootElement>
There is no built-in way (yet) of reversing arbitrary colormaps, but one simple solution is to actually not modify the colorbar but to create an inverting Normalize object:
from matplotlib.colors import Normalize
class InvertedNormalize(Normalize):
def __call__(self, *args, **kwargs):
return 1 - super(InvertedNormalize, self).__call__(*args, **kwargs)
You can then use this with plot_surface
and other Matplotlib plotting functions by doing e.g.
inverted_norm = InvertedNormalize(vmin=10, vmax=100)
ax.plot_surface(..., cmap=<your colormap>, norm=inverted_norm)
This will work with any Matplotlib colormap.
Unless you're doing vector graphics, there's no way to resize an image without potentially losing some image quality.
You can easlity configure SQLite with swift using single ton class as well.
Refer
https://github.com/hasyapanchasara/SQLite_SingleManagerClass
Method to create database
func methodToCreateDatabase() -> NSURL?{}
Method to insert, update and delete data
func methodToInsertUpdateDeleteData(strQuery : String) -> Bool{}
Method to select data
func methodToSelectData(strQuery : String) -> NSMutableArray{}
The correct answer is the following:
import numpy
numpy.shape(a)
In older versions of jquery you'll have to do it the "javascript way" using settimeout
setTimeout( function(){$('div').hide();} , 4000);
or
setTimeout( "$('div').hide();", 4000);
Recently with jquery 1.4 this solution has been added:
$("div").delay(4000).hide();
Of course replace "div" by the correct element using a valid jquery selector and call the function when the document is ready.
I was running mongod in a PowerShell instance. I was not getting any output in the powershell console from mongod. I clicked on the PowerShell instance where mongod was running, hit enter and and execution resumed. I am not sure what caused the execution to halt, but I can connect to this instance of mongo immediately now.
If another function needs to use a variable you pass it to the function as an argument.
Also global variables are not inherently nasty and evil. As long as they are used properly there is no problem with them.
You can also patern :
DF[DF.col.str.contains(pat = '(foo)', regex = True) ]
// Some more complex constant variable/pointer declaration.
// Observing cases when we get error and warning would help
// understanding it better.
int main(void)
{
char ca1[10]= "aaaa"; // char array 1
char ca2[10]= "bbbb"; // char array 2
char *pca1= ca1;
char *pca2= ca2;
char const *ccs= pca1;
char * const csc= pca2;
ccs[1]='m'; // Bad - error: assignment of read-only location ‘*(ccs + 1u)’
ccs= csc; // Good
csc[1]='n'; // Good
csc= ccs; // Bad - error: assignment of read-only variable ‘csc’
char const **ccss= &ccs; // Good
char const **ccss1= &csc; // Bad - warning: initialization from incompatible pointer type
char * const *cscs= &csc; // Good
char * const *cscs1= &ccs; // Bad - warning: initialization from incompatible pointer type
char ** const cssc= &pca1; // Good
char ** const cssc1= &ccs; // Bad - warning: initialization from incompatible pointer type
char ** const cssc2= &csc; // Bad - warning: initialization discards ‘const’
// qualifier from pointer target type
*ccss[1]= 'x'; // Bad - error: assignment of read-only location ‘**(ccss + 8u)’
*ccss= ccs; // Good
*ccss= csc; // Good
ccss= ccss1; // Good
ccss= cscs; // Bad - warning: assignment from incompatible pointer type
*cscs[1]= 'y'; // Good
*cscs= ccs; // Bad - error: assignment of read-only location ‘*cscs’
*cscs= csc; // Bad - error: assignment of read-only location ‘*cscs’
cscs= cscs1; // Good
cscs= cssc; // Good
*cssc[1]= 'z'; // Good
*cssc= ccs; // Bad - warning: assignment discards ‘const’
// qualifier from pointer target type
*cssc= csc; // Good
*cssc= pca2; // Good
cssc= ccss; // Bad - error: assignment of read-only variable ‘cssc’
cssc= cscs; // Bad - error: assignment of read-only variable ‘cssc’
cssc= cssc1; // Bad - error: assignment of read-only variable ‘cssc’
}
Within an htaccess file, the scope of the <Files>
directive only applies to that directory (I guess to avoid confusion when rules/directives in the htaccess of subdirectories get applied superceding ones from the parent).
So you can have:
<Files "log.txt">
Order Allow,Deny
Deny from all
</Files>
For Apache 2.4+, you'd use:
<Files "log.txt">
Require all denied
</Files>
In an htaccess file in your inscription
directory. Or you can use mod_rewrite to sort of handle both cases deny access to htaccess file as well as log.txt:
RewriteRule /?\.htaccess$ - [F,L]
RewriteRule ^/?inscription/log\.txt$ - [F,L]
You're almost there. As you can see, the onItemSelected
will give you a position
parameter, you can use this to retrieve the object from your adapter, as in getItemAtPosition(position)
.
Example:
spinner.setOnItemSelectedListener(this);
...
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
This will put a message on screen, with the selected item printed by its toString() method.
int a, b;
int c = a / b;
if(a % b) { c++; }
Checking if there is a remainder allows you to manually roundup the quotient of integer division.
result = soup.find('strong', text='text I am looking for').text
There's the more general but perhaps not as helpful to you Wireshark.
One of the SO server sites might be better suited for your question. In fact, it's already been asked on SuperUser.
Use the entity code  
instead.
is a HTML "character entity reference". There is no named entity for non-breaking space in XML, so you use the code  
.
Wikipedia includes a list of XML and HTML entities, and you can see that there are only 5 "predefined entities" in XML, but HTML has over 200. I'll also point over to Creating a space ( ) in XSL which has excellent answers.
Pretty straight forward, use relative path
string[] offerFiles = Directory.GetFiles(Server.MapPath("~/offers"), "*.csv");
You should use setState
function. If not, state won't save your change, no matter how you use forceUpdate.
Container {
handleEvent= () => { // use arrow function
//this.props.foo.bar = 123
//You should use setState to set value like this:
this.setState({foo: {bar: 123}});
};
render() {
return <Child bar={this.state.foo.bar} />
}
Child {
render() {
return <div>{this.props.bar}</div>
}
}
}
Your code seems not valid. I can not test this code.
git rm --cached file
will remove the file from the stage. That is, when you commit the file will be removed. git reset HEAD -- file
will simply reset file in the staging area to the state where it was on the HEAD commit, i.e. will undo any changes you did to it since last commiting. If that change happens to be newly adding the file, then they will be equivalent.
A bit of a cleaner way to do this:
SELECT DC.[name]
FROM [sys].[default_constraints] AS DC
WHERE DC.[parent_object_id] = OBJECT_ID('[Schema].[TableName]')
Well, according to the mysql_real_escape_string function reference page: "mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which escapes the following characters: \x00, \n, \r, \, ', " and \x1a."
With that in mind, then the function given in the second link you posted should do exactly what you need:
function mres($value)
{
$search = array("\\", "\x00", "\n", "\r", "'", '"', "\x1a");
$replace = array("\\\\","\\0","\\n", "\\r", "\'", '\"', "\\Z");
return str_replace($search, $replace, $value);
}
Straight from the Java Language Specification:
A method that is
native
is implemented in platform-dependent code, typically written in another programming language such as C, C++, FORTRAN,or assembly language. The body of anative
method is given as a semicolon only, indicating that the implementation is omitted, instead of a block.
Use the Character.toString()
method like so:
char mChar = 'l';
String s = Character.toString(mChar);
Here is an example:
MySqlConnection con = new MySqlConnection(
"Server=ServerName;Database=DataBaseName;UID=username;Password=password");
MySqlCommand cmd = new MySqlCommand(
" INSERT Into Test (lat, long) VALUES ('"+OSGconv.deciLat+"','"+
OSGconv.deciLon+"')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
You can achieve it using the library SectionedRecyclerViewAdapter, it has the concept of "Sections", where which Section has a Header, Footer and Content (list of items). In your case you might only need one Section but you can have many:
class MySection extends StatelessSection {
List<String> myList = Arrays.asList(new String[] {"Item1", "Item2", "Item3" });
public MySection() {
// call constructor with layout resources for this Section header, footer and items
super(R.layout.section_header, R.layout.section_footer, R.layout.section_item);
}
@Override
public int getContentItemsTotal() {
return myList.size(); // number of items of this section
}
@Override
public RecyclerView.ViewHolder getItemViewHolder(View view) {
// return a custom instance of ViewHolder for the items of this section
return new MyItemViewHolder(view);
}
@Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
MyItemViewHolder itemHolder = (MyItemViewHolder) holder;
// bind your view here
itemHolder.tvItem.setText(myList.get(position));
}
}
class MyItemViewHolder extends RecyclerView.ViewHolder {
private final TextView tvItem;
public MyItemViewHolder(View itemView) {
super(itemView);
tvItem = (TextView) itemView.findViewById(R.id.tvItem);
}
}
// Create an instance of SectionedRecyclerViewAdapter
SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();
MySection mySection = new MySection();
// Add your Sections
sectionAdapter.addSection(mySection);
// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);
unsigned mod(int a, unsigned b) {
return (a >= 0 ? a % b : b - (-a) % b);
}
The PerlMonks and PerlDoc links from cartman and Olafur are a great reference - below is my crack at a summary:
my
variables are lexically scoped within a single block defined by {}
or within the same file if not in {}
s. They are not accessible from packages/subroutines defined outside of the same lexical scope / block.
our
variables are scoped within a package/file and accessible from any code that use
or require
that package/file - name conflicts are resolved between packages by prepending the appropriate namespace.
Just to round it out, local
variables are "dynamically" scoped, differing from my
variables in that they are also accessible from subroutines called within the same block.
There is a library named Picasso which can efficiently load images from a URL. It can also load an image from a file.
Examples:
Load URL into ImageView without generating a bitmap:
Picasso.with(context) // Context
.load("http://abc.imgur.com/gxsg.png") // URL or file
.into(imageView); // An ImageView object to show the loaded image
Load URL into ImageView by generating a bitmap:
Picasso.with(this)
.load(artistImageUrl)
.into(new Target() {
@Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
/* Save the bitmap or do something with it here */
// Set it in the ImageView
theView.setImageBitmap(bitmap)
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
There are many more options available in Picasso. Here is the documentation.
(note: this answer has been updated on 2014-08-01 to make it more detailed, more accurate, and to add a live demo)
According to W3C CSS2.1 specification (“Omitted values are set to their initial values”), the following properties are equivalent:
border: hidden; border-style: hidden;
border-width: medium;
border-color: <the same as 'color' property>
border: none; border-style: none;
border-width: medium;
border-color: <the same as 'color' property>
border: 0; border-style: none;
border-width: 0;
border-color: <the same as 'color' property>
If these rules are the most specific ones applied to the borders of an element, then the borders won't be shown, either because of zero-width, or because of hidden
/none
style. So, at the first look, these three rules look equivalent. However, they behave in different ways when combined with other rules.
When a table is rendered using border-collapse: collapse
, then each rendered border is shared between multiple elements (inner borders are shared among as neighbor cells; outer borders are shared between cells and the table itself; but also rows, row groups, columns and column groups share borders). The specification defines some rules for border conflict resolution:
Borders with the
border-style
ofhidden
take precedence over all other conflicting borders. […]Borders with a style of
none
have the lowest priority. […]If none of the styles are
hidden
and at least one of them is notnone
, then narrow borders are discarded in favor of wider ones. […]If border styles differ only in color, […]
So, in a table context, border: hidden
(or border-style: hidden
) will have the highest priority and will make the shared border hidden, no matter what.
On the other end of the priorities, border: none
(or border-style: none
) have the lowest priority, followed by the zero-width border (because it is the narrowest border). This means that a computed value of border-style: none
and a computed value of border-width: 0
are essentially the same.
Since none
and 0
affect different properties (border-style
and border-width
), they will behave differently when a more specific rule defines just the style or just the width. See Chris answer for an example.
Want to see all these cases in one single page? Open the live demo!
I had similar problem - I want to replace picture on :hover but can't use BACKGRUND-IMAGE due to lack of Bootstrap's adaptive design.
If you like me only want to change the picture on :hover (but not insist of change SRC for the certain image tag) you can do something like this - it's CSS-only solution.
HTML:
<li>
<img src="/picts/doctors/SmallGray/Zharkova_smallgrey.jpg">
<img class="hoverPhoto" src="/picts/doctors/Small/Zharkova_small.jpg">
</li>
CSS:
li { position: relative; overflow: hidden; }
li img.hoverPhoto {
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
opacity: 0;
}
li.hover img { /* it's optional - for nicer transition effect */
opacity: 0;
-web-kit-transition: opacity 1s ease;
-moz-transition: opacity 1s ease;li
-o-transition: opacity 1s ease;
transition: opacity 1s ease;
}
li.hover img.hoverPhoto { opacity: 1; }
If you want IE7-compatible code you may hide/show :HOVER image by positioning not by opacity.
How about this?
fscanf(file,"%d %d %d %d %d %d %d",&line1_1,&line1_2, &line1_3, &line2_1, &line2_2, &line3_1, &line3_2);
In this case spaces in fscanf
match multiple occurrences of any whitespace until the next token in found.
Add a property to the form method="post"
.
Like this:
<form name="loginform" method="post">
The SUBTOTAL
function can be used if you want to get the count respecting any filters you use on the page.
=SUBTOTAL(103, A1:A200)
will help you get count of non-empty rows, respecting filters.
103 - is similar to COUNTA
, but ignores empty rows and also respects filters.
Reference : SUBTOTAL function
$(document).ready(function() {
$("#raaagh").click(function() {
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data) {
console.log(data);
$.ajax({
url:'ajax.php',
data: data,
dataType:'json',
success:function(data1) {
var y1=data1;
console.log(data1);
}
});
}
});
});
});
Use like this, first make a ajax call to get data, then your php function will return u the result which u wil get in data and pass that data to the new ajax call
When the ASP.NET Web API calls a method on a controller, it must set values for the parameters, a process called parameter binding.
By default, Web API uses the following rules to bind parameters:
If the parameter is a "simple" type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string.
For complex types, Web API tries to read the value from the message body, using a media-type formatter.
So, if you want to override the above default behaviour and force Web API to read a complex type from the URI, add the [FromUri]
attribute to the parameter. To force Web API to read a simple type from the request body, add the [FromBody]
attribute to the parameter.
So, to answer your question, the need of the [FromBody]
and [FromUri]
attributes in Web API is simply to override, if necessary, the default behaviour as described above. Note that you can use both attributes for a controller method, but only for different parameters, as demonstrated here.
There is a lot more information on the web if you google "web api parameter binding".
If you want to display more column values without an aggregation function use GROUPING SETS
instead of ROLLUP
:
SELECT
Type = ISNULL(Type, 'Total'),
SomeIntColumn = ISNULL(SomeIntColumn, 0),
TotalSales = SUM(TotalSales)
FROM atable
GROUP BY GROUPING SETS ((Type, SomeIntColumn ), ())
ORDER BY SomeIntColumn --Displays summary row as the first row in query result
My C# / LINQ solution is based on the cross product advice of @charlesbretana is below. You can specify a reference normal for the winding. It should work as long as the curve is mostly in the plane defined by the up vector.
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
namespace SolidworksAddinFramework.Geometry
{
public static class PlanePolygon
{
/// <summary>
/// Assumes that polygon is closed, ie first and last points are the same
/// </summary>
public static bool Orientation
(this IEnumerable<Vector3> polygon, Vector3 up)
{
var sum = polygon
.Buffer(2, 1) // from Interactive Extensions Nuget Pkg
.Where(b => b.Count == 2)
.Aggregate
( Vector3.Zero
, (p, b) => p + Vector3.Cross(b[0], b[1])
/b[0].Length()/b[1].Length());
return Vector3.Dot(up, sum) > 0;
}
}
}
with a unit test
namespace SolidworksAddinFramework.Spec.Geometry
{
public class PlanePolygonSpec
{
[Fact]
public void OrientationShouldWork()
{
var points = Sequences.LinSpace(0, Math.PI*2, 100)
.Select(t => new Vector3((float) Math.Cos(t), (float) Math.Sin(t), 0))
.ToList();
points.Orientation(Vector3.UnitZ).Should().BeTrue();
points.Reverse();
points.Orientation(Vector3.UnitZ).Should().BeFalse();
}
}
}
Or maybe:
var options = $("#options");
$.each(data, function() {
options.append(new Option(this.text, this.value));
});
SELECT (
SELECT COUNT(*)
FROM user_table
) AS tot_user,
(
SELECT COUNT(*)
FROM cat_table
) AS tot_cat,
(
SELECT COUNT(*)
FROM course_table
) AS tot_course
For android, Use: https://developer.android.com/reference/android/net/Uri#buildUpon()
URI oldUri = new URI(uri);
Uri.Builder builder = oldUri.buildUpon();
builder.appendQueryParameter("newParameter", "dummyvalue");
Uri newUri = builder.build();
for (char letter = 'A'; letter <= 'Z'; letter++)
{
Debug.WriteLine(letter);
}
A performance comparison:
import itertools
import timeit
big_list = [[0]*1000 for i in range(1000)]
timeit.repeat(lambda: list(itertools.chain.from_iterable(big_list)), number=100)
timeit.repeat(lambda: list(itertools.chain(*big_list)), number=100)
timeit.repeat(lambda: (lambda b: map(b.extend, big_list))([]), number=100)
timeit.repeat(lambda: [el for list_ in big_list for el in list_], number=100)
[100*x for x in timeit.repeat(lambda: sum(big_list, []), number=1)]
Producing:
>>> import itertools
>>> import timeit
>>> big_list = [[0]*1000 for i in range(1000)]
>>> timeit.repeat(lambda: list(itertools.chain.from_iterable(big_list)), number=100)
[3.016212113769325, 3.0148865239060227, 3.0126415732791028]
>>> timeit.repeat(lambda: list(itertools.chain(*big_list)), number=100)
[3.019953987082083, 3.528754223385439, 3.02181439266457]
>>> timeit.repeat(lambda: (lambda b: map(b.extend, big_list))([]), number=100)
[1.812084445152557, 1.7702404451095965, 1.7722977998725362]
>>> timeit.repeat(lambda: [el for list_ in big_list for el in list_], number=100)
[5.409658160700605, 5.477502077679354, 5.444318360412744]
>>> [100*x for x in timeit.repeat(lambda: sum(big_list, []), number=1)]
[399.27587954973444, 400.9240571138051, 403.7521153804846]
This is with Python 2.7.1 on Windows XP 32-bit, but @temoto in the comments above got from_iterable
to be faster than map+extend
, so it's quite platform and input dependent.
Stay away from sum(big_list, [])
This is what I use to upload the image through upload window:
//open upload window
upload.click();
//put path to your image in a clipboard
StringSelection ss = new StringSelection("C:\\IMG_3827.JPG");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
//imitate mouse events like ENTER, CTRL+C, CTRL+V
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
done
I had the same problem and as many others here have said none of the normal Kill commands worked. My problem file was an executable that was being run from a network share by a user on a Remote Desktop Server. With multiple shared users not an easy thing to restart in during a work day. Even when the user logged off the exe was still listed in Task Manager. I sent to the server where the folder was shared and from Computer Management -> Sessions found the user with the session still open from that RDP server even though he was logged off. Right Click -> Close Session and the file lock was released.
Beats me why I couldn't end the taks. The error message I was originally getting when I try and delete the file was "The action can't be completed because the file is open in System"
Hope this helps someone else.
I did try all the answers above and had no luck. After that I restart my iPhone and problem seems gone. I know it is so stupid but it worked. Answers above most probably solves the problem but if not try to restart your iOS device.
An engineered way to solve this if you already have files you need to push to Github/Server:
In Github/Server where your repo will live:
<YourPathAndRepoName>
)$git init --bare
Local Computer (Just put in any folder):
$touch .gitignore
$git clone <YourPathAndRepoName>
(This will create an empty folder with your Repo Name from Github/Server)
(Legitimately copy and paste all your files from wherever and paste them into this empty Repo)
$git add . && git commit -m "First Commit"
$git push origin master
select unique is not valid syntax for what you are trying to do
you want to use either select distinct or select distinctrow
And actually, you don't even need distinct/distinctrow in what you are trying to do. You can eliminate duplicates by choosing the appropriate union statement parameters.
the below query by itself will only provide distinct values
select col from table1
union
select col from table2
if you did want duplicates you would have to do
select col from table1
union all
select col from table2
Try this
DataSet ds = new DataSet("TimeRanges");
using(SqlConnection conn = new SqlConnection("ConnectionString"))
{
SqlCommand sqlComm = new SqlCommand("Procedure1", conn);
sqlComm.Parameters.AddWithValue("@Start", StartTime);
sqlComm.Parameters.AddWithValue("@Finish", FinishTime);
sqlComm.Parameters.AddWithValue("@TimeRange", TimeRange);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
in your HTML : <input type="file" id="yourFile">
don't forget to reference your js file or put the following script between <script></script>
in your script :
var fileToRead = document.getElementById("yourFile");
fileToRead.addEventListener("change", function(event) {
var files = fileToRead.files;
if (files.length) {
console.log("Filename: " + files[0].name);
console.log("Type: " + files[0].type);
console.log("Size: " + files[0].size + " bytes");
}
}, false);
You can't use forward declaration with the typedef struct.
The struct itself is an anonymous type, so you don't have an actual name to forward declare.
typedef struct{
int one;
int two;
}myStruct;
A forward declaration like this wont work:
struct myStruct; //forward declaration fails
void blah(myStruct* pStruct);
//error C2371: 'myStruct' : redefinition; different basic types
Use:
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
The option you should use is iDisplayLength:
$('#adminProducts').dataTable({
'iDisplayLength': 100
});
$('#table').DataTable({
"lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});
It will Load by default all entries.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
If you want to load by default 25 not all do this.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
});
You can do it the DOM way as well:
var div = document.getElementById('cart_item');
while(div.firstChild){
div.removeChild(div.firstChild);
}
You need to wrap them all in a character class. The current version means replace this sequence of characters with an empty string. When wrapped in square brackets it means replace any of these characters with an empty string.
var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");
Assuming you are fine with your list being printed [1,2,3], then an easy way in Python3 is:
mylist=[1,2,3,'lorem','ipsum','dolor','sit','amet']
print(f"There are {len(mylist):d} items in this lorem list: {str(mylist):s}")
Running this produces the following output:
There are 8 items in this lorem list: [1, 2, 3, 'lorem', 'ipsum', 'dolor', 'sit', 'amet']
For anyone still looking into this in order to learn specifically what a stack is, the term "stack" is referring to a "solution stack." A solution stack is simply a complete set of software to address a given problem, usually by combining to provide the platform or infrastructure necessary. This term is the parent of both "server stack" and "web stack." Accordingly, a LAMP stack is a specific and complete set of software specifically aimed at serving dynamic content over the web.
Some extra reading:
https://www.techopedia.com/definition/28154/solution-stack https://en.wikipedia.org/wiki/Solution_stack
You can use select into inside of a PLSQL block such as below.
Declare
l_variable assignment%rowtype
begin
select *
into l_variable
from assignment;
exception
when no_data_found then
dbms_output.put_line('No record avialable')
when too_many_rows then
dbms_output.put_line('Too many rows')
end;
This code will only work when there is exactly 1 row in assignment. Usually you will use this kind of code to select a specific row identified by a key number.
Declare
l_variable assignment%rowtype
begin
select *
into l_variable
from assignment
where ID=<my id number>;
exception
when no_data_found then
dbms_output.put_line('No record avialable')
when too_many_rows then
dbms_output.put_line('Too many rows')
end;
Both proposed possibilities (std::swap
and std::iter_swap
) work, they just have a slightly different syntax.
Let's swap a vector's first and second element, v[0]
and v[1]
.
We can swap based on the objects contents:
std::swap(v[0],v[1]);
Or swap based on the underlying iterator:
std::iter_swap(v.begin(),v.begin()+1);
Try it:
int main() {
int arr[] = {1,2,3,4,5,6,7,8,9};
std::vector<int> * v = new std::vector<int>(arr, arr + sizeof(arr) / sizeof(arr[0]));
// put one of the above swap lines here
// ..
for (std::vector<int>::iterator i=v->begin(); i!=v->end(); i++)
std::cout << *i << " ";
std::cout << std::endl;
}
Both times you get the first two elements swapped:
2 1 3 4 5 6 7 8 9
You don't need to parse the string, it's defined as a string already.
Just do:
private static String getStringInput (String prompt) {
String input = EZJ.getUserInput(prompt);
return input;
}
If you need to order your code into namespaces, just use the keyword namespace
:
file1.php
namespace foo\bar;
In file2.php
$obj = new \foo\bar\myObj();
You can also use use
. If in file2 you put
use foo\bar as mypath;
you need to use mypath
instead of bar
anywhere in the file:
$obj = new mypath\myObj();
Using use foo\bar;
is equal to use foo\bar as bar;
.
If you have the HTML
<form name="formname" .... id="form-first">
<iframe id="one" src="iframe2.html">
</iframe>
</form>
and JavaScript
function iframeRef( frameRef ) {
return frameRef.contentWindow
? frameRef.contentWindow.document
: frameRef.contentDocument
}
var inside = iframeRef( document.getElementById('one') )
inside
is now a reference to the document, so you can do getElementsByTagName('textarea')
and whatever you like, depending on what's inside the iframe src.
It's worth mentioning that the version from the 140byt.es collection is solving the task within minimum space and is worth a try for this purpose:
Code:
function m(a,b,c){for(c in b)b.hasOwnProperty(c)&&((typeof a[c])[0]=='o'?m(a[c],b[c]):a[c]=b[c])}
Usage for your purpose:
m(obj1,obj2);
Here's the original Gist.
grep is your good friend to achieve this.
grep -r <text_fo_find> <directory>
If you don't care about the case of the text to find, then use:
grep -ir <text_to_find> <directory>
It depends on the context. I think you're referring to the operating system's hostname (returned by hostname
when you're logged in). This command is for internal names only, so to query for a machine's name requires different naming systems. There are multiple systems which use names to identify hosts including DNS, DHCP, LDAP (DN's), hostname
, etc. and many systems use zeroconf to synchronize names between multiple naming systems. For this reason, results from hostname
will sometimes match results from dig
(see below) or other naming systems, but often times they will not match.
DNS is by far the most common and is used both on the internet (like google.com. A 216.58.218.142
) and at home (mDNS/LLMNR), so here's how to perform a reverse DNS lookup: dig -x <address>
(nslookup
and host
are simpler, provide less detail, and may even return different results; however, dig
is not included in Windows).
Note that hostnames within a CDN will not resolve to the canonical domain name (e.g. "google.com"), but rather the hostname of the host IP you queried (e.g. "dfw25s08-in-f142.1e100.net"; interesting tidbit: 1e100 is 1 googol).
Also note that DNS hosts can have more than one name. This is common for hosts with more than one webserver (virtual hosting), although this is becoming less common thanks to the proliferation of virtualization technologies. These hosts have multiple PTR DNS records.
Finally, note that DNS host records can be overridden by the local machine via /etc/hosts. If you're not getting the hostname you expect, be sure you check this file.
DHCP hostnames are queried differently depending on which DHCP server software is used, because (as far as I know) the protocol does not define a method for querying; however, most servers provide some way of doing this (usually with a privileged account).
Note DHCP names are usually synchronized with DNS server(s), so it's common to see the same hostnames in a DHCP client least table and in the DNS server's A (or AAAA for IPv6) records. Again, this is usually done as part of zeroconf.
Also note that just because a DHCP lease exists for a client, doesn't mean it's still being used.
NetBIOS for TCP/IP (NBT) was used for decades to perform name resolution, but has since been replaced by LLMNR for name resolution (part of zeroconf on Windows). This legacy system can still be queried with the nbtstat
(Windows) or nmblookup
(Linux).
Figured it out by testing all the stuff by myself. Couldn't find any topics about it tho, so I'll just leave the solution here. This might not be the only or even the best solution, but it works for my purposes (within getch's limits) and is better than nothing.
Note: proper keyDown()
which would recognize all the keys and actual key presses, is still valued.
Solution: using ord()
-function to first turn the getch()
into an integer (I guess they're virtual key codes, but not too sure) works fine, and then comparing the result to the actual number representing the wanted key. Also, if I needed to, I could add an extra chr()
around the number returned so that it would convert it to a character. However, I'm using mostly down arrow, esc, etc. so converting those to a character would be stupid. Here's the final code:
from msvcrt import getch
while True:
key = ord(getch())
if key == 27: #ESC
break
elif key == 13: #Enter
select()
elif key == 224: #Special keys (arrows, f keys, ins, del, etc.)
key = ord(getch())
if key == 80: #Down arrow
moveDown()
elif key == 72: #Up arrow
moveUp()
Also if someone else needs to, you can easily find out the keycodes from google, or by using python and just pressing the key:
from msvcrt import getch
while True:
print(ord(getch()))
There are two html entity code : ₹ ₹
After some research, I've came up with the following code that should be the answer to your question. (At least it worked for me)
Use this piece of code first. The $(document).ready
makes sure the code is executed when the form is loaded into the DOM:
$(document).ready(function()
{
$('#theIdOfMyForm').submit(function(event){
if(!this.checkValidity())
{
event.preventDefault();
}
});
});
Then just call $('#theIdOfMyForm').submit();
in your code.
UPDATE
If you actually want to show which field the user had wrong in the form then add the following code after event.preventDefault();
$('#theIdOfMyForm :input:visible[required="required"]').each(function()
{
if(!this.validity.valid)
{
$(this).focus();
// break
return false;
}
});
It will give focus on the first invalid input.
if("123".search(/^\d+$/) >= 0){
// its a number
}
It seems the closest is:
apt-cache policy
A simple solution:
<a href="#" onmouseover="this.style.color='orange';" onmouseout="this.style.color='';">My Link</a>
Or
<script>
/** Change the style **/
function overStyle(object){
object.style.color = 'orange';
// Change some other properties ...
}
/** Restores the style **/
function outStyle(object){
object.style.color = 'orange';
// Restore the rest ...
}
</script>
<a href="#" onmouseover="overStyle(this)" onmouseout="outStyle(this)">My Link</a>
In our particular case, we use Stash as our remote Git repository. We tried all the previous answers and nothing was working. We ended up having to do the following:
git branch –D branch-name (delete from local)
git push origin :branch-name (delete from remote)
Then when users went to pull changes, they needed to do the following:
git fetch -p
The log file is not visible because the slf4j configuration file location needs to passed to the java run command using the following arguments .(e.g.)
-Dlogging.config={file_location}\log4j2.xml
or this:
-Dlog4j.configurationFile={file_location}\log4j2.xml
It seems like Jetbrains made some renaming and moved settings around so the accepted answer is no longer 100% valid anymore.
Intellij 2018.3:
hard wrap
- idea will automatically wrap the line as you type, this is not what the OP was asking for
visual guide
- just a vertical line indicating a characters limit, default is 120
If you just want to change the visual guide
from the default 120
to lets say 80
in my example:
Also you can change the color or the visual guide
by clicking on the Foreground
:
Lastly, you can also set the visual guide
for all file types (unless specified) here:
Once you are able to parse those strings into a Date object comparing them is easy (Using the <
operator). Parsing the dates will depend on the format. You may take a look at Datejs which might simplify this task.
Follow these steps:
Start
button, then type cmd
.Command Prompt
option, then choose Run as administrator
.net use
, then press Enter
.net use /delete \\servername\foldername
where the servername\foldername is the drive that you wish to delete.The problem with other proposed solutions is that they will either drop characters that cannot be directly mapped to ASCII, or replace them with a marker character like ?
.
You might desire to have for example accented characters converted to that same character without the accent. There are a couple of tricks to do this (including building a static mapping table yourself or leveraging existing 'normalization' defined for unicode), but those methods are far from complete.
Your best bet is using the junidecode library, which cannot be complete either but incorporates a lot of experience in the most sane way of transliterating Unicode to ASCII.
The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.
The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete
to do so.
The following will truncate the log.
USE [yourdbname]
GO
-- TRUNCATE TRANSACTION LOG --
DBCC SHRINKFILE(yourdbname_log, 1)
BACKUP LOG yourdbname WITH TRUNCATE_ONLY
DBCC SHRINKFILE(yourdbname_log, 1)
GO
-- CHECK DATABASE HEALTH --
ALTER FUNCTION [dbo].[checker]() RETURNS int AS BEGIN RETURN 0 END
GO
Compound checking:
if (thing.foo && thing.foo.bar) {
... thing.foor.bar exists;
}
As already mentioned by several people, eq
is the right operator here.
If you use warnings;
in your script, you'll get warnings about this (and many other useful things); I'd recommend use strict;
as well.
Globbing uses brackets, hence the need to escape them with a slash \
. Alternatively, the following command-line switch will disable globbing:
--globoff
(or the short-option version: -g
)
Ex:
curl --globoff https://www.google.com?test[]=1
Should just be this:
var jobject = JsonConvert.DeserializeObject<RootObject>(jsonstring);
You can paste the json string to here: http://json2csharp.com/ to check your classes are correct.
Tables work differently; sometimes counter-intuitively.
The solution is to use width
on the table cells instead of max-width
.
Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.
I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.
table {_x000D_
width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
border: 0;_x000D_
border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
min-width: 10px;_x000D_
width: 20px;_x000D_
max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
min-width: 40px;_x000D_
width: 45px;_x000D_
max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
<tr>_x000D_
<td class="a">A</td>_x000D_
<td class="b">B</td>_x000D_
<td class="c">C</td>_x000D_
</tr>_x000D_
</table>
_x000D_
You can make a class for each label and inside it put:
display: inline-block;
And width
the value that you need.
You can use this :
IF OBJECT_ID (N'dbo.T', N'U') IS NOT NULL
BEGIN
print 'deleted table';
drop table t
END
else
begin
print 'table not found'
end
Create table t (id int identity(1,1) not null, name varchar(30) not null, lastname varchar(25) null)
insert into t( name, lastname) values('john','doe');
insert into t( name, lastname) values('rose',NULL);
Select * from t
1 john doe
2 rose NULL
-- clean
drop table t
Try this
select to_char(SYSDATE,'Month') from dual;
for full name and try this
select to_char(SYSDATE,'Mon') from dual;
for abbreviation
you can find more option here:
Interestingly, this solution can break, but a workaround:
Looking for my database called KeyWorks.accdb
which must exist:
Run this:
Dim strDataPath As String = GetSetting("KeyWorks", "dataPath", "01", "") 'get from registry
If Not strDataPath.Contains("KeyWorks.accdb") Then....etc.
If my database is named KeyWorksBB.accdb
, the If
statement will find this acceptable and exit the If
statement because it did indeed find KeyWorks
and accdb
.
If I surround the If
statement qualifier with single quotes like 'KeyWorks.accdb'
, it now looks for all the consecutive characters in order and would enter the If
block because it did not match.
I provide a more general and safer way to do this stuff,
".." <- function (x)
{
stopifnot(inherits(x, "character"))
stopifnot(length(x) == 1)
get(x, parent.frame(4))
}
set_colclass <- function(x, class){
stopifnot(all(class %in% c("integer", "numeric", "double","factor","character")))
for(i in intersect(names(class), names(x))){
f <- get(paste0("as.", class[i]))
x[, (..("i")):=..("f")(get(..("i")))]
}
invisible(x)
}
The function ..
makes sure we get a variable out of the scope of data.table; set_colclass will set the classes of your cols.
You can use it like this:
dt <- data.table(i=1:3,f=3:1)
set_colclass(dt, c(i="character"))
class(dt$i)
You can use prototype cells
with a custom height
, and then invoke cellForRowAtIndexPath:
and return its frame.height
.:.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [self tableView:tableView
cellForRowAtIndexPath:indexPath];
return cell.frame.size.height;
}
I tried several things, finally what worked for me was to delete (and move to trash) the .xib file in question. Then re-create it. To make things easier, I copied the stuff in the .xib temporarily to another .xib, then copied it back into the newly created one.
You can simply use Query Builder rather than Eloquent, this code directly update your data in the database :) This is a sample:
DB::table('post')
->where('id', 3)
->update(['title' => "Updated Title"]);
You can check the documentation here for more information: http://laravel.com/docs/5.0/queries#updates
JScript is Microsoft's equivalent of JavaScript.
Java is an Oracle product and used to be a Sun product.
Oracle bought Sun.
JavaScript + Microsoft = JScript
I'd recommend that you take a look at jQuery.
jQuery way:
$("html").addClass("myClass");
Kotlin code is a lot simpler:
if(isVisable) {
clearButton.visibility = View.INVISIBLE
}
else {
clearButton.visibility = View.VISIBLE
}
If we have a single server we can directly include it in the proxy_pass. But in case if we have many servers we use upstream to maintain the servers. Nginx will load-balance based on the incoming traffic.
The most common approach is to either lowercase or uppercase the search string and the data. But there are two problems with that.
There are at least three less frequently used solutions that might be more effective.
CREATE INDEX ON groups (name::citext);
. (But see below.)CREATE
INDEX ON groups (LOWER(name));
. Having done that, you can take advantage
of the index with queries like SELECT id FROM groups WHERE LOWER(name) = LOWER('ADMINISTRATOR');
, or SELECT id FROM groups WHERE LOWER(name) = 'administrator';
You have to remember to use LOWER(), though.The citext module doesn't provide a true case-insensitive data type. Instead, it behaves as if each string were lowercased. That is, it behaves as if you had called lower()
on each string, as in number 3 above. The advantage is that programmers don't have to remember to lowercase strings. But you need to read the sections "String Comparison Behavior" and "Limitations" in the docs before you decide to use citext.
To summarize and a bit simplify, you can use:
-- 0 - 9
select floor(random() * 10);
-- 0 - 10
SELECT floor(random() * (10 + 1));
-- 1 - 10
SELECT ceil(random() * 10);
And you can test this like mentioned by @user80168
-- 0 - 9
SELECT min(i), max(i) FROM (SELECT floor(random() * 10) AS i FROM generate_series(0, 100000)) q;
-- 0 - 10
SELECT min(i), max(i) FROM (SELECT floor(random() * (10 + 1)) AS i FROM generate_series(0, 100000)) q;
-- 1 - 10
SELECT min(i), max(i) FROM (SELECT ceil(random() * 10) AS i FROM generate_series(0, 100000)) q;
$time = '10:09';
$timestamp = strtotime($time);
$timestamp_one_hour_later = $timestamp + 3600; // 3600 sec. = 1 hour
// Formats the timestamp to HH:MM => outputs 11:09.
echo strftime('%H:%M', $timestamp_one_hour_later);
// As crolpa suggested, you can also do
// echo date('H:i', $timestamp_one_hour_later);
Check PHP manual for strtotime(), strftime() and date() for details.
BTW, in your initial code, you need to add some quotes otherwise you will get PHP syntax errors:
$time = 10:09; // wrong syntax
$time = '10:09'; // syntax OK
$time = date(H:i, strtotime('+1 hour')); // wrong syntax
$time = date('H:i', strtotime('+1 hour')); // syntax OK
You can create a "fake" delay between infinite animations purely with CSS. The way to do it is smartly define your keyframe animation points and your animation duration speed.
For example, if we wanted to animate a bouncing ball, and we wanted a good .5s to 1s delay between each bounce, we can do something like:
@keyframes bounce{
0%{
transform: translateY(0);
}
50%{
transform: translateY(25%);
}
75%{
transform: translateY(15%);
}
90%{
transform: translateY(0%);
}
100%{
transform: translateY(0);
}
}
What we do is make sure that the ball goes back to its original position much earlier than 100%. In my example, I'm doing it in 90% which provided me with around .1s delay which was good enough for me. But obviously for your case, you can either add more key frame points and change the transform values.
Furthermore, you can add additional animation duration to balance your key frame animations.
For example:
animation: bounce .5s ease-in-out infinite;
Lets say that we wanted the full animation to end in .5s, but we wanted an additional .2s in delay between the animations.
animation: bounce .7s ease-in-out infinite;
So we'll add an additional .2s delay, and in our key frame animations, we can add more percentage points to fill in the gaps of the .2s delay.
When we use multiple and
(where) condition with last (where + or where) the where condition fails most of the time. for that we can use the nested where function with parameters passing in that.
$feedsql = DB::table('feeds as t1')
->leftjoin('groups as t2', 't1.groups_id', '=', 't2.id')
->where('t2.status', 1)
->whereRaw("t1.published_on <= NOW()")
>whereIn('t1.groupid', $group_ids)
->where(function($q)use ($userid) {
$q->where('t2.contact_users_id', $userid)
->orWhere('t1.users_id', $userid);
})
->orderBy('t1.published_on', 'desc')->get();
The above query validate all where condition then finally checks where t2.status=1 and (where t2.contact_users_id='$userid' or where t1.users_id='$userid')
Try to avoid globals, instead you can use something like this
class myClass() {
private $myNumber;
public function setNumber($number) {
$this->myNumber = $number;
}
}
Now you can call
$class = new myClass();
$class->setNumber('1234');
There is no need to use angular http, you can get with js native functions
// you will ned this function to fetch the image blob._x000D_
async function getImage(url, fileName) {_x000D_
// on the first then you will return blob from response_x000D_
return await fetch(url).then(r => r.blob())_x000D_
.then((blob) => { // on the second, you just create a file from that blob, getting the type and name that intend to inform_x000D_
_x000D_
return new File([blob], fileName+'.'+ blob.type.split('/')[1]) ;_x000D_
});_x000D_
}_x000D_
_x000D_
// example url_x000D_
var url = 'https://img.freepik.com/vetores-gratis/icone-realista-quebrado-vidro-fosco_1284-12125.jpg';_x000D_
_x000D_
// calling the function_x000D_
getImage(url, 'your-name-image').then(function(file) {_x000D_
_x000D_
// with file reader you will transform the file in a data url file;_x000D_
var reader = new FileReader();_x000D_
reader.readAsDataURL(file);_x000D_
reader.onloadend = () => {_x000D_
_x000D_
// just putting the data url to img element_x000D_
document.querySelector('#image').src = reader.result ;_x000D_
}_x000D_
})
_x000D_
<img src="" id="image"/>
_x000D_
try this for your server config
app.configure(function() {
app.use(express.static(__dirname + '/public')); // set the static files location
app.use(express.logger('dev')); // log every request to the console
app.use(express.bodyParser()); // pull information from html in POST
app.use(express.methodOverride()); // simulate DELETE and PUT
app.use(express.favicon(__dirname + '/public/img/favicon.ico'));
});
then your callback functions to routes will look like:
function(req, res) {
res.sendfile('./public/index.html');
};
To print a specific row we have couple of pandas method
loc
- It only get label i.e column name or Featuresiloc
- Here i stands for integer, actually row number ix
- It is a mix of label as well as integerHow to use for specific row
loc
df.loc[row,column]
For first row and all column
df.loc[0,:]
For first row and some specific column
df.loc[0,'column_name']
iloc
For first row and all column
df.iloc[0,:]
For first row and some specific column i.e first three cols
df.iloc[0,0:3]
Easiest way to get it done is by adding required
into your select
Select the best option
<br/>
<select name="dd1" id="dd1" required>
<option value="none">None</option>
<option value="o1">option 1</option>
<option value="o2">option 2</option>
<option value="o3">option 3</option>
</select>
<br/><br/>?
To use the Combobox
in the way you intend, you could pass in an object to the cmbTripName.Items.Add
method.
That object should have FleetID
and FleetName
properties:
while (drd.Read())
{
cmbTripName.Items.Add(new Fleet(drd["FleetID"].ToString(), drd["FleetName"].ToString()));
}
cmbTripName.ValueMember = "FleetId";
cmbTripName.DisplayMember = "FleetName";
The Fleet
Class:
class Fleet
{
public Fleet(string fleetId, string fleetName)
{
FleetId = fleetId;
FleetName = fleetName
}
public string FleetId {get;set;}
public string FleetName {get;set;}
}
Or, You could probably do away with the need for a Fleet
class completely by using an anonymous type...
while (drd.Read())
{
cmbTripName.Items.Add(new {FleetId = drd["FleetID"].ToString(), FleetName = drd["FleetName"].ToString()});
}
cmbTripName.ValueMember = "FleetId";
cmbTripName.DisplayMember = "FleetName";
To expand on the answer given by Chris
if you want to store the date in a variable in a specific format, this is the shortest and most effective way as far as I know
>>> from datetime import date, timedelta
>>> yesterday = (date.today() - timedelta(days=1)).strftime('%m%d%y')
>>> yesterday
'020817'
If you want it as an integer (which can be useful)
>>> yesterday = int((date.today() - timedelta(days=1)).strftime('%m%d%y'))
>>> yesterday
20817
This code is for the headset profiles, probably it will work for other profiles too. First you need to provide profile listener (Kotlin code):
private val mProfileListener = object : BluetoothProfile.ServiceListener {
override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
if (profile == BluetoothProfile.HEADSET)
mBluetoothHeadset = proxy as BluetoothHeadset
}
override fun onServiceDisconnected(profile: Int) {
if (profile == BluetoothProfile.HEADSET) {
mBluetoothHeadset = null
}
}
}
Then while checking bluetooth:
mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET)
if (!mBluetoothAdapter.isEnabled) {
return Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
}
It takes a bit of time until onSeviceConnected is called. After that you may get the list of the connected headset devices from:
mBluetoothHeadset!!.connectedDevices
For Ubuntu 16: /etc/mysql/mysql.conf.d/mysqld.cnf
If you are still looking for further more customization,
Check out the following library: https://lokesh-coder.github.io/pretty-checkbox/
Thanks
I agree that the second way is preferable. The only real reason for that preference is the general preference that .NET classes not have public fields. However, if that field is readonly, I can't see how there would be any real objections other than a lack of consistency with other properties. The real difference between a readonly field and get-only property is that the readonly field provides a guarantee that its value will not change over the life of the object and a get-only property does not.
Is it as optional functionality.
If you won't provide it when user will try to purchase non-consumable product AppStore will restore old transaction. But your app will think that this is new transaction.
If you will provide restore mechanism then your purchase manager will see restored transaction.
If app should distinguish this options then you should provide functionality for restoring previously purchased products.
write in file config
$config['base_url'] = 'http://localhost:8000/test/content/home/';
Note : Use it if calculating / adding days from current date.
Be aware: this answer has issues (see comments)
var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);
It should be like
var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));
Environment: Windows 7 64 bit
In my case, I had to run emulator in verbose mode (emulator -verbose -avd Nexus_6_API_25
) to findout the fact that emulator detected two DNS servers, as shown below.
emulator: Found 2 DNS servers: 192.168.3.227 192.168.1.1
Out of the two DNS servers detected, only one has internet connection and it was the reason why emulator didn't get internet access.
To successfully connect android emulator to the internet, the DNS server which doesn't have the internet connection had to be disabled from the Control Panel\Network and Internet\Network Connections
.NetCore is a fine release from Microsoft and Visual Studio's latest version is also available for mac but there is still some limitation. Like for creating GUI based application on .net core you have to write code manually for everything. Like in older version of VS we just drag and drop the things and magic happens. But in VS latest version for mac every code has to be written manually. However you can make web application and console application easily on VS for mac.
To pass a string to the view as the Model, you can do:
public ActionResult Index()
{
string myString = "This is my string";
return View((object)myString);
}
You must cast it to an object so that MVC doesn't try to load the string as the view name, but instead pass it as the model. You could also write:
return View("Index", myString);
.. which is a bit more verbose.
Then in your view, just type it as a string:
@model string
<p>Value: @Model</p>
Then you can manipulate Model how you want.
For accessing it from a Layout page, it might be better to create an HtmlExtension for this:
public static string GetThemePath(this HtmlHelper helper)
{
return "/path-to-theme";
}
Then inside your layout page:
<p>Value: @Html.GetThemePath()</p>
Hopefully you can apply this to your own scenario.
Edit: explicit HtmlHelper code:
namespace <root app namespace>
{
public static class Helpers
{
public static string GetThemePath(this HtmlHelper helper)
{
return System.Web.Hosting.HostingEnvironment.MapPath("~") + "/path-to-theme";
}
}
}
Then in your view:
@{
var path = Html.GetThemePath();
// .. do stuff
}
Or:
<p>Path: @Html.GetThemePath()</p>
Edit 2:
As discussed, the Helper will work if you add a @using
statement to the top of your view, with the namespace pointing to the one that your helper is in.
http://www.amk.ca/python/writing/DB-API.html
Be careful when you simply append values of variables to your statements:
Imagine a user naming himself ';DROP TABLE Users;'
--
That's why you need to use sql escaping, which Python provides for you when you use the cursor.execute in a decent manner. Example in the url is:
cursor.execute("insert into Attendees values (?, ?, ?)", (name,
seminar, paid) )
Note: According to JDN96, the answer below may cause a memory leak by repeatedly destroying and recreating frames. However, I have not tested to verify this myself.
One way to switch frames in tkinter
is to destroy the old frame then replace it with your new frame.
I have modified Bryan Oakley's answer to destroy the old frame before replacing it. As an added bonus, this eliminates the need for a container
object and allows you to use any generic Frame
class.
# Multi-frame tkinter application v2.3
import tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.switch_frame(StartPage)
def switch_frame(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
class StartPage(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is the start page").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Open page one",
command=lambda: master.switch_frame(PageOne)).pack()
tk.Button(self, text="Open page two",
command=lambda: master.switch_frame(PageTwo)).pack()
class PageOne(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is page one").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Return to start page",
command=lambda: master.switch_frame(StartPage)).pack()
class PageTwo(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is page two").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Return to start page",
command=lambda: master.switch_frame(StartPage)).pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
switch_frame()
works by accepting any Class object that implements Frame
. The function then creates a new frame to replace the old one.
_frame
if it exists, then replaces it with the new frame..pack()
, such as menubars, will be unaffected.tkinter.Frame
.v2.3
- Pack buttons and labels as they are initialized
v2.2
- Initialize `_frame` as `None`.
- Check if `_frame` is `None` before calling `.destroy()`.
v2.1.1
- Remove type-hinting for backwards compatibility with Python 3.4.
v2.1
- Add type-hinting for `frame_class`.
v2.0
- Remove extraneous `container` frame.
- Application now works with any generic `tkinter.frame` instance.
- Remove `controller` argument from frame classes.
- Frame switching is now done with `master.switch_frame()`.
v1.6
- Check if frame attribute exists before destroying it.
- Use `switch_frame()` to set first frame.
v1.5
- Revert 'Initialize new `_frame` after old `_frame` is destroyed'.
- Initializing the frame before calling `.destroy()` results
in a smoother visual transition.
v1.4
- Pack frames in `switch_frame()`.
- Initialize new `_frame` after old `_frame` is destroyed.
- Remove `new_frame` variable.
v1.3
- Rename `parent` to `master` for consistency with base `Frame` class.
v1.2
- Remove `main()` function.
v1.1
- Rename `frame` to `_frame`.
- Naming implies variable should be private.
- Create new frame before destroying old frame.
v1.0
- Initial version.
Hi here is how i did it in one Project :
@Html.DropDownListFor(model => model.MyOption,
new List<SelectListItem> {
new SelectListItem { Value = "0" , Text = "Option A" },
new SelectListItem { Value = "1" , Text = "Option B" },
new SelectListItem { Value = "2" , Text = "Option C" }
},
new { @class="myselect"})
I hope it helps Somebody. Thanks
You have to modify two possible limits:
In conf\server.xml
<Connector port="80" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
maxPostSize="67589953" />
In webapps\manager\WEB-INF\web.xml
<multipart-config>
<!-- 52MB max -->
<max-file-size>52428800</max-file-size>
<max-request-size>52428800</max-request-size>
<file-size-threshold>0</file-size-threshold>
</multipart-config>
You need to have file system permission to create the directory.
Example: In Ubuntu 10.04 apache (php) runs as user: www-data in group: www-data
Meaning the user www-data needs access to create the directory.
You can try this yourself by using: 'su www-data' to become the www-data user.
As a quick fix, you can do: sudo chmod 777 my_parent_dir
Partial solution:
Put the things you want done in a shell-script, like so
#!/bin/bash
ls
echo "yey!"
And don't forget to 'chmod +x file
' to make it executable. Then you can
open -a Terminal.app scriptfile
and it will run in a new window. Add 'bash
' at the end of the script to keep the new session from exiting. (Although you might have to figure out how to load the users rc-files and stuff..)
You can use -
Ternary oprator to check wheather value set by POST/GET or not somthing like this
$value1 = $_POST['value1'] = isset($_POST['value1']) ? $_POST['value1'] : '';
$value2 = $_POST['value2'] = isset($_POST['value2']) ? $_POST['value2'] : '';
$value3 = $_POST['value3'] = isset($_POST['value3']) ? $_POST['value3'] : '';
$value4 = $_POST['value4'] = isset($_POST['value4']) ? $_POST['value4'] : '';
It seems that Maven doesn't like the JAVA_HOME
variable to have more than one value. In my case, the error was due to the presence of the additional path C:\Program Files\Java\jax-rs
(the whole path was C:\Program Files\Java\jdk1.8.0_20;C:\Program Files\Java\jax-rs
).
So I deleted the JAVA_HOME
variable and re-created it again with the single value C:\Program Files\Java\jdk1.8.0_20
.
How about maybe something like this?
var condCheck1 = new string[]{"a","b","c"};
var condCheck2 = new string[]{"a","b","c","A2"}
if(!condCheck1.Contains(columnName) && !checkbox.checked)
//statement 1
else if (!condCheck2.Contains(columnName))
//statment 2
Use zip(*list)
:
>>> l = [(1,2), (3,4), (8,9)]
>>> list(zip(*l))
[(1, 3, 8), (2, 4, 9)]
The zip()
function pairs up the elements from all inputs, starting with the first values, then the second, etc. By using *l
you apply all tuples in l
as separate arguments to the zip()
function, so zip()
pairs up 1
with 3
with 8
first, then 2
with 4
and 9
. Those happen to correspond nicely with the columns, or the transposition of l
.
zip()
produces tuples; if you must have mutable list objects, just map()
the tuples to lists or use a list comprehension to produce a list of lists:
map(list, zip(*l)) # keep it a generator
[list(t) for t in zip(*l)] # consume the zip generator into a list of lists
From the Javadoc for Character#getNumericValue
:
If the character does not have a numeric value, then -1 is returned. If the character has a numeric value that cannot be represented as a nonnegative integer (for example, a fractional value), then -2 is returned.
The character +
does not have a numeric value, so you're getting -1.
Update:
The reason that primitive conversion is giving you 43 is that the the character '+' is encoded as the integer 43.
First off it's important to understand that there are two kinds of "event listeners":
Scope event listeners registered via $on
:
$scope.$on('anEvent', function (event, data) {
...
});
Event handlers attached to elements via for example on
or bind
:
element.on('click', function (event) {
...
});
When $scope.$destroy()
is executed it will remove all listeners registered via $on
on that $scope.
It will not remove DOM elements or any attached event handlers of the second kind.
This means that calling $scope.$destroy()
manually from example within a directive's link function will not remove a handler attached via for example element.on
, nor the DOM element itself.
Note that remove
is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.
When element.remove()
is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on
.
It will not destroy the $scope associated with the element.
To make it more confusing there is also a jQuery event called $destroy
. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:
element.on('$destroy', function () {
scope.$destroy();
});
This depends on how the directive is "destroyed".
A normal case is that a directive is destroyed because ng-view
changes the current view. When this happens the ng-view
directive will destroy the associated $scope, sever all the references to its parent scope and call remove()
on the element.
This means that if that view contains a directive with this in its link function when it's destroyed by ng-view
:
scope.$on('anEvent', function () {
...
});
element.on('click', function () {
...
});
Both event listeners will be removed automatically.
However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references
.
Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.
For example if you have registered a listener on $rootScope
:
var unregisterFn = $rootScope.$on('anEvent', function () {});
scope.$on('$destroy', unregisterFn);
This is needed since $rootScope
is never destroyed during the lifetime of the application.
The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.
Another situation would be to cancel $interval
/$timeout
:
var promise = $interval(function () {}, 1000);
scope.$on('$destroy', function () {
$interval.cancel(promise);
});
If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:
var windowClick = function () {
...
};
angular.element(window).on('click', windowClick);
scope.$on('$destroy', function () {
angular.element(window).off('click', windowClick);
});
These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view
or ng-if
.
If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.
I wanted to add something very important. I use JohnnyHK method a lot but I noticed sometimes the changes didn't persist to the database. When I used .markModified
it worked.
User.findOne({username: oldUsername}, function (err, user) {
user.username = newUser.username;
user.password = newUser.password;
user.rights = newUser.rights;
user.markModified(username)
user.markModified(password)
user.markModified(rights)
user.save(function (err) {
if(err) {
console.error('ERROR!');
}
});
});
tell mongoose about the change with doc.markModified('pathToYourDate') before saving.
To make it work in Chrome (and bootply) i had to change code in this way:
<form class="form-horizontal">
<div class="form-group">
<label for="name" class="col-xs-2 control-label">Name</label>
<div class="col-xs-10">
<input type="text" class="form-control col-sm-10" name="name" placeholder="name" />
</div>
</div>
<div class="form-group">
<label for="birthday" class="col-xs-2 control-label">Birthday</label>
<div class="col-xs-10">
<div class="form-inline">
<input type="text" class="form-control" placeholder="year" />
<input type="text" class="form-control" placeholder="month" />
<input type="text" class="form-control" placeholder="day" />
</div>
</div>
</div>
</form>
export const authHandler = (config) => {
const authRegex = /^\/apiregex/;
if (!authRegex.test(config.url)) {
return store.fetchToken().then((token) => {
Object.assign(config.headers.common, { Authorization: `Bearer ${token}` });
return Promise.resolve(config);
});
}
return Promise.resolve(config);
};
axios.interceptors.request.use(authHandler);
Ran into some gotchas when trying to implement something similar and based on these answers this is what I came up with. The problems I was experiencing were:
Graphs are tough, because most non-trivial graph problems tend to require a decent amount of actual code to implement, if more than a sketch of an algorithm is required. A lot of it tends to come down to whether or not the candidate knows the shortest path and graph traversal algorithms, is familiar with cycle types and detection, and whether they know the complexity bounds. I think a lot of questions about this stuff comes down to trivia more than on the spot creative thinking ability.
I think problems related to trees tend to cover most of the difficulties of graph questions, but without as much code complexity.
I like the Project Euler problem that asks to find the most expensive path down a tree (16/67); common ancestor is a good warm up, but a lot of people have seen it. Asking somebody to design a tree class, perform traversals, and then figure out from which traversals they could rebuild a tree also gives some insight into data structure and algorithm implementation. The Stern-Brocot programming challenge is also interesting and quick to develop on a board (http://online-judge.uva.es/p/v100/10077.html).
If you are on Linux then make sure your File name must match with the string passed in the load model methods the first argument.
$this->load->model('Order_Model','order_model');
You can use the second argument using that you can call methods from your model and it will work on Linux and windows as well
$result = $this->order_model->get_order_details($orderID);
You should be able to use Windows "UNC" paths with robocopy. For example:
robocopy \\myServer\myFolder\myFile.txt \\myOtherServer\myOtherFolder
Robocopy has the ability to recover from certain types of network hiccups automatically.
Binding events from html is NOT recommended. This is recommended way:
document.getElementById('btn').addEventListener('click', function(){
pay();
cls();
});
I am seeing this error message when I run Firefox headless through selenium using xvfb. It turns out that the message was a red herring for me. The message is only a warning, not an error. It is not why Firefox was not starting correctly.
The reason that Firefox was not starting for me was that it had been updated to a version that was no longer compatible with the Selenium drivers that I was using. I upgraded the selenium drivers to the latest and Firefox starts up fine again (even with this warning message about RANDR).
New releases of Firefox are often only compatible with one or two versions of Selenium. Occasionally Firefox is released with NO compatible version of Selenium. When that happens, it may take a week or two for a new version of Selenium to get released. Because of this, I now keep a version of Firefox that is known to work with the version of Selenium that I have installed. In addition to the version of Firefox that is kept up to date by my package manager, I have a version installed in /opt/
(eg /opt/firefox31/
). The Selenium Java API takes an argument for the location of the Firefox binary to be used. The downside is that older versions of Firefox have known security vulnerabilities and shouldn't be used with untrusted content.
Take a look at my answer Maven and dependent modules.
The Maven Reactor plugin is designed to deal with building part of a project.
The particular goal you'll want to use it reactor:make
.
I have polished this missing subclass of QLabel
. It is awesome and works well.
aspectratiopixmaplabel.h
#ifndef ASPECTRATIOPIXMAPLABEL_H
#define ASPECTRATIOPIXMAPLABEL_H
#include <QLabel>
#include <QPixmap>
#include <QResizeEvent>
class AspectRatioPixmapLabel : public QLabel
{
Q_OBJECT
public:
explicit AspectRatioPixmapLabel(QWidget *parent = 0);
virtual int heightForWidth( int width ) const;
virtual QSize sizeHint() const;
QPixmap scaledPixmap() const;
public slots:
void setPixmap ( const QPixmap & );
void resizeEvent(QResizeEvent *);
private:
QPixmap pix;
};
#endif // ASPECTRATIOPIXMAPLABEL_H
aspectratiopixmaplabel.cpp
#include "aspectratiopixmaplabel.h"
//#include <QDebug>
AspectRatioPixmapLabel::AspectRatioPixmapLabel(QWidget *parent) :
QLabel(parent)
{
this->setMinimumSize(1,1);
setScaledContents(false);
}
void AspectRatioPixmapLabel::setPixmap ( const QPixmap & p)
{
pix = p;
QLabel::setPixmap(scaledPixmap());
}
int AspectRatioPixmapLabel::heightForWidth( int width ) const
{
return pix.isNull() ? this->height() : ((qreal)pix.height()*width)/pix.width();
}
QSize AspectRatioPixmapLabel::sizeHint() const
{
int w = this->width();
return QSize( w, heightForWidth(w) );
}
QPixmap AspectRatioPixmapLabel::scaledPixmap() const
{
return pix.scaled(this->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
}
void AspectRatioPixmapLabel::resizeEvent(QResizeEvent * e)
{
if(!pix.isNull())
QLabel::setPixmap(scaledPixmap());
}
Hope that helps!
(Updated resizeEvent
, per @dmzl's answer)
If your only requirement is to print the third field of every line, with each field delimited by a comma, you can use cut:
cut -d, -f3 file
-d,
sets the delimiter to a comma-f3
specifies that only the third field is to be printedA Worker Process is user mode code whose role is to process requests, such as processing requests to return a static page.
The worker process is controlled by the www service.
worker processes also run application code, Such as ASP .NET applications and XML web Services.
When Application pool receive the request, it simply pass the request to worker process (w3wp.exe) . The worker process“w3wp.exe” looks up the URL of the request in order to load the correct ISAPI extension. ISAPI extensions are the IIS way to handle requests for different resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll)and adds the mapping into IIS.
When Worker process loads the aspnet_isapi.dll, it start an HTTPRuntime, which is the entry point of an application. HTTPRuntime is a class which calls the ProcessRequest method to start Processing.
For more detail refer URL http://aspnetnova.blogspot.in/2011/12/how-iis-process-for-aspnet-requests.html
/proc/net/tcp -a list of open tcp sockets
/proc/net/udp -a list of open udp sockets
/proc/net/raw -a list all the 'raw' sockets
These are the files, use cat
command to view them. For example:
cat /proc/net/tcp
You can also use the lsof
command.
lsof is a command meaning "list open files", which is used in many Unix-like systems to report a list of all open files and the processes that opened them.
delete espresso dependencies in gradle file works for me.
delete those lines in app gradle file:
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
You turn off pack_propagate
by setting pack_propagate(0)
Turning off pack_propagate
here basically says don't let the widgets inside the frame control it's size. So you've set it's width and height to be 500. Turning off propagate stills allows it to be this size without the widgets changing the size of the frame to fill their respective width / heights which is what would happen normally
To turn off resizing the root window, you can set root.resizable(0, 0)
, where resizing is allowed in the x
and y
directions respectively.
To set a maxsize to window, as noted in the other answer you can set the maxsize
attribute or minsize
although you could just set the geometry of the root window and then turn off resizing. A bit more flexible imo.
Whenever you set grid
or pack
on a widget it will return None
. So, if you want to be able to keep a reference to the widget object you shouldn't be setting a variabe to a widget where you're calling grid
or pack
on it. You should instead set the variable to be the widget Widget(master, ....)
and then call pack
or grid
on the widget instead.
import tkinter as tk
def startgame():
pass
mw = tk.Tk()
#If you have a large number of widgets, like it looks like you will for your
#game you can specify the attributes for all widgets simply like this.
mw.option_add("*Button.Background", "black")
mw.option_add("*Button.Foreground", "red")
mw.title('The game')
#You can set the geometry attribute to change the root windows size
mw.geometry("500x500") #You want the size of the app to be 500x500
mw.resizable(0, 0) #Don't allow resizing in the x or y direction
back = tk.Frame(master=mw,bg='black')
back.pack_propagate(0) #Don't allow the widgets inside to determine the frame's width / height
back.pack(fill=tk.BOTH, expand=1) #Expand the frame to fill the root window
#Changed variables so you don't have these set to None from .pack()
go = tk.Button(master=back, text='Start Game', command=startgame)
go.pack()
close = tk.Button(master=back, text='Quit', command=mw.destroy)
close.pack()
info = tk.Label(master=back, text='Made by me!', bg='red', fg='black')
info.pack()
mw.mainloop()
Here is an old version I have that works on version 1.0 of the .NET framework and does not need generic types.
public static Array RemoveAt(Array source, int index)
{
if (source == null)
throw new ArgumentNullException("source");
if (0 > index || index >= source.Length)
throw new ArgumentOutOfRangeException("index", index, "index is outside the bounds of source array");
Array dest = Array.CreateInstance(source.GetType().GetElementType(), source.Length - 1);
Array.Copy(source, 0, dest, 0, index);
Array.Copy(source, index + 1, dest, index, source.Length - index - 1);
return dest;
}
This is used like this:
class Program
{
static void Main(string[] args)
{
string[] x = new string[20];
for (int i = 0; i < x.Length; i++)
x[i] = (i+1).ToString();
string[] y = (string[])MyArrayFunctions.RemoveAt(x, 3);
for (int i = 0; i < y.Length; i++)
Console.WriteLine(y[i]);
}
}
#!/bin/bash
goclean() {
local pkg=$1; shift || return 1
local ost
local cnt
local scr
# Clean removes object files from package source directories (ignore error)
go clean -i $pkg &>/dev/null
# Set local variables
[[ "$(uname -m)" == "x86_64" ]] \
&& ost="$(uname)";ost="${ost,,}_amd64" \
&& cnt="${pkg//[^\/]}"
# Delete the source directory and compiled package directory(ies)
if (("${#cnt}" == "2")); then
rm -rf "${GOPATH%%:*}/src/${pkg%/*}"
rm -rf "${GOPATH%%:*}/pkg/${ost}/${pkg%/*}"
elif (("${#cnt}" > "2")); then
rm -rf "${GOPATH%%:*}/src/${pkg%/*/*}"
rm -rf "${GOPATH%%:*}/pkg/${ost}/${pkg%/*/*}"
fi
# Reload the current shell
source ~/.bashrc
}
Usage:
# Either launch a new terminal and copy `goclean` into the current shell process,
# or create a shell script and add it to the PATH to enable command invocation with bash.
goclean github.com/your-username/your-repository
Set oShell = WScript.CreateObject("WSCript.shell")
oShell.run "cmd cd /d C:dir_test\file_test & sanity_check_env.bat arg1"
Lambda is not a object but a Functional Interface. One can define as many as Functional Interfaces as they can using the @FuntionalInterface as an annotation
@FuntionalInterface
public interface SumLambdaExpression {
public int do(int a, int b);
}
public class MyClass {
public static void main(String [] args) {
SumLambdaExpression s = (a,b)->a+b;
lambdaArgFunction(s);
}
public static void lambdaArgFunction(SumLambdaExpression s) {
System.out.println("Output : "+s.do(2,5));
}
}
The Output will be as follows
Output : 7
The Basic concept of a Lambda Expression is to define your own logic but already defined Arguments. So in the above code the you can change the definition of the do function from addition to any other definition, but your arguments are limited to 2.
Just throw any RuntimeException
from a method marked as @Transactional
.
By default all RuntimeException
s rollback transaction whereas checked exceptions don't. This is an EJB legacy. You can configure this by using rollbackFor()
and noRollbackFor()
annotation parameters:
@Transactional(rollbackFor=Exception.class)
This will rollback transaction after throwing any exception.
That is ambiguous because a pointer is just an address, so an int
can also be treated as a pointer – 0 (an int
) can be converted to unsigned int
or char *
equally easily.
The short answer is to call p.setval()
with something that's unambiguously one of the types it's implemented for: unsigned int
or char *
. p.setval(0U)
, p.setval((unsigned int)0)
, and p.setval((char *)0)
will all compile.
It's generally a good idea to stay out of this situation in the first place, though, by not defining overloaded functions with such similar types.
use this
System.Configuration.ConfigurationSettings.AppSettings.Get("Keyname")
pandas.isnull()
(also pd.isna()
, in newer versions) checks for missing values in both numeric and string/object arrays. From the documentation, it checks for:
NaN in numeric arrays, None/NaN in object arrays
Quick example:
import pandas as pd
import numpy as np
s = pd.Series(['apple', np.nan, 'banana'])
pd.isnull(s)
Out[9]:
0 False
1 True
2 False
dtype: bool
The idea of using numpy.nan
to represent missing values is something that pandas
introduced, which is why pandas
has the tools to deal with it.
Datetimes too (if you use pd.NaT
you won't need to specify the dtype)
In [24]: s = Series([Timestamp('20130101'),np.nan,Timestamp('20130102 9:30')],dtype='M8[ns]')
In [25]: s
Out[25]:
0 2013-01-01 00:00:00
1 NaT
2 2013-01-02 09:30:00
dtype: datetime64[ns]``
In [26]: pd.isnull(s)
Out[26]:
0 False
1 True
2 False
dtype: bool
Using overflow:hidden
/auto
and height for ie6 will suffice if the floating container has a parent element.
Either one of the #test could work, for the HTML stated below to clear floats.
#test {
overflow:hidden; // or auto;
_height:1%; forces hasLayout in IE6
}
<div id="test">
<div style="floatLeft"></div>
<div style="random"></div>
</div>
In cases when this refuses to work with ie6, just float the parent to clear float.
#test {
float: left; // using float to clear float
width: 99%;
}
Never really needed any other kind of clearing yet. Maybe it's the way I write my HTML.
{
"VALIDATON_ERROR": {
"code": 512,
"message": "Validation error"
},
"CONTINUE": {
"code": 100,
"message": "Continue"
},
"SWITCHING_PROTOCOLS": {
"code": 101,
"message": "Switching Protocols"
},
"PROCESSING": {
"code": 102,
"message": "Processing"
},
"OK": {
"code": 200,
"message": "OK"
},
"CREATED": {
"code": 201,
"message": "Created"
},
"ACCEPTED": {
"code": 202,
"message": "Accepted"
},
"NON_AUTHORITATIVE_INFORMATION": {
"code": 203,
"message": "Non Authoritative Information"
},
"NO_CONTENT": {
"code": 204,
"message": "No Content"
},
"RESET_CONTENT": {
"code": 205,
"message": "Reset Content"
},
"PARTIAL_CONTENT": {
"code": 206,
"message": "Partial Content"
},
"MULTI_STATUS": {
"code": 207,
"message": "Multi-Status"
},
"MULTIPLE_CHOICES": {
"code": 300,
"message": "Multiple Choices"
},
"MOVED_PERMANENTLY": {
"code": 301,
"message": "Moved Permanently"
},
"MOVED_TEMPORARILY": {
"code": 302,
"message": "Moved Temporarily"
},
"SEE_OTHER": {
"code": 303,
"message": "See Other"
},
"NOT_MODIFIED": {
"code": 304,
"message": "Not Modified"
},
"USE_PROXY": {
"code": 305,
"message": "Use Proxy"
},
"TEMPORARY_REDIRECT": {
"code": 307,
"message": "Temporary Redirect"
},
"PERMANENT_REDIRECT": {
"code": 308,
"message": "Permanent Redirect"
},
"BAD_REQUEST": {
"code": 400,
"message": "Bad Request"
},
"UNAUTHORIZED": {
"code": 401,
"message": "Unauthorized"
},
"PAYMENT_REQUIRED": {
"code": 402,
"message": "Payment Required"
},
"FORBIDDEN": {
"code": 403,
"message": "Forbidden"
},
"NOT_FOUND": {
"code": 404,
"message": "Not Found"
},
"METHOD_NOT_ALLOWED": {
"code": 405,
"message": "Method Not Allowed"
},
"NOT_ACCEPTABLE": {
"code": 406,
"message": "Not Acceptable"
},
"PROXY_AUTHENTICATION_REQUIRED": {
"code": 407,
"message": "Proxy Authentication Required"
},
"REQUEST_TIMEOUT": {
"code": 408,
"message": "Request Timeout"
},
"CONFLICT": {
"code": 409,
"message": "Conflict"
},
"GONE": {
"code": 410,
"message": "Gone"
},
"LENGTH_REQUIRED": {
"code": 411,
"message": "Length Required"
},
"PRECONDITION_FAILED": {
"code": 412,
"message": "Precondition Failed"
},
"REQUEST_TOO_LONG": {
"code": 413,
"message": "Request Entity Too Large"
},
"REQUEST_URI_TOO_LONG": {
"code": 414,
"message": "Request-URI Too Long"
},
"UNSUPPORTED_MEDIA_TYPE": {
"code": 415,
"message": "Unsupported Media Type"
},
"REQUESTED_RANGE_NOT_SATISFIABLE": {
"code": 416,
"message": "Requested Range Not Satisfiable"
},
"EXPECTATION_FAILED": {
"code": 417,
"message": "Expectation Failed"
},
"IM_A_TEAPOT": {
"code": 418,
"message": "I'm a teapot"
},
"INSUFFICIENT_SPACE_ON_RESOURCE": {
"code": 419,
"message": "Insufficient Space on Resource"
},
"METHOD_FAILURE": {
"code": 420,
"message": "Method Failure"
},
"UNPROCESSABLE_ENTITY": {
"code": 422,
"message": "Unprocessable Entity"
},
"LOCKED": {
"code": 423,
"message": "Locked"
},
"FAILED_DEPENDENCY": {
"code": 424,
"message": "Failed Dependency"
},
"PRECONDITION_REQUIRED": {
"code": 428,
"message": "Precondition Required"
},
"TOO_MANY_REQUESTS": {
"code": 429,
"message": "Too Many Requests"
},
"REQUEST_HEADER_FIELDS_TOO_LARGE": {
"code": 431,
"message": "Request Header Fields Too"
},
"UNAVAILABLE_FOR_LEGAL_REASONS": {
"code": 451,
"message": "Unavailable For Legal Reasons"
},
"INTERNAL_SERVER_ERROR": {
"code": 500,
"message": "Internal Server Error"
},
"NOT_IMPLEMENTED": {
"code": 501,
"message": "Not Implemented"
},
"BAD_GATEWAY": {
"code": 502,
"message": "Bad Gateway"
},
"SERVICE_UNAVAILABLE": {
"code": 503,
"message": "Service Unavailable"
},
"GATEWAY_TIMEOUT": {
"code": 504,
"message": "Gateway Timeout"
},
"HTTP_VERSION_NOT_SUPPORTED": {
"code": 505,
"message": "HTTP Version Not Supported"
},
"INSUFFICIENT_STORAGE": {
"code": 507,
"message": "Insufficient Storage"
},
"NETWORK_AUTHENTICATION_REQUIRED": {
"code": 511,
"message": "Network Authentication Required"
}
}
Here's a solution that is simple, short, easy to understand, and works perfectly for me. I needed to draw to the screen when another thread ends; but couldn't because the main thread has control of the screen. So:
(1) I created the global variable: boolean end1 = false;
The thread sets it to true when ending. That is picked up in the mainthread by "postDelayed" loop, where it is responded to.
(2) My thread contains:
void myThread() {
end1 = false;
new CountDownTimer(((60000, 1000) { // milliseconds for onFinish, onTick
public void onFinish()
{
// do stuff here once at end of time.
end1 = true; // signal that the thread has ended.
}
public void onTick(long millisUntilFinished)
{
// do stuff here repeatedly.
}
}.start();
}
(3) Fortunately, "postDelayed" runs in the main thread, so that's where in check the other thread once each second. When the other thread ends, this can begin whatever we want to do next.
Handler h1 = new Handler();
private void checkThread() {
h1.postDelayed(new Runnable() {
public void run() {
if (end1)
// resond to the second thread ending here.
else
h1.postDelayed(this, 1000);
}
}, 1000);
}
(4) Finally, start the whole thing running somewhere in your code by calling:
void startThread()
{
myThread();
checkThread();
}
I know this is a really old post, but I found it in searching for a solution to the same problem. I don't want a nested if-statement, and Switch is apparently newer than the version of Excel I'm using. I figured out what was going wrong with my code, so I figured I'd share here in case it helps someone else.
I remembered that VLOOKUP requires the source table to be sorted alphabetically/numerically for it to work. I was initially trying to do this...
=LOOKUP(LOWER(LEFT($T$3, 1)), {"s","l","m"}, {-1,1,0})
and it started working when I did this...
=LOOKUP(LOWER(LEFT($T$3, 1)), {"l","m","s"}, {1,0,-1})
I was initially thinking the last value might turn out to be a default, so I wanted the zero at the last place. That doesn't seem to be the behavior anyway, so I just put the possible matches in order, and it worked.
Edit: As a final note, I see that the example in the original post has letters in alphabetical order, but I imagine the real use case might have been different if the error was happening and the letters A, B, and C were just examples.
I suggest you using bootstrap which works perfectly:
@import url('http://getbootstrap.com/dist/css/bootstrap.css');_x000D_
html, body, .container-table {_x000D_
height: 100%;_x000D_
}_x000D_
.container-table {_x000D_
display: table;_x000D_
}_x000D_
.vertical-center-row {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0" />_x000D_
<title>Login Page | ... </title>_x000D_
_x000D_
<script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.0/bootstrap.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<div class="container container-table">_x000D_
<div class="row vertical-center-row">_x000D_
<div class="text-center col-md-4 col-md-offset-4" style="">_x000D_
<form id="login" action="dashboard.html" method="post">_x000D_
_x000D_
<div class="username">_x000D_
<div class="usernameinner">_x000D_
<input type="text" name="username" id="username" placeholder="Login" />_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="password">_x000D_
<div class="passwordinner">_x000D_
<input type="password" name="password" id="password" placeholder="Mot de passe" />_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<button id="login-button">Connexion</button>_x000D_
_x000D_
<div class="keep"><input type="checkbox" /> Gardez moi connecté</div>_x000D_
_x000D_
</form>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Because you set visibility either true or false.
try that
setVisible(0)
to visible true .
and setVisible(4)
to visible false.
Use conditional formatting instead of VBA to highlight errors.
Using a VBA loop like the one you posted will take a long time to process
the statement If cell.Value = "#N/A" Then
will never work. If you insist on using VBA to highlight errors, try this instead.
Sub ColorCells()
Dim Data As Range
Dim cell As Range
Set currentsheet = ActiveWorkbook.Sheets("Comparison")
Set Data = currentsheet.Range("A2:AW1048576")
For Each cell In Data
If IsError(cell.Value) Then
cell.Interior.ColorIndex = 3
End If
Next
End Sub
Be prepared for a long wait, since the procedure loops through 51 million cells
There are more efficient ways to achieve what you want to do. Update your question if you have a change of mind.
The default Apache root folder (localhost/) is /Library/WebServer/Documents
Also, make sure you have the PHP5 module loaded in /etc/apache2/httpd.conf
LoadModule php5_module libexec/apache2/libphp5.so
You forgot to add std::
namespace prefix to vector
class name.
A modified version to compensate network times and calculate with DateTime-Ticks (more precise than milliseconds)
public static DateTime GetNetworkTime()
{
const string NtpServer = "pool.ntp.org";
const int DaysTo1900 = 1900 * 365 + 95; // 95 = offset for leap-years etc.
const long TicksPerSecond = 10000000L;
const long TicksPerDay = 24 * 60 * 60 * TicksPerSecond;
const long TicksTo1900 = DaysTo1900 * TicksPerDay;
var ntpData = new byte[48];
ntpData[0] = 0x1B; // LeapIndicator = 0 (no warning), VersionNum = 3 (IPv4 only), Mode = 3 (Client Mode)
var addresses = Dns.GetHostEntry(NtpServer).AddressList;
var ipEndPoint = new IPEndPoint(addresses[0], 123);
long pingDuration = Stopwatch.GetTimestamp(); // temp access (JIT-Compiler need some time at first call)
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
socket.Connect(ipEndPoint);
socket.ReceiveTimeout = 5000;
socket.Send(ntpData);
pingDuration = Stopwatch.GetTimestamp(); // after Send-Method to reduce WinSocket API-Call time
socket.Receive(ntpData);
pingDuration = Stopwatch.GetTimestamp() - pingDuration;
}
long pingTicks = pingDuration * TicksPerSecond / Stopwatch.Frequency;
// optional: display response-time
// Console.WriteLine("{0:N2} ms", new TimeSpan(pingTicks).TotalMilliseconds);
long intPart = (long)ntpData[40] << 24 | (long)ntpData[41] << 16 | (long)ntpData[42] << 8 | ntpData[43];
long fractPart = (long)ntpData[44] << 24 | (long)ntpData[45] << 16 | (long)ntpData[46] << 8 | ntpData[47];
long netTicks = intPart * TicksPerSecond + (fractPart * TicksPerSecond >> 32);
var networkDateTime = new DateTime(TicksTo1900 + netTicks + pingTicks / 2);
return networkDateTime.ToLocalTime(); // without ToLocalTime() = faster
}
Use Convert.ToDouble(value)
rather than (double)value
. It takes an object
and supports all of the types you asked for! :)
Also, your method is always returning a string
in the code above; I'd recommend having the method indicate so, and give it a more obvious name (public string FormatLargeNumber(object value)
)
You cannot access var
with the generic.
Try something like
Console.WriteLine("Generic : {0}", test);
And override ToString
method [1]
[1] http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx
My guess is a wrong version of project A jar in your local maven repository. It seems that the dependency is resolved otherwise I think maven does not start compiling but usually these compiling error means that you have a version mix up. try to make a maven clean install
of your project A and see if it changes something for the project B...
Also a little more information on your setting could be useful:
@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs
sizes so you won't notice, but if you used anything else (e.g. col-sm
, col-md
, etc), you'd understand.
Another approach is to play with margins and padding. See the updated fiddle: http://jsfiddle.net/jz8j247x/1/
.left-side {
background-color: blue;
padding-bottom: 1000px;
margin-bottom: -1000px;
height: 100%;
}
.something {
height: 100%;
background-color: red;
padding-bottom: 1000px;
margin-bottom: -1000px;
height: 100%;
}
.row {
background-color: green;
overflow: hidden;
}
The common way of doing this is to transform the documents into TF-IDF vectors and then compute the cosine similarity between them. Any textbook on information retrieval (IR) covers this. See esp. Introduction to Information Retrieval, which is free and available online.
TF-IDF (and similar text transformations) are implemented in the Python packages Gensim and scikit-learn. In the latter package, computing cosine similarities is as easy as
from sklearn.feature_extraction.text import TfidfVectorizer
documents = [open(f) for f in text_files]
tfidf = TfidfVectorizer().fit_transform(documents)
# no need to normalize, since Vectorizer will return normalized tf-idf
pairwise_similarity = tfidf * tfidf.T
or, if the documents are plain strings,
>>> corpus = ["I'd like an apple",
... "An apple a day keeps the doctor away",
... "Never compare an apple to an orange",
... "I prefer scikit-learn to Orange",
... "The scikit-learn docs are Orange and Blue"]
>>> vect = TfidfVectorizer(min_df=1, stop_words="english")
>>> tfidf = vect.fit_transform(corpus)
>>> pairwise_similarity = tfidf * tfidf.T
though Gensim may have more options for this kind of task.
See also this question.
[Disclaimer: I was involved in the scikit-learn TF-IDF implementation.]
From above, pairwise_similarity
is a Scipy sparse matrix that is square in shape, with the number of rows and columns equal to the number of documents in the corpus.
>>> pairwise_similarity
<5x5 sparse matrix of type '<class 'numpy.float64'>'
with 17 stored elements in Compressed Sparse Row format>
You can convert the sparse array to a NumPy array via .toarray()
or .A
:
>>> pairwise_similarity.toarray()
array([[1. , 0.17668795, 0.27056873, 0. , 0. ],
[0.17668795, 1. , 0.15439436, 0. , 0. ],
[0.27056873, 0.15439436, 1. , 0.19635649, 0.16815247],
[0. , 0. , 0.19635649, 1. , 0.54499756],
[0. , 0. , 0.16815247, 0.54499756, 1. ]])
Let's say we want to find the document most similar to the final document, "The scikit-learn docs are Orange and Blue". This document has index 4 in corpus
. You can find the index of the most similar document by taking the argmax of that row, but first you'll need to mask the 1's, which represent the similarity of each document to itself. You can do the latter through np.fill_diagonal()
, and the former through np.nanargmax()
:
>>> import numpy as np
>>> arr = pairwise_similarity.toarray()
>>> np.fill_diagonal(arr, np.nan)
>>> input_doc = "The scikit-learn docs are Orange and Blue"
>>> input_idx = corpus.index(input_doc)
>>> input_idx
4
>>> result_idx = np.nanargmax(arr[input_idx])
>>> corpus[result_idx]
'I prefer scikit-learn to Orange'
Note: the purpose of using a sparse matrix is to save (a substantial amount of space) for a large corpus & vocabulary. Instead of converting to a NumPy array, you could do:
>>> n, _ = pairwise_similarity.shape
>>> pairwise_similarity[np.arange(n), np.arange(n)] = -1.0
>>> pairwise_similarity[input_idx].argmax()
3
Add a reference to the ngForm
directive in your html code and this gives you access to the form.
<form #myForm="ngForm" (ngSubmit)="addPost(); myForm.reset()"> ... </form>
Or pass the form to the function:
<form #myForm="ngForm" (ngSubmit)="addPost(myForm)"> ... </form>
addPost(form: NgForm){
this.newPost = {
title: this.title,
body: this.body
}
this._postService.addPost(this.newPost);
form.resetForm(); // or form.reset();
}
The difference between resetForm
and reset
is that the former will clear the form fields as well as any validation, while the later will only clear the fields. Use resetForm after the form is validated and submitted, otherwise use reset.
Adding another example for people who can't get the above to work.
With button press:
<form #heroForm="ngForm">
...
<button type="button" class="btn btn-default" (click)="newHero(); heroForm.reset()">New Hero</button>
</form>
Same thing applies above, you can also choose to pass the form to the newHero
function.
These commands worked for me:
npm uninstall -g cordova
npm uninstall -g ionic
One thing that nobody's mentioned is to visit the page. I had my designer file stop regenerating because I was including a user control that didn't exist (for various reasons), and none of the things suggested here worked. For whatever reason, I didn't get any errors in Visual Studio - besides the one complaining about the fact that my client-side controls didn't exist because they weren't being regenerated, of course.
It took actually visiting the page to get ASP.Net to tell me the error.
I had a .live("focus") event set to select() (highlight) the contents of a text input so that the user wouldn't have to select it before typing a new value.
$(formObj).select();
Because of quirks between different browsers, the select would sometimes be superseded by the click that caused it, and it would deselect the contents right after in favor of placing the cursor within the text field (worked mostly ok in FF but failed in IE)
I thought I could solve this by putting a slight delay on the select...
setTimeout(function(){$(formObj).select();},200);
This worked fine and the select would persist, but a funny problem arose.. If you tabbed from one field to the next, the focus would switch to the next field before the select took place. Since select steals focus, the focus would then go back and trigger a new "focus" event. This ended up in a cascade of input selects dancing all over the screen.
A workable solution would be to check that the field still has focus before executing the select(), but as mentioned, there's no simple way to check... I ended up just dispensing with the whole auto highlight, rather than turning what should be a single jQuery select() call into a huge function laden with subroutines...
You can add log4jdbc to your project. This adds logging of sql commands as they execute + a lot of other information.
Why not copy Microsoft.Web.Infrastructure.dll file manually to the server BIN folder. This works for. My project is VS2010 Website.
This file can be located:
C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40
Just copy and paste it in the BIN folder.
You probably need to include this in the web.config if you don't have it already
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</assemblies>
</compilation>
Reference: http://thedeveloperblog.com/
Here is how I add parameters:
sprocCommand.Parameters.Add(New SqlParameter("@Date_Of_Birth",Data.SqlDbType.DateTime))
sprocCommand.Parameters("@Date_Of_Birth").Value = DOB
I am assuming when you write out DOB there are no quotes.
Are you using a third-party control to get the date? I have had problems with the way the text value is generated from some of them.
Lastly, does it work if you type in the .Value attribute of the parameter without referencing DOB?
Commenting on Ken Bertelson solution and answering Jan Hettich:
the takes_ary_as_arg descTable[@] optsTable[@]
line in try_with_local_arys()
function sends:
descTable
and optsTable
arrays which are accessible to the takes_ary_as_arg
function. takes_ary_as_arg()
function receives descTable[@]
and optsTable[@]
as strings, that means $1 == descTable[@]
and $2 == optsTable[@]
.in the beginning of takes_ary_as_arg()
function it uses ${!parameter}
syntax, which is called indirect reference or sometimes double referenced, this means that instead of using $1
's value, we use the value of the expanded value of $1
, example:
baba=booba
variable=baba
echo ${variable} # baba
echo ${!variable} # booba
likewise for $2
.
argAry1=("${!1}")
creates argAry1
as an array (the brackets following =
) with the expanded descTable[@]
, just like writing there argAry1=("${descTable[@]}")
directly.
the declare
there is not required.N.B.: It is worth mentioning that array initialization using this bracket form initializes the new array according to the IFS
or Internal Field Separator which is by default tab, newline and space. in that case, since it used [@]
notation each element is seen by itself as if he was quoted (contrary to [*]
).
In BASH
, local variable scope is the current function and every child function called from it, this translates to the fact that takes_ary_as_arg()
function "sees" those descTable[@]
and optsTable[@]
arrays, thus it is working (see above explanation).
Being that case, why not directly look at those variables themselves? It is just like writing there:
argAry1=("${descTable[@]}")
See above explanation, which just copies descTable[@]
array's values according to the current IFS
.
This is passing, in essence, nothing by value - as usual.
I also want to emphasize Dennis Williamson comment above: sparse arrays (arrays without all the keys defines - with "holes" in them) will not work as expected - we would loose the keys and "condense" the array.
That being said, I do see the value for generalization, functions thus can get the arrays (or copies) without knowing the names:
for real copies: we can use an eval for the keys, for example:
eval local keys=(\${!$1})
and then a loop using them to create a copy.
Note: here !
is not used it's previous indirect/double evaluation, but rather in array context it returns the array indices (keys).
descTable
and optsTable
strings (without [@]
), we could use the array itself (as in by reference) with eval
. for a generic function that accepts arrays.This answer is an update, circa November 2019. None of the popular pip installs will give you a working setup on MacOS 10.13 (and likely other versions as well). Here is a simple way that I got things working:
brew install mysql
pip install mysqlclient
If you need help installing brew, see this site: https://brew.sh/
It sounds like you need to some background reading on what an FFT is (e.g. http://en.wikipedia.org/wiki/FFT). But to answer your questions:
Why does the x-axis (frequency) end at 500?
Because the input vector is length 1000. In general, the FFT of a length-N
input waveform will result in a length-N
output vector. If the input waveform is real, then the output will be symmetrical, so the first 501 points are sufficient.
Edit: (I didn't notice that the example padded the time-domain vector.)
The frequency goes to 500 Hz because the time-domain waveform is declared to have a sample-rate of 1 kHz. The Nyquist sampling theorem dictates that a signal with sample-rate fs
can support a (real) signal with a maximum bandwidth of fs/2
.
How do I know the frequencies are between 0 and 500?
See above.
Shouldn't the FFT tell me, in which limits the frequencies are?
No.
Does the FFT only return the amplitude value without the frequency?
The FFT simply assigns an amplitude (and phase) to every frequency bin.
Would suggest NOT using INSERT IGNORE as it ignores ALL errors (ie its a sloppy global ignore).
Instead, since in your example tag
is the unique key, use:
INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c') ON DUPLICATE KEY UPDATE tag=tag;
on duplicate key produces:
Query OK, 0 rows affected (0.07 sec)
<android . . . >
. . .
<manifest . . . >
. . .
<application>
<activity android:name=".MyActivity"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation">
</activity>
</application>
</manifest>
</android>