As @Sean said, fcntl()
is largely standardized, and therefore available across platforms. The ioctl()
function predates fcntl()
in Unix, but is not standardized at all. That the ioctl()
worked for you across all the platforms of relevance to you is fortunate, but not guaranteed. In particular, the names used for the second argument are arcane and not reliable across platforms. Indeed, they are often unique to the particular device driver that the file descriptor references. (The ioctl()
calls used for a bit-mapped graphics device running on an ICL Perq running PNX (Perq Unix) of twenty years ago never translated to anything else anywhere else, for example.)
Copied answer from the attached question.
You can use PM2, it's a production process manager for Node.js applications with a built-in load balancer.
Install PM2
$ npm install pm2 -g
Start an application
$ pm2 start app.js
If you using express then you can start your app like
pm2 start ./bin/www --name="app"
Listing all running processes:
$ pm2 list
It will list all process. You can then stop / restart your service by using ID or Name of the app with following command.
$ pm2 stop all
$ pm2 stop 0
$ pm2 restart all
To display logs
$ pm2 logs ['all'|app_name|app_id]
Padding is a way to add kind of a margin inside the Div.
Just Use
div { padding-left: 20px; }
And to mantain the size, you would have to -20px from the original width of the Div.
Matplotlib uses a dictionary from its colors.py module.
To print the names use:
# python2:
import matplotlib
for name, hex in matplotlib.colors.cnames.iteritems():
print(name, hex)
# python3:
import matplotlib
for name, hex in matplotlib.colors.cnames.items():
print(name, hex)
This is the complete dictionary:
cnames = {
'aliceblue': '#F0F8FF',
'antiquewhite': '#FAEBD7',
'aqua': '#00FFFF',
'aquamarine': '#7FFFD4',
'azure': '#F0FFFF',
'beige': '#F5F5DC',
'bisque': '#FFE4C4',
'black': '#000000',
'blanchedalmond': '#FFEBCD',
'blue': '#0000FF',
'blueviolet': '#8A2BE2',
'brown': '#A52A2A',
'burlywood': '#DEB887',
'cadetblue': '#5F9EA0',
'chartreuse': '#7FFF00',
'chocolate': '#D2691E',
'coral': '#FF7F50',
'cornflowerblue': '#6495ED',
'cornsilk': '#FFF8DC',
'crimson': '#DC143C',
'cyan': '#00FFFF',
'darkblue': '#00008B',
'darkcyan': '#008B8B',
'darkgoldenrod': '#B8860B',
'darkgray': '#A9A9A9',
'darkgreen': '#006400',
'darkkhaki': '#BDB76B',
'darkmagenta': '#8B008B',
'darkolivegreen': '#556B2F',
'darkorange': '#FF8C00',
'darkorchid': '#9932CC',
'darkred': '#8B0000',
'darksalmon': '#E9967A',
'darkseagreen': '#8FBC8F',
'darkslateblue': '#483D8B',
'darkslategray': '#2F4F4F',
'darkturquoise': '#00CED1',
'darkviolet': '#9400D3',
'deeppink': '#FF1493',
'deepskyblue': '#00BFFF',
'dimgray': '#696969',
'dodgerblue': '#1E90FF',
'firebrick': '#B22222',
'floralwhite': '#FFFAF0',
'forestgreen': '#228B22',
'fuchsia': '#FF00FF',
'gainsboro': '#DCDCDC',
'ghostwhite': '#F8F8FF',
'gold': '#FFD700',
'goldenrod': '#DAA520',
'gray': '#808080',
'green': '#008000',
'greenyellow': '#ADFF2F',
'honeydew': '#F0FFF0',
'hotpink': '#FF69B4',
'indianred': '#CD5C5C',
'indigo': '#4B0082',
'ivory': '#FFFFF0',
'khaki': '#F0E68C',
'lavender': '#E6E6FA',
'lavenderblush': '#FFF0F5',
'lawngreen': '#7CFC00',
'lemonchiffon': '#FFFACD',
'lightblue': '#ADD8E6',
'lightcoral': '#F08080',
'lightcyan': '#E0FFFF',
'lightgoldenrodyellow': '#FAFAD2',
'lightgreen': '#90EE90',
'lightgray': '#D3D3D3',
'lightpink': '#FFB6C1',
'lightsalmon': '#FFA07A',
'lightseagreen': '#20B2AA',
'lightskyblue': '#87CEFA',
'lightslategray': '#778899',
'lightsteelblue': '#B0C4DE',
'lightyellow': '#FFFFE0',
'lime': '#00FF00',
'limegreen': '#32CD32',
'linen': '#FAF0E6',
'magenta': '#FF00FF',
'maroon': '#800000',
'mediumaquamarine': '#66CDAA',
'mediumblue': '#0000CD',
'mediumorchid': '#BA55D3',
'mediumpurple': '#9370DB',
'mediumseagreen': '#3CB371',
'mediumslateblue': '#7B68EE',
'mediumspringgreen': '#00FA9A',
'mediumturquoise': '#48D1CC',
'mediumvioletred': '#C71585',
'midnightblue': '#191970',
'mintcream': '#F5FFFA',
'mistyrose': '#FFE4E1',
'moccasin': '#FFE4B5',
'navajowhite': '#FFDEAD',
'navy': '#000080',
'oldlace': '#FDF5E6',
'olive': '#808000',
'olivedrab': '#6B8E23',
'orange': '#FFA500',
'orangered': '#FF4500',
'orchid': '#DA70D6',
'palegoldenrod': '#EEE8AA',
'palegreen': '#98FB98',
'paleturquoise': '#AFEEEE',
'palevioletred': '#DB7093',
'papayawhip': '#FFEFD5',
'peachpuff': '#FFDAB9',
'peru': '#CD853F',
'pink': '#FFC0CB',
'plum': '#DDA0DD',
'powderblue': '#B0E0E6',
'purple': '#800080',
'red': '#FF0000',
'rosybrown': '#BC8F8F',
'royalblue': '#4169E1',
'saddlebrown': '#8B4513',
'salmon': '#FA8072',
'sandybrown': '#FAA460',
'seagreen': '#2E8B57',
'seashell': '#FFF5EE',
'sienna': '#A0522D',
'silver': '#C0C0C0',
'skyblue': '#87CEEB',
'slateblue': '#6A5ACD',
'slategray': '#708090',
'snow': '#FFFAFA',
'springgreen': '#00FF7F',
'steelblue': '#4682B4',
'tan': '#D2B48C',
'teal': '#008080',
'thistle': '#D8BFD8',
'tomato': '#FF6347',
'turquoise': '#40E0D0',
'violet': '#EE82EE',
'wheat': '#F5DEB3',
'white': '#FFFFFF',
'whitesmoke': '#F5F5F5',
'yellow': '#FFFF00',
'yellowgreen': '#9ACD32'}
You could plot them like this:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.colors as colors
import math
fig = plt.figure()
ax = fig.add_subplot(111)
ratio = 1.0 / 3.0
count = math.ceil(math.sqrt(len(colors.cnames)))
x_count = count * ratio
y_count = count / ratio
x = 0
y = 0
w = 1 / x_count
h = 1 / y_count
for c in colors.cnames:
pos = (x / x_count, y / y_count)
ax.add_patch(patches.Rectangle(pos, w, h, color=c))
ax.annotate(c, xy=pos)
if y >= y_count-1:
x += 1
y = 0
else:
y += 1
plt.show()
Pressing (Cmd + /) will create a single line comment. i.e. // Single line comment
Type (/**
and press the Tab key) to create a block comment ala
/**
* Comment block
*/
I believe to check if a key exists in a hash you just do
if (exists $strings{$string}) {
...
} else {
...
}
I might be late to the party, but as per my understanding , you're looking for something like this :
for(String params : Collections.list(httpServletRequest.getParameterNames())) {
// Whatever you want to do with your map
// Key : params
// Value : httpServletRequest.getParameter(params)
}
read filename ;
sed -i 's/letter/newletter/g' "$filename" #letter
^use as many of these as you need, and you can make your own BASIC encryption
the case above is for a new project. I hit upon this error while editing a fork of a well established library.
the typedef was included in the file I was editing but the struct wasn't.
The end result being that I was attempting to edit the struct in the wrong place.
If you run into this in a similar way look for other places where the struct is edited and try it there.
Your syntax isn't quite right: you need to list the fields in order before the INTO, and the corresponding target variables after:
SELECT Id, dateCreated
INTO iId, dCreate
FROM products
WHERE pName = iName
Notepad++ changed in the past couple of years, and it requires a few extra steps to set up a dark theme.
The answer by Amit-IO is good, but the example theme that is needed has stopped being maintained. The DraculaTheme is active. Just download the XML and put it in a themes folder. You may need Admin access in Windows.
C:\Users\YOUR_USER\AppData\Roaming\Notepad++\themes
NSDictionary -> NSData:
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:yourDictionary forKey:@"Some Key Value"];
[archiver finishEncoding];
[archiver release];
// Here, data holds the serialized version of your dictionary
// do what you need to do with it before you:
[data release];
NSData -> NSDictionary
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSDictionary *myDictionary = [[unarchiver decodeObjectForKey:@"Some Key Value"] retain];
[unarchiver finishDecoding];
[unarchiver release];
[data release];
You can do that with any class that conforms to NSCoding.
There were several problems in your code. Here you have a functional version you can analyze (Lets set 'hello' as the target word):
word = 'hello'
so_far = "-" * len(word) # Create variable so_far to contain the current guess
while word != so_far: # if still not complete
print(so_far)
guess = input('>> ') # get a char guess
if guess in word:
print("\nYes!", guess, "is in the word!")
new = ""
for i in range(len(word)):
if guess == word[i]:
new += guess # fill the position with new value
else:
new += so_far[i] # same value as before
so_far = new
else:
print("try_again")
print('finish')
I tried to write it for py3k with a py2k ide, be careful with errors.
EDIT:
The info below is only applicable to VS2008 and the 3.5 framework. VS2010 has a new registry location. Further details can be found on MSDN: How to Add or Remove References in Visual Studio.
ORIGINAL
It should be listed in the .NET tab of the Add Reference dialog. Assemblies that appear there have paths in registry keys under:
HKLM\Software\Microsoft\.NETFramework\AssemblyFolders\
I have a key there named Microsoft .NET Framework 3.5 Reference Assemblies with a string value of:
C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\
Navigating there I can see the actual System.Web.Extensions dll.
EDIT:
I found my .NET 4.0 version in:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Web.Extensions.dll
I'm running Win 7 64 bit, so if you're on a 32 bit OS drop the (x86).
To verify at server side using PHP. Two most important thing you need to consider.
1. $_POST['g-recaptcha-response']
2.$secretKey = '6LeycSQTAAAAAMM3AeG62pBslQZwBTwCbzeKt06V';
$verifydata = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&response='.$_POST['g-recaptcha-response']);
$response= json_decode($verifydata);
If you get $verifydata true, You done.
For more check out this
Google reCaptcha Using PHP | Only 2 Step Integration
As mentioned, for efficiency reasons sequential spaces are consolidated into one space the browser actually displays. Remember what the ML in HTML stand for. It's a Mark-up Language, designed to control how text is displayed.. not whitespace :p
Still, you can pretend the browser respects tabs since all the TAB does is prepend 4 spaces, and that's easy with CSS. either in line like ...
<div style="padding-left:4.00em;">Indenented text </div>
Or as a regular class in a style sheet
.tabbed {padding-left:4.00em;}
Then the HTML might look like
<p>regular paragraph regular paragraph regular paragraph</p>
<p class="tabbed">Indented text Indented text Indented text</p>
<p>regular paragraph regular paragraph regular paragraph</p>
There are two solutions posted on that page. The one with lower votes I would recommend if possible.
If you are using HTML5 then it is perfectly valid to put a div
inside of a
. As long as the div doesn't also contain some other specific elements like other link tags.
<a href="Music.html">
<div id="music" class="nav">
Music I Like
</div>
</a>
The solution you are confused about actually makes the link as big as its container div. To make it work in your example you just need to add position: relative
to your div. You also have a small syntax error which is that you have given the span a class instead of an id. You also need to put your span inside the link because that is what the user is clicking on. I don't think you need the z-index
at all from that example.
div { position: relative; }
.hyperspan {
position:absolute;
width:100%;
height:100%;
left:0;
top:0;
}
<div id="music" class="nav">Music I Like
<a href="http://www.google.com">
<span class="hyperspan"></span>
</a>
</div>
When you give absolute
positioning to an element it bases its location and size after the first parent it finds that is relatively positioned. If none, then it uses the document. By adding relative
to the parent div you tell the span to only be as big as that.
In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198
Let us take an example of dictionary:
numbers = {'first':0, 'second':1, 'third':3}
When I did
numbers.values()[index]
I got an error:'dict_values' object does not support indexing
When I did
numbers.itervalues()
to iterate and extract the values it is also giving an error:'dict' object has no attribute 'iteritems'
Hence I came up with new way of accessing dictionary elements by index just by converting them to tuples.
tuple(numbers.items())[key_index][value_index]
for example:
tuple(numbers.items())[0][0] gives 'first'
if u want to edit the values or sort the values the tuple object does not allow the item assignment. In this case you can use
list(list(numbers.items())[index])
You can try joda-time.
I had the same error message but was using psycopg2
to communicate with PostgreSQL. I fixed the permission issues by using the functions copy_from
and copy_expert
that will open the file on the client side as the user running the python script and feed the data to the database over STDIN
.
Refer to this link for further information.
Because you can only deactivate the active environment, so conda deactivate does not need nor accept arguments. The error message is very explicit here.
Just call conda deactivate https://github.com/conda/conda/issues/7296#issuecomment-389504269
Use the same function (cor
) on a data frame, e.g.:
> cor(VADeaths)
Rural Male Rural Female Urban Male Urban Female
Rural Male 1.0000000 0.9979869 0.9841907 0.9934646
Rural Female 0.9979869 1.0000000 0.9739053 0.9867310
Urban Male 0.9841907 0.9739053 1.0000000 0.9918262
Urban Female 0.9934646 0.9867310 0.9918262 1.0000000
Or, on a data frame also holding discrete variables, (also sometimes referred to as factors), try something like the following:
> cor(mtcars[,unlist(lapply(mtcars, is.numeric))])
mpg cyl disp hp drat wt qsec vs am gear carb
mpg 1.0000000 -0.8521620 -0.8475514 -0.7761684 0.68117191 -0.8676594 0.41868403 0.6640389 0.59983243 0.4802848 -0.55092507
cyl -0.8521620 1.0000000 0.9020329 0.8324475 -0.69993811 0.7824958 -0.59124207 -0.8108118 -0.52260705 -0.4926866 0.52698829
disp -0.8475514 0.9020329 1.0000000 0.7909486 -0.71021393 0.8879799 -0.43369788 -0.7104159 -0.59122704 -0.5555692 0.39497686
hp -0.7761684 0.8324475 0.7909486 1.0000000 -0.44875912 0.6587479 -0.70822339 -0.7230967 -0.24320426 -0.1257043 0.74981247
drat 0.6811719 -0.6999381 -0.7102139 -0.4487591 1.00000000 -0.7124406 0.09120476 0.4402785 0.71271113 0.6996101 -0.09078980
wt -0.8676594 0.7824958 0.8879799 0.6587479 -0.71244065 1.0000000 -0.17471588 -0.5549157 -0.69249526 -0.5832870 0.42760594
qsec 0.4186840 -0.5912421 -0.4336979 -0.7082234 0.09120476 -0.1747159 1.00000000 0.7445354 -0.22986086 -0.2126822 -0.65624923
vs 0.6640389 -0.8108118 -0.7104159 -0.7230967 0.44027846 -0.5549157 0.74453544 1.0000000 0.16834512 0.2060233 -0.56960714
am 0.5998324 -0.5226070 -0.5912270 -0.2432043 0.71271113 -0.6924953 -0.22986086 0.1683451 1.00000000 0.7940588 0.05753435
gear 0.4802848 -0.4926866 -0.5555692 -0.1257043 0.69961013 -0.5832870 -0.21268223 0.2060233 0.79405876 1.0000000 0.27407284
carb -0.5509251 0.5269883 0.3949769 0.7498125 -0.09078980 0.4276059 -0.65624923 -0.5696071 0.05753435 0.2740728 1.00000000
sometimes SECURITY issues prevent from asking for all the db's and you need to query one by one with the db prefix, for those cases i created this dynamic query
go
declare @Results table ([Name] nvarchar(max), [DataFileSizeMB] int, [LogFileSizeMB] int);
declare @QaQuery nvarchar(max)
declare @name nvarchar(max)
declare MY_CURSOR cursor
local static read_only forward_only
for
select name from master.dbo.sysdatabases where name not in ('master', 'tempdb', 'model', 'msdb', 'rdsadmin');
open MY_CURSOR
fetch next from MY_CURSOR into @name
while @@FETCH_STATUS = 0
begin
if(len(@name)>0)
begin
print @name + ' Column Exist'
set @QaQuery = N'select
'''+@name+''' as Name
,sum(case when type = 0 then size else 0 end) as DataFileSizeMB
,sum(case when type = 1 then size else 0 end) as LogFileSizeMB
from ['+@name+'].sys.database_files
group by replace(name, ''_log'', '''')';
insert @Results exec sp_executesql @QaQuery;
end
fetch next from MY_CURSOR into @name
end
close MY_CURSOR
deallocate MY_CURSOR
select * from @Results order by DataFileSizeMB desc
go
Can't figure out how to add to the code or reply to the message but here's support for jython that you can tack in before you give up:
# jython
try:
from java.lang import Runtime
runtime = Runtime.getRuntime()
res = runtime.availableProcessors()
if res > 0:
return res
except ImportError:
pass
There is less confusion. Take Font
for instance. It has a constructor that takes the name of the Font
you want, its size and its style (new Font(String, int, int)
). To this day I cannot remember if style or size goes first. If Font
had used an enum
for all of its different styles (PLAIN
, BOLD
, ITALIC
, BOLD_ITALIC
), its constructor would look like Font(String, Style, int)
, preventing any confusion. Unfortunately, enum
s weren't around when the Font
class was created, and since Java has to maintain reverse compatibility, we will always be plagued by this ambiguity.
Of course, this is just an argument for using an enum
instead of public static final
constants. Enums are also perfect for singletons and implementing default behavior while allowing for later customization (I.E. the strategy pattern). An example of the latter is java.nio.file
's OpenOption
and StandardOpenOption
: if a developer wanted to create his own non-standard OpenOption
, he could.
You can use this to refresh an Activity from within itself.
finish();
startActivity(getIntent());
If you want to create an Android application using c# language you can use Xamarin.
they created this great Cross Platform development tool which enables developers to develop iOS and Android apps in C# language.
Xamarin is offered in different licenses from free to enterprise levels but for not I will be using the starter version which is the free version. It includes the Xamarin Studio which is great start for those who want to try out creating their first apps for Android, they also offer a Business license which lets you develop in Visual Studio so you can use that rich experience similar to developing Web Apps or Windows Apps, then they have this Enterprise which contains everything
If above solutions doesn't work, try to change the default por from 3306, to another one (i.e. 3307)
In python 3 this is easy
myVariable = 5
for v in locals():
if id(v) == id("myVariable"):
print(v, locals()[v])
this will print:
myVariable 5
A less verbose version with AWK:
awk 'NR > 1e6' myfile.txt
But I would recommend using integer numbers.
If any of the above answers worked out, You can create new artifact directly from the admin side of (NEXUS Screen shot attached below).
Login to nexus
UI http://YOUR_URL:8081/nexus( username: admin
default password: admin123 )Click repositories
on the left side then click the repo, For eg: click release.artifact Upload
(last tab). GAV definition
as GAV Param
- Then enter your groupid , artifact id and version .Now you will be able to add the corrsponding in your project.(screenshot below)
In case that doesn't work there is another way that works especially well in Windows: Kill localhost:3000 process from Windows command line
To change action value of form dynamically, you can try below code:
below code is if you are opening some dailog box and inside that dailog box you have form and you want to change the action of it. I used Bootstrap dailog box and on opening of that dailog box I am assigning action value to the form.
$('#your-dailog-id').on('show.bs.modal', function (event) {
var link = $(event.relatedTarget);// Link that triggered the modal
var cURL= link.data('url');// Extract info from data-* attributes
$("#delUserform").attr("action", cURL);
});
If you are trying to change the form action on regular page, use below code
$("#yourElementId").change(function() {
var action = <generate_action>;
$("#formId").attr("action", action);
});
Uninstalling older versions of JDK would have worked. But it may be a workaround i guess. I faced the same issue and noticed that both new version of JDK and older version JDK path has been mentioned in 'path
' environmental variable.
Removing the older version JDK path from 'path
' environmental variable did the trick for me. Hope it helps someone too.
Suppose a 9800GT GPU:
https://www.tutorialspoint.com/cuda/cuda_threads.htm
A block cannot have more active threads than 512 therefore __syncthreads
can only synchronize limited number of threads. i.e. If you execute the following with 600 threads:
func1();
__syncthreads();
func2();
__syncthreads();
then the kernel must run twice and the order of execution will be:
Note:
The main point is __syncthreads
is a block-wide operation and it does not synchronize all threads.
I'm not sure about the exact number of threads that __syncthreads
can synchronize, since you can create a block with more than 512 threads and let the warp handle the scheduling. To my understanding it's more accurate to say: func1 is executed at least for the first 512 threads.
Before I edited this answer (back in 2010) I measured 14x8x32 threads were synchronized using __syncthreads
.
I would greatly appreciate if someone test this again for a more accurate piece of information.
If you are still getting that error after installing the 64 bit JRE, it means that the JVM running Gurobi package is still using the 32 bit JRE.
Check that you have updated the PATH and JAVA_HOME globally and in the command shell that you are using. (Maybe you just need to exit and restart it.)
Check that your command shell runs the right version of Java by running "java -version" and checking that it says it is a 64bit JRE.
If you are launching the example via a wrapper script / batch file, make sure that the script is using the right JRE. Modify as required ...
also, for syndicated content "Authors are encouraged to use the article element instead of the section element when it would make sense to syndicate the contents of the element."
After 2 hours of searching, I found a way to fix it with just one line of command. You need to know the version of the package (Just search up PACKAGE version).
Command:
python3 -m pip install --pre --upgrade PACKAGE==VERSION.VERSION.VERSION
You could try using scipy.ndimage.convolve
it allows convolution of multidimensional images. here is the docs
Origanally answered here
On Android, there is Uri class in package android.net . Note that Uri is part of android.net, while URI is part of java.net .
Uri class has many functions to extract query key-value pairs.
Following function returns key-value pairs in the form of HashMap.
In Java:
Map<String, String> getQueryKeyValueMap(Uri uri){
HashMap<String, String> keyValueMap = new HashMap();
String key;
String value;
Set<String> keyNamesList = uri.getQueryParameterNames();
Iterator iterator = keyNamesList.iterator();
while (iterator.hasNext()){
key = (String) iterator.next();
value = uri.getQueryParameter(key);
keyValueMap.put(key, value);
}
return keyValueMap;
}
In Kotlin:
fun getQueryKeyValueMap(uri: Uri): HashMap<String, String> {
val keyValueMap = HashMap<String, String>()
var key: String
var value: String
val keyNamesList = uri.queryParameterNames
val iterator = keyNamesList.iterator()
while (iterator.hasNext()) {
key = iterator.next() as String
value = uri.getQueryParameter(key) as String
keyValueMap.put(key, value)
}
return keyValueMap
}
If you have a command window open and call the commands manually, you can display a timestamp on each prompt, e.g.
prompt $d $t $_$P$G
It gives you something like:
23.03.2009 15:45:50,77
C:\>
If you have a small batch script that executes your commands, have an empty line before each command, e.g.
(empty line)
myCommand.exe
(next empty line)
myCommand2.exe
You can calculate the execution time for each command by the time information in the prompt. The best would probably be to pipe the output to a textfile for further analysis:
MyBatchFile.bat > output.txt
history.pushState(null, null, document.title);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.title);
});
This script will overwrite attempts to navigate back and forth with the state of the current page.
Update:
Some users have reported better success with using document.URL
instead of document.title
:
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});
foreach
:
foreach (var money in myMoney) {
Console.WriteLine("Amount is {0} and type is {1}", money.amount, money.type);
}
Alternatively, because it is a List<T>
.. which implements an indexer method []
, you can use a normal for
loop as well.. although its less readble (IMO):
for (var i = 0; i < myMoney.Count; i++) {
Console.WriteLine("Amount is {0} and type is {1}", myMoney[i].amount, myMoney[i].type);
}
It is already a list
type(my_set)
>>> <type 'list'>
Do you want something like
my_set = set([1,2,3,4])
my_list = list(my_set)
print my_list
>> [1, 2, 3, 4]
EDIT : Output of your last comment
>>> my_list = [1,2,3,4]
>>> my_set = set(my_list)
>>> my_new_list = list(my_set)
>>> print my_new_list
[1, 2, 3, 4]
I'm wondering if you did something like this :
>>> set=set()
>>> set([1,2])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object is not callable
Or use JodaTime:
DateTime lastWeek = new DateTime().minusDays(7);
def capitalizeWords(s):
return re.sub(r'\w+', lambda m:m.group(0).capitalize(), s)
re.sub
can take a function for the "replacement" (rather than just a string, which is the usage most people seem to be familiar with). This repl function will be called with an re.Match
object for each match of the pattern, and the result (which should be a string) will be used as a replacement for that match.
A longer version of the same thing:
WORD_RE = re.compile(r'\w+')
def capitalizeMatch(m):
return m.group(0).capitalize()
def capitalizeWords(s):
return WORD_RE.sub(capitalizeMatch, s)
This pre-compiles the pattern (generally considered good form) and uses a named function instead of a lambda.
The Swifty way is to use the new UIAlertController and closures:
// Create the alert controller
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
NSLog("OK Pressed")
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
}
// Add the actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// Present the controller
self.presentViewController(alertController, animated: true, completion: nil)
Swift 3:
// Create the alert controller
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
}
// Add the actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// Present the controller
self.present(alertController, animated: true, completion: nil)
They can be different on word-addressable machines (e.g., Cray PVP systems).
Most computers today are byte-addressable machines, where each address refers to a byte of memory. There, all data pointers are usually the same size, namely the size of a machine address.
On word-adressable machines, each machine address refers instead to a word larger than a byte. On these, a (char *) or (void *) pointer to a byte of memory has to contain both a word address plus a byte offset within the addresed word.
http://docs.cray.com/books/004-2179-001/html-004-2179-001/rvc5mrwh.html
As stated in other responses, the build tools requires the --all
flag to be installed. You also better use a -t
filter flag to avoid installing ALL the packages but there is no way to filter all the build tools.
There are already features requests for these two points in AOSP bug tracker. Feel free to vote for them, this might make them happen some day:
I am posting this answer because none of the other answers given here actually worked for me. I could not use COPY
from within Postgres, because I did not have the correct permissions. So I chose "Export grid rows" and saved the output as UTF-8.
The psql
version given by @Brian also did not work for me, for a different reason. The reason it did not work is that apparently the Windows command prompt (I was using Windows) was meddling around with the encoding on its own. I kept getting this error:
ERROR: character with byte sequence 0x81 in encoding "WIN1252" has no equivalent in encoding "UTF8"
The solution I ended up using was to write a short JDBC script (Java) which read the CSV file and issued insert statements directly into my Postgres table. This worked, but the command prompt also would have worked had it not been altering the encoding.
The invalid hostname indicates that the actual site you configured in the IIS Express configuration file is (most likely) not running. IIS Express doesn't have a process model like IIS does.
For your site to run it would need to be started explicitly (either by opening and accessing from webmatrix, or from command line calling iisexpress.exe (from it's installation directory) with the /site parameter.
In general, the steps to allow fully qualified DNS names to be used for local access are Let's use your example of the DNS name dev.example.com
Configure IIS Express binding for your site (eg:Site1) to include dev.example.com. Administrative privilege will be needed to use the binding. Alternatively, a one-time URL reservation can be made with http.sys using
netsh http add urlacl url=http://dev.example.com:<port>/ user=<user_name>
start iisexpress /site:Site1
or open Site1 in WebMatrix
I'm surprised nobody has mentioned it before, but FindBin::libs will always find your libs as it searches in all reasonable places relative to the location of your script.
#!/usr/bin/perl
use FindBin::libs;
use <your lib>;
I also tried to update a component from a jsf backing bean/class
You need to do the following after manipulating the UI component:
FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add(componentToBeRerendered.getClientId())
It is important to use the clientId instead of the (server-side) componentId!!
Note that $(element).offset()
tells you the position of an element relative to the document. This works great in most circumstances, but in the case of position:fixed
you can get unexpected results.
If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your position:fixed
element's offset()
value will be greater than the expected value by the amount you have scrolled.
If you are looking for a value relative to the viewport (window), rather than the document on a position:fixed element, you can subtract the document's scrollTop()
value from the fixed element's offset().top
value. Example: $("#el").offset().top - $(document).scrollTop()
If the position:fixed
element's offset parent is the document, you want to read parseInt($.css('top'))
instead.
From: http://www.danrigsby.com/blog/index.php/2008/06/17/rest-and-max-url-size/
According to some comments on Super User it still works :) It just should be copied back to the plugins folder (if it's in the disabled folder) or downloaded from Plugins Central. I have downloaded it a few minutes ago and succeeded in using it.
Of course, be warned: this plugin COULD be unstable in some situations - that's why it was disabled.
Depending on which OS you're using, if you are flexible, then CHOICE
can be used to wait on almost any key EXCEPT
enter
If you are really referring to what Microsoft insists on calling "Command Prompt" which is simply an MS-DOS emulator, then perhaps TIMEOUT
may suit your purpose (timeout /t -1
waits on any key, not just ENTER
) and of course CHOICE
is available again in recent WIN editions.
And a warning on SET /P
- whereas set /p DUMMY=Hit ENTER to continue...
will work,
set "dummy="
set /p DUMMY=Hit ENTER to continue...
if defined dummy (echo not just ENTER was pressed) else (echo just ENTER was pressed)
will detect whether just ENTER or something else, ending in ENTER was keyed in.
From SQL Server 2016 you can just use
DROP TABLE IF EXISTS ##CLIENTS_KEYWORD
On previous versions you can use
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
/*Then it exists*/
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD
(
client_id INT
)
You could also consider truncating the table instead rather than dropping and recreating.
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
TRUNCATE TABLE ##CLIENTS_KEYWORD
ELSE
CREATE TABLE ##CLIENTS_KEYWORD
(
client_id INT
)
The res.json()
function should be sufficient for most cases.
app.get('/', (req, res) => res.json({ answer: 42 }));
The res.json()
function converts the parameter you pass to JSON using JSON.stringify()
and sets the Content-Type
header to application/json; charset=utf-8
so HTTP clients know to automatically parse the response.
just do this
try
{
//some code
try
{
int idNumber = function2();
}
finally
{
do stuff here....
}
}
catch(Exception e)
{//... perhaps something here}
For all intents and purposes the finally block will always execute. Now there are a couple of exceptions where it won't actually execute: task killing the program, and there is a fast fail security exception which kills the application instantly. Other than that, an exception will be thrown in function 2, the finally block will execute the needed code and then catch the exception in the outer catch block.
You just need to call recyclerview.scrollToPosition(position)
. That's fine!
If you want to call it in adapter, just let your adapter has the instance of recyclerview or the activity or fragment which contains recyclerview,than implements the method getRecyclerview()
in them.
I hope it can help you.
I guess root of this question is that people believe that a call to a constructor creates the object. That is not the case. Java nowhere claims that a constructor call creates an object. It just does what we want constructor to do, like initialising some fields..that's all. So an abstract class's constructor being called doesn't mean that its object is created.
Like @ said
https://services.gradle.org/distributions/
Download The Latest Gradle Distribution File and Extract It, Then Copy all Files and Paste it Under:
C:\Users\{USERNAME}\.gradle\wrapper\dists\
but you have to first make Android Studio try downloading the zip file and cancel it.
That way you can get the hash and copy the file and put it under the hash
I don't know since which version of git this is working, but that's what you're searching for:
git submodule update --recursive
I use it with git pull
to update the root repository, too:
git pull && git submodule update --recursive
you don't, declare an interface that declares the methods you would like to call:
public interface MyInterface
{
void doStuff();
}
public class MyClass implements MyInterface
{
public void doStuff()
{
System.Console.Writeln("done!");
}
}
then you use
MyInterface mobj = (myInterface)obj;
mobj.doStuff();
If MyClass
is not under your control then you can't make it implement some interface, and the other option is to rely on reflection (see this tutorial).
I used this code to solve this problem.
<a href="https://twitter.com/intent/tweet?url=myUrl&text=myTitle" target="_blank"><img src="path_to_my_image"/></a>
You can check the tweet-button documentation here tweet-button
I use talib.CORREL for autocorrelation like this, I suspect you could do the same with other packages:
def autocorrelate(x, period):
# x is a deep indicator array
# period of sample and slices of comparison
# oldest data (period of input array) may be nan; remove it
x = x[-np.count_nonzero(~np.isnan(x)):]
# subtract mean to normalize indicator
x -= np.mean(x)
# isolate the recent sample to be autocorrelated
sample = x[-period:]
# create slices of indicator data
correls = []
for n in range((len(x)-1), period, -1):
alpha = period + n
slices = (x[-alpha:])[:period]
# compare each slice to the recent sample
correls.append(ta.CORREL(slices, sample, period)[-1])
# fill in zeros for sample overlap period of recent correlations
for n in range(period,0,-1):
correls.append(0)
# oldest data (autocorrelation period) will be nan; remove it
correls = np.array(correls[-np.count_nonzero(~np.isnan(correls)):])
return correls
# CORRELATION OF BEST FIT
# the highest value correlation
max_value = np.max(correls)
# index of the best correlation
max_index = np.argmax(correls)
When you update the configuration in the php.ini file, you might have to restart apache. Try running apachectl restart
or apache2ctl restart
, or something like that.
Also, in you ini file, make sure you have display_errors = on
, but only in a development environment, never in a production machine.
Also, the strictest error reporting is exactly what you have cited, E_ALL | E_STRICT
. You can find more information on error levels at the php docs.
the following code , install and uninstall the Service,
Open the command prompt and run the program as an administrator and fire the below command and press enter.
Syntax
To Install
C:\windows\microsoft.net\framework\v4.0.30319>InstallUtil.exe + Your copied path + \your service name + .exe
eg :Our Path InstallUtil.exe C:\MyFirstService\bin\Debug\MyFirstService.exe
To uninstall
C:\windows\microsoft.net\framework\v4.0.30319>InstallUtil.exe -u + Your copied path + \your service name + .exe
eg : Our path InstallUtil.exe -u C:\MyFirstService\bin\Debug\MyFirstService.exe
for more help you can see the following link: sample program
INSERT
INTO remotedblink.remotedatabase.remoteschema.remotetable
SELECT *
FROM mytable
There is no such thing as "the end of the table" in relational databases.
const express = require('express');_x000D_
let app = express();_x000D_
app.use(express.json());
_x000D_
This app.use(express.json) will now let you read the incoming post JSON object
Using single quotes for keys are not allowed in JSON. You need to use double quotes.
For your use-case perhaps this would be the easiest solution:
str = '{"a":1}';
If a property requires quotes, double quotes must be used. All property names must be surrounded by double quotes.
I know there are a lot of answers but I think that mine may be more convenient to many
extension String {
init(epoch: Double) {
let date = Date(timeIntervalSince1970: epoch)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy HH:mm:ssZZZ"
self = dateFormatter.string(from: date)
}
}
Works 100%.
import java.text.DecimalFormat;
public class Formatting {
public static void main(String[] args) {
double value = 22.2323242434342;
// or value = Math.round(value*100) / 100.0;
System.out.println("this is before formatting: "+value);
DecimalFormat df = new DecimalFormat("####0.00");
System.out.println("Value: " + df.format(value));
}
}
For me the following two steps fixed the issue:
I'm partial to scikits.statsmodels. Here an example:
import statsmodels.api as sm
import numpy as np
import matplotlib.pyplot as plt
X = np.random.rand(100)
Y = X + np.random.rand(100)*0.1
results = sm.OLS(Y,sm.add_constant(X)).fit()
print results.summary()
plt.scatter(X,Y)
X_plot = np.linspace(0,1,100)
plt.plot(X_plot, X_plot*results.params[0] + results.params[1])
plt.show()
The only tricky part is sm.add_constant(X)
which adds a columns of ones to X
in order to get an intercept term.
Summary of Regression Results
=======================================
| Dependent Variable: ['y']|
| Model: OLS|
| Method: Least Squares|
| Date: Sat, 28 Sep 2013|
| Time: 09:22:59|
| # obs: 100.0|
| Df residuals: 98.0|
| Df model: 1.0|
==============================================================================
| coefficient std. error t-statistic prob. |
------------------------------------------------------------------------------
| x1 1.007 0.008466 118.9032 0.0000 |
| const 0.05165 0.005138 10.0515 0.0000 |
==============================================================================
| Models stats Residual stats |
------------------------------------------------------------------------------
| R-squared: 0.9931 Durbin-Watson: 1.484 |
| Adjusted R-squared: 0.9930 Omnibus: 12.16 |
| F-statistic: 1.414e+04 Prob(Omnibus): 0.002294 |
| Prob (F-statistic): 9.137e-108 JB: 0.6818 |
| Log likelihood: 223.8 Prob(JB): 0.7111 |
| AIC criterion: -443.7 Skew: -0.2064 |
| BIC criterion: -438.5 Kurtosis: 2.048 |
------------------------------------------------------------------------------
I respect all the solutions given here.
But what I came to know after reading all these, we haven't observed that on which folder the struts.xml file or any configuration file which is necessary for the web application.
My SOULUTION IS:
Hope the problem solved.
From javadoc:
Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a > apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself
Use this package, it just works: https://github.com/jdunck/python-unicodecsv.
Here is a working sample.
<html>_x000D_
<script type="text/javascript">_x000D_
var canvas, ctx, flag = false,_x000D_
prevX = 0,_x000D_
currX = 0,_x000D_
prevY = 0,_x000D_
currY = 0,_x000D_
dot_flag = false;_x000D_
_x000D_
var x = "black",_x000D_
y = 2;_x000D_
_x000D_
function init() {_x000D_
canvas = document.getElementById('can');_x000D_
ctx = canvas.getContext("2d");_x000D_
w = canvas.width;_x000D_
h = canvas.height;_x000D_
_x000D_
canvas.addEventListener("mousemove", function (e) {_x000D_
findxy('move', e)_x000D_
}, false);_x000D_
canvas.addEventListener("mousedown", function (e) {_x000D_
findxy('down', e)_x000D_
}, false);_x000D_
canvas.addEventListener("mouseup", function (e) {_x000D_
findxy('up', e)_x000D_
}, false);_x000D_
canvas.addEventListener("mouseout", function (e) {_x000D_
findxy('out', e)_x000D_
}, false);_x000D_
}_x000D_
_x000D_
function color(obj) {_x000D_
switch (obj.id) {_x000D_
case "green":_x000D_
x = "green";_x000D_
break;_x000D_
case "blue":_x000D_
x = "blue";_x000D_
break;_x000D_
case "red":_x000D_
x = "red";_x000D_
break;_x000D_
case "yellow":_x000D_
x = "yellow";_x000D_
break;_x000D_
case "orange":_x000D_
x = "orange";_x000D_
break;_x000D_
case "black":_x000D_
x = "black";_x000D_
break;_x000D_
case "white":_x000D_
x = "white";_x000D_
break;_x000D_
}_x000D_
if (x == "white") y = 14;_x000D_
else y = 2;_x000D_
_x000D_
}_x000D_
_x000D_
function draw() {_x000D_
ctx.beginPath();_x000D_
ctx.moveTo(prevX, prevY);_x000D_
ctx.lineTo(currX, currY);_x000D_
ctx.strokeStyle = x;_x000D_
ctx.lineWidth = y;_x000D_
ctx.stroke();_x000D_
ctx.closePath();_x000D_
}_x000D_
_x000D_
function erase() {_x000D_
var m = confirm("Want to clear");_x000D_
if (m) {_x000D_
ctx.clearRect(0, 0, w, h);_x000D_
document.getElementById("canvasimg").style.display = "none";_x000D_
}_x000D_
}_x000D_
_x000D_
function save() {_x000D_
document.getElementById("canvasimg").style.border = "2px solid";_x000D_
var dataURL = canvas.toDataURL();_x000D_
document.getElementById("canvasimg").src = dataURL;_x000D_
document.getElementById("canvasimg").style.display = "inline";_x000D_
}_x000D_
_x000D_
function findxy(res, e) {_x000D_
if (res == 'down') {_x000D_
prevX = currX;_x000D_
prevY = currY;_x000D_
currX = e.clientX - canvas.offsetLeft;_x000D_
currY = e.clientY - canvas.offsetTop;_x000D_
_x000D_
flag = true;_x000D_
dot_flag = true;_x000D_
if (dot_flag) {_x000D_
ctx.beginPath();_x000D_
ctx.fillStyle = x;_x000D_
ctx.fillRect(currX, currY, 2, 2);_x000D_
ctx.closePath();_x000D_
dot_flag = false;_x000D_
}_x000D_
}_x000D_
if (res == 'up' || res == "out") {_x000D_
flag = false;_x000D_
}_x000D_
if (res == 'move') {_x000D_
if (flag) {_x000D_
prevX = currX;_x000D_
prevY = currY;_x000D_
currX = e.clientX - canvas.offsetLeft;_x000D_
currY = e.clientY - canvas.offsetTop;_x000D_
draw();_x000D_
}_x000D_
}_x000D_
}_x000D_
</script>_x000D_
<body onload="init()">_x000D_
<canvas id="can" width="400" height="400" style="position:absolute;top:10%;left:10%;border:2px solid;"></canvas>_x000D_
<div style="position:absolute;top:12%;left:43%;">Choose Color</div>_x000D_
<div style="position:absolute;top:15%;left:45%;width:10px;height:10px;background:green;" id="green" onclick="color(this)"></div>_x000D_
<div style="position:absolute;top:15%;left:46%;width:10px;height:10px;background:blue;" id="blue" onclick="color(this)"></div>_x000D_
<div style="position:absolute;top:15%;left:47%;width:10px;height:10px;background:red;" id="red" onclick="color(this)"></div>_x000D_
<div style="position:absolute;top:17%;left:45%;width:10px;height:10px;background:yellow;" id="yellow" onclick="color(this)"></div>_x000D_
<div style="position:absolute;top:17%;left:46%;width:10px;height:10px;background:orange;" id="orange" onclick="color(this)"></div>_x000D_
<div style="position:absolute;top:17%;left:47%;width:10px;height:10px;background:black;" id="black" onclick="color(this)"></div>_x000D_
<div style="position:absolute;top:20%;left:43%;">Eraser</div>_x000D_
<div style="position:absolute;top:22%;left:45%;width:15px;height:15px;background:white;border:2px solid;" id="white" onclick="color(this)"></div>_x000D_
<img id="canvasimg" style="position:absolute;top:10%;left:52%;" style="display:none;">_x000D_
<input type="button" value="save" id="btn" size="30" onclick="save()" style="position:absolute;top:55%;left:10%;">_x000D_
<input type="button" value="clear" id="clr" size="23" onclick="erase()" style="position:absolute;top:55%;left:15%;">_x000D_
</body>_x000D_
</html>
_x000D_
static object Lock = new object();
lock (Lock)
{
// do stuff
}
Try if that works
sc = spark.sparkContext
# Infer the schema, and register the DataFrame as a table.
schemaPeople = spark.createDataFrame(RddName)
schemaPeople.createOrReplaceTempView("RddName")
To get rid of additional whitespace, you could change the code like this:
intarray[i]=Integer.parseInt(str.trim()); // No more Exception in this line
The $http
legacy promise methods success
and error
have been deprecated. Use the standard then
method instead. Have a look at the docs https://docs.angularjs.org/api/ng/service/$http
Now the right way to use is:
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
The response object has these properties:
A response status code between 200 and 299 is considered a success status and will result in the success callback being called.
Use datetime.datetime.fromtimestamp
:
>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'
%f
directive is only supported by datetime.datetime.strftime
, not by time.strftime
.
UPDATE Alternative using %
, str.format
:
>>> import time
>>> s, ms = divmod(1236472051807, 1000) # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
SHORTEST and FASTEST: str.replace(/ /g, '');
Benchmark:
Here my results - (2018.07.13) MacOs High Sierra 10.13.3 on Chrome 67.0.3396 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit) ):
Short string similar to examples from OP question
The fastest solution on all browsers is / /g
(regexp1a) - Chrome 17.7M (operation/sec), Safari 10.1M, Firefox 8.8M. The slowest for all browsers was split-join
solution. Change
to \s
or add +
or i
to regexp slows down processing.
For string about ~3 milion character results are:
You can run it on your machine: https://jsperf.com/remove-string-spaces/1
According to documentation:
random.sample(population, k)
Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
Basically, it picks k unique random elements, a sample, from a sequence:
>>> import random
>>> c = list(range(0, 15))
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> random.sample(c, 5)
[9, 2, 3, 14, 11]
random.sample
works also directly from a range:
>>> c = range(0, 15)
>>> c
range(0, 15)
>>> random.sample(c, 5)
[12, 3, 6, 14, 10]
In addition to sequences, random.sample
works with sets too:
>>> c = {1, 2, 4}
>>> random.sample(c, 2)
[4, 1]
However, random.sample
doesn't work with arbitrary iterators:
>>> c = [1, 3]
>>> random.sample(iter(c), 5)
TypeError: Population must be a sequence or set. For dicts, use list(d).
Just another alternative solution for those who want to pass variables to a script which is sourced using flask, I only managed to get this working by defining the variables outside and then calling the script as follows:
<script>
var myfileuri = "/static/my_csv.csv"
var mytableid = 'mytable';
</script>
<script type="text/javascript" src="/static/test123.js"></script>
If I input jinja variables in test123.js
it doesn't work and you will get an error.
Try the steps described here: http://avaminzhang.wordpress.com/2011/11/24/python-version-2-7-required-which-was-not-found-in-the-registry/
The Exception it self says it all java.lang.ClassNotFoundException: org.json.JSONObject
You have not added the necessary jar file which will be having org.json.JSONObject
class to your classpath
.
You can Download it From Here
imagesLoaded Plugin is way to go ,if you need a crossbrowser solution
$("<img>", {src: 'image.jpg'}).imagesLoaded( function( $images, $proper, $broken ){
if($broken.length > 0){
//Error CallBack
console.log('Error');
}
else{
// Load CallBack
console.log('Load');
}
});
If You Just Need a IE WorkAround,This Will Do
var img = $("<img>", {
error: function() {console.log('error'); },
load: function() {console.log('load');}
});
img.attr('src','image.jpg');
The problem here is that you have defined ID as a field in your data file when what you want is to just use an expression without any data from the data file. You can fix this by defining ID as an expression (or a sequence in this case)
ID EXPRESSION "ID_SEQ.nextval"
or
ID SEQUENCE(count)
See: http://docs.oracle.com/cd/B28359_01/server.111/b28319/ldr_field_list.htm#i1008234 for all options
Make sure your docker repositry name matches your local docker repo name. e.g lets say if you local repo name "kavashgar/nodjsapp"
then your should also have a repo names "kavashgar" in docker hub
+
selector is called Adjacent Sibling Selector
.
For example, the selector p + p
, selects the p
elements immediately following the p
elements
It can be thought of as a looking outside
selector which checks for the immediately following element.
Here is a sample snippet to make things more clear:
body {_x000D_
font-family: Tahoma;_x000D_
font-size: 12px;_x000D_
}_x000D_
p + p {_x000D_
margin-left: 10px;_x000D_
}
_x000D_
<div>_x000D_
<p>Header paragraph</p>_x000D_
<p>This is a paragraph</p>_x000D_
<p>This is another paragraph</p>_x000D_
<p>This is yet another paragraph</p>_x000D_
<hr>_x000D_
<p>Footer paragraph</p>_x000D_
</div>
_x000D_
Since we are one the same topic, it is worth mentioning another selector, ~
selector, which is General Sibling Selector
For example, p ~ p
selects all the p
which follows the p
doesn't matter where it is, but both p
should be having the same parent.
Here is how it looks like with the same markup:
body {_x000D_
font-family: Tahoma;_x000D_
font-size: 12px;_x000D_
}_x000D_
p ~ p {_x000D_
margin-left: 10px;_x000D_
}
_x000D_
<div>_x000D_
<p>Header paragraph</p>_x000D_
<p>This is a paragraph</p>_x000D_
<p>This is another paragraph</p>_x000D_
<p>This is yet another paragraph</p>_x000D_
<hr>_x000D_
<p>Footer paragraph</p>_x000D_
</div>
_x000D_
Notice that the last p
is also matched in this sample.
Changing the order of classpath artifacts in the Java Build Path resolved it for me.
This should fix it.
With template literals, you can use multiple spaces or multi-line strings and string interpolation. Template Literals are a new ES2015 / ES6 feature that allows you to work with strings. The syntax is very simple, just use backticks instead of single or double quotes:
let a = `something something`;
and to make multiline strings just press enter to create a new line, with no special characters:
let a = `something
something`;
The results are exactly the same as you write in the string.
It may be the typo if you incorrectly wrote the placeholder
word.
In my case I misspelled it as placehoder
and got the error like this:
AttributeError: 'module' object has no attribute 'placehoder'
You need to look into Ajax; Start here this is the best way to stay on the current page and be able to send inputs to php.
<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<h3>Start typing a name in the input field below:</h3>
<form action="">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
This gets the users input on the textbox and opens the webpage gethint.php?q=ja from here the php script can do anything with $_GET['q'] and echo back to the page James, Jason....etc
// Simplest way
var originalContent = $('select').html();
$('select').change(function() {
$('select').html(originalContent); //Restore Original Content
$('select option[myfilter=1]').remove(); // Filter my options
});
<div class="field">
<label class="field-label" for="photo">Your photo</label>
<input class="field-input" type="file" name="photo" id="photo" value="photo" />
</div>
and the css
input[type="file"]
{
color: transparent;
background-color: #F89406;
border: 2px solid #34495e;
width: 100%;
height: 36px;
border-radius: 3px;
}
The best way to solve this problem "X-CSRF-TOKEN" is to add the following code to your main layout, and continue making your ajax calls normally:
In header
<meta name="csrf-token" content="{{ csrf_token() }}" />
In script
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
Use
print"{:.2f}".format(a)
instead of
print"{0:.2f}".format(a)
Because the latter may lead to output errors when trying to output multiple variables (see comments).
i had the same issues a longtime then i got the solution by the below code. please use
parent.jQuery.fancybox.close()
CHARINDEX is what you are looking for
select CHARINDEX('@', '[email protected]')
-----------
8
(1 row(s) affected)
-or-
select CHARINDEX('c', 'abcde')
-----------
3
(1 row(s) affected)
I had the similar issue showing the error
For more information about this error navigate to the report server on the local server machine, or enable remote errors Query execution failed for dataset 'PrintInvoice'.
Solution: 1) The error may be with the dataset in some cases, you can always check if the dataset is populating the exact data you are expecting by going to the dataset properties and choosing 'Query Designer' and try 'Run', If you can successfully able to pull the fields you are expecting, then you can be sure that there isn't any problem with the dataset, which takes us to next solution.
2) Even though the error message says "Query Failed Execution for the dataset", another probable chances are with the datasource connection, make sure you have connected to the correct datasource that has the tables you need and you have permissions to access that datasource.
rm .git/refs/remotes/origin/master
It works to me!
Try
//*[text()='qwerty']
because .
is your current element
You can easily write the method to do that :
public static String toCamelCase(final String init) {
if (init == null)
return null;
final StringBuilder ret = new StringBuilder(init.length());
for (final String word : init.split(" ")) {
if (!word.isEmpty()) {
ret.append(Character.toUpperCase(word.charAt(0)));
ret.append(word.substring(1).toLowerCase());
}
if (!(ret.length() == init.length()))
ret.append(" ");
}
return ret.toString();
}
Since there are dozens of ways to do it, here is another one:
tree -d -L 1 -i --noreport
I've had the same error on Windows. I solved it with (after on cmd: mysql -u root):
mysql> SOURCE C:/users/xxx/xxxx/metropolises.sql;
Be sure you type the right file path
Very good question. The Java Language specification confirms your suggestion.
For example, the following code is correct:
short x = 3; x += 4.6;
and results in x having the value 7 because it is equivalent to:
short x = 3; x = (short)(x + 4.6);
A race condition is an undesirable situation that occurs when two or more process can access and change the shared data at the same time.It occurred because there were conflicting accesses to a resource . Critical section problem may cause race condition. To solve critical condition among the process we have take out only one process at a time which execute the critical section.
If your image is stored in a Blob format (i.e. in a database) you can use the same technique explained by Billal Begueradj to convert your image from Blobs to a byte array.
In my case, I needed my images where stored in a blob column in a db table:
def select_all_X_values(conn):
cur = conn.cursor()
cur.execute("SELECT ImageData from PiecesTable")
rows = cur.fetchall()
return rows
I then created a helper function to change my dataset into np.array:
X_dataset = select_all_X_values(conn)
imagesList = convertToByteIO(np.array(X_dataset))
def convertToByteIO(imagesArray):
"""
# Converts an array of images into an array of Bytes
"""
imagesList = []
for i in range(len(imagesArray)):
img = Image.open(BytesIO(imagesArray[i])).convert("RGB")
imagesList.insert(i, np.array(img))
return imagesList
After this, I was able to use the byteArrays in my Neural Network.
plt.imshow(imagesList[0])
It's an unsigned integer type exactly the size of a pointer. Whenever you need to do something unusual with a pointer - like for example invert all bits (don't ask why) you cast it to uintptr_t
and manipulate it as a usual integer number, then cast back.
You can do this conversion with the OpenSSL library
Windows binaries can be found here:
http://www.slproweb.com/products/Win32OpenSSL.html
Once you have the library installed, the command you need to issue is:
openssl x509 -in mycert.crt -out mycert.pem -outform PEM
If you installed brew, cmd below will be helpful:
brew cask install java
For me, what caused this error was that I accidentally had the same message being sent twice to the same class member. When I right clicked on the button in the gui, I could see the method name twice, and I just deleted one. Newbie mistake in my case for sure, but wanted to get it out there for other newbies to consider.
Without jQuery:
document.getElementById('file').onchange = function(){
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent){
// Entire file
console.log(this.result);
// By lines
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
console.log(lines[line]);
}
};
reader.readAsText(file);
};
HTML:
<input type="file" name="file" id="file">
Remember to put your javascript code after the file field is rendered.
Explanation: When you install a new laravel project on your folder(for example myfolder) using the composer, it installs the complete laravel project inside your folder(myfolder/laravel) than artisan is inside laravel.that's, why you see an error,
Could not open input file: artisan
Solution: You have to go inside by command prompt to that location or move laravel files inside your folder.
I too needed a rounded ImageView, I used the below code, you can modify it accordingly:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class RoundedImageView extends ImageView {
public RoundedImageView(Context context) {
super(context);
}
public RoundedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = ((BitmapDrawable) drawable).getBitmap();
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
int w = getWidth();
@SuppressWarnings("unused")
int h = getHeight();
Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
canvas.drawBitmap(roundBitmap, 0, 0, null);
}
public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap sbmp;
if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
float factor = smallest / radius;
sbmp = Bitmap.createScaledBitmap(bmp,
(int) (bmp.getWidth() / factor),
(int) (bmp.getHeight() / factor), false);
} else {
sbmp = bmp;
}
Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final String color = "#BAB399";
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, radius, radius);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor(color));
canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
radius / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(sbmp, rect, rect, paint);
return output;
}
}
The simplest solution is a pair of mutually recursive functions.
The first function generates all the prime numbers:
The second function returns the prime factors of a given number n
in increasing order.
n
.The largest prime factor of n
is the last number given by the second function.
This algorithm requires a lazy list or a language (or data structure) with call-by-need semantics.
For clarification, here is one (inefficient) implementation of the above in Haskell:
import Control.Monad
-- All the primes
primes = 2 : filter (ap (<=) (head . primeFactors)) [3,5..]
-- Gives the prime factors of its argument
primeFactors = factor primes
where factor [] n = []
factor xs@(p:ps) n =
if p*p > n then [n]
else let (d,r) = divMod n p in
if r == 0 then p : factor xs d
else factor ps n
-- Gives the largest prime factor of its argument
largestFactor = last . primeFactors
Making this faster is just a matter of being more clever about detecting which numbers are prime and/or factors of n
, but the algorithm stays the same.
These answers were all so close to the answer that I needed. This is an attempt to expand on them.
If you're running from within a .bat
file and you want a single line that allows you to export a complicated command like jq -r ".Credentials.AccessKeyId" c:\temp\mfa-getCreds.json
to a variable named AWS_ACCESS_KEY
then you want this:
FOR /F "tokens=* USEBACKQ" %%g IN (`jq -r ".Credentials.AccessKeyId" c:\temp\mfa-getCreds.json`) do (SET "AWS_ACCESS_KEY=%%g")
If you're at the C:\
prompt you want a single line that allows you to run a complicated command like jq -r ".Credentials.AccessKeyId" c:\temp\mfa-getCreds.json
to a variable named AWS_ACCESS_KEY
then you want this:
FOR /F "tokens=* USEBACKQ" %g IN (`jq -r ".Credentials.AccessKeyId" c:\temp\mfa-getCreds.json`) do (SET "AWS_ACCESS_KEY=%g")
The only difference between the two answers above is that on the command line, you use a single % in your variable. In a batch file, you have to double up on the percentage signs (%%).
Since the command includes colons, quotes, and parentheses, you need to include the USEBACKQ
line in the options so that you can use backquotes to specify the command to run and then all kinds of funny characters inside of it.
The easiest way to add the font programatically to a TextView is to, first, add the font file in your Assets folder in the project. For example your font path is looking like this: assets/fonts/my_font.otf
And add it to a TextView as:
Kotlin
val font_path = "fonts/my_font.otf"
myTypeface = Typeface.createFromAsset(MyApplication.getInstance().assets, font_path)
textView.typeface = myTypeface
Java
String font_path = "fonts/my_font.otf";
Typeface myTypeface = Typeface.createFromAsset(MyApplication.getInstance().assets, font_path)
textView.setTypeface(myTypeface);
If the user doesn't have Chrome, it will throw an exception like this:
//chrome.exe http://xxx.xxx.xxx --incognito
//chrome.exe http://xxx.xxx.xxx -incognito
//chrome.exe --incognito http://xxx.xxx.xxx
//chrome.exe -incognito http://xxx.xxx.xxx
private static void Chrome(string link)
{
string url = "";
if (!string.IsNullOrEmpty(link)) //if empty just run the browser
{
if (link.Contains('.')) //check if it's an url or a google search
{
url = link;
}
else
{
url = "https://www.google.com/search?q=" + link.Replace(" ", "+");
}
}
try
{
Process.Start("chrome.exe", url + " --incognito");
}
catch (System.ComponentModel.Win32Exception e)
{
MessageBox.Show("Unable to find Google Chrome...",
"chrome.exe not found!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
At the point you are calling your function, the rest of the page has not rendered and so the element is not in existence at that point. Try calling your function on window.onload
maybe. Something like this:
<html>
<head>
<title></title>
<script type="text/javascript">
window.onload = function(){
var refButton = document.getElementById("btnButton");
refButton.onclick = function() {
alert('I am clicked!');
}
};
</script>
</head>
<body>
<form id="form1">
<div>
<input id="btnButton" type="button" value="Click me"/>
</div>
</form>
</body>
</html>
"I'd like to paste yanked text into Vim command line."
While the top voted answer is very complete, I prefer editing the command history.
In normal mode, type: q:
. This will give you a list of recent commands, editable and searchable with normal vim commands. You'll start on a blank command line at the bottom.
For the exact thing that the article asks, pasting a yanked line (or yanked anything) into a command line, yank your text and then: q:p
(get into command history edit mode, and then (p)ut your yanked text into a new command line. Edit at will, enter to execute.
To get out of command history mode, it's the opposite. In normal mode in command history, type: :q
+ enter
You can chain class selectors without a space between them:
.a.b {
color: #666;
}
Note that, if it matters to you, IE6 treats .a.b
as .b
, so in that browser both div.a.b
and div.b
will have gray text. See this answer for a comparison between proper browsers and IE6.
CASE AlarmEventTransactions.DeviceID
should just be CASE
.
You are mixing the 2 forms of the CASE
expression.
I was able to find a solution/workaround of redirecting output to a file and then to the console:
dir > a.txt | type a.txt
where dir is the command which output needs to be redirected, a.txt a file where to store output.
Actually the correct answer to this is to just add the schema to your document, like so
<packages xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
...and you're done :)
If the XSD is not already cached and unavailable, you can add it as follows from the NuGet console
Install-Package NuGet.Manifest.Schema -Version 2.0.0
Once this is done, as noted in a comment below, you may want to move it from your current folder to the official schema folder that is found in
%VisualStudioPath%\Xml\Schemas
You can use fprintf/sprintf with familiar C syntax. Maybe something like:
fprintf('x = %d, y = %d \n x+y=%d \n x*y=%d \n x/y=%f\n', x,y,d,e,f)
reading your comment, this is how you use your functions from the main program:
x = 2;
y = 2;
[d e f] = answer(x,y);
fprintf('%d + %d = %d\n', x,y,d)
fprintf('%d * %d = %d\n', x,y,e)
fprintf('%d / %d = %f\n', x,y,f)
Also for the answer() function, you can assign the output values to a vector instead of three distinct variables:
function result=answer(x,y)
result(1)=addxy(x,y);
result(2)=mxy(x,y);
result(3)=dxy(x,y);
and call it simply as:
out = answer(x,y);
This should do:
Assembly assem = Assembly.GetExecutingAssembly();
AssemblyName aName = assem.GetName();
return aName.Version.ToString();
if type(input('enter = '))==int:
print 'Entered number is an Integer'
else:
print 'Entered number isn't an Integer'
This'll work to check out whether number is an integer or not
There is also a change between Java 7 and Java 8. Admittedly it involves the a deprecated call, but I had to add a "/" to get our program working! Here is the link discussing it Why does servletContext.getRealPath returns null on tomcat 8?
If you want to remove all the files in the %TEMP%
folder you could just do this:
del %TEMP%\*.* /f /s /q
That will remove everything, any file with any extension (*.*
) and do the same for all sub-folders (/s
), without prompting you for anything (/q
), it will just do it, including read only files (/f
).
Hope this helps.
void Keep()
Calling this method with in the current action ensures that all the items in TempData are not removed at the end of the current request.
@model MyProject.Models.EmpModel;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "About";
var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
TempData.Keep(); // retains all strings values
}
void Keep(string key)
Calling this method with in the current action ensures that specific item in TempData is not removed at the end of the current request.
@model MyProject.Models.EmpModel;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "About";
var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
TempData.Keep("emp"); // retains only "emp" string values
}
In your widget's Info.plist file, don't forget to set your AllowNetworkAccess
key to true.
Shortcut doing this on Mac: Press command+Shift+A (Action) and type "class count to use import with *" Press Enter. Enter a higher number there like 999
"Alter column position" in the PostgreSQL Wiki says:
PostgreSQL currently defines column order based on the
attnum
column of thepg_attribute
table. The only way to change column order is either by recreating the table, or by adding columns and rotating data until you reach the desired layout.
That's pretty weak, but in their defense, in standard SQL, there is no solution for repositioning a column either. Database brands that support changing the ordinal position of a column are defining an extension to SQL syntax.
One other idea occurs to me: you can define a VIEW
that specifies the order of columns how you like it, without changing the physical position of the column in the base table.
You get only the name because you return only the name return "login";
. It's @RestController
and this controller returns data rather than a view; because of this, you get only content that you return from method.
If you want to show view with this name you need to use Spring MVC, see this example.
If you want to have unique values in a lookup object you can do something like this:
Creating a lookup object
var lookup = {};
Setting up the hashcode function
function getHashCode(obj) {
var hashCode = '';
if (typeof obj !== 'object')
return hashCode + obj;
for (var prop in obj) // No hasOwnProperty needed
hashCode += prop + getHashCode(obj[prop]); // Add key + value to the result string
return hashCode;
}
Object
var key = getHashCode({ 1: 3, 3: 7 });
// key = '1337'
lookup[key] = true;
Array
var key = getHashCode([1, 3, 3, 7]);
// key = '01132337'
lookup[key] = true;
Other types
var key = getHashCode('StackOverflow');
// key = 'StackOverflow'
lookup[key] = true;
Final result
{ 1337: true, 01132337: true, StackOverflow: true }
Do note that getHashCode
doesn't return any value when the object or array is empty
getHashCode([{},{},{}]);
// '012'
getHashCode([[],[],[]]);
// '012'
This is similar to @ijmacd solution only getHashCode
doesn't has the JSON
dependency.
Read the tutorial on Java Web applications.
Basically Web applications are a part of the Java EE standard. A lot of people only use the Web (servlets) part with additional frameworks thrown in, most notably Spring but also Struts, Seam and others.
All you need is an IDE like IntelliJ, Eclipse or Netbeans, the JDK, the Java EE download and a servlet container like Tomcat (or a full-blown application server like Glassfish or JBoss).
Here is a Tomcat tutorial.
I had this issue with a custom list and while it's not possible to use the auto-generated ID column to create a calculated column, it is possible to use a workflow to do the heavy lifting.
I created a new workflow variable of type Number and set it to be the value of the ID column in the current item. Then it's simply a matter of calculating the custom column value and setting it - in my case I just needed the numbering to begin at 100,000.
This applies to Mac and Windows users (I use on Mac) . I've used several of the listed answers over the years and have found that FileZilla suits my needs well when editing files on a remote host that I have SSH access to. It's also quick to setup.
View/Edit
. This brings up my default editor (Sublime) but it will work with any editor you have installed.
Usually two arrays will have some small numeric errors,
You can use numpy.allclose(A,B)
, instead of (A==B).all()
. This returns a bool True/False
Is this what you are looking for:
Using OBJECT CATALOG VIEWS
SELECT T.name AS Table_Name ,
C.name AS Column_Name ,
P.name AS Data_Type ,
P.max_length AS Size ,
CAST(P.precision AS VARCHAR) + '/' + CAST(P.scale AS VARCHAR) AS Precision_Scale
FROM sys.objects AS T
JOIN sys.columns AS C ON T.object_id = C.object_id
JOIN sys.types AS P ON C.system_type_id = P.system_type_id
WHERE T.type_desc = 'USER_TABLE';
Using INFORMATION SCHEMA VIEWS
SELECT TABLE_SCHEMA ,
TABLE_NAME ,
COLUMN_NAME ,
ORDINAL_POSITION ,
COLUMN_DEFAULT ,
DATA_TYPE ,
CHARACTER_MAXIMUM_LENGTH ,
NUMERIC_PRECISION ,
NUMERIC_PRECISION_RADIX ,
NUMERIC_SCALE ,
DATETIME_PRECISION
FROM INFORMATION_SCHEMA.COLUMNS;
Reference : My Blog - http://dbalink.wordpress.com/2008/10/24/querying-the-object-catalog-and-information-schema-views/
You can also use linq extensions for DataSets:
var imagePaths = dt.AsEnumerble().Select(r => r.Field<string>("ImagePath");
foreach(string imgPath in imagePaths)
{
TextBox1.Text = imgPath;
}
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.
Alter TABLE `tableName` MODIFY COLUMN `ColumnName` datatype(length);
Ex :
Alter TABLE `tbl_users` MODIFY COLUMN `dup` VARCHAR(120);
Just like the mechanical card sorters of long ago, first sort by the least significant key, then the next most significant, etc. No library required, works with any number of keys and any combination of ascending and descending keys.
dd <- dd[order(dd$b, decreasing = FALSE),]
Now we're ready to do the most significant key. The sort is stable, and any ties in the most significant key have already been resolved.
dd <- dd[order(dd$z, decreasing = TRUE),]
This may not be the fastest, but it is certainly simple and reliable
For me what worked is the following:
sudo xcode-select --reset
Then like in @High6's answer:
sudo xcodebuild -license
This will reveal a license which I assume is some Xcode license. Scroll to the bottom using space (or the mouse) then tap agree
.
This is what worked for me on MacOS Mojave v 10.14.
Based in this implementation with Node.js of JWT with refresh token:
1) In this case they use a uid and it's not a JWT. When they refresh the token they send the refresh token and the user. If you implement it as a JWT, you don't need to send the user, because it would inside the JWT.
2) They implement this in a separated document (table). It has sense to me because a user can be logged in in different client applications and it could have a refresh token by app. If the user lose a device with one app installed, the refresh token of that device could be invalidated without affecting the other logged in devices.
3) In this implementation it response to the log in method with both, access token and refresh token. It seams correct to me.
I got an error when I used
<git config --global http.proxy http://user:password@proxy_addr:port>
The error is that the config file cannot be identified as there is no such file. I changed the command to
<git config --system http.proxy http://user:password@proxy_addr:port>
I am running git on the Windows 7 command prompt.
The above command references the config file in GIT_HOME/etc/gitconfig
.
The --global
option does not.
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.
Yes:
from django.conf.urls.defaults import ... # is for django 1.3
from django.conf.urls import ... # is for django 1.4
I met this problem too.
Regular expressions with character classes (e.g. [[:digit:]]
) are not supported in the default regular expression syntax used by find
. You need to specify a different regex type such as posix-extended
in order to use them.
Take a look at GNU Find's Regular Expression documentation which shows you all the regex types and what they support.
This should work:
reload(my.module)
From the Python docs
Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter.
If running Python 3.4 and up, do import importlib
, then do importlib.reload(nameOfModule)
.
Don't forget the caveats of using this method:
When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem, but if the new version of a module does not define a name that was defined by the old version, the old definition is not removed.
If a module imports objects from another module using from ... import ...
, calling reload()
for the other module does not redefine the objects imported from it — one way around this is to re-execute the from
statement, another is to use import
and qualified names (module.*name*
) instead.
If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.
/* Drop all non-system stored procs */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 ORDER BY [name])
WHILE @name is not null
BEGIN
SELECT @SQL = 'DROP PROCEDURE [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped Procedure: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
/* Drop all views */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 ORDER BY [name])
WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = 'DROP VIEW [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped View: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
/* Drop all functions */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 ORDER BY [name])
WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = 'DROP FUNCTION [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped Function: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
/* Drop all Foreign Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
WHILE @name is not null
BEGIN
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
WHILE @constraint IS NOT NULL
BEGIN
SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint) +']'
EXEC (@SQL)
PRINT 'Dropped FK Constraint: ' + @constraint + ' on ' + @name
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO
/* Drop all Primary Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
WHILE @name IS NOT NULL
BEGIN
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
WHILE @constraint is not null
BEGIN
SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint)+']'
EXEC (@SQL)
PRINT 'Dropped PK Constraint: ' + @constraint + ' on ' + @name
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO
/* Drop all tables */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])
WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = 'DROP TABLE [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped Table: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
Strict aliasing is not allowing different pointer types to the same data.
This article should help you understand the issue in full detail.
html {_x000D_
padding: 20px 0;_x000D_
background-color: #efefef;_x000D_
}_x000D_
_x000D_
body {_x000D_
width: 400px;_x000D_
padding: 40px;_x000D_
margin: 0 auto;_x000D_
background: #fff;_x000D_
box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.5);_x000D_
}_x000D_
_x000D_
video {_x000D_
width: 400px;_x000D_
display: block;_x000D_
}
_x000D_
<video onloadeddata="this.play();this.muted=false;" poster="https://durian.blender.org/wp-content/themes/durian/images/void.png" playsinline loop muted controls>_x000D_
<source src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4" />_x000D_
Your browser does not support the video tag or the file format of this video._x000D_
</video>
_x000D_
The official way to find out if you have 4.5 installed (and not 4.0) is in the registry keys :
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full
Relesae DWORD needs to be bigger than 378675 Here is the Microsoft doc for it
all the other answers of checking the minor version after 4.0.30319.xxxxx seem correct though (msbuild.exe -version , or properties of clr.dll), i just needed something documented (not a blog)
Try the below code:
$my_string = "'name', 'name2', 'name3',";
echo substr(trim($my_string), 0, -1);
Use this code to remove the last character of the string.
int random(int min, int max) //range : [min, max]
{
static bool first = true;
if (first)
{
srand( time(NULL) ); //seeding for the first time only!
first = false;
}
return min + rand() % (( max + 1 ) - min);
}
SELECT some_cols
FROM prefix_users
WHERE (some conditions)
ORDER BY pic_set DESC, last_activity;
It depends how many times you're going to want to find this information, if more than once:
Set<Boolean> flags = new HashSet<Boolean>(myArray);
flags.contains(false);
Otherwise a short circuited loop:
for (i = 0; i < myArray.length; i++) {
if (!myArray[i]) return false;
}
return true;
I can't guarantee it's the simplest, but I like MarkerWithLabel. As shown in the basic example, CSS styles define the label's appearance and options in the JavaScript define the content and placement.
.labels {
color: red;
background-color: white;
font-family: "Lucida Grande", "Arial", sans-serif;
font-size: 10px;
font-weight: bold;
text-align: center;
width: 60px;
border: 2px solid black;
white-space: nowrap;
}
JavaScript:
var marker = new MarkerWithLabel({
position: homeLatLng,
draggable: true,
map: map,
labelContent: "$425K",
labelAnchor: new google.maps.Point(22, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 0.75}
});
The only part that may be confusing is the labelAnchor. By default, the label's top left corner will line up to the marker pushpin's endpoint. Setting the labelAnchor's x-value to half the width defined in the CSS width property will center the label. You can make the label float above the marker pushpin with an anchor point like new google.maps.Point(22, 50)
.
In case access to the links above are blocked, I copied and pasted the packed source of MarkerWithLabel into this JSFiddle demo. I hope JSFiddle is allowed in China :|
I think you can achieve what you are looking for by combining number 1 with calling a function like in number 3.
You don't want to execute scripts on page load and prefer to call a function later on? Fine, just create a function that returns the value you would have set in a variable:
function getContextPath() {
return "<%=request.getContextPath()%>";
}
It's a function so it wont be executed until you actually call it, but it returns the value directly, without a need to do DOM traversals or tinkering with URLs.
At this point I agree with @BalusC to use EL:
function getContextPath() {
return "${pageContext.request.contextPath}";
}
or depending on the version of JSP fallback to JSTL:
function getContextPath() {
return "<c:out value="${pageContext.request.contextPath}" />";
}
When above problem exists and you have Two Factor Authentication enabled, just do the following:
Inside Application Loader login with your apple id and App Specific Password you just created.
Upload your ipa to itunesconnect.
Since index positioning in Python is 0-based, there won't actually be an element in index
at the location corresponding to len(DF)
. You need that to be last_row = len(DF) - 1
:
In [49]: dfrm
Out[49]:
A B C
0 0.120064 0.785538 0.465853
1 0.431655 0.436866 0.640136
2 0.445904 0.311565 0.934073
3 0.981609 0.695210 0.911697
4 0.008632 0.629269 0.226454
5 0.577577 0.467475 0.510031
6 0.580909 0.232846 0.271254
7 0.696596 0.362825 0.556433
8 0.738912 0.932779 0.029723
9 0.834706 0.002989 0.333436
[10 rows x 3 columns]
In [50]: dfrm.drop(dfrm.index[len(dfrm)-1])
Out[50]:
A B C
0 0.120064 0.785538 0.465853
1 0.431655 0.436866 0.640136
2 0.445904 0.311565 0.934073
3 0.981609 0.695210 0.911697
4 0.008632 0.629269 0.226454
5 0.577577 0.467475 0.510031
6 0.580909 0.232846 0.271254
7 0.696596 0.362825 0.556433
8 0.738912 0.932779 0.029723
[9 rows x 3 columns]
However, it's much simpler to just write DF[:-1]
.
In addition to 2 mechanisms already mentioned, there is also global feature that can be used to suppress all failures caused by unknown (unmapped) properties:
// jackson 1.9 and before
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// or jackson 2.0
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
This is the default used in absence of annotations, and can be convenient fallback.
Option #1: You can come up with a new UI design that does not require simultaneous horizontal and vertical scrolling.
Option #2: You can obtain the source code to ScrollView
and HorizontalScrollView
, learn how the core Android team implemented those, and create your own BiDirectionalScrollView
implementation.
Option #3: You can get rid of the dependencies that are requiring you to use the widget system and draw straight to the Canvas.
Option #4: If you stumble upon an open source application that seems to implement what you seek, look to see how they did it.
Make them display: block
in your CSS.
While I do love using CHECKSUM, I feel that a better way to go is using NEWID()
, just because you don't have to go through a complicated math to generate simple numbers .
ROUND( 1000 *RAND(convert(varbinary, newid())), 0)
You can replace the 1000
with whichever number you want to set as the limit, and you can always use a plus sign to create a range, let's say you want a random number between 100
and 200
, you can do something like :
100 + ROUND( 100 *RAND(convert(varbinary, newid())), 0)
Putting it together in your query :
UPDATE CattleProds
SET SheepTherapy= ROUND( 1000 *RAND(convert(varbinary, newid())), 0)
WHERE SheepTherapy IS NULL
Use List<T>.Insert
While not relevant to your specific example, if performance is important also consider using LinkedList<T>
because inserting an item to the start of a List<T>
requires all items to be moved over. See When should I use a List vs a LinkedList.
I prefer creating a custom map that extends HashMap. Then just override get() to add extra logic so that if the map doesnt contain your key. It will a create a new instance of the nested map, add it, then return it.
public class KMap<K, V> extends HashMap<K, V> {
public KMap() {
super();
}
@Override
public V get(Object key) {
if (this.containsKey(key)) {
return super.get(key);
} else {
Map<K, V> value = new KMap<K, V>();
super.put((K)key, (V)value);
return (V)value;
}
}
}
Now you can use it like so:
Map<Integer, Map<Integer, Map<String, Object>>> nestedMap = new KMap<Integer, Map<Integer, Map<String, Object>>>();
Map<String, Object> map = (Map<String, Object>) nestedMap.get(1).get(2);
Object obj= new Object();
map.put(someKey, obj);
please make sure your jar file is in the libs directory of your project in you are using newer ADT version with your eclipse.
rapidjson is a C++ JSON parser/generator designed to be fast and small memory footprint.
There is a performance comparison with YAJL and JsonCPP.
Update:
I created an open source project Native JSON benchmark, which evaluates 29 (and increasing) C/C++ JSON libraries, in terms of conformance and performance. This should be an useful reference.
The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:
ffmpeg -i input.mov -qscale 0 output.mp4
Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0
):
ffmpeg -i input.mov -q:v 0 output.mp4
All fields in JavaScript (and in TypeScript) can have the value null
or undefined
.
You can make the field optional which is different from nullable.
interface Employee1 {
name: string;
salary: number;
}
var a: Employee1 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee1 = { name: 'Bob' }; // Not OK, you must have 'salary'
var c: Employee1 = { name: 'Bob', salary: undefined }; // OK
var d: Employee1 = { name: null, salary: undefined }; // OK
// OK
class SomeEmployeeA implements Employee1 {
public name = 'Bob';
public salary = 40000;
}
// Not OK: Must have 'salary'
class SomeEmployeeB implements Employee1 {
public name: string;
}
Compare with:
interface Employee2 {
name: string;
salary?: number;
}
var a: Employee2 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee2 = { name: 'Bob' }; // OK
var c: Employee2 = { name: 'Bob', salary: undefined }; // OK
var d: Employee2 = { name: null, salary: 'bob' }; // Not OK, salary must be a number
// OK, but doesn't make too much sense
class SomeEmployeeA implements Employee2 {
public name = 'Bob';
}
It's more convenient to use a session, this way you don't have to remember to set headers each time:
session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})
session.get('https://httpbin.org/headers')
By default, session also manages cookies for you. In case you want to disable that, see this question.
This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.
However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.
In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.
Here is a simple example based on a SAP system I have access to.
Public Sub SimpleSAPExport()
Set SapGuiAuto = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI
Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
Set session = SAPCon.Children(0) 'Get the first session (window) on that connection
'Start the transaction to view a table
session.StartTransaction "SE16"
'Select table T001
session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
session.findById("wnd[0]/tbar[1]/btn[7]").Press
'Set our selection criteria
session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
session.findById("wnd[0]/tbar[1]/btn[8]").press
'Click the export to file button
session.findById("wnd[0]/tbar[1]/btn[45]").press
'Choose the export format
session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
session.findById("wnd[1]/tbar[0]/btn[0]").press
'Choose the export filename
session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"
'Export the file
session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub
To help find the names of elements such aswnd[1]/tbar[0]/btn[0]
you can use script recording.
Click the customize local layout button, it probably looks a bit like this:
Then find the Script Recording and Playback menu item.
Within that the More
button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.
The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI")
defines the SapGuiAuto object.
If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx
in the SAP GUI installation folder.
As you can't import a .txt file, I would suggest to read words this way.
list_ = open("world.txt").read().split()
import com.google.common.collect.Lists;
...
ArrayList<String> getSymbolsPresent = Lists.newArrayList("item 1", "item 2");
...
to check button call event first we need to spy on method which will be called after button click so our first line will be spyOn spy methode take two arguments 1) component name 2) method to be spy i.e: 'onSubmit' remember not use '()' only name required then we need to make object of button to be clicked now we have to trigger the event handler on which we will add click event then we expect our code to call the submit method once
it('should call onSubmit method',() => {
spyOn(component, 'onSubmit');
let submitButton: DebugElement =
fixture.debugElement.query(By.css('button[type=submit]'));
fixture.detectChanges();
submitButton.triggerEventHandler('click',null);
fixture.detectChanges();
expect(component.onSubmit).toHaveBeenCalledTimes(1);
});
Just replace <div class="container">
with <div class="container-fluid">
, which is the container with no margins on both sides.
I think this is the best solution because it avoids some useless overriding and makes use of built-in classes, it's clean.
To select the node's contents call:
window.getSelection().selectAllChildren(
document.getElementById(id)
);
This works on all modern browsers including IE9+ (in standards mode).
function select(id) {_x000D_
window.getSelection()_x000D_
.selectAllChildren(_x000D_
document.getElementById("target-div") _x000D_
);_x000D_
}
_x000D_
#outer-div { padding: 1rem; background-color: #fff0f0; }_x000D_
#target-div { padding: 1rem; background-color: #f0fff0; }_x000D_
button { margin: 1rem; }
_x000D_
<div id="outer-div">_x000D_
<div id="target-div">_x000D_
Some content for the _x000D_
<br>Target DIV_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<button onclick="select(id);">Click to SELECT Contents of #target-div</button>
_x000D_
The original answer below is obsolete since window.getSelection().addRange(range);
has been deprecated
All of the examples above use:
var range = document.createRange();
range.selectNode( ... );
but the problem with that is that it selects the Node itself including the DIV tag etc.
To select the Node's text as per the OP question you need to call instead:
range.selectNodeContents( ... )
So the full snippet would be:
function selectText( containerid ) {
var node = document.getElementById( containerid );
if ( document.selection ) {
var range = document.body.createTextRange();
range.moveToElementText( node );
range.select();
} else if ( window.getSelection ) {
var range = document.createRange();
range.selectNodeContents( node );
window.getSelection().removeAllRanges();
window.getSelection().addRange( range );
}
}
Another possible fix that just worked for me:
If you have Assembly A, which references Assembly B, both of which reference a non-project (external) assembly X, and Assembly B's code will not recognize that you have referenced X, then try the following steps in order:
Apparently, VS will not recognize a reference to an external assembly in a project that is a dependency of another project that already references the external. By setting up the references again from the ground up, you overcome this. It's just very odd.
You need to prevent the default event (following the link), otherwise your link will load a new page:
$(document).ready(function(){
$('.play_navigation a').click(function(e){
e.preventDefault();
console.log("this is the click");
});
});
As pointed out in comments, if your link has no href, then it's not a link, use something else.
Not working? Your code is A MESS! and ready() events everywhere... clean it, put all your scripts in ONE ready event and then try again, it will very likely sort things out.
The above answer did not work for me -
The following worked
$('input[type=checkbox]').each(function()
{
this.checked = false;
});
This makes sure all the checkboxes are unchecked.
After I realized that I could use label ::
to make comments and comment out code REM
just looked plain ugly to me. As has been mentioned the double-colon can cause problems when used inside ()
blocked code, but I've discovered a work-around by alternating between the labels ::
and :
space
:: This, of course, does
:: not cause errors.
(
:: But
: neither
:: does
: this.
)
It's not ugly like REM
, and actually adds a little style to your code.
So outside of code blocks I use ::
and inside them I alternate between ::
and :
.
By the way, for large hunks of comments, like in the header of your batch file, you can avoid special commands and characters completely by simply goto
ing over your comments. This let's you use any method or style of markup you want, despite that fact that if CMD
ever actually tried to processes those lines it'd throw a hissy.
@echo off
goto :TopOfCode
=======================================================================
COOLCODE.BAT
Useage:
COOLCODE [/?] | [ [/a][/c:[##][a][b][c]] INPUTFILE OUTPUTFILE ]
Switches:
/? - This menu
/a - Some option
/c:## - Where ## is which line number to begin the processing at.
:a - Some optional method of processing
:b - A third option for processing
:c - A forth option
INPUTFILE - The file to process.
OUTPUTFILE - Store results here.
Notes:
Bla bla bla.
:TopOfCode
CODE
.
.
.
Use what ever notation you wish *
's, @
's etc.
Just used the Nathan's solution and it works fine. I needed to convert ISO-8859-1 to Unicode:
string isocontent = Encoding.GetEncoding("ISO-8859-1").GetString(fileContent, 0, fileContent.Length);
byte[] isobytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(isocontent);
byte[] ubytes = Encoding.Convert(Encoding.GetEncoding("ISO-8859-1"), Encoding.Unicode, isobytes);
return Encoding.Unicode.GetString(ubytes, 0, ubytes.Length);
You may want to use the appendTo
function (which adds to the end of the element):
$("#source").appendTo("#destination");
Alternatively you could use the prependTo
function (which adds to the beginning of the element):
$("#source").prependTo("#destination");
Example:
$("#appendTo").click(function() {_x000D_
$("#moveMeIntoMain").appendTo($("#main"));_x000D_
});_x000D_
$("#prependTo").click(function() {_x000D_
$("#moveMeIntoMain").prependTo($("#main"));_x000D_
});
_x000D_
#main {_x000D_
border: 2px solid blue;_x000D_
min-height: 100px;_x000D_
}_x000D_
_x000D_
.moveMeIntoMain {_x000D_
border: 1px solid red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="main">main</div>_x000D_
<div id="moveMeIntoMain" class="moveMeIntoMain">move me to main</div>_x000D_
_x000D_
<button id="appendTo">appendTo main</button>_x000D_
<button id="prependTo">prependTo main</button>
_x000D_
I'm unable to reproduce your problem but have you tried converting it to an integer first?
image_name_data['id'] = image_name_data['id'].astype(int).astype('str')
Then, regarding your more general question you could use map
(as in this answer). In your case:
image_name_data['id'] = image_name_data['id'].map('{:.0f}'.format)
Andrew's @andrew-wei answer works great. You can also chain a few together, depending on what you are trying to do. This, for example, gets you an image with alt, title and caption with a line break and bold and italics in different parts of the caption:
img + br + strong {margin-top: 5px; margin-bottom: 7px; font-style:italic; font-size: 12px; }
img + br + strong + em {margin-top: 5px; margin-bottom: 7px; font-size: 12px; font-style:italic;}
With the following <img>
markdown:
![description](https://img.jpg "description")
***Image:*** *description*
just set -config
parameter location correctly, i.e :
openssl .................... -config C:\bin\apache\apache2.4.9\conf\openssl.cnf
In Oracle database we can achieve like this.
CREATE TABLE Student(
StudentID Number(38, 0) not null,
DepartmentID Number(38, 0) not null,
PRIMARY KEY (StudentID, DepartmentID)
);
Swift 5:
let homeTab = UITabBarItem(title: "Home", image: UIImage(named: "YOUR_IMAGE_NAME_FROM_ASSETS")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal), tag: 1)
Visual Studio 2013 has a pretty cool visualizer built in.
File -> Open -> File pick your .xsd and then drag elements from XML Schema Explorer onto the designer surface.