>>> import datetime, time
>>> time = time.strftime("%H:%M:%S:%MS", time.localtime())
>>> print time
'00:21:38:20S'
If you just want the bug fix to be integrated into the branch, git cherry-pick
the relevant commit(s).
If the strings are the same length, then I would go for '%x' % ()
of the built-in xor (^
).
Examples -
>>>a = '290b6e3a'
>>>b = 'd6f491c5'
>>>'%x' % (int(a,16)^int(b,16))
'ffffffff'
>>>c = 'abcd'
>>>d = '12ef'
>>>'%x' % (int(a,16)^int(b,16))
'b922'
If the strings are not the same length, truncate the longer string to the length of the shorter using a slice longer = longer[:len(shorter)]
ax.title.set_text('My Plot Title')
seems to work too.
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
ax1.title.set_text('First Plot')
ax2.title.set_text('Second Plot')
ax3.title.set_text('Third Plot')
ax4.title.set_text('Fourth Plot')
plt.show()
awk
awk '{gsub(/two.*/,"")}1' file
Ruby
ruby -ne 'print $_.gsub(/two.*/,"")' file
Except the permissions, the problem can be open_basedir. If you are using it (and I suggest to use it) then check the settings at the VirtualHost :
php_admin_value open_basedir <YOUR ROOT>
Perhaps this will help:
List of XML and HTML character entity references:
In SGML, HTML and XML documents, the logical constructs known as character data and attribute values consist of sequences of characters, in which each character can manifest directly (representing itself), or can be represented by a series of characters called a character reference, of which there are two types: a numeric character reference and a character entity reference. This article lists the character entity references that are valid in HTML and XML documents.
That article lists the following five predefined XML entities:
quot "
amp &
apos '
lt <
gt >
In case you need the answer to be a member of the input numpy array:
Just to add that the percentile function in numpy by default calculates the output as a linear weighted average of the two neighboring entries in the input vector. In some cases people may want the returned percentile to be an actual element of the vector, in this case, from v1.9.0 onwards you can use the "interpolation" option, with either "lower", "higher" or "nearest".
import numpy as np
x=np.random.uniform(10,size=(1000))-5.0
np.percentile(x,70) # 70th percentile
2.075966046220879
np.percentile(x,70,interpolation="nearest")
2.0729677997904314
The latter is an actual entry in the vector, while the former is a linear interpolation of two vector entries that border the percentile
I use ToString() then split and parse the spit array in flags.
[Flags]
public enum ABC {
a = 1,
b = 2,
c = 4
};
public IEnumerable<ABC> Getselected (ABC flags)
{
var values = flags.ToString().Split(',');
var enums = values.Select(x => (ABC)Enum.Parse(typeof(ABC), x.Trim()));
return enums;
}
ABC temp= ABC.a | ABC.b;
var list = getSelected (temp);
foreach (var item in list)
{
Console.WriteLine(item.ToString() + " ID=" + (int)item);
}
In a .txt
file opened with Notepad++,
press Ctrl-F
go in the tab "Replace"
write the regex pattern \|.+
in the space Find what
and let the space Replace with blank
Then tick the choice matches newlines after the choice Regular expression
and press two times on the Replace button
Try something like this inside ThisOutlookSession
:
Private Sub Application_NewMail()
Call Your_main_macro
End Sub
My outlook vba just fired when I received an email and had that application event open.
Edit: I just tested a hello world msg box and it ran after being called in the application_newmail
event when an email was received.
There are 3 methods that I use to debug when developing React Native apps:
console.log()
: shows in consoleconsole.warn()
: shows in yellow box bottom of applicationalert()
: shows as a prompt just like it does in webAt date git prompts:
use "git rm --cached <file>..." to unstage
if files were not in the repo. It unstages the files keeping them there.use "git reset HEAD <file>..." to unstage
if the files were in the repo, and you are adding them as modified. It keeps the files as they are, and unstages them.At my knowledge you cannot undo the git add --
but you can unstage a list of files as mentioned above.
In general, this is a really bad way of doing things due to multipath interference. This is definitely more of an RF engineering question than a coding one.
Tl;dr, the wifi RF energy gets scattered in different directions after bouncing off walls, people, the floor etc. There's no way of telling where you are by trianglation alone, unless you're in an empty room with the wifi beacons placed in exactly the right place.
Google is able to get away with this because they essentially can map where every wifi SSID is to a GPS location when any android user (who opts in to their service) walks into range. That way, the next time a user walks by there, even without a perfect GPS signal, the google mothership can tell where you are. Typically, they'll use that in conjunction with a crappy GPS signal.
What I have seen done is a grid of Zigbee or BTLE devices. If you know where these are laid out, you can used the combined RSS to figure out relatively which ones you're closest to, and go from there.
Solution on windows : restarted docker
On windows I used --use-container option during sam build
So, in order to fix stuck process, I've restarted docker
ls -p | grep -v /
ls -p lets you show / after the folder name, which acts as a tag for you to remove.
This will return the database name, table name, column name and the datatype of the column specified by a database parameter:
declare @database nvarchar(25)
set @database = ''
SELECT cu.table_catalog,cu.VIEW_SCHEMA, cu.VIEW_NAME, cu.TABLE_NAME,
cu.COLUMN_NAME,c.DATA_TYPE,c.character_maximum_length
from INFORMATION_SCHEMA.VIEW_COLUMN_USAGE as cu
JOIN INFORMATION_SCHEMA.COLUMNS as c
on cu.TABLE_SCHEMA = c.TABLE_SCHEMA and c.TABLE_CATALOG =
cu.TABLE_CATALOG
and c.TABLE_NAME = cu.TABLE_NAME
and c.COLUMN_NAME = cu.COLUMN_NAME
where cu.TABLE_CATALOG = @database
order by cu.view_name,c.COLUMN_NAME
I ran into this and eventually figured out it was because I was trying to use NSNumber
as dictionary keys, and property lists only allow strings as keys. The documentation for setObject:forKey:
doesn't mention this limitation, but the About Property Lists page that it links to does:
By convention, each Cocoa and Core Foundation object listed in Table 2-1 is called a property-list object. Conceptually, you can think of “property list” as being an abstract superclass of all these classes. If you receive a property list object from some method or function, you know that it must be an instance of one of these types, but a priori you may not know which type. If a property-list object is a container (that is, an array or dictionary), all objects contained within it must also be property-list objects. If an array or dictionary contains objects that are not property-list objects, then you cannot save and restore the hierarchy of data using the various property-list methods and functions. And although NSDictionary and CFDictionary objects allow their keys to be objects of any type, if the keys are not string objects, the collections are not property-list objects.
(Emphasis mine)
Changing this line:
var doc = new jsPDF('L', 'px', [w, h]);
var doc = new jsPDF('L', 'pt', [w, h]);
To fix the dimensions.
Something going wrong is get_words()
always returning one less than the actual word count, so eventually you attempt to:
char *newbuff[words]; /* Words is one less than the actual number,
so this is declared to be too small. */
newbuff[count2] = (char *)malloc(strlen(buffer))
count2
, eventually, is always one more than the number of elements you've declared for newbuff[]
. Why malloc()
isn't returning a valid ptr, though, I don't know.
Here are two methods to achieve the same thing:
Using parameters and return (recommended)
def other_function(parameter):
return parameter + 5
def main_function():
x = 10
print(x)
x = other_function(x)
print(x)
When you run main_function
, you'll get the following output
>>> 10
>>> 15
Using globals (never do this)
x = 0 # The initial value of x, with global scope
def other_function():
global x
x = x + 5
def main_function():
print(x) # Just printing - no need to declare global yet
global x # So we can change the global x
x = 10
print(x)
other_function()
print(x)
Now you will get:
>>> 0 # Initial global value
>>> 10 # Now we've set it to 10 in `main_function()`
>>> 15 # Now we've added 5 in `other_function()`
one of the simplest ways to create a string matrix is as follow :
x = [ {'first string'} {'Second parameter} {'Third text'} {'Fourth component'} ]
Use the with statement.
{% with total=business.employees.count %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
I can't imply the code in first paragraph in this answer. Maybe the template language had deprecated the old format.
I think you should use python wheels for distribution instead of egg now.
Wheels are the new standard of python distribution and are intended to replace eggs. Support is offered in pip >= 1.4 and setuptools >= 0.8.
Try the value
property, like this:
var fu1 = document.getElementById("FileUpload1");
alert("You selected " + fu1.value);
NOTE: It looks like FileUpload1
is an ASP.Net server-side FileUpload control.
If so, you should get its ID using the ClientID
property, like this:
var fu1 = document.getElementById("<%= FileUpload1.ClientID %>");
When I have an attribute id, this is my preffered way in underscore:
var x = [{i:2}, {i:2, x:42}, {i:4}, {i:3}];
_.chain(x).indexBy("i").values().value();
// > [{i:2, x:42}, {i:4}, {i:3}]
This can be done by using:
Response.Redirect("http://localhost/YourControllerName/ActionMethodName?querystring1=querystringvalue1&querystring2=querystringvalue2&querystring3=querystringvalue3");
Try adding the -f
option to show the function names :
addr2line -f -e a.out 0x4005BDC
using System.Diagnostics;
...
var st = new StackTrace();
var sf = st.GetFrame(0);
var currentMethodName = sf.GetMethod();
Or, if you'd like to have a helper method:
[MethodImpl(MethodImplOptions.NoInlining)]
public string GetCurrentMethod()
{
var st = new StackTrace();
var sf = st.GetFrame(1);
return sf.GetMethod().Name;
}
Updated with credits to @stusmith.
LocalStorage:
Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. Available size is 5MB which considerably more space to work with than a typical 4KB cookie.
The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.
The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
It works on same-origin policy. So, data stored will only be available on the same origin.
Cookies:
We can set the expiration time for each cookie
The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.
The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.
sessionStorage:
Changes are only available per window (or tab in browsers like Chrome and Firefox). Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted The data is available only inside the window/tab in which it was set.
The data is not persistent i.e. it will be lost once the window/tab is closed. Like localStorage, it works on same-origin policy. So, data stored will only be available on the same origin.
$json_data = '{ "Languages:" : [ "English", "Spanish" ] }';
$lang_data = json_decode($json_data);
var_dump($lang_data);
This is not possible as of May 2017, because Postman only works with HTTP methods such as POST, GET, PUT, DELETE.
P/S: There is a request for this if you want to upvote: github.com/postmanlabs/postman-app-support/issues/4009
Try this:
<input type="button" value="Reload" onClick="history.go(0)">
curl -iv https://your.domain.io
That will give you cert and header output if you do not wish to use openssl command.
You need to make TestGetMethod async
too and attach await in front of GetIdList();
will unwrap the task to List<int>
, So if your helper function is returning Task make sure you have await as you are calling the function async
too.
public Task<List<int>> TestGetMethod()
{
return GetIdList();
}
async Task<List<int>> GetIdList()
{
using (HttpClient proxy = new HttpClient())
{
string response = await proxy.GetStringAsync("www.test.com");
List<int> idList = JsonConvert.DeserializeObject<List<int>>();
return idList;
}
}
Another option
public async void TestGetMethod(List<int> results)
{
results = await GetIdList(); // await will unwrap the List<int>
}
This should work:
$('.myClass, .myOtherClass').removeClass('theclass');
You must add the multiple selectors all in the first argument to $(), otherwise you are giving jQuery a context in which to search, which is not what you want.
It's the same as you would do in CSS.
try this:
select convert(varchar, dob2, 101)
select convert(varchar, dob2, 102)
select convert(varchar, dob2, 103)
select convert(varchar, dob2, 104)
select convert(varchar, dob2, 105)
select convert(varchar, dob2, 106)
select convert(varchar, dob2, 107)
select convert(varchar, dob2, 108)
select convert(varchar, dob2, 109)
select convert(varchar, dob2, 110)
select convert(varchar, dob2, 111)
select convert(varchar, dob2, 112)
select convert(varchar, dob2, 113)
refernces: http://msdn.microsoft.com/en-us/library/ms187928.aspx
You could also just use regular expressions to accomplish a slightly simpler job if this is enough for you (e.g. as seen in [1]).
They are build in into javascript so you can use them without any libraries.
function isValidDate(dateString) {
var regEx = /^\d{4}-\d{2}-\d{2}$/;
return dateString.match(regEx) != null;
}
would be a function to check if the given string is four numbers - two numbers - two numbers (almost yyyy-mm-dd). But you can do even more with more complex expressions, e.g. check [2].
isValidDate("23-03-2012") // false
isValidDate("1987-12-24") // true
isValidDate("22-03-1981") // false
isValidDate("0000-00-00") // true
Another simple way:
Dir.mkdir('tmp/excel') unless Dir.exist?('tmp/excel')
Reorient your mental model of the functionality of "CASCADE" by thinking of adding a FK to an already existing cascade (i.e. a waterfall). The source of this waterfall is a primary key (PK). Deletes flow down.
So if you define a FK's on_delete as "CASCADE," you're adding this FK's record to a cascade of deletes originating from the PK. The FK's record may participate in this cascade or not ("SET_NULL"). In fact, a record with a FK may even prevent the flow of the deletes! Build a dam with "PROTECT."
Try to do <a href="#" class="arrow">
instead. (Note the sharp #
character).
I am running node.js on Windows with npm. The trick is simply use cygwin. I followed the howto under https://github.com/joyent/node/wiki/Building-node.js-on-Cygwin-(Windows) . But make sure that you use version 0.4.11 of nodejs or npm will fail!
sudo sh -c "echo 127.0.0.1 localhost >> /etc/hosts"
When working with async functions or observables provided by 3rd party libraries, for example Cloud firestore, I've found functions the waitFor
method shown below (TypeScript, but you get the idea...) to be helpful when you need to wait on some process to complete, but you don't want to have to embed callbacks within callbacks within callbacks nor risk an infinite loop.
This method is sort of similar to a while (!condition)
sleep loop, but
yields asynchronously and performs a test on the completion condition at regular intervals till true or timeout.
export const sleep = (ms: number) => {
return new Promise(resolve => setTimeout(resolve, ms))
}
/**
* Wait until the condition tested in a function returns true, or until
* a timeout is exceeded.
* @param interval The frenequency with which the boolean function contained in condition is called.
* @param timeout The maximum time to allow for booleanFunction to return true
* @param booleanFunction: A completion function to evaluate after each interval. waitFor will return true as soon as the completion function returns true.
*/
export const waitFor = async function (interval: number, timeout: number,
booleanFunction: Function): Promise<boolean> {
let elapsed = 1;
if (booleanFunction()) return true;
while (elapsed < timeout) {
elapsed += interval;
await sleep(interval);
if (booleanFunction()) {
return true;
}
}
return false;
}
The say you have a long running process on your backend you want to complete before some other task is undertaken. For example if you have a function that totals a list of accounts, but you want to refresh the accounts from the backend before you calculate, you can do something like this:
async recalcAccountTotals() : number {
this.accountService.refresh(); //start the async process.
if (this.accounts.dirty) {
let updateResult = await waitFor(100,2000,()=> {return !(this.accounts.dirty)})
}
if(!updateResult) {
console.error("Account refresh timed out, recalc aborted");
return NaN;
}
return ... //calculate the account total.
}
Yes, it's possible. for example checkout:
<div class="singleMatch" ng-if="match.date | date:'ddMMyyyy' === main.date && match.team1.code === main.team1code && match.team2.code === main.team2code">
//Do something here
</div>
D = {}
is a dictionary not set.
>>> d = {}
>>> type(d)
<type 'dict'>
Use D = set()
:
>>> d = set()
>>> type(d)
<type 'set'>
>>> d.update({1})
>>> d.add(2)
>>> d.update([3,3,3])
>>> d
set([1, 2, 3])
update: added safer method
check out the previous (unchanged) state of your file; notice the double dash
git checkout HEAD^ -- /path/to/file
commit it:
git commit -am "revert changes on this file, not finished with it yet"
push it, no force needed:
git push
get back to your unfinished work, again do (3 times arrow up):
git checkout HEAD^ -- /path/to/file
To modify the last commit of the repository HEAD, obfuscating your accidentally pushed work, while potentially running into a conflict with your colleague who may have pulled it already, and who will grow grey hair and lose lots of time trying to reconcile his local branch head with the central one:
To remove file change from last commit:
to revert the file to the state before the last commit, do:
git checkout HEAD^ /path/to/file
to update the last commit with the reverted file, do:
git commit --amend
to push the updated commit to the repo, do:
git push -f
Really, consider using the preferred method mentioned before.
You may use this package renderer, I have written to solve this kind of problem, it's a wrapper to serve JSON, JSONP, XML, HTML etc.
Your first problem is that you are passing -3 to the 2nd parameter of Columns.Add. It needs to be -2 for it to auto-size the column. Source: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columns.aspx (look at the comments on the code example at the bottom)
private void initListView()
{
// Add columns
lvRegAnimals.Columns.Add("Id", -2,HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);
}
You can also use the other overload, Add(string). E.g:
lvRegAnimals.Columns.Add("Id");
lvRegAnimals.Columns.Add("Name");
lvRegAnimals.Columns.Add("Age");
Reference for more overloads: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columnheadercollection.aspx
Second, to add items to the ListView, you need to create instances of ListViewItem and add them to the listView's Items collection. You will need to use the string[] constructor.
var item1 = new ListViewItem(new[] {"id123", "Tom", "24"});
var item2 = new ListViewItem(new[] {person.Id, person.Name, person.Age});
lvRegAnimals.Items.Add(item1);
lvRegAnimals.Items.Add(item2);
You can also store objects in the item's Tag property.
item2.Tag = person;
And then you can extract it
var person = item2.Tag as Person;
Let me know if you have any questions and I hope this helps!
Seems like a permissions issue. This is what worked for me
sudo chown -R $(whoami) /Library/Ruby/Gems/*
or in your case
sudo chown -R $(whoami) /usr/local/lib/ruby/gems/2.0.0/gems/
What does this do:
This is telling the system to change the files to change the ownership to the current user. Something must have gotten messed up when something got installed. Usually this is because there are multiple accounts or users are using sudo to install when they should not always have to.
Long story short you have to use atoi()
ed:
If you are interested in doing this the right way :
char szNos[] = "12345";
char *pNext;
long output;
output = strtol (szNos, &pNext, 10); // input, ptr to next char in szNos (null here), base
The CSS specification requires that position:fixed
be anchored to the viewport, not the containing positioned element.
If you must specify your coordinates relative to a parent, you will have to use JavaScript to find the parent's position relative to the viewport first, then set the child (fixed) element's position accordingly.
ALTERNATIVE: Some browsers have sticky
CSS support which limits an element to be positioned within both its container and the viewport. Per the commit message:
sticky
... constrains an element to be positioned inside the intersection of its container box, and the viewport.A stickily positioned element behaves like position:relative (space is reserved for it in-flow), but with an offset that is determined by the sticky position. Changed isInFlowPositioned() to cover relative and sticky.
Depending on your design goals, this behavior may be helpful in some cases. It is currently a working draft, and has decent support, aside from table elements. position: sticky
still needs a -webkit
prefix in Safari.
See caniuse for up-to-date stats on browser support.
The general solution to interpreting a char as a string is string("HELLO"[1])
.
Rich's solution also works, of course.
To create an option that needs no value, set the action
[docs] of it to 'store_const'
, 'store_true'
or 'store_false'
.
Example:
parser.add_argument('-s', '--simulate', action='store_true')
Yes its quite easy. I faced a similar problem. Just add the css property "pointer-events" to the iframe div and set it to 'none'.
Example:< iframe style="pointer-events:none" src= ........ >
SideNote: This fix would disable all other mouse events on the map. It worked for me since we didnt require any user interaction on the map.
You could use an extension method for fun. Typically I don't recommend attaching extension methods to such a general purpose class like string, but like I said this is fun. I borrowed @Luke's answer since there is no point in re-inventing the wheel.
[Test]
public void Should_remove_first_occurrance_of_string() {
var source = "ProjectName\\Iteration\\Release1\\Iteration1";
Assert.That(
source.RemoveFirst("\\Iteration"),
Is.EqualTo("ProjectName\\Release1\\Iteration1"));
}
public static class StringExtensions {
public static string RemoveFirst(this string source, string remove) {
int index = source.IndexOf(remove);
return (index < 0)
? source
: source.Remove(index, remove.Length);
}
}
iterator object contains the same number of elements what your collection contained.
List<E> a =...;
Iterator<E> i = a.iterator();
int size = a.size();//Because iterators size is equal to list a's size.
But instead of getting the size of iterator and iterating through index 0 to that size, it is better to iterate through the method next() of the iterator.
i had similar problem, i matched the entries in a particular column of two data sets and cbind only if it matched. For two data sets, data1 & data2, i am adding a column in data1 from data2 after comparing first column of both.
for(i in 1:nrow(data1){
for( j in 1:nrow(data2){
if (data1[i,1]==data2[j,1]) data1[i,3]<- data2[j,2]
}
}
I got confused by this also. There are two commands relevant here:
docker run Run a command in a new container
docker start Start one or more stopped containers
Other answers posted here for this question did not work for me using the latest Visual Studio 2017 Enterprise edition (as of 2018-09-18).
Instead, I used this method:
Once installed, close and restart Visual Studio. Go to File->New Project and search for the word Installer. You'll know you have the correct templates installed if you see a list that looks something like this:
I figured this out, it was just a naming conflict issue: if you use TheBackground instead of Background it works as posted in the first example. The property Background was interfering with the Window property background.
Unfortunately, that's not an Angular2 error, that's an error your browser is running into (i.e. outside of your app).
That CORS header will have to be added to that endpoint on the server before you can make ANY requests.
You can use divs with the float: left;
attribute which will make them appear horizontally next to each other, but then you may need to use clearing on the following elements to make sure they don't overlap.
This will be the simplest solution. I tried most of the solutions in the internet but only this helped me.
@print{
@page :footer {color: #fff }
@page :header {color: #fff}
}
In order to complete BlueM's accepted answer, you can desactivate it here:
Tools > Options > Debugging > General Output Settings > Thread Exit Messages : Off
EDITED: This guy really brought it home and has a good little tutorial http://instantiatorgratification.blogspot.com/2013/05/google-play-services-with-android-studio.html
one side note: I had played around so much that I needed to do a gradlew clean
to get it to run succesfully
If you have imported your project or are working from the Sample Maps application located in \extras\google\google_play_services\samples\maps check out this tutorial.
https://stackoverflow.com/a/16598478/2414698
If you are creating a new project from scratch then note Xav's comments on that same post. He describes that Android Studio uses a different compiler and that you have to modify the build.gradle file manually. I did this with success. I copied
into my lib directory and added the following to my build.gradle file
dependencies {
compile files('libs/android-support-v4.jar')
compile files('libs/google-play-services.jar')
}
Also, if this is a new project check out this post, too.
I just had a related problem (which is how I found this thread), where my dynamically added row and column styles were not taking effect. I usually consider SuspendLayout()/ResumeLayout() as optimizations, but in this case, wrapping my code in them made the rows and columns behave correctly.
If you use a "text variable" tk.StringVar()
, you can just set()
that.
No need to use the Entry delete and insert. Moreover, those functions don't work when the Entry is disabled or readonly! The text variable method, however, does work under those conditions as well.
import Tkinter as tk
...
entryText = tk.StringVar()
entry = tk.Entry( master, textvariable=entryText )
entryText.set( "Hello World" )
How about?
function callHttpService(url, params){
// Assume params contains key/value request params
let queryStrings = '';
for(let key in params){
queryStrings += `${key}=${params[key]}&`
}
const fullUrl = `${url}?queryStrings`
//make http request with fullUrl
}
Just add to @Bert's solution to make it more clear:
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
const router = new VueRouter({
routes,
linkExactActiveClass: "active" // active class for *exact* links.
})
As one can see, this line should be removed:
linkActiveClass: "active", // active class for non-exact links.
this way, ONLY the current link is hi-lighted. This should apply to most of the cases.
David
Here is a list of sitemap generators (from which obviously you can get the list of URLs from a site): http://code.google.com/p/sitemap-generators/wiki/SitemapGenerators
Web Sitemap Generators
The following are links to tools that generate or maintain files in the XML Sitemaps format, an open standard defined on sitemaps.org and supported by the search engines such as Ask, Google, Microsoft Live Search and Yahoo!. Sitemap files generally contain a collection of URLs on a website along with some meta-data for these URLs. The following tools generally generate "web-type" XML Sitemap and URL-list files (some may also support other formats).
Please Note: Google has not tested or verified the features or security of the third party software listed on this site. Please direct any questions regarding the software to the software's author. We hope you enjoy these tools!
Server-side Programs
- Enarion phpSitemapsNG (PHP)
- Google Sitemap Generator (Linux/Windows, 32/64bit, open-source)
- Outil en PHP (French, PHP)
- Perl Sitemap Generator (Perl)
- Python Sitemap Generator (Python)
- Simple Sitemaps (PHP)
- SiteMap XML Dynamic Sitemap Generator (PHP) $
- Sitemap generator for OS/2 (REXX-script)
- XML Sitemap Generator (PHP) $
CMS and Other Plugins:
- ASP.NET - Sitemaps.Net
- DotClear (Spanish)
- DotClear (2)
- Drupal
- ECommerce Templates (PHP) $
- Ecommerce Templates (PHP or ASP) $
- LifeType
- MediaWiki Sitemap generator
- mnoGoSearch
- OS Commerce
- phpWebSite
- Plone
- RapidWeaver
- Textpattern
- vBulletin
- Wikka Wiki (PHP)
- WordPress
Downloadable Tools
- GSiteCrawler (Windows)
- GWebCrawler & Sitemap Creator (Windows)
- G-Mapper (Windows)
- Inspyder Sitemap Creator (Windows) $
- IntelliMapper (Windows) $
- Microsys A1 Sitemap Generator (Windows) $
- Rage Google Sitemap Automator $ (OS-X)
- Screaming Frog SEO Spider and Sitemap generator (Windows/Mac) $
- Site Map Pro (Windows) $
- Sitemap Writer (Windows) $
- Sitemap Generator by DevIntelligence (Windows)
- Sorrowmans Sitemap Tools (Windows)
- TheSiteMapper (Windows) $
- Vigos Gsitemap (Windows)
- Visual SEO Studio (Windows)
- WebDesignPros Sitemap Generator (Java Webstart Application)
- Weblight (Windows/Mac) $
- WonderWebWare Sitemap Generator (Windows)
Online Generators/Services
- AuditMyPc.com Sitemap Generator
- AutoMapIt
- Autositemap $
- Enarion phpSitemapsNG
- Free Sitemap Generator
- Neuroticweb.com Sitemap Generator
- ROR Sitemap Generator
- ScriptSocket Sitemap Generator
- SeoUtility Sitemap Generator (Italian)
- SitemapDoc
- Sitemapspal
- SitemapSubmit
- Smart-IT-Consulting Google Sitemaps XML Validator
- XML Sitemap Generator
- XML-Sitemaps Generator
CMS with integrated Sitemap generators
- Concrete5
Google News Sitemap Generators The following plugins allow publishers to update Google News Sitemap files, a variant of the sitemaps.org protocol that we describe in our Help Center. In addition to the normal properties of Sitemap files, Google News Sitemaps allow publishers to describe the types of content they publish, along with specifying levels of access for individual articles. More information about Google News can be found in our Help Center and Help Forums.
- WordPress Google News plugin
Code Snippets / Libraries
- ASP script
- Emacs Lisp script
- Java library
- Perl script
- PHP class
- PHP generator script
If you believe that a tool should be added or removed for a legitimate reason, please leave a comment in the Webmaster Help Forum.
Here are the steps:
I think if you want to use extension methods you need to use the GroupJoin
var query =
people.GroupJoin(pets,
person => person,
pet => pet.Owner,
(person, petCollection) =>
new { OwnerName = person.Name,
Pet = PetCollection.Select( p => p.Name )
.DefaultIfEmpty() }
).ToList();
You may have to play around with the selection expression. I'm not sure it would give you want you want in the case where you have a 1-to-many relationship.
I think it's a little easier with the LINQ Query syntax
var query = (from person in context.People
join pet in context.Pets on person equals pet.Owner
into tempPets
from pets in tempPets.DefaultIfEmpty()
select new { OwnerName = person.Name, Pet = pets.Name })
.ToList();
I got the error in the following case:
I simply avoided the obfuscation and the error is gone. not a real solution, but at least I know what caused it...
You can install TortoiseGit for Windows and include integration in context menu. I consider it the best tool to work with Git on Windows.
Since JavaScript doesn't have function overload options object can be used instead. If there are one or two required arguments, it's better to keep them separate from the options object. Here is an example on how to use options object and populated values to default value in case if value was not passed in options object.
function optionsObjectTest(x, y, opts) {
opts = opts || {}; // default to an empty options object
var stringValue = opts.stringValue || "string default value";
var boolValue = !!opts.boolValue; // coerces value to boolean with a double negation pattern
var numericValue = opts.numericValue === undefined ? 123 : opts.numericValue;
return "{x:" + x + ", y:" + y + ", stringValue:'" + stringValue + "', boolValue:" + boolValue + ", numericValue:" + numericValue + "}";
}
here is an example on how to use options object
press WIN+R and from the run dialog run dialog Execute the following: **%appdata%..\Local\Android**
You should now be presented with Folder Explorer displaying the parent directory of the SDK.
With the newer versions of angularjs the correct answer to this question is to use ng-if
:
<ul>
<li ng-if="list.length === 0">( No items in this list yet! )</li>
<li ng-repeat="item in list">{{ item }}</li>
</ul>
This solution will not flicker when the list is about to download either because the list has to be defined and with a length of 0 for the message to display.
Here is a plunker to show it in use: http://plnkr.co/edit/in7ha1wTlpuVgamiOblS?p=preview
Tip: You can also show a loading text or spinner:
<li ng-if="!list">( Loading... )</li>
Generally we want to add images, txt, doc and etc files inside our Java project and specific folder such as /images. I found in search that in JAVA, we can get path from Root to folder which we specify as,
String myStorageFolder= "/images"; // this is folder name in where I want to store files.
String getImageFolderPath= request.getServletContext().getRealPath(myStorageFolder);
Here, request is object of HttpServletRequest. It will get the whole path from Root to /images folder. You will get output like,
C:\Users\STARK\Workspaces\MyEclipse.metadata.me_tcat7\webapps\JavaProject\images
In my case I was facing same error. One of my project solution was referring an assembly from different NuGet location. I just changed it to correct location to solve this error and rebuild. and wow the project get build successfully and all other error gone away.
They aren't the same though, are they? One is a copy, the other is a swap. Hence the function names.
My favourite is:
a = b;
Where a
and b
are vectors.
If you're using a Unix like OS (Linux, OSX, etc) then you can use a combination of find
and egrep
to search for require statements containing your package name:
find . -path ./node_modules -prune -o -name "*.js" -exec egrep -ni 'name-of-package' {} \;
If you search for the entire require('name-of-package')
statement, remember to use the correct type of quotation marks:
find . -path ./node_modules -prune -o -name "*.js" -exec egrep -ni 'require("name-of-package")' {} \;
or
find . -path ./node_modules -prune -o -name "*.js" -exec egrep -ni "require('name-of-package')" {} \;
The downside is that it's not fully automatic, i.e. it doesn't extract package names from package.json
and check them. You need to do this for each package yourself. Since package.json
is just JSON this could be remedied by writing a small script that uses child_process.exec
to run this command for each dependency. And make it a module. And add it to the NPM repo...
help(input)
shows what keyboard shortcuts produce EOF, namely, Unix: Ctrl-D, Windows: Ctrl-Z+Return:
input([prompt]) -> string
Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading.
You could reproduce it using an empty file:
$ touch empty
$ python3 -c "input()" < empty
Traceback (most recent call last):
File "<string>", line 1, in <module>
EOFError: EOF when reading a line
You could use /dev/null
or nul
(Windows) as an empty file for reading. os.devnull
shows the name that is used by your OS:
$ python3 -c "import os; print(os.devnull)"
/dev/null
Note: input()
happily accepts input from a file/pipe. You don't need stdin
to be connected to the terminal:
$ echo abc | python3 -c "print(input()[::-1])"
cba
Either handle EOFError
in your code:
try:
reply = input('Enter text')
except EOFError:
break
Or configure your editor to provide a non-empty input when it runs your script e.g., by using a customized command line if it allows it: python3 "%f" < input_file
According to the documentation since Symfony 2.1 simply use this shortcut :
$user = $this->getUser();
The above is still working on Symfony 3.2 and is a shortcut for this :
$user = $this->get('security.token_storage')->getToken()->getUser();
The
security.token_storage
service was introduced in Symfony 2.6. Prior to Symfony 2.6, you had to use thegetToken()
method of thesecurity.context
service.
Example : And if you want directly the username :
$username = $this->getUser()->getUsername();
The user will be an object and the class of that object will depend on your user provider.
In an SQL query, if the inner query executes for every row of the outer query. If the inner query is executed for once and the result is consumed by the outer query, then it is called as non co-related query.
In Visual Studio 2015 (community edition), System.Windows.Forms
is not available and hence we can't use MessageBox.Show("text")
.
Use this Instead:
var Msg = new MessageDialog("Some String here", "Title of Message Box");
await Msg.ShowAsync();
Note: Your function must be defined async to use above await Msg.ShowAsync()
.
I have an Activity that extends ListActivity.
I tried doing something like this in onCreate:
ListView listView = getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.i("Hello!", "Y u no see me?");
}
});
But that didn't work.
Instead I simply needed to override onListItemClick:
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Log.i("Hello!", "Clicked! YAY!");
}
You can use JS + Ajax. For example, if you have any button you can say it what it must do on click event. Here the code:
<input id="btnFilterData" type="button" value="myBtn">
Here your button in html: in the script section, you need to use this code (This section should be at the end of the document):
<script type="text/javascript">
$('#btnFilterData').click(function () {
myFunc();
});
</script>
And finally, you need to add ajax function (In another script section, which should be placed at the begining of the document):
function myFunc() {
$.ajax({
type: "GET",
contentType: "application/json",
url: "/myController/myFuncOnController",
data: {
//params, which you can pass to yu func
},
success: function(result) {
error: function (errorData) {
}
});
};
Using recursion, conditionals can be substituted using function pointer arithmetic:
#include <stdio.h>
#include <stdlib.h> // for: void exit(int CODE)
// function pointer
typedef void (*fptr)(int);
void next(int n)
{
printf("%d\n", n);
// pointer to next function to call
fptr fp = (fptr)(((n != 0) * (unsigned int) next) +
((n == 0) * (unsigned int) exit));
// decrement and call either ``next'' or ``exit''
fp(n-1);
}
int main()
{
next(1000);
}
Note that there are no conditionals; n!=0
and n==0
are branchless operations. (Though, we perform a branch in the tail call).
You can use :
abs_num = (num < 0) ? -num : num;
When installing on ubuntu via .deb
you can use sudo apt search cudnn | grep installed
.idea/modules.xml
You do not want to remove entire .idea directory, because it contains e.g. dictionaries and shelved changes.
If it were not for the dashes and underscores, the easiest solution would be
my_little_string.isalnum()
(Section 3.6.1 of the Python Library Reference)
This should work!
[HttpPost]
public ActionResult RedirectToImages(int id)
{
return RedirectToAction("Index", "ProductImageManeger", new { id = id });
}
[HttpGet]
public ViewResult Index(int id)
{
return View(_db.ProductImages.Where(rs => rs.ProductId == id).ToList());
}
Notice that you don't have to pass the name of view if you are returning the same view as implemented by the action.
Your view should inherit the model as this:
@model <Your class name>
You can then access your model in view as:
@Model.<property_name>
There's a great guide here:
https://discussions.apple.com/docs/DOC-3083
However, it didn't work for me first try. I found this tip: run "httpd -t" in Terminao to check the syntax of your config files. Turns out using copy & paste from the tutorial introduced some strange characters. After fixing this, it worked great. There are some links from the guide for adding MySQL as well.
This worked much better for me than MAMP. With MAMP, I was having delays of about 20 seconds or so before changes to the .php file would be reflected in the browser when you refresh, even if you cleared the cache, history, cookies, etc.
This problem was resolved in MAMP PRO, but MAMP PRO had a new issue of its own: the .php files would be downloaded instead of being rendered as a page in the browser! I contacted support and they didn't know what was going on.
The built-in Apache server didn't have any of these issues. Definitely the way to go. The guide below is almost identical to the one above, but it has user comments that are helpful:
http://osxdaily.com/2012/09/02/start-apache-web-server-mac-os-x/#comment-572991
Update: Jan-2019
First create public folder under resources and create index.html file. Use WebMvcConfigurer instead of WebMvcConfigurerAdapter.
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebAppConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/index.html");
}
}
You need to put your directory structure in your project directory. And then click "Show All Files" icon in the top of Solution Explorer toolbox. After that, the added directory will be shown up. You will then need to select this directory, right click, and choose "Include in Project."
Use ternary operator:
echo (($test == '') ? $redText : '');
echo $test == '' ? $redText : ''; //removed parenthesis
But in this case you can't use shorter reversed version because it will return bool(true)
in first condition.
echo (($test != '') ?: $redText); //this will not work properly for this case
In Java, 2D arrays are really arrays of arrays with possibly different lengths (there are no guarantees that in 2D arrays that the 2nd dimension arrays all be the same length)
You can get the length of any 2nd dimension array as z[n].length
where 0 <= n < z.length
.
If you're treating your 2D array as a matrix, you can simply get z.length
and z[0].length
, but note that you might be making an assumption that for each array in the 2nd dimension that the length is the same (for some programs this might be a reasonable assumption).
You can check your respone content, just console.log it and you will see whitch property have a status code. If you do not understand jsons, please refer to the video: https://www.youtube.com/watch?v=Bv_5Zv5c-Ts
It explains very basic knowledge that let you feel more comfortable with javascript.
You can do it with shorter version of ajax request, please see code above:
$.get("example.url.com", function(data) {
console.log(data);
}).done(function() {
// TO DO ON DONE
}).fail(function(data, textStatus, xhr) {
//This shows status code eg. 403
console.log("error", data.status);
//This shows status message eg. Forbidden
console.log("STATUS: "+xhr);
}).always(function() {
//TO-DO after fail/done request.
console.log("ended");
});
Example console output:
error 403
STATUS: Forbidden
ended
In polyfills.ts
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es7/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/weak-set';
import 'core-js/es6/set';
/** IE10 and IE11 requires the following for NgClass support on SVG elements */
import 'classlist.js'; // Run `npm install --save classlist.js`.
/** Evergreen browsers require these. **/
import 'core-js/es6/reflect';
import 'core-js/es7/reflect';
/**
* Required to support Web Animations `@angular/animation`.
* Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation
**/
import 'web-animations-js'; // Run `npm install --save web-animations-js`.
The same answer : JOptionpane with an example :)
package experiments;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class CreateDialogFromOptionPane {
public static void main(final String[] args) {
final JFrame parent = new JFrame();
JButton button = new JButton();
button.setText("Click me to show dialog!");
parent.add(button);
parent.pack();
parent.setVisible(true);
button.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
String name = JOptionPane.showInputDialog(parent,
"What is your name?", null);
}
});
}
}
To convert a time in one timezone to another timezone in Python, you could use datetime.astimezone():
so, below code is to convert the local time to other time zone.
# Time conversion from local time
import datetime
import pytz
dt_today = datetime.datetime.today() # Local time
dt_India = dt_today.astimezone(pytz.timezone('Asia/Kolkata'))
dt_London = dt_today.astimezone(pytz.timezone('Europe/London'))
India = (dt_India.strftime('%m/%d/%Y %H:%M'))
London = (dt_London.strftime('%m/%d/%Y %H:%M'))
print("Indian standard time: "+India+" IST")
print("British Summer Time: "+London+" BST")
import pytz
for tz in pytz.all_timezones:
print(tz)
Do the following steps:
Download the Flutter SDK Flutter SDK Archive
Extract it where do you want (for example /home/development/flutter
)
Set your PATH, edit your file with this command gedit ~/.profile
, you need to add this line
export PATH=[location_where_you_extracted_flutter]/flutter/bin:$PATH
I showed you above where I've extracted mine, so my export will look like this
export PATH=/home/myUser/development/flutter/bin:$PATH
source ~/.profile
to load the changesflutter doctor
should work!I'm not sure what wget is, but to get a file from the web and store it locally, you can use NSData:
NSString *stringURL = @"http://www.somewhere.com/thefile.png";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.png"];
[urlData writeToFile:filePath atomically:YES];
}
A better(error-free) code would be like:
function isReallyNumber(data) {
return typeof data === 'number' && !isNaN(data);
}
This will handle empty strings as well. Another reason, isNaN("12")
equals to false
but "12"
is a string and not a number, so it should result to true
. Lastly, a bonus link which might interest you.
As an alternative to explicitly catching and handling the exception you could tell Oracle to catch and automatically ignore the exception by including a /*+ hint */
in the insert statement. This is a little faster than explicitly catching the exception and then articulating how it should be handled. It is also easier to setup. The downside is that you do not get any feedback from Oracle that an exception was caught.
Here is an example where we would be selecting from another table, or perhaps an inner query, and inserting the results into a table called TABLE_NAME
which has a unique constraint on a column called IDX_COL_NAME
.
INSERT /*+ ignore_row_on_dupkey_index(TABLE_NAME(IDX_COL_NAME)) */
INTO TABLE_NAME(
INDEX_COL_NAME
, col_1
, col_2
, col_3
, ...
, col_n)
SELECT
INDEX_COL_NAME
, col_1
, col_2
, col_3
, ...
, col_n);
This is not a great solution if your goal it to catch and handle (i.e. print out or update the row that is violating the constraint). But if you just wanted to catch it and ignore the violating row then then this should do the job.
Some last version of Ubuntu installs Python 3.4 by default and the CMake version from Ubuntu (2.8) only searches up to Python 3.3.
Try to add set(Python_ADDITIONAL_VERSIONS 3.4)
before the find_package
statement.
Remember to clean CMakeCache.txt
too.
Php has a super sexy function for this, just pass the array to it:
$json = json_encode($var);
$.ajax({
url:"Example.php",
type:"POST",
dataType : "json",
success:function(msg){
console.info(msg);
}
});
simples :)
test.xml:
<?xml version="1.0" encoding="utf-8"?>
<Contacts>
<Node>
<ID>123</ID>
<Name>ABC</Name>
</Node>
<Node>
<ID>124</ID>
<Name>DEF</Name>
</Node>
</Contacts>
Select a single node:
XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123"; // id to be selected
XElement Contact = (from xml2 in XMLDoc.Descendants("Node")
where xml2.Element("ID").Value == id
select xml2).FirstOrDefault();
Console.WriteLine(Contact.ToString());
Delete a single node:
XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123";
var Contact = (from xml2 in XMLDoc.Descendants("Node")
where xml2.Element("ID").Value == id
select xml2).FirstOrDefault();
Contact.Remove();
XMLDoc.Save("test.xml");
Add new node:
XDocument XMLDoc = XDocument.Load("test.xml");
XElement newNode = new XElement("Node",
new XElement("ID", "500"),
new XElement("Name", "Whatever")
);
XMLDoc.Element("Contacts").Add(newNode);
XMLDoc.Save("test.xml");
Setting textbox backgroundcolor with multiple colors on single click.
Note:- using HTML and Javscript.
< input id="ClickMe_btn" onclick="setInterval(function () { ab() }, 3000);" type="button" value="ClickMe" />
var arr, i = 0; arr = ["Red", "Blue", "Green", " Orange ", "Purple", "Yellow", "Brown", "Lime", "Grey"]; // We provide array as input.
function ab()
{ document.getElementById("Text").style.backgroundColor = arr[i];
window.alert(arr[i]);
i++;
}
Note: You can change milliseconds, with setInterval 2nd parameter.
What worked for me now is:
CSS:
.right {
text-align: right;
margin-right: 1em;
}
.left {
text-align: left;
margin-left: 1em;
}
HTML:
<table width="100%">
<tbody>
<tr>
<td class="left">
<input id="abort" type="submit" name="abort" value="Back">
<input id="save" type="submit" name="save" value="Save">
</td>
<td class="right">
<input id="delegate" type="submit" name="delegate" value="Delegate">
<input id="unassign" type="submit" name="unassign" value="Unassign">
<input id="complete" type="submit" name="complete" value="Complete">
</td>
</tr>
</tbody>
</table>
See the following fiddle:
For me the issue wasn't six
but rst2pdf
itself. head -1 $(which rst2pdf)
(3.8) didn't match python3 --version
(3.9). My solution:
pip3 install rst2pdf
Remember that with the binding redirection
oldVersion="0.0.0.0-6.0.0.0"
You are saying that the old versions of the dll are between version 0.0.0.0 and version 6.0.0.0.
NoSuchMethodError : I have spend couple of hours fixing this issue, finally fixed it by just renaming package name , clean and build ... Try clean build first if it doesn't works try renaming the class name or package name and clean build...it should be fixed. Good luck.
I hope this can help someone. Determine the nav offset through js and then apply sticky position css to nav:
But first, we will define the styles in the stylesheet, like so.
.sticky {
position: fixed;
width: 100%;
left: 0;
top: 0;
z-index: 100;
border-top: 0;
}
Then, we will apply that class to the navigation conditionally with jQuery.
$(document).ready(function() {
var stickyNavTop = $('.nav').offset().top;
var stickyNav = function(){
var scrollTop = $(window).scrollTop();
if (scrollTop > stickyNavTop) {
$('.nav').addClass('sticky');
} else {
$('.nav').removeClass('sticky');
}
};
stickyNav();
$(window).scroll(function() {
stickyNav();
});
});
ISO-8859-1 is an all-inclusive charset, in the sense that it's guaranteed not to throw MalformedInputException. So it's good for debugging, even if your input is not in this charset. So:-
req.setCharacterEncoding("ISO-8859-1");
I had some double-right-quote/double-left-quote characters in my input, and both US-ASCII and UTF-8 threw MalformedInputException on them, but ISO-8859-1 worked.
Are you putting this line inside the class declaration? In that case you should remove the JSONDeserializer::
.
How much a stack can grow?
You can use a VM option named ss
to adjust the maximum stack size. A VM option is usually passed using -X{option}. So you can use java -Xss1M
to set the maximum of stack size to 1M.
Each thread has at least one stack. Some Java Virtual Machines(JVM) put Java stack(Java method calls) and native stack(Native method calls in VM) into one stack, and perform stack unwinding using a Managed to Native Frame, known as M2NFrame. Some JVMs keep two stacks separately. The Xss
set the size of the Java Stack in most cases.
For many JVMs, they put different default values for stack size on different platforms.
Can we limit this growth?
When a method call occurs, a new stack frame will be created on the stack of that thread. The stack will contain local variables, parameters, return address, etc. In java, you can never put an object on stack, only object reference can be stored on stack. Since array is also an object in java, arrays are also not stored on stack. So, if you reduce the amount of your local primitive variables, parameters by grouping them into objects, you can reduce the space on stack. Actually, the fact that we cannot explicitly put objects on java stack affects the performance some time(cache miss).
Does stack has some default minimum value or default maximum value?
As I said before, different VMs are different, and may change over versions. See here.
how does garbage collection work on stack?
Garbage collections in Java is a hot topic. Garbage collection aims to collect unreachable objects in the heap. So that needs a definition of 'reachable.' Everything on the stack constitutes part of the root set references in GC. Everything that is reachable from every stack of every thread should be considered as live. There are some other root set references, like Thread objects and some class objects.
This is only a very vague use of stack on GC. Currently most JVMs are using a generational GC. This article gives brief introduction about Java GC. And recently I read a very good article talking about the GC on .net. The GC on oracle jvm is quite similar so I think that might also help you.
The error here, is since calling the DataFrame constructor with scalar values (where it expects values to be a list/dict/... i.e. have multiple columns):
pd.DataFrame(d)
ValueError: If using all scalar values, you must must pass an index
You could take the items from the dictionary (i.e. the key-value pairs):
In [11]: pd.DataFrame(d.items()) # or list(d.items()) in python 3
Out[11]:
0 1
0 2012-07-02 392
1 2012-07-06 392
2 2012-06-29 391
3 2012-06-28 391
...
In [12]: pd.DataFrame(d.items(), columns=['Date', 'DateValue'])
Out[12]:
Date DateValue
0 2012-07-02 392
1 2012-07-06 392
2 2012-06-29 391
But I think it makes more sense to pass the Series constructor:
In [21]: s = pd.Series(d, name='DateValue')
Out[21]:
2012-06-08 388
2012-06-09 388
2012-06-10 388
In [22]: s.index.name = 'Date'
In [23]: s.reset_index()
Out[23]:
Date DateValue
0 2012-06-08 388
1 2012-06-09 388
2 2012-06-10 388
Take a look at debug_toolbar, it's very useful for debugging.
Documentation and source is available at http://django-debug-toolbar.readthedocs.io/.
You can't insert the values into timestamp column explicitly. It is auto-generated. Do not use this column in your insert statement. Refer http://msdn.microsoft.com/en-us/library/ms182776(SQL.90).aspx for more details.
You could use a datetime instead of a timestamp like this:
create table demo (
ts datetime
)
insert into demo select current_timestamp
select ts from demo
Returns:
2014-04-04 09:20:01.153
Apache Spark does not support native CSV output on disk.
You have four available solutions though:
You can convert your Dataframe into an RDD :
def convertToReadableString(r : Row) = ???
df.rdd.map{ convertToReadableString }.saveAsTextFile(filepath)
This will create a folder filepath. Under the file path, you'll find partitions files (e.g part-000*)
What I usually do if I want to append all the partitions into a big CSV is
cat filePath/part* > mycsvfile.csv
Some will use coalesce(1,false)
to create one partition from the RDD. It's usually a bad practice, since it may overwhelm the driver by pulling all the data you are collecting to it.
Note that df.rdd
will return an RDD[Row]
.
With Spark <2, you can use databricks spark-csv library:
Spark 1.4+:
df.write.format("com.databricks.spark.csv").save(filepath)
Spark 1.3:
df.save(filepath,"com.databricks.spark.csv")
With Spark 2.x the spark-csv
package is not needed as it's included in Spark.
df.write.format("csv").save(filepath)
You can convert to local Pandas data frame and use to_csv
method (PySpark only).
Note: Solutions 1, 2 and 3 will result in CSV format files (part-*
) generated by the underlying Hadoop API that Spark calls when you invoke save
. You will have one part-
file per partition.
add this to your ~/.bashrc
:
alias cleanscreen="screen -ls | tail -n +2 | head -n -2 | awk '{print $1}'| xargs -I{} screen -S {} -X quit"
Then use cleanscreen
to clean all screen session.
As long as you're not doing any INSERT or UPDATE statements in your stored procedure, you will probably want to make it a function.
Stored procedures are for executing by an outside program, or on a timed interval.
The answers here will explain it better than I can:
Below are the rules if you believe it's random. A utility function can be created on the basis of these rules.
If the value contains a comma, newline or double quote, then the String value should be returned enclosed in double quotes.
Any double quote characters in the value should be escaped with another double quote.
If the value does not contain a comma, newline or double quote, then the String value should be returned unchanged.
I think you'll find your answer if you refer to this post: Deserialize JSON into C# dynamic object?
There are various ways of achieving what you want here. The System.Web.Helpers.Json approach (a few answers down) seems to be the simplest.
This ...
horse = Horse.find(:first,:offset=>rand(Horse.count))
unless @suggested_horses.exists?(horse.id)
@suggested_horses<< horse
end
Should probably be this ...
horse = Horse.find(:first,:offset=>rand(Horse.count))
unless @suggested_horses.include?(horse)
@suggested_horses<< horse
end
The continue statement is used in loop control structure when you need to jump to the next iteration of the loop immediately.
It can be used with for loop or while loop. The Java continue statement is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition.
In case of an inner loop, it continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.
for example
class Example{
public static void main(String args[]){
System.out.println("Start");
for(int i=0; i<10; i++){
if(i==5){continue;}
System.out.println("i : "+i);
}
System.out.println("End.");
}
}
output:
Start
i : 0
i : 1
i : 2
i : 3
i : 4
i : 6
i : 7
i : 8
i : 9
End.
[number 5 is skip]
Swift 3+: Try these line of code
let num: Double = 1.5
let str = String(format: "%.2f", num)
I know this is an old question, but for anybody reading this who is stuck with the same question and who may be overwhelmed with all the terminology, here's a good, simple analogy to help you understand this distinction between iterables and iterators:
Think of a public library. Old school. With paper books. Yes, that kind of library.
A shelf full of books would be like an iterable. You can see the long line of books in the shelf. You may not know how many, but you can see that it is a long collection of books.
The librarian would be like the iterator. He can point to a specific book at any moment in time. He can insert/remove/modify/read the book at that location where he's pointing. He points, in sequence, to each book at a time every time you yell out "next!" to him. So, you normally would ask him: "has Next?", and he'll say "yes", to which you say "next!" and he'll point to the next book. He also knows when he's reached the end of the shelf, so that when you ask: "has Next?" he'll say "no".
I know it's a bit silly, but I hope this helps.
Some people have commented about readability, saying "Oh it doesn't help readability that much, who cares?"
Suppose you need a check before the main code:
if precondition_fails(message): continue
''' main code here '''
Note you can do this after the main code was written without changing that code in anyway. If you diff the code, only the added line with "continue" will be highlighted since there are no spacing changes to the main code.
Imagine if you have to do a breakfix of production code, which turns out to simply be adding a line with continue. It's easy to see that's the only change when you review the code. If you start wrapping the main code in if/else, diff will highlight the newly indented code, unless you ignore spacing changes, which is dangerous particularly in Python. I think unless you've been in the situation where you have to roll out code on short notice, you might not fully appreciate this.
Here is a complete example
class Example
{
public static void Main()
{
double x, y;
int i;
x = 10.0;
y = 3.0;
// cast double to int, fractional component lost (Line to be replaced)
i = (int) (x / y);
Console.WriteLine("Integer outcome of x / y: " + i);
}
}
If you want to round the number to the closer integer do the following:
i = (int) Math.Round(x / y); // Line replaced
Understand Introspection
dir()
equivalenttype()
equivalentdis
module to see how various language constructs workDoing these things will
These JavaScript solutions give you the milliseconds or the seconds since the midnight, January 1st, 1970.
The IE 9+ solution(IE 8 or the older version doesn't support this.):
var timestampInMilliseconds = Date.now();
var timestampInSeconds = Date.now() / 1000; // A float value; not an integer.
timestampInSeconds = Math.floor(Date.now() / 1000); // Floor it to get the seconds.
timestampInSeconds = Date.now() / 1000 | 0; // Also you can do floor it like this.
timestampInSeconds = Math.round(Date.now() / 1000); // Round it to get the seconds.
To get more information about Date.now()
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now
The generic solution:
// ‘+’ operator makes the operand numeric.
// And ‘new’ operator can be used without the arguments ‘(……)’.
var timestampInMilliseconds = +new Date;
var timestampInSeconds = +new Date / 1000; // A float value; not an intger.
timestampInSeconds = Math.floor(+new Date / 1000); // Floor it to get the seconds.
timestampInSeconds = +new Date / 1000 | 0; // Also you can do floor it like this.
timestampInSeconds = Math.round(+new Date / 1000); // Round it to get the seconds.
Be careful to use, if you don't want something like this case.
if(1000000 < Math.round(1000000.2)) // false.
Since you are not interested in keeping any data, drop the entire database and create a new one.
why not keep it simple
cd SOME_PATH && run_some_command && cd -
the last 'cd' command will take you back to the last pwd directory. This should work on all *nix systems.
a:visited
{
color: #881033;
}
(or whatever color you want it to be)
text-decoration
is for underlining(overlining etc.
decoration
ist not a valid css rule.
Not only is the boolean datatype missing in Oracle's SQL (not PL/SQL), but they also have no clear recommendation about what to use instead. See this thread on asktom. From recommending CHAR(1) 'Y'/'N'
they switch to NUMBER(1) 0/1
when someone points out that 'Y'/'N'
depends on the English language, while e.g. German programmers might use 'J'/'N'
instead.
The worst thing is that they defend this stupid decision just like they defend the ''=NULL
stupidity.
If you want that image to be zoomed on mouse hover :
$(document).ready( function() {
$('#div img').hover(
function() {
$(this).animate({ 'zoom': 1.2 }, 400);
},
function() {
$(this).animate({ 'zoom': 1 }, 400);
});
});
?or you may do like this if zoom in and out buttons are used :
$("#ZoomIn").click(ZoomIn());
$("#ZoomOut").click(ZoomOut());
function ZoomIn (event) {
$("#div img").width(
$("#div img").width() * 1.2
);
$("#div img").height(
$("#div img").height() * 1.2
);
},
function ZoomOut (event) {
$("#div img").width(
$("#imgDtls").width() * 0.5
);
$("#div img").height(
$("#div img").height() * 0.5
);
}
After Rebuild the project issue resolved..
Main issue is that you first need to set the location of your x and y ticks. Also, it helps to use the more object-oriented interface to matplotlib. Namely, interact with the axes
object directly.
import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data)
# put the major ticks at the middle of each cell, notice "reverse" use of dimension
ax.set_yticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_xticks(np.arange(data.shape[1])+0.5, minor=False)
ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()
Hope that helps.
Assuming you have Notepad++, an often-missed feature is 'Find in files', which is extremely fast and comes with filters, regular expressions, replace and all the N++ goodies.
If you accidently deleted your R in eclipse by "project clean" (don´t do this) Rightclick on your Projectfile -> Restore from local History...
recreate your R
My Case:
What I Did:
and...
If you are looking for where the project folder was created. I noticed when I typed in the git bash.
$ git init projectName
it will tell me, where the project folder is for that project.
For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).
This can be caused in many ways:
#include
the header that defines it.#ifndef BLAH_H
) are defective (your #ifndef BLAH_H
doesn't match your #define BALH_H
due to a typo or copy+paste mistake).#define MYHEADER_H
, even if they are in separate directories)new Vector()
should be new Vector<int>()
)NamespaceA::NamespaceB
, AND a <global scope>::NamespaceB
, if you are already within NamespaceA
, it'll look in NamespaceA::NamespaceB
and not bother checking <global scope>::NamespaceB
) unless you explicitly access it.To explicitly access something in the global namespace, prefix it with ::
, as if the global namespace is a namespace with no name (e.g. ::MyType
or ::MyNamespace::MyType
).
The error as reported appears when the variables are null (or empty):
$ unset var3 var4; var5=$(($var4-$var3))
bash: -: syntax error: operand expected (error token is "-")
That could happen because the value given to bc was incorrect. That might well be that bc needs UPPERcase values. It needs BFCA3000
, not bfca3000
. That is easily fixed in bash, just use the ^^
expansion:
var3=bfca3000; var3=`echo "ibase=16; ${var1^^}" | bc`
That will change the script to this:
#!/bin/bash
var1="bfca3000"
var2="efca3250"
var3="$(echo "ibase=16; ${var1^^}" | bc)"
var4="$(echo "ibase=16; ${var2^^}" | bc)"
var5="$(($var4-$var3))"
echo "Diference $var5"
But there is no need to use bc [1], as bash could perform the translation and substraction directly:
#!/bin/bash
var1="bfca3000"
var2="efca3250"
var5="$(( 16#$var2 - 16#$var1 ))"
echo "Diference $var5"
[1]Note: I am assuming the values could be represented in 64 bit math, as the difference was calculated in bash in your original script. Bash is limited to integers less than ((2**63)-1) if compiled in 64 bits. That will be the only difference with bc which does not have such limit.
You can use this following code. work just on chrome browser.
function failed(e) {_x000D_
// video playback failed - show a message saying why_x000D_
switch (e.target.error.code) {_x000D_
case e.target.error.MEDIA_ERR_ABORTED:_x000D_
alert('You aborted the video playback.');_x000D_
break;_x000D_
case e.target.error.MEDIA_ERR_NETWORK:_x000D_
alert('A network error caused the video download to fail part-way.');_x000D_
break;_x000D_
case e.target.error.MEDIA_ERR_DECODE:_x000D_
alert('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');_x000D_
break;_x000D_
case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:_x000D_
alert('The video could not be loaded, either because the server or network failed or because the format is not supported.');_x000D_
break;_x000D_
default:_x000D_
alert('An unknown error occurred.');_x000D_
break;_x000D_
}_x000D_
}
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">_x000D_
_x000D_
<head>_x000D_
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />_x000D_
<meta name="author" content="Amin Developer!" />_x000D_
_x000D_
<title>Untitled 1</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<p><video src="http://jell.yfish.us/media/Jellyfish-3-Mbps.mkv" type='video/x-matroska; codecs="theora, vorbis"' autoplay controls onerror="failed(event)" ></video></p>_x000D_
<p><a href="YOU mkv FILE LINK GOES HERE TO DOWNLOAD">Download the video file</a>.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Unless you are 100% sure that the code being evaluated is from a trusted source (usually your own application) then it's a surefire way of exposing your system to a cross-site scripting attack.
I think if you try:
Sub Macro3()
a = ActiveSheet.UsedRange.Columns.Count - 3
End Sub
with a watch on a
you will see it does make a difference.
To see command-line flags, use:
gcc -march=native -E -v - </dev/null 2>&1 | grep cc1
If you want to see the compiler/precompiler defines set by certain parameters, do this:
echo | gcc -dM -E - -march=native
for(int i=0;i<str.length();i++)
{
System.out.println(str.charAt(i));
}
If you want to use this answer, I found out that when you are using MacDown on MacOs, you can <div style="text-align: justify">
at the beginning of the document to justify all text and keep all code
formating. Maybe it works on other editors too, for you to try ;)
OrbitControls and TrackballControls seems to be good for this purpose.
controls = new THREE.TrackballControls( camera );
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
update in render
controls.update();
Here's a variant of this answer that uses metaclasses to avoid the messy syntax, and use the typing
-style List[int]
syntax:
class template(type):
def __new__(metacls, f):
cls = type.__new__(metacls, f.__name__, (), {
'_f': f,
'__qualname__': f.__qualname__,
'__module__': f.__module__,
'__doc__': f.__doc__
})
cls.__instances = {}
return cls
def __init__(cls, f): # only needed in 3.5 and below
pass
def __getitem__(cls, item):
if not isinstance(item, tuple):
item = (item,)
try:
return cls.__instances[item]
except KeyError:
cls.__instances[item] = c = cls._f(*item)
item_repr = '[' + ', '.join(repr(i) for i in item) + ']'
c.__name__ = cls.__name__ + item_repr
c.__qualname__ = cls.__qualname__ + item_repr
c.__template__ = cls
return c
def __subclasscheck__(cls, subclass):
for c in subclass.mro():
if getattr(c, '__template__', None) == cls:
return True
return False
def __instancecheck__(cls, instance):
return cls.__subclasscheck__(type(instance))
def __repr__(cls):
import inspect
return '<template {!r}>'.format('{}.{}[{}]'.format(
cls.__module__, cls.__qualname__, str(inspect.signature(cls._f))[1:-1]
))
With this new metaclass, we can rewrite the example in the answer I link to as:
@template
def List(member_type):
class List(list):
def append(self, member):
if not isinstance(member, member_type):
raise TypeError('Attempted to append a "{0}" to a "{1}" which only takes a "{2}"'.format(
type(member).__name__,
type(self).__name__,
member_type.__name__
))
list.append(self, member)
return List
l = List[int]()
l.append(1) # ok
l.append("one") # error
This approach has some nice benefits
print(List) # <template '__main__.List[member_type]'>
print(List[int]) # <class '__main__.List[<class 'int'>, 10]'>
assert List[int] is List[int]
assert issubclass(List[int], List) # True
git add -u .
git add --update .
Try
location ~ ^/(first/location|second/location)/ {
...
}
The ~
means to use a regular expression for the url. The ^
means to check from the first character. This will look for a /
followed by either of the locations and then another /
.
I feel like all the answers showing use of a CTE or Sub Query are sufficient fixes for this, but I don't see anyone getting to the heart of why OP has a problem. The reason why what OP suggested doesn't work is due to logical query processing order here:
- FROM
- ON
- JOIN
- WHERE
- GROUP BY
- WITH CUBE/ROLLUP
- HAVING
- SELECT
- DISTINCT
- ORDER BY
- TOP
- OFFSET/FETCH
I believe this contributes to the answer greatly, because it explains why issues like this one occur. WHERE
is always processed before SELECT
making a CTE or Sub Query necessary for many functions. You will see this a lot in SQL Server.
The @Query annotation allows to execute native queries by setting the nativeQuery flag to true.
Quote from Spring Data JPA reference docs.
Also, see this section on how to do it with a named native query.
As of Vista, cacls
is deprecated. Here's the first couple of help lines:
C:\>cacls
NOTE: Cacls is now deprecated, please use Icacls.
Displays or modifies access control lists (ACLs) of files
You should use icacls
instead. This is how you grant John full control over D:\test
folder and all its subfolders:
C:\>icacls "D:\test" /grant John:(OI)(CI)F /T
According do MS documentation:
F
= Full ControlCI
= Container Inherit - This flag indicates that subordinate containers will inherit this ACE.OI
= Object Inherit - This flag indicates that subordinate files will inherit the ACE./T
= Apply recursively to existing files and sub-folders. (OI
and CI
only apply to new files and sub-folders). Credit: comment by @AlexSpence.For complete documentation, you may run "icacls
" with no arguments or see the Microsoft documentation here and here
Run gpresult
at a Windows command prompt. You'll get an abundance of information about the current domain, current user, user & computer security groups, group policy names, Active Directory Distinguished Name, and so on.
It seems to be a python bug (that works perfectly in vim).
The source of the problem is the (\s*...)+ bit. Basically , you can't do (\s*)+
which make sense , because you are trying to repeat something which can be null.
>>> re.compile(r"(\s*)+")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.py", line 180, in compile
return _compile(pattern, flags)
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.py", line 233, in _compile
raise error, v # invalid expression
sre_constants.error: nothing to repeat
However (\s*\1)
should not be null, but we know it only because we know what's in \1. Apparently python doesn't ... that's weird.
The href is probably generated in a javascript function. For example with jQuery:
$(function() {
$('a.view').attr('href', 'http://www.google.com');
});
As explained in the documentation, by using an @RequestParam
annotation:
public @ResponseBody String byParameter(@RequestParam("foo") String foo) {
return "Mapped by path + method + presence of query parameter! (MappingController) - foo = "
+ foo;
}
Indeed this relies on the programmer's preferences. I personally use: numeric(15,4)
to conform to the Generally Accepted Accounting Principles (GAAP).
In addition to CMS´ answer you may want to consider putting the style in an external stylesheet and assign the style to the id, like this:
#divCheckbox {
display: none;
}
The reason for my answer on this is because the most upvoted answer itself failed to solve my problem. I have figured out this problem by doing this.
<activity android:name="NAME OF YOUR ACTIVITY"
android:label="" />
Hope this will help others too.
It's is the best solution:
Car
.find()
.populate({
path: 'pages.page.components'
})
You need to make your anchor display: block
or display: inline-block;
and then it will accept the width and height values.
Please Try to pass parameters in httpoptions
, you can follow function below
deleteAction(url, data) {
const authToken = sessionStorage.getItem('authtoken');
const options = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
Authorization: 'Bearer ' + authToken,
}),
body: data,
};
return this.client.delete(url, options);
}
You want to use the stringizing operator:
#define STRING(s) #s
int main()
{
const char * cstr = STRING(abc); //cstr == "abc"
}
In many cases, you have an interface and pass along an object that implements it. Dialogs for example have the OnClickListener.
Just as a random example:
// The callback interface
interface MyCallback {
void callbackCall();
}
// The class that takes the callback
class Worker {
MyCallback callback;
void onEvent() {
callback.callbackCall();
}
}
// Option 1:
class Callback implements MyCallback {
void callbackCall() {
// callback code goes here
}
}
worker.callback = new Callback();
// Option 2:
worker.callback = new MyCallback() {
void callbackCall() {
// callback code goes here
}
};
I probably messed up the syntax in option 2. It's early.
Very interesting question.
I don't see any difference w.r.t safety or versatility, since you can do the same thing with pointer or reference. I also don't think there is any visible difference in performance since references are implemented by pointers.
But I think using reference is better because it is consistent with the standard library. For example, chaining in iostream is done by reference rather than pointer.
mylist = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
print mylist
j=0
for i in mylist:
mylist[j]=i.rstrip("8")
j+=1
print mylist
var pinIcon = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(12, 18)
);
When you define a Foreign Key in table B referencing the Primary Key of table A it means that when a value is in B, it must be in A. This is to prevent unconsistent modifications to the tables.
In your example, your tables contain:
tblDomare with PRIMARY KEY (PersNR)
:
PersNR |fNamn |eNamn |Erfarenhet
-----------|----------|-----------|----------
6811034679 |'Bengt' |'Carlberg' |10
7606091347 |'Josefin' |'Backman' |4
8508284163 |'Johanna' |'Backman' |1
---------------------------------------------
tblBana:
BanNR
-----
1
2
3
-----
This statement:
ALTER TABLE tblDomare
ADD FOREIGN KEY (PersNR)
REFERENCES tblBana(BanNR);
says that any line in tblDomare
with key PersNR
must have a correspondence in table tblBana
on key BanNR
. Your error is because you have lines inserted in tblDomare
with no correspondence in tblBana
.
2 solutions to fix your issue:
tblBana
with BanNR in (6811034679, 7606091347, 8508284163)tblDomare
that have no correspondence in tblBana
(but your table would be empty)General advice: you should have the Foreign Key constraint before populating the tables. Foreign keys are here to prevent the user of the table from filling the tables with inconsistencies.
I expand on spectra‘s answer so people don’t have to try it for themselves.
This was done on Oracle Database 11g Express Edition Release 11.2.0.2.0 - Production.
CREATE TABLE CUSTOMERS
(
CUSTOMER_ID NUMBER NOT NULL,
FOO FLOAT NOT NULL,
JOIN_DATE DATE NOT NULL,
CUSTOMER_STATUS VARCHAR2(8) NOT NULL,
CUSTOMER_NAME VARCHAR2(20) NOT NULL,
CREDITRATING VARCHAR2(10)
);
select column_name, data_type, nullable, data_length, data_precision, data_scale
from user_tab_columns where table_name ='CUSTOMERS';
Which yields
COLUMN_NAME DATA_TYPE NULLABLE DATA_LENGTH DATA_PRECISION DATA_SCALE
CUSTOMER_ID NUMBER N 22
FOO FLOAT N 22 126
JOIN_DATE DATE N 7
CUSTOMER_STATUS VARCHAR2 N 8
CUSTOMER_NAME VARCHAR2 N 20
CREDITRATING VARCHAR2 Y 10
You can specify hosting URL without any changes to your app.
Create a Properties/launchSettings.json
file in your project directory and fill it with something like this:
{
"profiles": {
"MyApp1-Dev": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:5001/"
}
}
}
dotnet run
command should pick your launchSettings.json
file and will display it in the console:
C:\ProjectPath [master =]
? dotnet run
Using launch settings from C:\ProjectPath\Properties\launchSettings.json...
Hosting environment: Development
Content root path: C:\ProjectPath
Now listening on: http://localhost:5001
Application started. Press Ctrl+C to shut down.
More details: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments
you need to use add class open
in <div class="btn-group open">
and in li
add class="active"
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
final RelativeLayout relativeLayout = new RelativeLayout(this);
final TextView tv1 = new TextView(this);
tv1.setText("tv1 is here");
// Setting an ID is mandatory.
tv1.setId(View.generateViewId());
relativeLayout.addView(tv1);
final TextView tv2 = new TextView(this);
tv2.setText("tv2 is here");
// We are defining layout params for tv2 which will be added to its parent relativelayout.
// The type of the LayoutParams depends on the parent type.
RelativeLayout.LayoutParams tv2LayoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
//Also, we want tv2 to appear below tv1, so we are adding rule to tv2LayoutParams.
tv2LayoutParams.addRule(RelativeLayout.BELOW, tv1.getId());
//Now, adding the child view tv2 to relativelayout, and setting tv2LayoutParams to be set on view tv2.
relativeLayout.addView(tv2);
tv2.setLayoutParams(tv2LayoutParams);
//Or we can combined the above two steps in one line of code
//relativeLayout.addView(tv2, tv2LayoutParams);
this.setContentView(relativeLayout);
}
}
The following code -
element.sendKeys("");
tries to find an input tag box to enter some information, while
new Actions(driver).moveToElement(element).perform();
is more appropriate as it will work for image elements, link elements, dropdown boxes etc.
Therefore using moveToElement() method makes more sense to focus on any generic WebElement on the web page.
For an input box you will have to click() on the element to focus.
new Actions(driver).moveToElement(element).click().perform();
while for links and images the mouse will be over that particular element,you can decide to click() on it depending on what you want to do.
If the click() on an input tag does not work -
Since you want this function to be generic, you first check if the webElement is an input tag or not by -
if("input".equals(element.getTagName()){
element.sendKeys("");
}
else{
new Actions(driver).moveToElement(element).perform();
}
You can make similar changes based on your preferences.
If you use a JavaScript library, consider Dojo Toolkit which is compatible (after minor modifications) with the Closure Compiler's Advanced mode compilation.
Dojo – The Only JavaScript Library Compatible with The Closure Compiler
Code compiled with Closure Advanced mode is almost impossible to reverse-engineer, even passing through a beautifier, as the entire code base (includinhg the library) is obfuscated. It is also 25% small on average.
JavaScript code that is merely minified (YUI Compressor, Uglify etc.) is easy to reverse-engineer after passing through a beautifier.
Since I can't comment, let me do this in the form of an answer:
to build on culebrón's answer or Yuji 'Tomita' Tomita's answer, the dictionary passed into the function is in the form of a string, so perhaps use ast.literal_eval to convert the string to a dictionary first, like in this example.
With this edit, the code should look like this:
# code for custom template tag
@register.filter(name='lookup')
def lookup(value, arg):
value_dict = ast.literal_eval(value)
return value_dict.get(arg)
<!--template tag (in the template)-->
{{ mydict|lookup:item.name }}
I've created a function to handle sed
difference between MacOS (tested on MacOS 10.12) and other OS:
OS=`uname`
# $(replace_in_file pattern file)
function replace_in_file() {
if [ "$OS" = 'Darwin' ]; then
# for MacOS
sed -i '' -e "$1" "$2"
else
# for Linux and Windows
sed -i'' -e "$1" "$2"
fi
}
Usage:
$(replace_in_file 's,MASTER_HOST.*,MASTER_HOST='"$MASTER_IP"',' "./mysql/.env")
Where:
,
is a delimeter
's,MASTER_HOST.*,MASTER_HOST='"$MASTER_IP"','
is pattern
"./mysql/.env"
is path to file
Alternatively, If you are using Apache then you can use .htaccess
file to enforce your URLs to use https
prefix. On Laravel 5.4, I added the following lines to my .htaccess
file and it worked for me.
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
No, goto
is not used, but you can define labels and leave a loop up to the label. You can use break
or continue
followed by the label. So you can jump out more than one loop level. Have a look at the tutorial.
If url
helper is loaded, use
current_url();
will be better
Try ISDATE()
function in SQL Server. If 1, select valid date. If 0 selects invalid dates.
SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)
FROM AuditTrail
WHERE ISDATE(LoginTime) = 1
EDIT :
As per your update i need to extract the date only and remove the time, then you could simply use the inner CONVERT
SELECT CONVERT(VARCHAR, LoginTime, 101) FROM AuditTrail
or
SELECT LEFT(LoginTime,10) FROM AuditTrail
EDIT 2 :
The major reason for the error will be in your date in WHERE clause.ie,
SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <=
CAST('06/18/2012' AS DATE)
will be different from
SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <=
CAST('18/06/2012' AS DATE)
CONCLUSION
In EDIT 2 the first query tries to filter in mm/dd/yyyy
format, while the second query tries to filter in dd/mm/yyyy
format. Either of them will fail and throws error
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
So please make sure to filter date either with mm/dd/yyyy
or with dd/mm/yyyy
format, whichever works in your db.
Interestingly no one answers the question, OP isn't using a strongly typed int[]
but an Array
.
You have to cast the Array
to what it actually is, an int[]
, then you can use ToList
:
List<int> intList = ((int[])ints).ToList();
Note that Enumerable.ToList
calls the list constructor that first checks if the argument can be casted to ICollection<T>
(which an array implements), then it will use the more efficient ICollection<T>.CopyTo
method instead of enumerating the sequence.
Enable the log for table
mysql> SET GLOBAL general_log = 'ON';
mysql> SET global log_output = 'table';
View log by select query
select * from mysql.general_log
Based on the other answers, here is how I got the numbers I needed in Python;
from decimal import Decimal
def gcd(a,b):
if b == 0:
return a
return gcd(b, a%b)
def closest_aspect_ratio(width, height):
g = gcd(width, height)
x = Decimal(str(float(width)/float(g)))
y = Decimal(str(float(height)/float(g)))
dec = Decimal(str(x/y))
return dict(x=x, y=y, dec=dec)
>>> closest_aspect_ratio(1024, 768)
{'y': Decimal('3.0'),
'x': Decimal('4.0'),
'dec': Decimal('1.333333333333333333333333333')}
my_data
is a struct with name
as a field and data[]
is arry of structs, you are initializing each index. read following:
5.20 Designated Initializers:
In a structure initializer, specify the name of a field to initialize with
.fieldname ='
before the element value. For example, given the following structure,struct point { int x, y; };
the following initialization
struct point p = { .y = yvalue, .x = xvalue };
is equivalent to
struct point p = { xvalue, yvalue };
Another syntax which has the same meaning, obsolete since GCC 2.5, is
fieldname:'
, as shown here:struct point p = { y: yvalue, x: xvalue };
You can also write:
my_data data[] = {
{ .name = "Peter" },
{ .name = "James" },
{ .name = "John" },
{ .name = "Mike" }
};
as:
my_data data[] = {
[0] = { .name = "Peter" },
[1] = { .name = "James" },
[2] = { .name = "John" },
[3] = { .name = "Mike" }
};
or:
my_data data[] = {
[0].name = "Peter",
[1].name = "James",
[2].name = "John",
[3].name = "Mike"
};
Second and third forms may be convenient as you don't need to write in order for example all of the above example are equivalent to:
my_data data[] = {
[3].name = "Mike",
[1].name = "James",
[0].name = "Peter",
[2].name = "John"
};
If you have multiple fields in your struct (for example, an int age
), you can initialize all of them at once using the following:
my_data data[] = {
[3].name = "Mike",
[2].age = 40,
[1].name = "James",
[3].age = 23,
[0].name = "Peter",
[2].name = "John"
};
To understand array initialization read Strange initializer expression?
Additionally, you may also like to read @Shafik Yaghmour's answer for switch case: What is “…” in switch-case in C code
Use getRGB(), it helps ( no complicated programs )
Returns an array of integer pixels in the default RGB color model (TYPE_INT_ARGB) and default sRGB color space, from a portion of the image data.
To my knowledge these are the rules for calling subroutines and functions in VBScript:
Call
keyword enclose the arguments in parenthesisSince you probably wont be using the Call
keyword you only need to learn the rule that if you call a function and want to assign or use the return value you need to enclose the arguments in parenthesis. Otherwise, don't use parenthesis.
Here are some examples:
WScript.Echo 1, "two", 3.3
- calling a subroutine
WScript.Echo(1, "two", 3.3)
- syntax error
Call WScript.Echo(1, "two", 3.3)
- keyword Call
requires parenthesis
MsgBox "Error"
- calling a function "like" a subroutine
result = MsgBox("Continue?", 4)
- calling a function where the return value is used
WScript.Echo (1 + 2)*3, ("two"), (((3.3)))
- calling a subroutine where the arguments are computed by expressions involving parenthesis (note that if you surround a variable by parenthesis in an argument list it changes the behavior from call by reference to call by value)
WScript.Echo(1)
- apparently this is a subroutine call using parenthesis but in reality the argument is simply the expression (1)
and that is what tends to confuse people that are used to other programming languages where you have to specify parenthesis when calling subroutines
I'm not sure how to interpret your example, Randomize()
. Randomize
is a subroutine that accepts a single optional argument but even if the subroutine didn't have any arguments it is acceptable to call it with an empty pair of parenthesis. It seems that the VBScript parser has a special rule for an empty argument list. However, my advice is to avoid this special construct and simply call any subroutine without using parenthesis.
I'm quite sure that these syntactic rules applies across different versions of operating systems.
Multiply by 1.
result = 1. * a / b
or, using the float function
result = float(a) / b
I think this is a solution that solves your problem easily: (return true if any of the parameters is not null)
public boolean isUserEmpty(){
boolean isEmpty;
isEmpty = isEmpty = Stream.of(id,
name)
.anyMatch(userParameter -> userParameter != null);
return isEmpty;}
Another solution to the same task is:(you can change it to if(isEmpty==0) checks if all the parameters are null.
public boolean isUserEmpty(){
long isEmpty;
isEmpty = Stream.of(id,
name)
.filter(userParameter -> userParameter != null).count();
if (isEmpty > 0) {
return true;
} else {
return false;
}
}
Using you current code, make this tweak:
public void listf(String directoryName, List<File> files) {
File directory = new File(directoryName);
// Get all files from a directory.
File[] fList = directory.listFiles();
if(fList != null)
for (File file : fList) {
if (file.isFile()) {
files.add(file);
} else if (file.isDirectory()) {
listf(file.getAbsolutePath(), files);
}
}
}
}
I got the resources on C# (Desktop WPF W/ .NET Framework 4.8) using the code below
{DefaultNamespace}.Properties.Resources.{ResourceName}