This works:
df['date'].dt.year
Now:
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
gives this data frame:
date Count year month
0 2010-06-30 525 2010 6
1 2010-07-30 136 2010 7
2 2010-08-31 125 2010 8
3 2010-09-30 84 2010 9
4 2010-10-29 4469 2010 10
Not tested but should work
products.sort((a,b)=>a.title.rendered > b.title.rendered)
You just need to put attribute "selected" on a particular option instead direct to select element.
Here is snippet for same and multiple working example with different values.
Select Option 3 :- _x000D_
<select name="hall" id="hall">_x000D_
<option>1</option>_x000D_
<option>2</option>_x000D_
<option selected="selected">3</option>_x000D_
<option>4</option>_x000D_
<option>5</option>_x000D_
</select>_x000D_
_x000D_
<br/>_x000D_
<br/>_x000D_
<br/>_x000D_
Select Option 5 :- _x000D_
<select name="hall" id="hall">_x000D_
<option>1</option>_x000D_
<option>2</option>_x000D_
<option>3</option>_x000D_
<option>4</option>_x000D_
<option selected="selected">5</option>_x000D_
</select>_x000D_
_x000D_
<br/>_x000D_
<br/>_x000D_
<br/>_x000D_
Select Option 2 :- _x000D_
<select name="hall" id="hall">_x000D_
<option>1</option>_x000D_
<option selected="selected">2</option>_x000D_
<option>3</option>_x000D_
<option>4</option>_x000D_
<option>5</option>_x000D_
</select>
_x000D_
1) Others (especially dirkgently) have noted that buffer needs to be allocated some memory space. For smallish values of N (say, N <= 4096), you can also allocate it on the stack:
#define BUFFER_SIZE 4096
char buffer[BUFFER_SIZE]
This saves you the worry of ensuring that you delete[]
the buffer should an exception be thrown.
But remember that stacks are finite in size (so are heaps, but stacks are finiter), so you don't want to put too much there.
2) On a -1 return code, you should not simply return immediately (throwing an exception immediately is even more sketchy.) There are certain normal conditions that you need to handle, if your code is to be anything more than a short homework assignment. For example, EAGAIN may be returned in errno if no data is currently available on a non-blocking socket. Have a look at the man page for read(2).
To get a full list of colors to use in plots:
import matplotlib.colors as colors
colors_list = list(colors._colors_full_map.values())
So, you can use in that way quickly:
scatter(X,Y, color=colors_list[0])
scatter(X,Y, color=colors_list[1])
scatter(X,Y, color=colors_list[2])
...
scatter(X,Y, color=colors_list[-1])
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
boolean sameDay = cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) &&
cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR);
Note that "same day" is not as simple a concept as it sounds when different time zones can be involved. The code above will for both dates compute the day relative to the time zone used by the computer it is running on. If this is not what you need, you have to pass the relevant time zone(s) to the Calendar.getInstance()
calls, after you have decided what exactly you mean with "the same day".
And yes, Joda Time's LocalDate
would make the whole thing much cleaner and easier (though the same difficulties involving time zones would be present).
There is certainly a shorter notation, but that was my approach:
gulp.task('check_env', function () {
return new Promise(function (resolve, reject) {
// gulp --dev
var env = process.argv[3], isDev;
if (env) {
if (env == "--dev") {
log.info("Dev Mode on");
isDev = true;
} else {
log.info("Dev Mode off");
isDev = false;
}
} else {
if (variables.settings.isDev == true) {
isDev = true;
} else {
isDev = false;
}
}
resolve();
});
});
If you want to set the env based to the actual Git branch (master/develop):
gulp.task('set_env', function (cb) {
exec('git rev-parse --abbrev-ref HEAD', function (err, stdout, stderr) {
git__branch = stdout.replace(/(\r\n|\n|\r)/gm, "");
if (git__branch == "develop") {
log.info("?Develop Branch");
isCompressing = false;
} else if (git__branch == "master") {
log.info("Master Branch");
isCompressing = true;
} else {
//TODO: check for feature-* branch
log.warn("Unknown " + git__branch + ", maybe feat?");
//isCompressing = variables.settings.isCompressing;
}
log.info(stderr);
cb(err);
});
return;
})
P.s. For the log I added the following:
var log = require('fancy-log');
In Case you need it, thats my default Task:
gulp.task('default',
gulp.series('set_env', gulp.parallel('build_scss', 'minify_js', 'minify_ts', 'minify_html', 'browser_sync_func', 'watch'),
function () {
}));
Suggestions for optimization are welcome.
You called an incorrect method of String class, try:
int tmpInt = 10;
String tmpStr10 = String.valueOf(tmpInt);
You can also do:
int tmpInt = 10;
String tmpStr10 = Integer.toString(tmpInt);
I agree that the out-of-source build is the best answer. But for the times when you just must do an in-source build, I have written a Python script available here, which:
Do you mean search and replace a string in all files matched by grep?
perl -p -i -e 's/oldstring/newstring/g' `grep -ril searchpattern *`
Edit
Since this seems to be a fairly popular question thought I'd update.
Nowadays I mostly use ack-grep
as it's more user-friendly. So the above command would be:
perl -p -i -e 's/old/new/g' `ack -l searchpattern`
To handle whitespace in file names you can run:
ack --print0 -l searchpattern | xargs -0 perl -p -i -e 's/old/new/g'
you can do more with ack-grep
. Say you want to restrict the search to HTML files only:
ack --print0 --html -l searchpattern | xargs -0 perl -p -i -e 's/old/new/g'
And if white space is not an issue it's even shorter:
perl -p -i -e 's/old/new/g' `ack -l --html searchpattern`
perl -p -i -e 's/old/new/g' `ack -f --html` # will match all html files
This is the easiest way that I found to install a plugin locally at eclipse -
Ibrahim's comment on the other answer is the correct way to alter an existing user's home directory.
usermod -d /newhome/username username
usermod
is the command to edit an existing user.
-d
(abbreviation for --home
) will change the user's home directory.
usermod -m -d /newhome/username username
-m
(abbreviation for --move-home
) will move the content from the user's current directory to the new directory.
To add background Image, React Native is based on component, the ImageBackground Component requires two props style={{}} and source={require('')}
<ImageBackground source={require('./wallpaper.jpg')} style={{width: '100%', height: '100%'}}>
<....yourContent Goes here...>
</ImageBackground>
I find this code and is resolve my problem.
http://arcware.net/setting-http-header-authorization-for-web-services/
protected override WebRequest GetWebRequest(Uri uri)
{
// Assuming authValue is set from somewhere, such as the config file
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(uri);
request.Headers.Add("Authorization", string.Format("Basic {0}", authValue));
return request;
}
If you want to extract just a simple piece of information, you can get that using git show
with the --format=<string>
option...and ask it not to give you the diff with --no-patch
. This means you can get a printf-style output of whatever you want, which might often be a single field.
For instance, to get just the shortened hash (%h
) you could say:
$ git show --format="%h" --no-patch
4b703eb
If you're looking to save that into an environment variable in bash (a likely thing for people to want to do) you can use the $()
syntax:
$ GIT_COMMIT="$(git show --format="%h" --no-patch)"
$ echo $GIT_COMMIT
4b703eb
The full list of what you can do is in git show --help
. But here's an abbreviated list of properties that might be useful:
%H
commit hash%h
abbreviated commit hash%T
tree hash%t
abbreviated tree hash%P
parent hashes%p
abbreviated parent hashes%an
author name%ae
author email%at
author date, UNIX timestamp%aI
author date, strict ISO 8601 format%cn
committer name%ce
committer email%ct
committer date, UNIX timestamp%cI
committer date, strict ISO 8601 format%s
subject%f
sanitized subject line, suitable for a filename%gD
reflog selector, e.g., refs/stash@{1}%gd
shortened reflog selector, e.g., stash@{1}In case anyone is looking for recursive.
<?php
echo scanDirectoryImages("images");
/**
* Recursively search through directory for images and display them
*
* @param array $exts
* @param string $directory
* @return string
*/
function scanDirectoryImages($directory, array $exts = array('jpeg', 'jpg', 'gif', 'png'))
{
if (substr($directory, -1) == '/') {
$directory = substr($directory, 0, -1);
}
$html = '';
if (
is_readable($directory)
&& (file_exists($directory) || is_dir($directory))
) {
$directoryList = opendir($directory);
while($file = readdir($directoryList)) {
if ($file != '.' && $file != '..') {
$path = $directory . '/' . $file;
if (is_readable($path)) {
if (is_dir($path)) {
return scanDirectoryImages($path, $exts);
}
if (
is_file($path)
&& in_array(end(explode('.', end(explode('/', $path)))), $exts)
) {
$html .= '<a href="' . $path . '"><img src="' . $path
. '" style="max-height:100px;max-width:100px" /></a>';
}
}
}
}
closedir($directoryList);
}
return $html;
}
Try using float: left
(or right
) instead of display: inline
. Inline display replaces list-item display, which is what adds the bullet points.
At least in 10.11 (El Capitan), the man page for umount indicates:
Due to the complex and interwoven nature of Mac OS X, umount may fail often. It is recommended that diskutil(1) (as in, "diskutil unmount /mnt") be used instead.
This approach (e.g., "diskutil umount path/to/mount/point") allows me to unmount sshfs-mounted content, and does not require sudo. (And I believe that it should work back through at least 10.8.)
If you run in linux, open file netbeans.conf using nano or anything else.
nano netbeans-8.2/etc/netbeans.conf
and edit jdkhome or directory for jdk
netbeans_jdkhome="/usr/lib/jvm/java-1.8.0-openjdk-amd64"
you can check your jdk version with
java -version
or
ls /usr/lib/jvm
Based on the accepted answer and the answer of @LeoCaseiro here is what I ended up using in my case :
@media (max-width: 767px) {
.table-responsive{
overflow-x: auto;
overflow-y: auto;
}
}
@media (min-width: 767px) {
.table-responsive{
overflow: inherit !important; /* Sometimes needs !important */
}
}
on big screens the dropdown won't be hidden behind the reponsive-table and in small screen it will be hidden but it's ok because there is scrolls bar in mobile anyway.
Hope this help someone.
Your -vm argument seems ok BUT it's position is wrong. According to this Eclipse Wiki entry :
The -vm option must occur before the -vmargs option, since everything after -vmargs is passed directly to the JVM.
So your -vm argument is not taken into account and it fails over to your default java installation, which is probably 1.6.0_65.
Or you could just add some content to the div and use inline-table
Using a dict wouldn't like double your memory usage unless the objects you're storing are really tiny, since the values are only pointers to the actual objects:
>>> a = 'foo'
>>> b = [a]
>>> c = [a]
>>> b[0] is c[0]
True
In that example, 'foo' is only stored once. Does that make a difference for you? And exactly how many items are we talking about anyway?
Combine Remove Old Backup files with above script then this can perform backup by a scheduler, keep last 10 backup files
echo off
:: set folder to save backup files ex. BACKUPPATH=c:\backup
set BACKUPPATH=<<back up folder here>>
:: set Sql Server location ex. set SERVERNAME=localhost\SQLEXPRESS
set SERVERNAME=<<sql host here>>
:: set Database name to backup
set DATABASENAME=<<db name here>>
:: filename format Name-Date (eg MyDatabase-2009-5-19_1700.bak)
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
set DATESTAMP=%mydate%_%mytime%
set BACKUPFILENAME=%BACKUPPATH%\%DATABASENAME%-%DATESTAMP%.bak
echo.
sqlcmd -E -S %SERVERNAME% -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = N'%BACKUPFILENAME%' WITH INIT , NOUNLOAD , NAME = N'%DATABASENAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.
:: In this case, we are choosing to keep the most recent 10 files
:: Also, the files we are looking for have a 'bak' extension
for /f "skip=10 delims=" %%F in ('dir %BACKUPPATH%\*.bak /s/b/o-d/a-d') do del "%%F"
The Eclipse releases are named after the moons of Jupiter, and each denotes a successive release.
Helios is the current release you can download eclipse as your programming needs http://www.eclipse.org/downloads/
The previous answer is fine, but I'm one of those guys that's firmly against mixing behavior with presentation (putting JavaScript in my HTML) so I prefer to put my event handling logic in my JavaScript files. Additionally, not all browsers implement event (or e) the same way. You may want to do a check prior to running any logic:
document.onkeydown = TabExample;
function TabExample(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var tabKey = 9;
if(evt.keyCode == tabKey) {
// do work
}
}
\040
matches exactly the space character.
New Link
Escape sequences for Regex PHP
There are several of this same question (1, 2). One way of doing it is using canvas. Here's a working solution. Here you can see some working examples of using this library.
Use tr:first-child
to take the first tr
:
.category_table tr:first-child td {
vertical-align: top;
}
If you have nested tables, and you don't want to apply styles to the inner rows, add some child selectors so only the top-level td
s in the first top-level tr
get the styles:
.category_table > tbody > tr:first-child > td {
vertical-align: top;
}
What you can do to solve this is:
C:\xampp\php
.Django querysets are lazy. That means a query will hit the database only when you specifically ask for the result.
So until you print or actually use the result of a query you can filter further with no database access.
As you can see below your code only executes one sql query to fetch only the last 10 items.
In [19]: import logging
In [20]: l = logging.getLogger('django.db.backends')
In [21]: l.setLevel(logging.DEBUG)
In [22]: l.addHandler(logging.StreamHandler())
In [23]: User.objects.all().order_by('-id')[:10]
(0.000) SELECT "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user" ORDER BY "auth_user"."id" DESC LIMIT 10; args=()
Out[23]: [<User: hamdi>]
This seems to be the supported native method in OS X:
cd /Applications/eclipse/
open -n Eclipse.app
Be sure to specify the ".app" version (directory); in OS X Mountain Lion erroneously using the symbolic link such as open -n eclipse
, might get one GateKeeper stopping access:
"eclipse" can't be opened because it is from an unidentified developer.
Your security preferences allow installation of only apps from the Mac App Store and identified developers.
Even removing the extended attribute com.apple.quarantine
does not fix that. Instead, simply using the ".app" version will rely on your previous consent, or prompt you once:
"Eclipse" is an application downloaded from the Internet. Are you sure you want to open it?
JSON is a valid datatype in PostgreSQL database as well. However, MySQL database has not officially supported JSON yet. But it's baking: http://mysqlserverteam.com/json-labs-release-native-json-data-type-and-binary-format/
I also agree that there are many valid cases that some data is better be serialized to a string in a database. The primary reason might be when it's not regularly queried, and when it's own schema might change - you don't want to change the database schema corresponding to that. The second reason is when the serialized string is directly from external sources, you may not want to parse all of them and feed in the database at any cost until you use any. So I'll be waiting for the new MySQL release to support JSON since it'll be easier for switching between different database then.
Since other questions are being redirected to this one which ask about asanyarray
or other array creation routines, it's probably worth having a brief summary of what each of them does.
The differences are mainly about when to return the input unchanged, as opposed to making a new array as a copy.
array
offers a wide variety of options (most of the other functions are thin wrappers around it), including flags to determine when to copy. A full explanation would take just as long as the docs (see Array Creation, but briefly, here are some examples:
Assume a
is an ndarray
, and m
is a matrix
, and they both have a dtype
of float32
:
np.array(a)
and np.array(m)
will copy both, because that's the default behavior.np.array(a, copy=False)
and np.array(m, copy=False)
will copy m
but not a
, because m
is not an ndarray
.np.array(a, copy=False, subok=True)
and np.array(m, copy=False, subok=True)
will copy neither, because m
is a matrix
, which is a subclass of ndarray
.np.array(a, dtype=int, copy=False, subok=True)
will copy both, because the dtype
is not compatible.Most of the other functions are thin wrappers around array
that control when copying happens:
asarray
: The input will be returned uncopied iff it's a compatible ndarray
(copy=False
).asanyarray
: The input will be returned uncopied iff it's a compatible ndarray
or subclass like matrix
(copy=False
, subok=True
).ascontiguousarray
: The input will be returned uncopied iff it's a compatible ndarray
in contiguous C order (copy=False
, order='C')
.asfortranarray
: The input will be returned uncopied iff it's a compatible ndarray
in contiguous Fortran order (copy=False
, order='F'
).require
: The input will be returned uncopied iff it's compatible with the specified requirements string.copy
: The input is always copied.fromiter
: The input is treated as an iterable (so, e.g., you can construct an array from an iterator's elements, instead of an object
array with the iterator); always copied.There are also convenience functions, like asarray_chkfinite
(same copying rules as asarray
, but raises ValueError
if there are any nan
or inf
values), and constructors for subclasses like matrix
or for special cases like record arrays, and of course the actual ndarray
constructor (which lets you create an array directly out of strides over a buffer).
Another simple way:
ActiveSheet.Rows(ActiveSheet.UsedRange.Rows.Count+1).Select
Selection.EntireRow.Delete
or simpler:
ActiveSheet.Rows(ActiveSheet.UsedRange.Rows.Count+1).EntireRow.Delete
Funny, I was just playing around writing this same query out in SQL Server and then LINQ.
SELECT
DATENAME(mm, article.Created) AS Month,
DATENAME(yyyy, article.Created) AS Year,
COUNT(*) AS Total
FROM Articles AS article
GROUP BY
DATENAME(mm, article.Created),
DATENAME(yyyy, article.Created)
ORDER BY Month, Year DESC
It produces the following ouput (example).
Month | Year | Total
January | 2009 | 2
I notice that all the prior answers use older Win32 User library functions to accomplish this. I think this will work in most cases, but will work less reliably over time.
Now, not having done this, I can't tell you how well it will work, but I do know that a current Windows technology might be a better solution: the Desktop Windows Manager API.
DWM is the same technology that lets you see live thumbnail previews of apps using the taskbar and task switcher UI. I believe it is closely related to Remote Terminal services.
I think that a probable problem that might happen when you force an app to be a child of a parent window that is not the desktop window is that some application developers will make assumptions about the device context (DC), pointer (mouse) position, screen widths, etc., which may cause erratic or problematic behavior when it is "embedded" in the main window.
I suspect that you can largely eliminate these problems by relying on DWM to help you manage the translations necessary to have an application's windows reliably be presented and interacted with inside another application's container window.
The documentation assumes C++ programming, but I found one person who has produced what he claims is an open source C# wrapper library: https://bytes.com/topic/c-sharp/answers/823547-desktop-window-manager-wrapper. The post is old, and the source is not on a big repository like GitHub, bitbucket, or sourceforge, so I don't know how current it is.
Yes,
with open('filename.txt') as fp:
for line in fp:
print line
is the way to go.
It is not more verbose. It is more safe.
I might be off here, but it seems that the answer is quite obvious: Look at reference paths in the project properties. In our setup I added our common repository folder, to the ref path GUI window, like so
That way I can copy my dlls (ready for publish) to this folder and every developer now gets the updated DLL every time it builds from this folder.
If the dll is found in the Solution, the builder should prioritize the local version over the published team version.
You can use Length annotation for a column. By using it you can maximize or minimize column length. Length annotation only be used for Strings
.
@Column(name = "NAME", nullable = false, length = 50)
@Length(max = 50)
public String getName() {
return this.name;
}
v-flex does not have a display flex! Inspect v-flex in your browser and you will find out it is just a simple block div.
So, you should override it with display: flex
in your HTML or CSS to make it work with justify-content.
If you are using Visual Studio with NTVS, you can set the environment variables on the project properties page:
As you can see, the Configuration and Platform dropdowns are disabled (I haven't looked too far into why this is), but if you edit your .njsproj
file as follows:
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugSymbols>true</DebugSymbols>
<Environment>NODE_ENV=development</Environment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DebugSymbols>true</DebugSymbols>
<Environment>NODE_ENV=production</Environment>
</PropertyGroup>
The 'Debug / Release' dropdown will then control how the variable is set before starting Node.js.
Try using the net use
command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.
net use \\<network-location>\<some-share> password /USER:username
Don't leave a trailing \ at the end of the
You can assign an id to the specific link and add CSS. See the steps below:
1.Add an id of your choice (must be a unique name; can only start with text, not a number):
<a href="/abc/xyz" id="smallLinkButton">def</a>
Then add the necessary CSS as follows:
#smallLinkButton:hover,active,visited{
text-decoration: none;
}
I haven't been using jquery for a while but you might be looking for this:
The method based on list comprehension and groupby
, which stores all the split dataframes in a list variable and can be accessed using the index.
Example:
ans = [pd.DataFrame(y) for x, y in DF.groupby('column_name', as_index=False)]***
ans[0]
ans[0].column_name
Here is a jQuery plugin that does exactly that: http://fixedheadertable.com/
Usage:
$('selector').fixedHeaderTable({ fixedColumn: 1 });
Set the fixedColumn
option if you want any number of columns to be also fixed for horizontal scrolling.
EDIT: This example http://www.datatables.net/examples/basic_init/scroll_y.html is much better in my opinion, although with DataTables you'll need to get a better understanding of how it works in general.
EDIT2: For Bootstrap to work with DataTables you need to follow the instructions here: http://datatables.net/blog/Twitter_Bootstrap_2 (I have tested this and it works)- For Bootstrap 3 there's a discussion here: http://datatables.net/forums/discussion/comment/53462 - (I haven't tested this)
template <class outType, class inType>
outType safe_cast(inType pointer)
{
void* temp = static_cast<void*>(pointer);
return static_cast<outType>(temp);
}
I tried to conclude and wrote a simple safe cast using templates. Note that this solution doesn't guarantee to cast pointers on a functions.
Wow. I know this is an ancient thread but all I can say is do not call TimeZone.setDefault() in any user-level code. This always sets the Timezone for the whole JVM and is nearly always a very bad idea. Learn to use the joda.time library or the new DateTime class in Java 8 which is very similar to the joda.time library.
>= ES6:
Number.MIN_SAFE_INTEGER;
Number.MAX_SAFE_INTEGER;
<= ES5
From the reference:
Number.MAX_VALUE;
Number.MIN_VALUE;
console.log('MIN_VALUE', Number.MIN_VALUE);
console.log('MAX_VALUE', Number.MAX_VALUE);
console.log('MIN_SAFE_INTEGER', Number.MIN_SAFE_INTEGER); //ES6
console.log('MAX_SAFE_INTEGER', Number.MAX_SAFE_INTEGER); //ES6
_x000D_
I came up with an generic, interesting solution to this problem:
class SafeInvocator(object):
def __init__(self, module):
self._module = module
def _safe(self, func):
def inner(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
return None
return inner
def __getattr__(self, item):
obj = getattr(self.module, item)
return self._safe(obj) if hasattr(obj, '__call__') else obj
and you can use it like so:
safe_json = SafeInvocator(json)
text = "{'foo':'bar'}"
item = safe_json.loads(text)
if item:
# do something
1 and 2 are SAML 1.1 because those URIs were part of the OASIS SAML 1.1 standard. Section 8.3 of the linked PDF for the OASIS SAML 2.0 standard explains this:
Where possible an existing URN is used to specify a protocol. In the case of IETF protocols, the URN of the most current RFC that specifies the protocol is used. URI references created specifically for SAML have one of the following stems, according to the specification set version in which they were first introduced:
urn:oasis:names:tc:SAML:1.0: urn:oasis:names:tc:SAML:1.1: urn:oasis:names:tc:SAML:2.0:
I use moment for all my time manipulation/display needs (both client side, and node.js if you use it), if you just need a simple format the answers above will do, if you are looking for something a bit more complex, moment is the way to go IMO.
You can do it like this.
Models.TestModels obj = new Models.TestModels();
foreach (var item in obj.sp)
{
Console.Write(item.Key);
Console.Write(item.Value.name);
Console.Write(item.Value.age);
}
The problem you most likely have right now is that the collection is private. If you add public to the beginning of this line
Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>
You should be able to access it from the function inside your controller.
Edit: Adding functional example of the full TestModels
implementation.
Your TestModels
class should look something like this.
public class TestModels
{
public Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>();
public TestModels()
{
sp.Add(0, new {name="Test One", age=5});
sp.Add(1, new {name="Test Two", age=7});
}
}
You probably want to read up on the dynamic keyword as well.
Actually I have imports messed up. In latest version of RxJS we can import it like that:
import 'rxjs/add/observable/of';
We just open-sourced this jquery plug-in Github: tactivos/jquery-sew.
Sounds like a good job for regular expressions.
Laravel validation rules support regular expressions. Both 4.X and 5.X versions are supporting it :
This might help too:
Given the comment of "say Windows XP as an example", then your options are:
Interact directly with the operating system via its API, which for Microsoft Windows is surprise surprise call Windows API. The definitive reference for the WinAPI is Microsoft's MSDN website. A popular online beginner tutorial for that is theForger's Win32 API Programming Tutorial. The classic book for that is Charles Petzold's Programming Windows, 5th Edition.
Use a platform (both in terms of OS and compiler) specific library such as MFC, which wraps the WinAPI into C++ class. The reference for that is again MSDN. A classic book for that is Jeff Prosise's Programming Windows with MFC, 2nd Edition. If you are using say CodeGear C++ Builder, then the option here is VCL.
Use a cross platform library such as GTK+ (C++ wrapper: gtkmm), Qt, wxWidgets, or FLTK that wrap the specific OS's API. The advantages with these are that in general, your program could been compiled for different OS without having to change the source codes. As have already been mentioned, they each have its own strengths and weaknesses. One consideration when selecting which one to use is its license. For the examples given, GTK+ & gtkmm is license under LGPL, Qt is under various licenses including proprietary option, wxWidgets is under its own wxWindows Licence (with a rename to wxWidgets Licence), and FLTK is under LGPL with exception. For reference, tutorial, and or books, refer to each one's website for details.
This version produces JSON that is more compact and in my opinion more readable since you can see more at one time. It does this by formatting the deepest layer inline or like a compact array structure.
The code has no dependencies but is more complex.
{
"name":"Seller",
"schema":"dbo",
"CaptionFields":["Caption","Id"],
"fields":[
{"name":"Id","type":"Integer","length":"10","autoincrement":true,"nullable":false},
{"name":"FirstName","type":"Text","length":"50","autoincrement":false,"nullable":false},
{"name":"LastName","type":"Text","length":"50","autoincrement":false,"nullable":false},
{"name":"LotName","type":"Text","length":"50","autoincrement":false,"nullable":true},
{"name":"LotDetailsURL","type":"Text","length":"255","autoincrement":false,"nullable":true}
]
}
The code follows
private class IndentJsonInfo
{
public IndentJsonInfo(string prefix, char openingTag)
{
Prefix = prefix;
OpeningTag = openingTag;
Data = new List<string>();
}
public string Prefix;
public char OpeningTag;
public bool isOutputStarted;
public List<string> Data;
}
internal static string IndentJSON(string jsonString, int startIndent = 0, int indentSpaces = 2)
{
if (String.IsNullOrEmpty(jsonString))
return jsonString;
try
{
var jsonCache = new List<IndentJsonInfo>();
IndentJsonInfo currentItem = null;
var sbResult = new StringBuilder();
int curIndex = 0;
bool inQuotedText = false;
var chunk = new StringBuilder();
var saveChunk = new Action(() =>
{
if (chunk.Length == 0)
return;
if (currentItem == null)
throw new Exception("Invalid JSON: No container.");
currentItem.Data.Add(chunk.ToString());
chunk = new StringBuilder();
});
while (curIndex < jsonString.Length)
{
var cChar = jsonString[curIndex];
if (inQuotedText)
{
// Get the rest of quoted text.
chunk.Append(cChar);
// Determine if the quote is escaped.
bool isEscaped = false;
var excapeIndex = curIndex;
while (excapeIndex > 0 && jsonString[--excapeIndex] == '\\') isEscaped = !isEscaped;
if (cChar == '"' && !isEscaped)
inQuotedText = false;
}
else if (Char.IsWhiteSpace(cChar))
{
// Ignore all whitespace outside of quotes.
}
else
{
// Outside of Quotes.
switch (cChar)
{
case '"':
chunk.Append(cChar);
inQuotedText = true;
break;
case ',':
chunk.Append(cChar);
saveChunk();
break;
case '{':
case '[':
currentItem = new IndentJsonInfo(chunk.ToString(), cChar);
jsonCache.Add(currentItem);
chunk = new StringBuilder();
break;
case '}':
case ']':
saveChunk();
for (int i = 0; i < jsonCache.Count; i++)
{
var item = jsonCache[i];
var isLast = i == jsonCache.Count - 1;
if (!isLast)
{
if (!item.isOutputStarted)
{
sbResult.AppendLine(
"".PadLeft((startIndent + i) * indentSpaces) +
item.Prefix + item.OpeningTag);
item.isOutputStarted = true;
}
var newIndentString = "".PadLeft((startIndent + i + 1) * indentSpaces);
foreach (var listItem in item.Data)
{
sbResult.AppendLine(newIndentString + listItem);
}
item.Data = new List<string>();
}
else // If Last
{
if (!(
(item.OpeningTag == '{' && cChar == '}') ||
(item.OpeningTag == '[' && cChar == ']')
))
{
throw new Exception("Invalid JSON: Container Mismatch, Open '" + item.OpeningTag + "', Close '" + cChar + "'.");
}
string closing = null;
if (item.isOutputStarted)
{
var newIndentString = "".PadLeft((startIndent + i + 1) * indentSpaces);
foreach (var listItem in item.Data)
{
sbResult.AppendLine(newIndentString + listItem);
}
closing = cChar.ToString();
}
else
{
closing =
item.Prefix + item.OpeningTag +
String.Join("", currentItem.Data.ToArray()) +
cChar;
}
jsonCache.RemoveAt(i);
currentItem = (jsonCache.Count > 0) ? jsonCache[jsonCache.Count - 1] : null;
chunk.Append(closing);
}
}
break;
default:
chunk.Append(cChar);
break;
}
}
curIndex++;
}
if (inQuotedText)
throw new Exception("Invalid JSON: Incomplete Quote");
else if (jsonCache.Count != 0)
throw new Exception("Invalid JSON: Incomplete Structure");
else
{
if (chunk.Length > 0)
sbResult.AppendLine("".PadLeft(startIndent * indentSpaces) + chunk);
var result = sbResult.ToString();
return result;
}
}
catch (Exception ex)
{
throw; // Comment out to return unformatted text if the format failed.
// Invalid JSON, skip the formatting.
return jsonString;
}
}
The function allows you to specify a starting point for the indentation because I use this as part of a process that assembles very large JSON formatted backup files.
imwrite(A,filename)
writes image data A to the file specified by filename, inferring the file format from the extension
The best solution is to install the different Python versions in multiple paths.
eg. C:\Python27 for 2.7, and C:\Python33 for 3.3.
Read this for more info: How to run multiple Python versions on Windows
Check out this answer, which describes, how to get ID response. First, you need to create method get data:
const https = require('https');
getFbData = (accessToken, apiPath, callback) => {
const options = {
host: 'graph.facebook.com',
port: 443,
path: `${apiPath}access_token=${accessToken}`, // apiPath example: '/me/friends'
method: 'GET'
};
let buffer = ''; // this buffer will be populated with the chunks of the data received from facebook
const request = https.get(options, (result) => {
result.setEncoding('utf8');
result.on('data', (chunk) => {
buffer += chunk;
});
result.on('end', () => {
callback(buffer);
});
});
request.on('error', (e) => {
console.log(`error from facebook.getFbData: ${e.message}`)
});
request.end();
}
Then simply use your method whenever you want, like this:
getFbData(access_token, '/me?fields=id&', (result) => {
console.log(result);
});
Use DateTime::createFromFormat
$date = date_create_from_format('d/m/Y:H:i:s', $s);
$date->getTimestamp();
When using -c
command, as a tricky way, instead of reading the stdin
(and more flexible in some cases) you can pass a shell script command as well to your python command by putting the shell command in quotes within a parenthesis started by $
sign.
e.g.
python3 -c "import sys; print(len(sys.argv[1].split('\n')))" "$(cat ~/.goldendict/history)"
This will count the number of lines from goldendict's history file.
By turning them into integers instead:
percent = (int(pyc) / int(tpy)) * 100;
In python 3, the input()
function returns a string. Always. This is a change from Python 2; the raw_input()
function was renamed to input()
.
I just had this problem setting up my new laptop. The issue for me was that my toolchain (CodeSourcery) is 32bit and I had not installed the 32bit libs.
sudo apt-get install ia32-libs
JonSkeet has a good answer but as an alternative if you wanted to keep the result more portable you could convert the date into an ISO 8601 format which could then be read into most other frameworks but this may fall outside your requirements.
value.ToUniversalTime().ToString("O");
It's still an attribute. Setting it to:
<input type="button" name=myButton value="disable" disabled="disabled">
... is valid.
An easy and usable way to solve this problem
getGetSuppor(filter): Observale<any[]> {
return this.https.get<any[]>('/api/callCenter/getSupport' + '?' + this.toQueryString(filter));
}
private toQueryString(query): string {
var parts = [];
for (var property in query) {
var value = query[propery];
if (value != null && value != undefined)
parts.push(encodeURIComponent(propery) + '=' + encodeURIComponent(value))
}
return parts.join('&');
}
Add sudo to your command line, like:
$ sudo firebase init
The plus sign is the historic encoding for a space character in URL parameters, as documented in the help for the urlencode()
function.
That same page contains the answer you need - use rawurlencode()
instead to get RFC 3986 compatible encoding.
In Python, You can Try...
from encodings.aliases import aliases
alias_values = set(aliases.values())
for encoding in set(aliases.values()):
try:
df=pd.read_csv("test.csv", encoding=encoding)
print('successful', encoding)
except:
pass
when I send only one object from the client to server all works well.
when I attempt to send several objects one after another on the same stream I get
StreamCorruptedException
.
Actually, your client code is writing one object to the server and reading multiple objects from the server. And there is nothing on the server side that is writing the objects that the client is trying to read.
protected bool CheckIfPalindrome(string text)
{
if (text != null)
{
string strToUpper = Text.ToUpper();
char[] toReverse = strToUpper.ToCharArray();
Array.Reverse(toReverse );
String strReverse = new String(toReverse);
if (strToUpper == toReverse)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
Use this the sipmlest way.
Adding the padding is rather... fiddly. Here's the function I wrote with the help of the comments in this thread as well as the wiki page for base64 (it's surprisingly helpful) https://en.wikipedia.org/wiki/Base64#Padding.
import logging
import base64
def base64_decode(s):
"""Add missing padding to string and return the decoded base64 string."""
log = logging.getLogger()
s = str(s).strip()
try:
return base64.b64decode(s)
except TypeError:
padding = len(s) % 4
if padding == 1:
log.error("Invalid base64 string: {}".format(s))
return ''
elif padding == 2:
s += b'=='
elif padding == 3:
s += b'='
return base64.b64decode(s)
You can also use importlib
directly
import importlib
try:
importlib.import_module(module_name)
except ImportError:
# Handle error
In windows
$exec = 'ipconfig | findstr /R /C:"IPv4.*"';
exec($exec, $output);
preg_match('/\d+\.\d+\.\d+\.\d+/', $output[0], $matches);
print_r($matches[0]);
only with this:
const a = true; const b = false;
console.log(+a);//1 console.log(+b);//0
I need something similiar with angular reactive form:
let myMap = new Map().set(0, {status: 'VALID'}).set(1, {status: 'INVALID'});
let mapToArray = Array.from(myMap.values());
let isValid = mapToArray.every(x => x.status === 'VALID');
The following code works fine:
@using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
and generates as expected:
<form action="/Upload/Upload" enctype="multipart/form-data" method="post">
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
</form>
On the other hand if you are writing this code inside the context of other server side construct such as an if
or foreach
you should remove the @
before the using
. For example:
@if (SomeCondition)
{
using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
}
As far as your server side code is concerned, here's how to proceed:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Upload");
}
I would use a dict to pass and return values from a function:
Use variable form as defined in form.
form = {
'level': 0,
'points': 0,
'game': {
'name': ''
}
}
def test(form):
form['game']['name'] = 'My game!'
form['level'] = 2
return form
>>> print(test(form))
{u'game': {u'name': u'My game!'}, u'points': 0, u'level': 2}
This is the most efficient way for me and for processing unit.
You have to pass just one pointer in and return just one pointer out.
You do not have to change functions' (thousands of them) arguments whenever you make a change in your code.
I'd say use <em>
to emphasize inline elements. Use a class for block elements like blocks of text. CSS or not, the text still has to be tagged. Whether its for semantics or for visual aid, I'm assuming you'd be using it for something meaningful...
If you're emphasizing text for ANY reason, you could use <em>
, or a class that italicizes your text.
It's OK to break the rules sometimes!
Yes, there is one. It is an eclipse-plugin called Visual Editor. You can download it here
I am not sure did you see this list of MS SQL Modules for Node JS
Share your experience after using one if possible .
Good Luck
im not really that good at C , but i believe this code should get you complete single line till the end...
#include<stdio.h>
int main()
{
char line[1024];
FILE *f=fopen("filename.txt","r");
fscanf(*f,"%[^\n]",line);
printf("%s",line);
}
There are three scenarios (that I can think of) where you would call a method in a subclass where the method exits in the parent class:
Method is not overwritten by subclass, only exists in parent.
This is the same as your example, and generally it's better to use $this -> get_species();
You are right that in this case the two are effectively the same, but the method has been inherited by the subclass, so there is no reason to differentiate. By using $this
you stay consistent between inherited methods and locally declared methods.
Method is overwritten by the subclass and has totally unique logic from the parent.
In this case, you would obviously want to use $this -> get_species();
because you don't want the parent's version of the method executed. Again, by consistently using $this
, you don't need to worry about the distinction between this case and the first.
Method extends parent class, adding on to what the parent method achieves.
In this case, you still want to use `$this -> get_species();
when calling the method from other methods of the subclass. The one place you will call the parent method would be from the method that is overwriting the parent method. Example:
abstract class Animal {
function get_species() {
echo "I am an animal.";
}
}
class Dog extends Animal {
function __construct(){
$this->get_species();
}
function get_species(){
parent::get_species();
echo "More specifically, I am a dog.";
}
}
The only scenario I can imagine where you would need to call the parent method directly outside of the overriding method would be if they did two different things and you knew you needed the parent's version of the method, not the local. This shouldn't be the case, but if it did present itself, the clean way to approach this would be to create a new method with a name like get_parentSpecies()
where all it does is call the parent method:
function get_parentSpecies(){
parent::get_species();
}
Again, this keeps everything nice and consistent, allowing for changes/modifications to the local method rather than relying on the parent method.
One other possible implementation, more cumbersome than the .bind() solution, but one that helps to make the point that expect() requires a function that provides a this
context to the covered function, you can use a call()
, e.g.,
expect(function() {model.get.call(model, 'z');}).to.throw('...');
Here is code to render arbitrary HTML into a canvas:
function render_html_to_canvas(html, ctx, x, y, width, height) {
var xml = html_to_xml(html);
xml = xml.replace(/\#/g, '%23');
var data = "data:image/svg+xml;charset=utf-8,"+'<svg xmlns="http://www.w3.org/2000/svg" width="'+width+'" height="'+height+'">' +
'<foreignObject width="100%" height="100%">' +
xml+
'</foreignObject>' +
'</svg>';
var img = new Image();
img.onload = function () {
ctx.drawImage(img, x, y);
}
img.src = data;
}
function html_to_xml(html) {
var doc = document.implementation.createHTMLDocument('');
doc.write(html);
// You must manually set the xmlns if you intend to immediately serialize
// the HTML document to a string as opposed to appending it to a
// <foreignObject> in the DOM
doc.documentElement.setAttribute('xmlns', doc.documentElement.namespaceURI);
// Get well-formed markup
html = (new XMLSerializer).serializeToString(doc.body);
return html;
}
example:
const ctx = document.querySelector('canvas').getContext('2d');
const html = `
<p>this
<p>is <span style="color:red; font-weight: bold;">not</span>
<p><i>xml</i>!
<p><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABWElEQVQ4jZ2Tu07DQBBFz9jjvEAQqAlQ0CHxERQ0/AItBV9Ew8dQUNBQIho6qCFE4Nhex4u85OHdWAKxzfWsx0d3HpazdGITA4kROjl0ckFrnYJmQlJrKsQZxFOIMyEqIMpADGhSZpikB1hAGsovdxABGuepC/4L0U7xRTG/riG3J8fuvdifPKnmasXp5c2TB1HNPl24gNTnpeqsgmj1eFgayoHvRDWbLBOKJbn9WLGYflCCpmM/2a4Au6/PTjdH+z9lCJQ9vyeq0w/ve2kA3vaOnI6k4Pz+0Y24yP3Gapy+Bw6qdfsCRZfWSWgclCCVXTZu5LZFXKJJ2sepW2KYNCENB3U5pw93zLoDjNK6E7rTFcgbkGYJtiLckxCiw4W1OURsxUE5BokQiQj3JIToVtKwlhsurq+YDYbMBjuU/W3KtT3xIbrpAD7E60lwQohuaMtP8ldI0uMbGfC1r1zyWPUAAAAASUVORK5CYII=">`;
render_html_to_canvas(html, ctx, 0, 0, 300, 150);
function render_html_to_canvas(html, ctx, x, y, width, height) {
var data = "data:image/svg+xml;charset=utf-8," + '<svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + height + '">' +
'<foreignObject width="100%" height="100%">' +
html_to_xml(html) +
'</foreignObject>' +
'</svg>';
var img = new Image();
img.onload = function() {
ctx.drawImage(img, x, y);
}
img.src = data;
}
function html_to_xml(html) {
var doc = document.implementation.createHTMLDocument('');
doc.write(html);
// You must manually set the xmlns if you intend to immediately serialize
// the HTML document to a string as opposed to appending it to a
// <foreignObject> in the DOM
doc.documentElement.setAttribute('xmlns', doc.documentElement.namespaceURI);
// Get well-formed markup
html = (new XMLSerializer).serializeToString(doc.body);
return html;
}
_x000D_
<canvas></canvas>
_x000D_
It turns out that, out of the four possible permutations of including or excluding trailing or leading forward slashes on the BaseAddress
and the relative URI passed to the GetAsync
method -- or whichever other method of HttpClient
-- only one permutation works. You must place a slash at the end of the BaseAddress
, and you must not place a slash at the beginning of your relative URI, as in the following example.
using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri("http://something.com/api/");
var response = await client.GetAsync("resource/7");
}
Even though I answered my own question, I figured I'd contribute the solution here since, again, this unfriendly behavior is undocumented. My colleague and I spent most of the day trying to fix a problem that was ultimately caused by this oddity of HttpClient
.
You can "link" a code file between two projects. Right click your project, choose Add
-> Existing item
, and then click the down arrow next to the Add
button:
In my experience linking is simpler than creating a library. Linked code results in a single executable with a single version.
Or you can tell javascript where to write it.
<script type="text/javascript">
var elem = document.getElementById('myDiv');
var msg= 'Hello<br />';
elem.innerHTML = msg;
</script>
You can combine this with other functions to have function write content after being evaluated.
for maven project , you should add this dependency
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
Turn on less secure apps for your account: https://www.google.com/settings/security/lesssecureapps
you can also do
SELECT SQL_CALC_FOUND_ROWS * FROM tbl limit 0, 20
The row count of the select statement (without the limit) is captured in the same select statement so that you don't need to query the table size again. You get the row count using SELECT FOUND_ROWS();
I know this is an old question, but I thought I would share this little trick.
var diff = $(old_array).not(new_array).get();
diff
now contains what was in old_array
that is not in new_array
The python libs are obsolete with this function. I've done one that works correctly:
import os
import shutil
def copydirectorykut(src, dst):
os.chdir(dst)
list=os.listdir(src)
nom= src+'.txt'
fitx= open(nom, 'w')
for item in list:
fitx.write("%s\n" % item)
fitx.close()
f = open(nom,'r')
for line in f.readlines():
if "." in line:
shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
else:
if not os.path.exists(dst+'/'+line[:-1]):
os.makedirs(dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
f.close()
os.remove(nom)
os.chdir('..')
For the people looking for regular polygons:
function regPolyPath(r,p,ctx){ //Radius, #points, context
//Azurethi was here!
ctx.moveTo(r,0);
for(i=0; i<p+1; i++){
ctx.rotate(2*Math.PI/p);
ctx.lineTo(r,0);
}
ctx.rotate(-2*Math.PI/p);
}
Use:
//Get canvas Context
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.translate(60,60); //Moves the origin to what is currently 60,60
//ctx.rotate(Rotation); //Use this if you want the whole polygon rotated
regPolyPath(40,6,ctx); //Hexagon with radius 40
//ctx.rotate(-Rotation); //remember to 'un-rotate' (or save and restore)
ctx.stroke();
Here is my little utility helper for splitting paths int file, path tokens:
import os
# usage: file, path = splitPath(s)
def splitPath(s):
f = os.path.basename(s)
p = s[:-(len(f))-1]
return f, p
As others have mentioned: CSS-3 says that you can use the rgba(...)
syntax to specify a border color with an opacity (alpha) value.
here's a quick example if you'd like to check it.
It works in Safari and Chrome (probably works in all webkit browsers).
It works in Firefox
I doubt that it works at all in IE, but I suspect that there is some filter or behavior that will make it work.
There's also this stackoverflow post, which suggests some other issues--namely, that the border renders on-top-of any background color (or background image) that you've specified; thus limiting the usefulness of border alpha in many cases.
To ignore a field, annotate it with @Transient
so it will not be mapped by hibernate.
Source: Hibernate Annotations.
If you want to SELECT
based on the value of another SELECT
, then you probably want a "subselect":
http://beginner-sql-tutorial.com/sql-subquery.htm
For example, (from the link above):
You want the first and last names from table "student_details" ...
But you only want this information for those students in "science" class:
SELECT id, first_name
FROM student_details
WHERE first_name IN (SELECT first_name
FROM student_details
WHERE subject= 'Science');
Frankly, I'm not sure this is what you're looking for or not ... but I hope it helps ... at least a little...
IMHO...
Use Enumerable.Select<TSource, TResult> Method (IEnumerable<TSource>, Func<TSource, Int32, TResult>)
list = list.Cast<object>().Select( (v, i) => new {Value= v, Index = i});
foreach(var row in list)
{
bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row.Value)).IsChecked;
row.Index ...
}
I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).
Read my answer there for a fuller explaination, but in short:
They removed it deliberately, because compat mode is not actually really very good for testing compatibility.
If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.
The only way to get compat mode in IE11 is to set the X-UA-Compatible
header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.
After a lot of searching and taking the lord's name in vain i finally got it.I have installed TLS 1.2 on the Server where my wcf service is running.My client was configured correctly but the it was built on .NET 4.5.1 whereas the wcf was on .NET 4.6.1. Both client and server must be at the same .NET Version if you are using TLS 1.2. I hope it helps someone someday:-)
You have to set LANG as well, look for files named 'sp1*.msb', and set for instance export LANG=us if you find a file name sp1us.msb. The error message could sure be better :)
I have come up with two statements that can divide positive and negative numbers into integers and fractions without compromising accuracy (bit overflow) and speed.
x = 100.1323 # A number to be divided into integers and fractions
# The two statement to divided a number into integers and fractions
i = int(x) # A positive or negative integer
f = (x*1e17-i*1e17)/1e17 # A positive or negative fraction
E.g. 100.1323
-> 100
, 0.1323
or -100.1323
-> -100
, -0.1323
Speedtest
The performance test shows that the two statements are faster than math.modf
, as long as they are not put into their own function or method.
test.py
:
#!/usr/bin/env python
import math
import cProfile
""" Get the performance of both statements and math.modf. """
X = -100.1323 # The number to be divided into integers and fractions
LOOPS = range(5*10**6) # Number of loops
def scenario_a():
""" The integers (i) and the fractions (f)
come out as integer and float. """
for _ in LOOPS:
i = int(X) # -100
f = (X*1e17-i*1e17)/1e17 # -0.1323
def scenario_b():
""" The integers (i) and the fractions (f)
come out as float.
NOTE: The only difference between this
and math.modf is the accuracy. """
for _ in LOOPS:
i = int(X) # -100
i, f = float(i), (X*1e17-i*1e17)/1e17 # (-100.0, -0.1323)
def scenario_c():
""" Performance test of the statements in a function. """
def modf(x):
i = int(x)
return i, (x*1e17-i*1e17)/1e17
for _ in LOOPS:
i, f = modf(X) # (-100, -0.1323)
def scenario_d():
for _ in LOOPS:
f, i = math.modf(X) # (-100.0, -0.13230000000000075)
def scenario_e():
""" Convert the integer part to real integer. """
for _ in LOOPS:
f, i = math.modf(X) # (-100.0, -0.13230000000000075)
i = int(i) # -100
if __name__ == '__main__':
cProfile.run('scenario_a()')
cProfile.run('scenario_b()')
cProfile.run('scenario_c()')
cProfile.run('scenario_d()')
cProfile.run('scenario_e()')
Output:
4 function calls in 1.312 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 1.312 1.312 <string>:1(<module>)
1 1.312 1.312 1.312 1.312 test.py:10(scenario_a)
1 0.000 0.000 1.312 1.312 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
4 function calls in 1.887 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 1.887 1.887 <string>:1(<module>)
1 1.887 1.887 1.887 1.887 test.py:18(scenario_b)
1 0.000 0.000 1.887 1.887 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
5000004 function calls in 2.797 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 2.797 2.797 <string>:1(<module>)
1 1.261 1.261 2.797 2.797 test.py:27(scenario_c)
5000000 1.536 0.000 1.536 0.000 test.py:31(modf)
1 0.000 0.000 2.797 2.797 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
5000004 function calls in 1.852 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 1.852 1.852 <string>:1(<module>)
1 1.050 1.050 1.852 1.852 test.py:38(scenario_d)
1 0.000 0.000 1.852 1.852 {built-in method builtins.exec}
5000000 0.802 0.000 0.802 0.000 {built-in method math.modf}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
5000004 function calls in 2.467 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 2.467 2.467 <string>:1(<module>)
1 1.652 1.652 2.467 2.467 test.py:42(scenario_e)
1 0.000 0.000 2.467 2.467 {built-in method builtins.exec}
5000000 0.815 0.000 0.815 0.000 {built-in method math.modf}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
NOTE:
The statement can be faster with modulo, but modulo can not be used to split negative numbers into integer and fraction parts.
i, f = int(x), x*1e17%1e17/1e17 # x can not be negative
ng g component component name
before you type this commend check you will be in your project directive path
i found this code to be useful when timing things:
public class Et {
public Et() {
reset();
}
public void reset() {
t0=System.nanoTime();
}
public long t0() {
return t0;
}
public long dt() {
return System.nanoTime()-t0();
}
public double etms() {
return etms(dt());
}
@Override public String toString() {
return etms()+" ms.";
}
public static double etms(long dt) {
return dt/1000000.; // 1_000_000. breaks cobertura
}
private Long t0;
}
I personally made this python code to change the color of a whole image opened or created with openCV . I am sorry if it's not good enough , I am beginner .
def OpenCvImgColorChanger(img,blue = 0,green = 0,red = 0):
line = 1
ImgColumn = int(img.shape[0])-2
ImgRaw = int(img.shape[1])-2
for j in range(ImgColumn):
for i in range(ImgRaw):
if i == ImgRaw-1:
line +=1
img[line][i][2] = int(red)
img[line][i][1] = int(green)
img[line][i][0] = int(blue)
While I respect the answer from qkrijger explaining how you can work around this issue I think there is a lot more we can learn about what's going on here ...
To actually answer your question of "why" ... I think it would for helpful for you to understand how the docker stop
command works and that all processes should be shutdown cleanly to prevent problems when you try to restart them (file corruption etc).
Problem: What if docker did start SSH from it's command and started RabbitMQ from your Docker file? "The docker stop command attempts to stop a running container first by sending a SIGTERM signal to the root process (PID 1) in the container." Which process is docker tracking as PID 1 that will get the SIGTERM? Will it be SSH or Rabbit?? "According to the Unix process model, the init process -- PID 1 -- inherits all orphaned child processes and must reap them. Most Docker containers do not have an init process that does this correctly, and as a result their containers become filled with zombie processes over time."
Answer: Docker simply takes that last CMD as the one that will get launched as the root process with PID 1 and get the SIGTERM from docker stop
.
Suggested solution: You should use (or create) a base image specifically made for running more than one service, such as phusion/baseimage
It should be important to note that tini exists exactly for this reason, and as of Docker 1.13 and up, tini is officially part of Docker, which tells us that running more than one process in Docker IS VALID .. so even if someone claims to be more skilled regarding Docker, and insists that you absurd for thinking of doing this, know that you are not. There are perfectly valid situations for doing so.
Good to know:
My answer is "neither one".
I believe the most "Pythonic" way to do things is to NOT check beforehand if the key is in a dictionary and instead just write code that assumes it's there and catch any KeyErrors that get raised because it wasn't.
This is usually done with enclosing the code in a try...except
clause and is a well-known idiom usually expressed as "It's easier to ask forgiveness than permission" or with the acronym EAFP, which basically means it is better to try something and catch the errors instead for making sure everything's OK before doing anything. Why validate what doesn't need to be validated when you can handle exceptions gracefully instead of trying to avoid them? Because it's often more readable and the code tends to be faster if the probability is low that the key won't be there (or whatever preconditions there may be).
Of course, this isn't appropriate in all situations and not everyone agrees with the philosophy, so you'll need to decide for yourself on a case-by-case basis. Not surprisingly the opposite of this is called LBYL for "Look Before You Leap".
As a trivial example consider:
if 'name' in dct:
value = dct['name'] * 3
else:
logerror('"%s" not found in dictionary, using default' % name)
value = 42
vs
try:
value = dct['name'] * 3
except KeyError:
logerror('"%s" not found in dictionary, using default' % name)
value = 42
Although in the case it's almost exactly the same amount of code, the second doesn't spend time checking first and is probably slightly faster because of it (try...except block isn't totally free though, so it probably doesn't make that much difference here).
Generally speaking, testing in advance can often be much more involved and the savings gain from not doing it can be significant. That said, if 'name' in dict:
is better for the reasons stated in the other answers.
If you're interested in the topic, this message titled "EAFP vs LBYL (was Re: A little disappointed so far)" from the Python mailing list archive probably explains the difference between the two approached better than I have here. There's also a good discussion about the two approaches in the book Python in a Nutshell, 2nd Ed by Alex Martelli in chapter 6 on Exceptions titled Error-Checking Strategies. (I see there's now a newer 3rd edition, publish in 2017, which covers both Python 2.7 and 3.x).
Several years later, just to add another simple base R solution that isn't present here for some reason- xtabs
xtabs(Frequency ~ Category, df)
# Category
# First Second Third
# 30 5 34
Or if you want a data.frame
back
as.data.frame(xtabs(Frequency ~ Category, df))
# Category Freq
# 1 First 30
# 2 Second 5
# 3 Third 34
As documented in ?legend
you do this like so:
plot(1:10,type = "n")
abline(v=seq(1,10,1), col='grey', lty='dotted')
legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white")
points(1:10,1:10)
Line breaks are achieved with the new line character \n
. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.
Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).
I use a similar method to dasblinkenlight's in a function to return a single key value from a Cookie containing a JSON array loaded into a Dictionary as follows:
/// <summary>
/// Gets a single key Value from a Json filled cookie with 'cookiename','key'
/// </summary>
public static string GetSpecialCookieKeyVal(string _CookieName, string _key)
{
//CALL COOKIE VALUES INTO DICTIONARY
Dictionary<string, string> dictCookie =
JsonConvert.DeserializeObject<Dictionary<string, string>>
(MyCookinator.Get(_CookieName));
string value;
if (dictCookie.TryGetValue( _key, out value))
{
return value;
}
else
{
return "0";
}
}
Where "MyCookinator.Get()" is another simple Cookie function getting an http cookie overall value.
I can stop at the first requirement "A daemon which cannot be stopped ..."
Not possible my friend; however, you can achieve the same with a much better tool, a kernel module.
http://www.infoq.com/articles/inotify-linux-file-system-event-monitoring
All daemons can be stopped. Some are more easily stopped than others. Even a daemon pair with the partner in hold down, respawning the partner if lost, can be stopped. You just have to work a little harder at it.
SELECT DATABASE();
p.s. I didn't want to take the liberty of modifying @cwallenpoole's answer to reflect the fact that this is a MySQL question and not an Oracle question and doesn't need DUAL
.
Note that if you include android:id...
into the <include />
tag, it will override whatever id was defined inside the included layout. For example:
<include
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/some_id_if_needed"
layout="@layout/yourlayout" />
yourlayout.xml:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/some_other_id">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/button1" />
</LinearLayout>
Then you would reference this included layout in code as follows:
View includedLayout = findViewById(R.id.some_id_if_needed);
Button insideTheIncludedLayout = (Button)includedLayout.findViewById(R.id.button1);
I found that I needed to group by the month and year so neither of the above worked for me. Instead I used date_format
SELECT date
FROM blog
GROUP BY DATE_FORMAT(date, "%m-%y")
ORDER BY YEAR(date) DESC, MONTH(date) DESC
First declare your timer
var timer: Timer?
Then add line in viewDidLoad() or in any function you want to start the timer
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(action), userInfo: nil, repeats: false)
This is the func you will callback it to do something it must be @objc
@objc func action () {
print("done")
}
Copy xampp_start.exe
from your XAMPP install directory to C:\Users\YOUR USERNAME\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
.
Replace YOUR USERNAME
with your username.
Use a public static class and access it from anywhere.
public static class MyGlobals {
public const string Prefix = "ID_"; // cannot change
public static int Total = 5; // can change because not const
}
used like so, from master page or anywhere:
string strStuff = MyGlobals.Prefix + "something";
textBox1.Text = "total of " + MyGlobals.Total.ToString();
You don't need to make an instance of the class; in fact you can't because it's static. Just use it directly. All members inside a static class must also be static. The string Prefix isn't marked static because new
const
is implicitly static by nature.
The static class can be anywhere in your project. It doesn't have to be part of Global.asax or any particular page because it's "global" (or at least as close as we can get to that concept in object-oriented terms.)
You can make as many static classes as you like and name them whatever you want.
Sometimes programmers like to group their constants by using nested static classes. For example,
public static class Globals {
public static class DbProcedures {
public const string Sp_Get_Addresses = "dbo.[Get_Addresses]";
public const string Sp_Get_Names = "dbo.[Get_First_Names]";
}
public static class Commands {
public const string Go = "go";
public const string SubmitPage = "submit_now";
}
}
and access them like so:
MyDbCommand proc = new MyDbCommand( Globals.DbProcedures.Sp_Get_Addresses );
proc.Execute();
//or
string strCommand = Globals.Commands.Go;
It may be due to the access of the tomcat installation path(C:\Program Files\Apache Software Foundation\Tomcat 9.0) wasn't available with the current user.
Use runlike from git repository https://github.com/lavie/runlike
To install runlike
pip install runlike
As it accept container id as an argument so to extract container id use following command
docker ps -a -q
You are good to use runlike to extract complete docker run command with following command
runlike <docker container ID>
I think the problem is in your JOIN
condition.
SELECT user.user_fname,
user.user_lname,
parent.user_fname,
parent.user_lname
FROM users AS user
JOIN users AS parent
ON parent.user_id = user.user_parent_id
WHERE user.user_id = $_GET[id]
Edit:
You should probably use LEFT JOIN
if there are users with no parents.
For me, align="center"
was enough to center FOO
vertically:
<v-row align="center">
<v-col>FOO</v-col>
</row>
Here’s some code that works in Firefox, Opera, and Chrome (unlike every other answer posted here). Here is a different demo of code that works in IE11 too. The following example might not work in Safari or Internet Explorer.
/*!
* Dynamically changing favicons with JavaScript
* Works in all A-grade browsers except Safari and Internet Explorer
* Demo: http://mathiasbynens.be/demo/dynamic-favicons
*/
// HTML5™, baby! http://mathiasbynens.be/notes/document-head
document.head = document.head || document.getElementsByTagName('head')[0];
function changeFavicon(src) {
var link = document.createElement('link'),
oldLink = document.getElementById('dynamic-favicon');
link.id = 'dynamic-favicon';
link.rel = 'shortcut icon';
link.href = src;
if (oldLink) {
document.head.removeChild(oldLink);
}
document.head.appendChild(link);
}
You would then use it as follows:
var btn = document.getElementsByTagName('button')[0];
btn.onclick = function() {
changeFavicon('http://www.google.com/favicon.ico');
};
Fork away or view a demo.
best thing to use:
long currenTime = System.currentTimeMillis();
long oneHourLater = currentTime + TimeUnit.HOURS.toMillis(1l);
Similarly, you can add MONTHS, DAYS, MINUTES etc
Is that trying to execute C:\Documents
with arguments of "and", "Settings/flow_model/flow.exe"
?
Also, you might consider subprocess.call()
.
Project -> Clean -> Clean all Projects and then Project -> Build Project worked for me (I did the un-checking generate make-file automatically and then rechecking it before doing this). This was for an AVR (micro-processor programming) project through the AVR CDT plugin in eclipse Juno though.
I believe the problem with "go to" packages is that they would work diferently for each language.
If you use Javascript js-hyperclick and hyperclick (since code-links is deprecated) may do what you need.
Use symbols-view
package which let your search and jump to functions declaration but just of current opened file. Unfortunately, I don't know of any other language's equivalent.
There is also another package which could be useful for go-to in Python: python-tools
As of May 2016, recent version of Atom now support "Go-To" natively. At the GitHub repo for this module you get a list of the following keys:
symbols-view:toggle-file-symbols
to Show all symbols in current filesymbols-view:toggle-project-symbols
to Show all symbols in the projectsymbols-view:go-to-declaration
to Jump to the symbol under the cursor symbols-view:return-from-declaration
to Return from the jumpI now only have one thing missing with Atom for this: mouse click bindings. There's an open issue on Github if anyone want to follow that feature.
PS: This is not an answer but just a supplement to the above answers.
Just for the future reference, I have included a good example that might help us to clear our doubt:
Try the following. In this example I shall create a file selector which can be used to select a file and then I shall try to retrieve the name of the file that I selected: The HTML code is below:
<html>
<body>
<form action="#" method="post">
<input id ="myfile" type="file"/>
</form>
<script type="text/javascript" src="jquery.js"> </script>
<script type="text/javascript" src="code.js"> </script>
</body>
</html>
The code.js file contains the following jQuery code. Try to use both of the jQuery code snippets one by one and see the output.
jQuery code with attr('value'):
$('#myfile').change(function(){
alert($(this).attr('value'));
$('#mybutton').removeAttr('disabled');
});
jQuery code with val():
$('#myfile').change(function(){
alert($(this).val());
$('#mybutton').removeAttr('disabled');
});
Output:
The output of jQuery code with attr('value') will be 'undefined'. The output of jQuery code with val() will the file name that you selected.
Explanation: Now you may understand easily what the top answers wanted to convey. The output of jQuery code with attr('value') will be 'undefined' because initially there was no file selected so the value is undefined. It is better to use val() because it gets the current value.
In order to see why the undefined value is returned try this code in your HTML and you'll see that now the attr.('value') returns 'test' always, because the value is 'test' and previously it was undefined.
<input id ="myfile" type="file" value='test'/>
I hope it was useful to you.
For encoding to base64 in Angular2, you can use btoa() function.
Example:-
console.log(btoa("stringAngular2"));
// Output:- c3RyaW5nQW5ndWxhcjI=
For decoding from base64 in Angular2, you can use atob() function.
Example:-
console.log(atob("c3RyaW5nQW5ndWxhcjI="));
// Output:- stringAngular2
It seems that this problem can occur if you put whitespace in your Realm name. I had name set to Debugging Realm
and I got this error. When I changed to DebuggingRealm
it worked.
You can still have whitespace in the display name. Odd that keycloak doesn't check for this on admin input.
You can use the splice
method on an array to remove the elements.
for example if you have an array with the name arr
use the following:
arr.splice(2, 1);
so here the element with index 2 will be the starting point and the argument 2 will determine how many elements to be deleted.
If you want to delete the last element of the array named arr
then do this:
arr.splice(arr.length-1, 1);
This will return arr with the last element deleted.
Example:
var arr = ["orange", "mango", "banana", "sugar", "tea"];
arr.splice(arr.length-1, 1)
console.log(arr); // return ["orange", "mango", "banana", "sugar"]
I would like to slightly rewrite keytarhero's response:
Sub CopyWorkbook()
Dim sh as Worksheet, wb as workbook
Set wb = workbooks("Target workbook")
For Each sh in workbooks("source workbook").Worksheets
sh.Copy After:=wb.Sheets(wb.sheets.count)
Next sh
End Sub
Edit: You can also build an array of sheet names and copy that at once.
Workbooks("source workbook").Worksheets(Array("sheet1","sheet2")).Copy _
After:=wb.Sheets(wb.sheets.count)
Note: copying a sheet from an XLS? to an XLS will result into an error. The opposite works fine (XLS to XLSX)
I would avoid using component state since this could be difficult to manage and prone to issues that can be difficult to troubleshoot.
You should use either cookies
or localStorage
for persisting a user's session data. You can also use a closure as a wrapper around your cookie
or localStorage
data.
Here is a simple example of a UserProfile
closure that will hold the user's name.
var UserProfile = (function() {
var full_name = "";
var getName = function() {
return full_name; // Or pull this from cookie/localStorage
};
var setName = function(name) {
full_name = name;
// Also set this in cookie/localStorage
};
return {
getName: getName,
setName: setName
}
})();
export default UserProfile;
When a user logs in, you can populate this object with user name, email address etc.
import UserProfile from './UserProfile';
UserProfile.setName("Some Guy");
Then you can get this data from any component in your app when needed.
import UserProfile from './UserProfile';
UserProfile.getName();
Using a closure will keep data outside of the global namespace, and make it is easily accessible from anywhere in your app.
If you're getting this error in the build somewhere else, while your IDE says everything is perfectly fine, then check that you are using the same Java versions in both places.
For example, Java 7 and Java 8 have different APIs, so calling a non-existent API in an older Java version would cause this error.
Update PHP 7.4
Curly brace access syntax is deprecated since PHP 7.4
Update 2019
Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.
Simply iterate its using {}
Example:
$videos{0}->id
This way your object is not destroyed and you can easily iterate through object.
For PHP 5.6 and below use this
$videos{0}['id']
Both array() and the stdClass objects can be accessed using the
current()
key()
next()
prev()
reset()
end()
functions.
So, if your object looks like
object(stdClass)#19 (3) {
[0]=>
object(stdClass)#20 (22) {
["id"]=>
string(1) "123"
etc...
Then you can just do;
$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object
If you need the key for some reason, you can do;
reset($obj); //Ensure that we're at the first element
$key = key($obj);
Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4
2022 Update:
After PHP 7.4, using current()
, end()
, etc functions on objects is deprecated.
In newer versions of PHP, use the ArrayIterator class:
$objIterator = new ArrayIterator($obj);
$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object
$key = $objIterator->key(); // and gets the key
It's only supposed to send the information to the server. The reason that it must preceed the file field is that it has to come before the file payload in the request for the server to be able to use it to check the size of the upload.
How the value is used on the server depends on what you use to take care of the upload. The code is supposedly intended for a specific upload component that specifically looks for that value.
It seems that the built in upload support in PHP is one to use this field value.
Consider a restaurant. The creation of "today's meal" is a factory pattern, because you tell the kitchen "get me today's meal" and the kitchen (factory) decides what object to generate, based on hidden criteria.
The builder appears if you order a custom pizza. In this case, the waiter tells the chef (builder) "I need a pizza; add cheese, onions and bacon to it!" Thus, the builder exposes the attributes the generated object should have, but hides how to set them.
If you are using Java 8, a shorter version for Jersey2 than the answer provided by Aleksandr.
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL");
// Create a new X509TrustManager
sslContext.init(null, getTrustManager(), null);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw e;
}
final Client client = ClientBuilder.newBuilder().hostnameVerifier((s, session) -> true)
.sslContext(sslContext).build();
return client;
private TrustManager[] getTrustManager() {
return new TrustManager[] {
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
}
};
}
My problem occurs when I try to open https. I don't use SSL.
It's Tomcat bug.
Today 12/02/2017 newest official version from Debian repositories is Tomcat 8.0.14
Solution is to download from official site and install newest package of Tomcat 8, 8.5, 9 or upgrade to newest version(8.5.x) from jessie-backports
Add to /etc/apt/sources.list
deb http://ftp.debian.org/debian jessie-backports main
Then update and install Tomcat from jessie-backports
sudo apt-get update && sudo apt-get -t jessie-backports install tomcat8
public byte[] loadBinaryFile (String name) {
try {
DataInputStream dis = new DataInputStream(new FileInputStream(name));
byte[] theBytes = new byte[dis.available()];
dis.read(theBytes, 0, dis.available());
dis.close();
return theBytes;
} catch (IOException ex) {
}
return null;
} // ()
The feedback you get on the interactive interpreter uses repr
too. When you type in an expression (let it be expr
), the interpreter basically does result = expr; if result is not None: print repr(result)
. So the second line in your example is formatting the string foo
into the representation you want ('foo'
). And then the interpreter creates the repr
esentation of that, leaving you with double quotes.
Why when I combine %r with double-quote and single quote escapes and print them out, it prints it the way I'd write it in my .py file but not the way I'd like to see it?
I'm not sure what you're asking here. The text single ' and double " quotes
, when run through repr
, includes escapes for one kind of quote. Of course it does, otherwise it wouldn't be a valid string literal by Python rules. That's precisely what you asked for by calling repr
.
Also note that the eval(repr(x)) == x
analogy isn't meant literal. It's an approximation and holds true for most (all?) built-in types, but the main thing is that you get a fairly good idea of the type and logical "value" from looking the the repr
output.
You do not need jQuery just to do this! All you need is a tiny and very light vanilla Javascript and a css class (as in all the answers above) :
First define a CSS class in your stylesheet called current.
Second add the following pure JavaScript either in your existing JavaScript file or in a separate js script file (but add script tage link to it in the head of the pages) or event just add it in a script tag just before the closing body tag, it will still work in all these cases.
function highlightCurrent() {
const curPage = document.URL;
const links = document.getElementsByTagName('a');
for (let link of links) {
if (link.href == curPage) {
link.classList.add("current");
}
}
}
document.onreadystatechange = () => {
if (document.readyState === 'complete') {
highlightCurrent()
}
};
The 'href' attribute of current link should be the absolute path as given by document.URL (console.log it to make sure it is the same)
It is possible to print a 15 decimal number in C++ using the following:
#include <iomanip>
#include <iostream>
cout << fixed << setprecision(15) << " The Real_Pi is: " << real_pi << endl;
cout << fixed << setprecision(15) << " My Result_Pi is: " << my_pi << endl;
cout << fixed << setprecision(15) << " Processing error is: " << Error_of_Computing << endl;
cout << fixed << setprecision(15) << " Processing time is: " << End_Time-Start_Time << endl;
_getch();
return 0;
I also come across same problem, I changed transaction timeout to 15 minutes and it works. I hope this helps.
TransactionOptions options = new TransactionOptions();
options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
options.Timeout = new TimeSpan(0, 15, 0);
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required,options))
{
sp1();
sp2();
...
}
This will only work to column Z, but you can drag this horizontally and vertically.
=INDIRECT("'"&$D$2&"'!"&CHAR((COLUMN()+64))&ROW())
Your comparison function is not even wrong.
Its arguments should be the type stored in the range, i.e. std::pair<K,V>
, not const void*
.
It should return bool
not a positive or negative value. Both (bool)1
and (bool)-1
are true
so your function says every object is ordered before every other object, which is clearly impossible.
You need to model the less-than operator, not strcmp
or memcmp
style comparisons.
See StrictWeakOrdering which describes the properties the function must meet.
See String.format
method.
String s = "hello %s!";
s = String.format(s, "world");
assertEquals(s, "hello world!"); // should be true
As @Peter Cullen answer mention, your script will meet browser timeout first. So its good idea to provide some log output, then flush()
, but connection have buffer and you'll not see anything unless much output provided. Here are code snippet what helps provide reliable log:
set_time_limit(0);
...
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();
you need to decode the bytes
of you want a string:
b = b'1234'
print(b.decode('utf-8')) # '1234'
I think a solution is to put count in back ticks
.filter("`count` >= 2")
Make sure you import csv file using Pandas
import pandas as pd
condition = pd.isnull(data[i][j])
namespace std
{
// define std::byte
enum class byte : unsigned char {};
};
This if your C++ version does not have std::byte will define a byte type in namespace std. Normally you don't want to add things to std, but in this case it is a standard thing that is missing.
std::byte from the STL does much more operations.
We can use numpy.insert
. This has the advantage of flexibility. You only need to specify the index you want to insert to.
s1 = pd.Series([5, 6, 7])
s2 = pd.Series([7, 8, 9])
df = pd.DataFrame([list(s1), list(s2)], columns = ["A", "B", "C"])
pd.DataFrame(np.insert(df.values, 0, values=[2, 3, 4], axis=0))
0 1 2
0 2 3 4
1 5 6 7
2 7 8 9
For np.insert(df.values, 0, values=[2, 3, 4], axis=0)
, 0 tells the function the place/index you want to place the new values.
Ubuntu comes with a version of PIP from precambrian and that's how you have to upgrade it if you do not want to spend hours and hours debugging pip related issues.
apt-get remove python-pip python3-pip
wget https://bootstrap.pypa.io/get-pip.py
python get-pip.py
python3 get-pip.py
As you observed I included information for both Python 2.x and 3.x
Convert the image to a byte[]
and store that in the database.
Add this column to your model:
public byte[] Content { get; set; }
Then convert your image to a byte array and store that like you would any other data:
public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using(var ms = new MemoryStream())
{
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
}
public Image ByteArrayToImage(byte[] byteArrayIn)
{
using(var ms = new MemoryStream(byteArrayIn))
{
var returnImage = Image.FromStream(ms);
return returnImage;
}
}
Source: Fastest way to convert Image to Byte array
var image = new ImageEntity()
{
Content = ImageToByteArray(image)
};
_context.Images.Add(image);
_context.SaveChanges();
When you want to get the image back, get the byte array from the database and use the ByteArrayToImage
and do what you wish with the Image
This stops working when the byte[]
gets to big. It will work for files under 100Mb
log4j2 has a very flexible configuration system (which IMHO is more a distraction than a help), you can even use JSON. See https://logging.apache.org/log4j/2.x/manual/configuration.html for a reference.
Personally, I just recently started using log4j2, but I'm tending toward the "strict XML" configuration (that is, using attributes instead of element names), which can be schema-validated.
Here is my simple example using autoconfiguration and strict mode, using a "Property" for setting the filename:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorinterval="30" status="info" strict="true">
<Properties>
<Property name="filename">log/CelsiusConverter.log</Property>
</Properties>
<Appenders>
<Appender type="Console" name="Console">
<Layout type="PatternLayout" pattern="%d %p [%t] %m%n" />
</Appender>
<Appender type="Console" name="FLOW">
<Layout type="PatternLayout" pattern="%C{1}.%M %m %ex%n" />
</Appender>
<Appender type="File" name="File" fileName="${filename}">
<Layout type="PatternLayout" pattern="%d %p %C{1.} [%t] %m%n" />
</Appender>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="File" />
<AppenderRef ref="Console" />
<!-- Use FLOW to trace down exact method sending the msg -->
<!-- <AppenderRef ref="FLOW" /> -->
</Root>
</Loggers>
</Configuration>
Simply just add auto_increment Constraint In column or MODIFY COLUMN :-
ALTER TABLE `emp` MODIFY COLUMN `id` INT NOT NULL UNIQUE AUTO_INCREMENT FIRST;
Or add a column first then change column as -
1. Alter TABLE `emp` ADD COLUMN `id`;
2. ALTER TABLE `emp` CHANGE COLUMN `id` `Emp_id` INT NOT NULL UNIQUE AUTO_INCREMENT FIRST;
Try to use:
location.reload(true);
When this method receives a true
value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.
More info:
Here is pure Bootstrap 4 with CSS 3 solution.
<div class="modal fade2" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
.fade2 {
transform: scale(0.9);
opacity: 0;
transition: all .2s linear;
display: block !important;
}
.fade2.show {
opacity: 1;
transform: scale(1);
}
$('#exampleModal').modal();
function afterModalTransition(e) {
e.setAttribute("style", "display: none !important;");
}
$('#exampleModal').on('hide.bs.modal', function (e) {
setTimeout( () => afterModalTransition(this), 200);
})
Full example here.
Maybe it will help someone.
--
Thank you @DavidDomain too.
Another avenue that hasn't been considered is that your postgres was installed by pgvm
(Postgres Version Manager).
Uninstall with pgvm uninstall 9.0.3
We do get similar error when we sometimes run our express app. We have to follow the same in that case. We need to check if its running in any terminal. If you want to find and kill process, follow these steps:
OR
Use a single command to close all the running node processes.
ps aux | awk '/node/{print $2}' | xargs kill -9
Things have changed quite a bit since 2010 when this was posted and I haven't tried all the other answers but I have tried a few, and I found this to work the best for me using python3.6.
I was able to fetch about ~150 unique domains per second running on AWS.
import pandas as pd
import concurrent.futures
import requests
import time
out = []
CONNECTIONS = 100
TIMEOUT = 5
tlds = open('../data/sample_1k.txt').read().splitlines()
urls = ['http://{}'.format(x) for x in tlds[1:]]
def load_url(url, timeout):
ans = requests.head(url, timeout=timeout)
return ans.status_code
with concurrent.futures.ThreadPoolExecutor(max_workers=CONNECTIONS) as executor:
future_to_url = (executor.submit(load_url, url, TIMEOUT) for url in urls)
time1 = time.time()
for future in concurrent.futures.as_completed(future_to_url):
try:
data = future.result()
except Exception as exc:
data = str(type(exc))
finally:
out.append(data)
print(str(len(out)),end="\r")
time2 = time.time()
print(f'Took {time2-time1:.2f} s')
print(pd.Series(out).value_counts())
tl;dr: (try it here)
If you have the following HTML:
<div id="menu" style="display: none;">
<!-- menu stuff in here -->
<ul><li>Menu item</li></ul>
</div>
<div class="parent">Hover over me to show the menu here</div>
then you can use the following JavaScript code:
$(".parent").mouseover(function() {
// .position() uses position relative to the offset parent,
var pos = $(this).position();
// .outerWidth() takes into account border and padding.
var width = $(this).outerWidth();
//show the menu directly over the placeholder
$("#menu").css({
position: "absolute",
top: pos.top + "px",
left: (pos.left + width) + "px"
}).show();
});
But it doesn't work!
This will work as long as the menu and the placeholder have the same offset parent. If they don't, and you don't have nested CSS rules that care where in the DOM the #menu
element is, use:
$(this).append($("#menu"));
just before the line that positions the #menu
element.
But it still doesn't work!
You might have some weird layout that doesn't work with this approach. In that case, just use jQuery.ui's position plugin (as mentioned in an answer below), which handles every conceivable eventuality. Note that you'll have to show()
the menu element before calling position({...})
; the plugin can't position hidden elements.
Update notes 3 years later in 2012:
(The original solution is archived here for posterity)
So, it turns out that the original method I had here was far from ideal. In particular, it would fail if:
Luckily, jQuery introduced methods (position()
and outerWidth()
) way back in 1.2.6 that make finding the right values in the latter case here a lot easier. For the former case, append
ing the menu element to the placeholder works (but will break CSS rules based on nesting).
If you check a cluster using NIS, the only way to see if a user has a crontab entry ist according to Matt's answer /var/spool/cron/tabs.
grep -v "#" -R /var/spool/cron/tabs
Base 64 for html:
file="DSC_0251.JPG"
type=$(identify -format "%m" "$file" | tr '[A-Z]' '[a-z]')
echo "data:image/$type;base64,$(base64 -w 0 "$file")"
As a one-liner:
var result = Regex.Replace(input, @"[^\x00-\x7F]", c =>
string.Format(@"\u{0:x4}", (int)c.Value[0]));
Use this one line query, replace desired_column_name by your column name.
SELECT TABLE_NAME FROM information_schema.columns WHERE column_name = 'desired_column_name';
The following illustrates the syntax of the STR_TO_DATE()
function:
STR_TO_DATE(str,fmt);
The STR_TO_DATE()
converts the str string into a date value based on the fmt format string. The STR_TO_DATE()
function may return a DATE , TIME, or DATETIME value based on the input and format strings. If the input string is illegal, the STR_TO_DATE()
function returns NULL.
The following statement converts a string into a DATE value.
SELECT STR_TO_DATE('21,5,2013','%d,%m,%Y');
Based on the format string ‘%d, %m, %Y’, the STR_TO_DATE()
function scans the ‘21,5,2013’ input string.
STR_TO_DATE()
function keeps finding a match for the third format specifier %Y ,
which is four-digit year e.g., 2012,2013, etc., and it takes the
number 2013 as the year value.The STR_TO_DATE()
function ignores extra characters at the end of the input string when it parses the input string based on the format string. See the following example:
SELECT STR_TO_DATE('21,5,2013 extra characters','%d,%m,%Y');
More Details : Reference
The return type of Html.RenderAction
is void
that means it directly renders the responses in View where the return type of Html.Action
is MvcHtmlString
You can catch its render view in controller and modify it by using following method
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
This will return the Html string of the View.
This is also applicable to Html.Partial
and Html.RenderPartial
It's also possible to use jQuery's .load()
$('#submitform').click(function() {
$('#showresults').load('getinfo.asp #showresults', {
txtsearch: $('#appendedInputButton').val()
}, function() {
// alert('Load was performed.')
// $('#showresults').slideDown('slow')
});
});
unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.
We could modify the example above to use only part of the document that is fetched:
$( "#result" ).load( "ajax/test.html #container" );
When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.
I'm using this:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myUrl);
System.Diagnostics.Stopwatch timer = new Stopwatch();
timer.Start();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
statusCode = response.StatusCode.ToString();
response.Close();
timer.Stop();
Change modifier from public to internal. .Net deliberately uses private modifier instead of the public, due to preventing any illegal access to your methods/properties/controls out of your project. In fact, public modifier can accessible wherever, so They are really dangerous. Any body out of your project can access to your methods/properties. But In internal modifier no body (other of your current project) can access to your methods/properties.
Suppose you are creating a project, which has some secret fields. So If these fields being accessible out of your project, it can be dangerous, and against to your initial ideas. As one good recommendation, I can say always use internal modifier instead of public modifier.
But some strange!
I must tell also in VB.Net while our methods/properties are still private, it can be accessible from other forms/class by calling form as a variable with no any problem else.
I don't know why in this programming language behavior is different from C#. As we know both are using same Platform and they claim they are almost same Back end Platform, but as you see, they still behave differently.
But I've solved this problem with two approaches. Either; by using Interface (Which is not a recommend, as you know, Interfaces usually need public modifier, and using a public modifier is not recommend (As I told you above)),
Or
Declare your whole Form in somewhere static class and static variable and there is still internal modifier. Then when you suppose to use that form for showing to users, so pass new Form()
construction to that static class/variable. Now It can be Accessible every where as you wish. But you still need some thing more.
You declare your element internal modifier too in Designer File of Form. While your Form is open, it can be accessible everywhere. It can work for you very well.
Consider This Example.
Suppose you want to access to a Form's TextBox.
So the first job is declaration of a static variable in a static class (The reason of static is ease of access without any using new keywork at future).
Second go to designer class of that Form which supposes to be accessed by other Forms. Change its TextBox modifier declaration from private to internal. Don't worry; .Net never change it again to private modifier after your changing.
Third when you want to call that form to open, so pass the new Form Construction to that static variable-->>static class.
Fourth; from any other Forms (wherever in your project) you can access to that form/control while From is open.
Look at code below (We have three object.
1- a static class (in our example we name it A
)
2 - Any Form else which wants to open the final Form (has TextBox, in our example FormB
).
3 - The real Form which we need to be opened, and we suppose to access to its internal TextBox1
(in our example FormC
).
Look at codes below:
internal static class A
{
internal static FormC FrmC;
}
FormB ...
{
'(...)
A.FrmC = new FormC();
'(...)
}
FormC (Designer File) . . .
{
internal System.Windows.Forms.TextBox TextBox1;
}
You can access to that static Variable (here FormC
) and its internal control (here Textbox1
) wherever and whenever as you wish, while FormC
is open.
Any Comment/idea let me know. I glad to hear from you or any body else about this topic more. Honestly I have had some problems regard to this mentioned problem in past. The best way was the second solution that I hope it can work for you. Let me know any new idea/suggestion.
You will have to provide a link to your file that is accessible through the browser, that is for instance:
<a href="http://my.domain.com/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">
versus
<a href="C:/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">
If you expose your "Projecten" folder directly to the public, then you may only have to provide the link as such:
<a href="/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">
But beware, that your files can then be indexed by search engines, can be accessed by anybody having this link, etc.
An oblique answer to the question is to write all the code as classes, apart from the index.php files, which are then the only points of entry. PHP files that contain classes will not cause anything to happen, even if they are invoked directly through Apache.
A direct answer is to include the following in .htaccess:
<FilesMatch "\.php$">
Order Allow,Deny
Deny from all
</FilesMatch>
<FilesMatch "index[0-9]?\.php$">
Order Allow,Deny
Allow from all
</FilesMatch>
This will allow any file like index.php, index2.php etc to be accessed, but will refuse access of any kind to other .php files. It will not affect other file types.
For your interest, to do the same with double
double doubleVal = 1.745;
double doubleVal2 = 0.745;
doubleVal = Math.round(doubleVal * 100 + 0.005) / 100.0;
doubleVal2 = Math.round(doubleVal2 * 100 + 0.005) / 100.0;
System.out.println("bdTest: " + doubleVal); //1.75
System.out.println("bdTest1: " + doubleVal2);//0.75
or just
double doubleVal = 1.745;
double doubleVal2 = 0.745;
System.out.printf("bdTest: %.2f%n", doubleVal);
System.out.printf("bdTest1: %.2f%n", doubleVal2);
both print
bdTest: 1.75
bdTest1: 0.75
I prefer to keep code as simple as possible. ;)
As @mshutov notes, you need to add a little more to ensure that a half value always rounds up. This is because numbers like 265.335
are a little less than they appear.
no problem doing it with asp.... it's most natural to do so with MVC, but can be done with standard asp as well.
The MVC framework has all sorts of helper classes for JSON, if you can, I'd suggest sussing in some MVC-love, if not, you can probably easily just get the JSON helper classes used by MVC in and use them in the context of asp.net.
edit:
here's an example of how to return JSON data with MVC. This would be in your controller class. This is out of the box functionality with MVC--when you crate a new MVC project this stuff gets auto-created so it's nothing special. The only thing that I"m doing is returning an actionResult that is JSON. The JSON method I'm calling is a method on the Controller class. This is all very basic, default MVC stuff:
public ActionResult GetData()
{
var data = new { Name="kevin", Age=40 };
return Json(data, JsonRequestBehavior.AllowGet);
}
This return data could be called via JQuery as an ajax call thusly:
$.get("/Reader/GetData/", function(data) { someJavacriptMethodOnData(data); });
I'd suggest using a pseudo element in place of the overlay element. Because pseudo elements can't be added on enclosed img
elements, you would still need to wrap the img
element though.
LIVE EXAMPLE HERE -- EXAMPLE WITH TEXT
<div class="image">
<img src="http://i.stack.imgur.com/Sjsbh.jpg" alt="" />
</div>
As for the CSS, set optional dimensions on the .image
element, and relatively position it. If you are aiming for a responsive image, just omit the dimensions and this will still work (example). It's just worth noting that the dimensions must be on the parent element as opposed to the img
element itself, see.
.image {
position: relative;
width: 400px;
height: 400px;
}
Give the child img
element a width of 100%
of the parent and add vertical-align:top
to fix the default baseline alignment issues.
.image img {
width: 100%;
vertical-align: top;
}
As for the pseudo element, set a content value and absolutely position it relative to the .image
element. A width/height of 100%
will ensure that this works with varying img
dimensions. If you want to transition the element, set an opacity of 0
and add the transition properties/values.
.image:after {
content: '\A';
position: absolute;
width: 100%; height:100%;
top:0; left:0;
background:rgba(0,0,0,0.6);
opacity: 0;
transition: all 1s;
-webkit-transition: all 1s;
}
Use an opacity of 1
when hovering over the pseudo element in order to facilitate the transition:
.image:hover:after {
opacity: 1;
}
For the simplest approach, just add the text as the pseudo element's content
value:
.image:after {
content: 'Here is some text..';
color: #fff;
/* Other styling.. */
}
That should work in most instances; however, if you have more than one img
element, you might not want the same text to appear on hover. You could therefore set the text in a data-*
attribute and therefore have unique text for every img
element.
.image:after {
content: attr(data-content);
color: #fff;
}
With a content
value of attr(data-content)
, the pseudo element adds the text from the .image
element's data-content
attribute:
<div data-content="Text added on hover" class="image">
<img src="http://i.stack.imgur.com/Sjsbh.jpg" alt="" />
</div>
You can add some styling and do something like this:
In the above example, the :after
pseudo element serves as the black overlay, while the :before
pseudo element is the caption/text. Since the elements are independent of each other, you can use separate styling for more optimal positioning.
.image:after, .image:before {
position: absolute;
opacity: 0;
transition: all 0.5s;
-webkit-transition: all 0.5s;
}
.image:after {
content: '\A';
width: 100%; height:100%;
top: 0; left:0;
background:rgba(0,0,0,0.6);
}
.image:before {
content: attr(data-content);
width: 100%;
color: #fff;
z-index: 1;
bottom: 0;
padding: 4px 10px;
text-align: center;
background: #f00;
box-sizing: border-box;
-moz-box-sizing:border-box;
}
.image:hover:after, .image:hover:before {
opacity: 1;
}
At first see this question to see how you can find if a link has a jQuery handler assigned to it.
Next use:
$("a").attr("onclick")
to see if there is a javascript event assigned to it.
If any of the above is true, then call the click method. If not, get the link:
$("a").attr("href")
and follow it.
I am afraid I don't know what to do if addEventListener is used to add an event handler. If you are in charge of the full page source, use only jQuery event handlers.
If you download Java Development Kit(JDK) then there is a difference as it contains native libraries which differ for different architectures:
In addition you can use 32-bit JDK(x86) on 64-bit OS. But you can not use 64-bit JDK on 32-bit OS.
At the same time you can run compiled Java classes on any JVM. It does not matter whether it 32 or 64-bit.
In x0n's example, it should be:
SET ROWCOUNT @top
SELECT * from sometable
SET ROWCOUNT 0
Well, the basic premise here is: no, it is not secure yet.
Basically, you can't run crypto in JavaScript: JavaScript Crypto Considered Harmful.
The problem is that you can't reliably get the crypto code into the browser, and even if you could, JS isn't designed to let you run it securely. So until browsers have a cryptographic container (which Encrypted Media Extensions provide, but are being rallied against for their DRM purposes), it will not be possible to do securely.
As far as a "Better way", there isn't one right now. Your only alternative is to store the data in plain text, and hope for the best. Or don't store the information at all. Either way.
Either that, or if you need that sort of security, and you need local storage, create a custom application...
For python you could use openpyxl for all 2010 and newer file formats (xlsx).
Al Sweigart has a full tutorial from automate the boring parts on working with excel spreadsheets its very indepth and the whole book and accompanying Udemy course are great resources.
From his example
>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> wb.get_sheet_names()
['Sheet1', 'Sheet2', 'Sheet3']
>>> sheet = wb.get_sheet_by_name('Sheet3')
>>> sheet
<Worksheet "Sheet3">
Understandably once you have this access you can now use psycopg to parse the data to postgres as you normally would do.
This is a link to a list of python resources at python-excel also xlwings provides a large array of features for using python in place of vba in excel.
If the src is already set then the event is firing in the cached case before you even get the event handler bound. So, you should trigger the event based off .complete
also.
code sample:
$("img").one("load", function() {
//do stuff
}).each(function() {
if(this.complete || /*for IE 10-*/ $(this).height() > 0)
$(this).load();
});
In C# it also works with a null as the 4th parameter.
@Html.ActionLink( "Front Page", "Index", "Home", null, new { @class = "MenuButtons" })
ssize_t
is not included in the standard and isn't portable. size_t
should be used when handling the size of objects (there's ptrdiff_t
too, for pointer differences).
You can also create a public property.
// Using and namespace...
public partial class FormOptions : Form
{
private string _MyString; // Use this
public string MyString { // in
get { return _MyString; } // .NET
} // 2.0
public string MyString { get; } // In .NET 3.0 or newer
// The rest of the form code
}
Then you can get it with:
FormOptions formOptions = new FormOptions();
formOptions.ShowDialog();
string myString = formOptions.MyString;
This might be a bit overkill, but I always use the the np.take
function for any wrap-around indexing:
>>> a = np.array([1, 2, 3])
>>> np.take(a, range(0, len(a)+1), mode='wrap')
array([1, 2, 3, 1])
>>> np.take(a, range(-1, len(a)+1), mode='wrap')
array([3, 1, 2, 3, 1])
Use /fonts/ or /font/ before font type name in your CSS stylesheet. I face this error but after that its working fine.
@font-face {
font-family: 'robotoregular';
src: url('../fonts/Roboto-Regular-webfont.eot');
src: url('../fonts/Roboto-Regular-webfont.eot?#iefix') format('embedded-opentype'),
url('../fonts/Roboto-Regular-webfont.woff') format('woff'),
url('../fonts/Roboto-Regular-webfont.ttf') format('truetype'),
url('../fonts/Roboto-Regular-webfont.svg#robotoregular') format('svg');
font-weight: normal;
font-style: normal;
}
.modal.in .modal-dialog {
width:100% !important;
min-height: 100%;
margin: 0 0 0 0 !important;
bottom: 0px !important;
top: 0px;
}
.modal-content {
border:0px solid rgba(0,0,0,.2) !important;
border-radius: 0px !important;
-webkit-box-shadow: 0 0px 0px rgba(0,0,0,.5) !important;
box-shadow: 0 3px 9px rgba(0,0,0,.5) !important;
height: auto;
min-height: 100%;
}
.modal-dialog {
position: fixed !important;
margin:0px !important;
}
.bootstrap-dialog .modal-header {
border-top-left-radius: 0px !important;
border-top-right-radius: 0px !important;
}
@media (min-width: 768px)
.modal-dialog {
width: 100% !important;
margin: 0 !important;
}
I found an easy way to render this out... simply declare a dynamic object and assign the first item within the dynamic object to be your collection class...This example assumes you're using Newtonsoft.Json
private class YourModelClass
{
public string firstName { get; set; }
public string lastName { get; set; }
}
var collection = new List<YourModelClass>();
var collectionWrapper = new {
myRoot = collection
};
var output = JsonConvert.SerializeObject(collectionWrapper);
What you should end up with is something like this:
{"myRoot":[{"firstName":"John", "lastName": "Citizen"}, {...}]}
Wrote this for one of my sites and probably is the most foolproof solution. Especially since even Modernizr can get false positives on touch detection.
If you're using jQuery
$(window).one({
mouseover : function(){
Modernizr.touch = false; // Add this line if you have Modernizr
$('html').removeClass('touch').addClass('mouse');
}
});
or just pure JS...
window.onmouseover = function(){
window.onmouseover = null;
document.getElementsByTagName("html")[0].className += " mouse";
}
if you want to hold the arguments from Terminal, try the following code:
A = ARGV[0].to_i
B = ARGV[1].to_i
puts "#{A} + #{B} = #{A + B}"
Perhaps there is a shorter way but this works for me.
<script language='JavaScript' type='text/javascript'>
function validateThisFrom(thisForm) {
if (thisForm.FIELDNAME.value == "") {
alert("Please make a selection");
thisForm.FIELDNAME.focus();
return false;
}
if (thisForm.FIELDNAME2.value == "") {
alert("Please make a selection");
thisForm.FIELDNAME2.focus();
return false;
}
}
</script>
<form onSubmit="return validateThisFrom (this);">
<select name="FIELDNAME" class="form-control">
<option value="">- select -</option>
<option value="value 1">Visible info of Value 1</option>
<option value="value 2">Visible info of Value 2</option>
</select>
<select name="FIELDNAME2" class="form-control">
<option value="">- select -</option>
<option value="value 1">Visible info of Value 1</option>
<option value="value 2">Visible info of Value 2</option>
</select>
</form>
Java reverse an int value - Principles
Modding (%) the input int by 10 will extract off the rightmost digit. example: (1234 % 10) = 4
Multiplying an integer by 10 will "push it left" exposing a zero to the right of that number, example: (5 * 10) = 50
Dividing an integer by 10 will remove the rightmost digit. (75 / 10) = 7
Java reverse an int value - Pseudocode:
a. Extract off the rightmost digit of your input number. (1234 % 10) = 4
b. Take that digit (4) and add it into a new reversedNum.
c. Multiply reversedNum by 10 (4 * 10) = 40, this exposes a zero to the right of your (4).
d. Divide the input by 10, (removing the rightmost digit). (1234 / 10) = 123
e. Repeat at step a with 123
Java reverse an int value - Working code
public int reverseInt(int input) {
long reversedNum = 0;
long input_long = input;
while (input_long != 0) {
reversedNum = reversedNum * 10 + input_long % 10;
input_long = input_long / 10;
}
if (reversedNum > Integer.MAX_VALUE || reversedNum < Integer.MIN_VALUE) {
throw new IllegalArgumentException();
}
return (int) reversedNum;
}
You will never do anything like this in the real work-world. However, the process by which you use to solve it without help is what separates people who can solve problems from the ones who want to, but can't unless they are spoon fed by nice people on the blogoblags.
Well /etc/crontab
just an ascii file so the simplest is to just
echo "*/15 * * * * root date" >> /etc/crontab
which will add a job which will email you every 15 mins. Adjust to taste, and test via grep
or other means whether the line was already added to make your script idempotent.
On Ubuntu et al, you can also drop files in /etc/cron.*
which is easier to do and test for---plus you don't mess with (system) config files such as /etc/crontab
.