Factors are paired. 1
and 24
, 2
and 12
, 3
and 8
, 4
and 6
.
An improvement of your algorithm could be to iterate to the square root of num
instead of all the way to num
, and then calculate the paired factors using num / i
.
Here is another alternate without reduce that performs well with large numbers. It uses sum
to flatten the list.
def factors(n):
return set(sum([[i, n//i] for i in xrange(1, int(n**0.5)+1) if not n%i], []))
There is actually a truly invisible character: U+FEFF
.
This character is called the Byte Order Mark and is related to the Unicode 8 system. It is a really confusing concept that can be explained HERE The Byte Order Mark or BOM
for short is an invisible character that doesn't take up any space. You can copy the character bellow between the >
and <
.
Here is the character:
> <
How to catch this character in action:
>
and <
,You will notice that when your caret gets to the place you pasted the character, it will briefly stop for around half a second. This is becuase the caret is passing over the invisible character. Even though you can't see it doesn't mean it isn't there. The caret still sees that there is a character in that area that you pasted the BOM and will pass through it. Since the BOM is invisble, the caret will look like it has paused for a brief moment. You can past the BOM multiple times in an area and redo the steps above to really show the affect. Good luck!
EDIT: Sadly, Stackoverflow doesn't like the character. Here is an example from w3.org: https://www.w3.org/International/questions/examples/phpbomtest.php
select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
from (select id, name, author_id, count(1) as count_1
from names
group by id, name, author_id) n1
inner join (select distinct(author_id), count(1) as total_count
from names) n2
on (n2.author_id = n1.author_id)
Where true
used distinct
if more inner join, because more join group performance is slow
The above suggestion works, but only if the annotation is used on the getter method. If the annotations is used where the member is declared, nothing will happen.
public String getStringValue(){
return (this.stringValue == null) ? "Default" : stringValue;
}
This like a trick,
UILabel *customLabel = [[UILabel alloc] init];
UIColor *color = [UIColor blueColor];
customLabel.layer.shadowColor = [color CGColor];
customLabel.layer.shadowRadius = 5.0f;
customLabel.layer.shadowOpacity = 1;
customLabel.layer.shadowOffset = CGSizeZero;
customLabel.layer.masksToBounds = NO;
I also tried to update a component from a jsf backing bean/class
You need to do the following after manipulating the UI component:
FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add(componentToBeRerendered.getClientId())
It is important to use the clientId instead of the (server-side) componentId!!
This will also happen when your module- and/or project-jdk aren't properly configured.
Execute the following procedure for example as user system.
Set p_owner to the schema owner and p_readonly to the name of the readonly user.
create or replace
procedure createReadOnlyUser(p_owner in varchar2, p_readonly in varchar2)
AUTHID CURRENT_USER is
BEGIN
execute immediate 'create user '||p_readonly||' identified by '||p_readonly;
execute immediate 'grant create session to '||p_readonly;
execute immediate 'grant select any dictionary to '||p_readonly;
execute immediate 'grant create synonym to '||p_readonly;
FOR R IN (SELECT owner, object_name from all_objects where object_type in('TABLE', 'VIEW') and owner=p_owner) LOOP
execute immediate 'grant select on '||p_owner||'.'||R.object_name||' to '||p_readonly;
END LOOP;
FOR R IN (SELECT owner, object_name from all_objects where object_type in('FUNCTION', 'PROCEDURE') and owner=p_owner) LOOP
execute immediate 'grant execute on '||p_owner||'.'||R.object_name||' to '||p_readonly;
END LOOP;
FOR R IN (SELECT owner, object_name FROM all_objects WHERE object_type in('TABLE', 'VIEW') and owner=p_owner) LOOP
EXECUTE IMMEDIATE 'create synonym '||p_readonly||'.'||R.object_name||' for '||R.owner||'."'||R.object_name||'"';
END LOOP;
FOR R IN (SELECT owner, object_name from all_objects where object_type in('FUNCTION', 'PROCEDURE') and owner=p_owner) LOOP
execute immediate 'create synonym '||p_readonly||'.'||R.object_name||' for '||R.owner||'."'||R.object_name||'"';
END LOOP;
END;
Probably is the use of the "on" event that Bootstrap use a lot and was inserted at jQuery 1.7 http://api.jquery.com/on/
If you don't want to have it point to anything, you probably shouldn't be using the <a>
(anchor) tag.
If you want something to look like a link but not act like a link, it's best to use the appropriate element (such as <span>
) and then style it using CSS:
<span class="fake-link" id="fake-link-1">Am I a link?</span>
.fake-link {
color: blue;
text-decoration: underline;
cursor: pointer;
}
Also, given that you tagged this question "jQuery", I am assuming that you want to attach a click event hander. If so, just do the same thing as above and then use something like the following JavaScript:
$('#fake-link-1').click(function() {
/* put your code here */
});
Unfortunately, adding the javaee-(web)-api as a dependency doesn't give you the Javadoc or the Source to the Servlet Api to browse them from within the IDE. This is also the case for all other dependencies (JPA, EJB, ...) If you need the Servlet API sources/javadoc, you can add the following to your pom.xml (works at least for JBoss&Glassfish):
Repository:
<repository>
<id>jboss-public-repository-group</id>
<name>JBoss Public Repository Group</name>
<url>https://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
Dependency:
<!-- Servlet 3.0 Api Specification -->
<dependency>
<groupId>org.jboss.spec.javax.servlet</groupId>
<artifactId>jboss-servlet-api_3.0_spec</artifactId>
<version>1.0.0.Beta2</version>
<scope>provided</scope>
</dependency>
I completely removed the javaee-api from my dependencies and replaced it with the discrete parts (javax.ejb, javax.faces, ...) to get the sources and Javadocs for all parts of Java EE 6.
EDIT:
Here is the equivalent Glassfish dependency (although both dependencies should work, no matter what appserver you use).
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.servlet</artifactId>
<version>3.0</version>
<scope>provided</scope>
</dependency>
basically hidden fields will be more useful and advantages to use with multi step form. we can use hidden fields to pass one step information to next step using hidden and keep it forwarding till the end step.
Cross-site request forgery is a very common website vulnerability. Requiring a secret, user-specific token in all form submissions will prevent CSRF attacks since attack sites cannot guess what the proper token is and any form submissions they perform on the behalf of the user will always fail.
If you need to store what step in a multi-page form the user is currently on, use hidden input fields. The user doesn't need to see this information, so hide it in a hidden input field.
General rule: Use the field to store anything that the user doesn't need to see, but that you want to send to the server on form submission.
AFAIK, there is no way to do this reliably, unless you switch to an array. Which honestly, doesn't seem strange - it's seems pretty straight forward to me that arrays are countable, and objects aren't.
Probably the closest you'll get is something like this
// Monkey patching on purpose to make a point
Object.prototype.length = function()
{
var i = 0;
for ( var p in this ) i++;
return i;
}
alert( {foo:"bar", bar: "baz"}.length() ); // alerts 3
But this creates problems, or at least questions. All user-created properties are counted, including the _length function itself! And while in this simple example you could avoid it by just using a normal function, that doesn't mean you can stop other scripts from doing this. so what do you do? Ignore function properties?
Object.prototype.length = function()
{
var i = 0;
for ( var p in this )
{
if ( 'function' == typeof this[p] ) continue;
i++;
}
return i;
}
alert( {foo:"bar", bar: "baz"}.length() ); // alerts 2
In the end, I think you should probably ditch the idea of making your objects countable and figure out another way to do whatever it is you're doing.
You do not need to do with web.config You can use short property during catch value of the passing list For example declare a model like
public class BookModel
{
public decimal id { get; set; } // 1
public string BN { get; set; } // 2 Book Name
public string BC { get; set; } // 3 Bar Code Number
public string BE { get; set; } // 4 Edition Name
public string BAL { get; set; } // 5 Academic Level
public string BCAT { get; set; } // 6 Category
}
here i use short proporties like BC =barcode BE=book edition and so on
There is no automated uninstaller.
You have to remove Eclipse manually. At least Eclipse does not write anything in the system registry, so deleting some directories and files is enough.
Note: I use Unix style paths in this answer but the locations should be the same on Windows or Unix systems, so ~
refers to the user home directory even on Windows.
According to this discussion about uninstalling Eclipse, the reasoning for not providing an uninstaller is that the Eclipse installer is supposed to just automate a few tasks that in the past had to be done manually (like downloading and extracting Eclipse and adding shortcuts), so they also can be undone manually. There is no entry in "Programs and Features" because the installer does not register anything in the system registry.
Just delete the Eclipse directory and any desktop and start menu shortcuts and be done with it, if you don't mind a few leftover files.
In my opinion this is generally enough and I would stop here, because multiple Eclipse installations can share some files and you don't accidentally want to delete those shared files. You also keep all your projects.
If you really want to remove Eclipse without leaving any traces, you have to manually delete
~/eclipse/photon/
)The installer has a "Bundle Pools" menu entry which lists the locations of all bundle pools. If you have other Eclipse installations on your system you can use the "Cleanup Agent" to clean up unused bundles. If you don't have any other Eclipse installations you can delete the whole bundle pool directory instead (by default ~/p2/
).
If you want to completely remove the Eclipse installer too, delete the installer's executable and the ~/.eclipse/
directory.
Depending on what kind of work you did with Eclipse, there can be more directories that you may want to delete. If you used Maven, then ~/.m2/
contains the Maven cache and settings (shared with Maven CLI and other IDEs). If you develop Eclipse plugins, then there might be JUnit workspaces from test runs, next to you Eclipse workspace. Likewise other build tools and development environments used in Eclipse could have created similar directories.
If you want to delete your projects and workspace metadata, you have to delete your workspace(s). The default workspace location is ´~/workspace/´. You can also search for the .metadata
directory to get all Eclipse workspaces on your machine.
If you are working with Git projects, these are generally not saved in the workspace but in the ~/git/
directory.
Basically, there are three main characters which should be always escaped in your HTML and XML files, so they don't interact with the rest of the markups, so as you probably expect, two of them gonna be the syntax wrappers, which are <>, they are listed as below:
1) < (<)
2) > (>)
3) & (&)
Also we may use double-quote (") as " and the single quote (') as &apos
Avoid putting dynamic content in <script>
and <style>
.These rules are not for applied for them. For example, if you have to include JSON in a , replace < with \x3c, the U+2028 character with \u2028, and U+2029 with \u2029 after JSON serialisation.)
HTML Escape Characters: Complete List: http://www.theukwebdesigncompany.com/articles/entity-escape-characters.php
So you need to escape <, or & when followed by anything that could begin a character reference. Also The rule on ampersands is the only such rule for quoted attributes, as the matching quotation mark is the only thing that will terminate one. But if you don’t want to terminate the attribute value there, escape the quotation mark.
Changing to UTF-8 means re-saving your file:
Using the character encoding UTF-8 for your page means that you can avoid the need for most escapes and just work with characters. Note, however, that to change the encoding of your document, it is not enough to just change the encoding declaration at the top of the page or on the server. You need to re-save your document in that encoding. For help understanding how to do that with your application read Setting encoding in web authoring applications.Invisible or ambiguous characters:
A particularly useful role for escapes is to represent characters that are invisible or ambiguous in presentation.
One example would be Unicode character U+200F RIGHT-TO-LEFT MARK. This character can be used to clarify directionality in bidirectional text (eg. when using the Arabic or Hebrew scripts). It has no graphic form, however, so it is difficult to see where these characters are in the text, and if they are lost or forgotten they could create unexpected results during later editing. Using ? (or its numeric character reference equivalent ?) instead makes it very easy to spot these characters.
An example of an ambiguous character is U+00A0 NO-BREAK SPACE. This type of space prevents line breaking, but it looks just like any other space when used as a character. Using makes it quite clear where such spaces appear in the text.
Windows 10 home version with latest android studio (Nov/2019):
Enable virtualization from BIOS. If you have a laptop, google how to access the BIOS.
Enable via Windows Features: "Windows Hypervisor Platform". Restart. No need for Hyper-V and Win10 Pro.
Done. Open Android Studio, the annoying warning is gone, emulator starts just fine.
setTimeout would not hold and resume on your own thread however Thread.sleep does. There is no actual equal in Javascript
Rather than using a proxy, I'm using the Firefox plugin "Modify Headers" to insert headers (in my case, to fake a login using the Single Sign On so I can test as different people).
The warning:
deprecated conversion from string constant to 'char*'
is given because you are doing somewhere (not in the code you posted) something like:
void foo(char* str);
foo("hello");
The problem is that you are trying to convert a string literal (with type const char[]
) to char*
.
You can convert a const char[]
to const char*
because the array decays to the pointer, but what you are doing is making a mutable a constant.
This conversion is probably allowed for C compatibility and just gives you the warning mentioned.
string str = intVar.ToString();
In some conditions, you do not have to use ToString()
string str = "hi " + intVar;
Also as a minor enhancement.
The main reason for the try/catch block is that e1 could be null for the initial movement. in addition to the try/catch, include a test for null and return. similar to the following
if (e1 == null || e2 == null) return false;
try {
...
} catch (Exception e) {}
return false;
You can't do this, which is by design. The Django framework authors intended a strict separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation logic.
So you have several options. The easiest is to do the filtering, then pass the result to render_to_response
. Or you could write a method in your model so that you can say {% for object in data.filtered_set %}
. Finally, you could write your own template tag, although in this specific case I would advise against that.
Use count(d.ertek)
or count(d.id)
instead of count(d)
. This can be happen when you have composite primary key at your entity.
"matt b" has it right, but to be specific, the "install" goal copies your built target to the local repository on your file system; useful for small changes across projects not currently meant for the full group.
The "deploy" goal uploads it to your shared repository for when your work is finished, and then can be shared by other people who require it for their project.
In your case, it seems that "install" is used to make the management of the deployment easier since CI's local repo is the shared repo. If CI was on another box, it would have to use the "deploy" goal.
I found that the following code, when inserted into the site's footer, worked well enough:
<script type="text/javascript">
$("#nav-ask").remove();
</script>
This may or may not require jquery. The site I'm editing has jquery, but unfortunately I'm no javascripter, so I only have a limited knowledge of what's going on here, and the requirements of this code snippet...
Try using a wildcard like this
=VLOOKUP(LEFT(A1,3)&"*",B$2:B$22,1,FALSE)
so if A1 is "barry" that formula will return the first value in B2:B22
that starts with "bar"
<c:set var="baseURL" value="${pageContext.request.requestURL.substring(0, pageContext.request.requestURL.length() - pageContext.request.requestURI.length())}${pageContext.request.contextPath}/" />
<head>
<base href="${baseURL}" />
First of all, I don't think that your intention is to actually use punctuation as delimiters in the split functions. Your description suggests that you simply want to eliminate punctuation from the resultant strings.
I come across this pretty frequently, and my usual solution doesn't require re.
(requires import string
):
split_without_punc = lambda text : [word.strip(string.punctuation) for word in
text.split() if word.strip(string.punctuation) != '']
# Call function
split_without_punc("Hey, you -- what are you doing?!")
# returns ['Hey', 'you', 'what', 'are', 'you', 'doing']
As a traditional function, this is still only two lines with a list comprehension (in addition to import string
):
def split_without_punctuation2(text):
# Split by whitespace
words = text.split()
# Strip punctuation from each word
return [word.strip(ignore) for word in words if word.strip(ignore) != '']
split_without_punctuation2("Hey, you -- what are you doing?!")
# returns ['Hey', 'you', 'what', 'are', 'you', 'doing']
It will also naturally leave contractions and hyphenated words intact. You can always use text.replace("-", " ")
to turn hyphens into spaces before the split.
For a more general solution (where you can specify the characters to eliminate), and without a list comprehension, you get:
def split_without(text: str, ignore: str) -> list:
# Split by whitespace
split_string = text.split()
# Strip any characters in the ignore string, and ignore empty strings
words = []
for word in split_string:
word = word.strip(ignore)
if word != '':
words.append(word)
return words
# Situation-specific call to general function
import string
final_text = split_without("Hey, you - what are you doing?!", string.punctuation)
# returns ['Hey', 'you', 'what', 'are', 'you', 'doing']
Of course, you can always generalize the lambda function to any specified string of characters as well.
To use uint8_t
type alias, you have to include stdint.h
standard header.
i fought with eclipse 3.5.0 (galileo) for days, i had to use this version because I am doing blackberry development and eclipse comes bundle with blackberry specifics so i need to use the package they bundled, which was not 3.5.0 (not the 3.5.1) , BUT SirFabel saved the day, thanks to all who contributed to this post
I used 3.5.0 and did "Set the following system property in you eclipse.ini file: -Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient For more details on this: wiki.eclipse.org/… - Configure only the HTTP and HTTPS proxies. Not SOCKS!! "
and I am able to get through my companies proxy!!!!
If you want to print the bytes as chars you can use the String constructor.
byte[] bytes = new byte[] { -1, -128, 1, 127 };
System.out.println(new String(bytes, 0));
May be you used notepad++ for creating/updating this file.
EOL(Edit->EOL Conversion) Conversion by default is Windows.
Change EOL Conversion in Notepad++
Edit -> EOL Conversion -> Unix (LF)
def get_dict_from_pd(df, key_col, row_col):
result = dict()
for i in set(df[key_col].values):
is_i = df[key_col] == i
result[i] = list(df[is_i][row_col].values)
return result
this is my sloution, a basic loop
The accepted answer is wrong. The quote is correct, the assertion that PUT and POST must have it is incorrect. There is no requirement that PUT or POST actually have additional content. Nor is there a prohibition against GET actually having content.
The RFCs say exactly what they mean .. IFF your side (client OR origin server) will be sending additional content, beyond the HTTP headers, it SHOULD specify a Content-Type header. But note it is allowable to omit the Content-Type and still include content (say, by using a Content-Length header).
I'm using Edge Version 81.0.416.64 (Official build) (64-bit) and its based on the Chromium open source project.
Press F12 to get into Dev Tools.
Click Network Tab
Check Disable cache
I've modified M-WaJeEh's answer a bit to take into account compound drawables on the sides.
The getCompoundPaddingXXXX()
methods return padding of the view + drawable space
. See for example: TextView.getCompoundPaddingLeft()
Issue: This fixes the measurement of the width and height of the TextView space available for the text. If we don't take the drawable size into account, it is ignored and the text will end up overlapping the drawable.
Updated segment adjustTextSize(String)
:
private void adjustTextSize(final String text) {
if (!mInitialized) {
return;
}
int heightLimit = getMeasuredHeight() - getCompoundPaddingBottom() - getCompoundPaddingTop();
mWidthLimit = getMeasuredWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight();
mAvailableSpaceRect.right = mWidthLimit;
mAvailableSpaceRect.bottom = heightLimit;
int maxTextSplits = text.split(" ").length;
AutoResizeTextView.super.setMaxLines(Math.min(maxTextSplits, mMaxLines));
super.setTextSize(
TypedValue.COMPLEX_UNIT_PX,
binarySearch((int) mMinTextSize, (int) mMaxTextSize,
mSizeTester, mAvailableSpaceRect));
}
When you use df.apply()
, each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label]
.
So this should work:
df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))
I wrote this generic type converter. It works with Nullable and standard values, converting between all convertible types - not just string. It handles all sorts of scenarios that you'd expect (default values, null values, other values, etc...)
I've been using this for about a year in dozens of production programs, so it should be pretty solid.
public static T To<T>(this IConvertible obj)
{
Type t = typeof(T);
if (t.IsGenericType
&& (t.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
if (obj == null)
{
return (T)(object)null;
}
else
{
return (T)Convert.ChangeType(obj, Nullable.GetUnderlyingType(t));
}
}
else
{
return (T)Convert.ChangeType(obj, t);
}
}
public static T ToOrDefault<T>
(this IConvertible obj)
{
try
{
return To<T>(obj);
}
catch
{
return default(T);
}
}
public static bool ToOrDefault<T>
(this IConvertible obj,
out T newObj)
{
try
{
newObj = To<T>(obj);
return true;
}
catch
{
newObj = default(T);
return false;
}
}
public static T ToOrOther<T>
(this IConvertible obj,
T other)
{
try
{
return To<T>(obj);
}
catch
{
return other;
}
}
public static bool ToOrOther<T>
(this IConvertible obj,
out T newObj,
T other)
{
try
{
newObj = To<T>(obj);
return true;
}
catch
{
newObj = other;
return false;
}
}
public static T ToOrNull<T>
(this IConvertible obj)
where T : class
{
try
{
return To<T>(obj);
}
catch
{
return null;
}
}
public static bool ToOrNull<T>
(this IConvertible obj,
out T newObj)
where T : class
{
try
{
newObj = To<T>(obj);
return true;
}
catch
{
newObj = null;
return false;
}
}
Convert hh:mm:ss
string to seconds in one line. Also allowed h:m:s
format and mm:ss
, m:s
etc
'08:45:20'.split(':').reverse().reduce((prev, curr, i) => prev + curr*Math.pow(60, i), 0)
I had this error also, make sure the exe the service is pointing to is stopped. Also make sure you don't have any Windows dialog boxes behind your other windows. That is why mine wasn't deleting. There was a windows message behind it saying this service has been deleted or something similar.. just had to click ok, there it went.
There is the RowIndex
property for the CurrentCell
property for the DataGridView.
datagridview.CurrentCell.RowIndex
Handle the SelectionChanged
event and find the index of the selected row as above.
You can use IsNull function
select
isnull(rtrim(ltrim([FirstName]))+' ','') +
isnull(rtrim(ltrim([SecondName]))+' ','') +
isnull(rtrim(ltrim([Surname]))+' ','') +
isnull(rtrim(ltrim([SecondSurname])),'')
from TableDat
if one column is null you would get an empty char
Compatible with Microsoft SQL Server 2008+
I know it has been answered good few times already, but I like below way of doing this. I hope it will help someone.
//attach object (search for row)
TableName tn = _context.TableNames.Attach(new TableName { PK_COLUMN = YOUR_VALUE});
// set new value
tn.COLUMN_NAME_TO_UPDATE = NEW_COLUMN_VALUE;
// set column as modified
_context.Entry<TableName>(tn).Property(tnp => tnp.COLUMN_NAME_TO_UPDATE).IsModified = true;
// save change
_context.SaveChanges();
If you want to pass a parameter to onCreate() then you have to create a new intent with adding extra and call StartActivity with it. Here is a simple example which i did using this way.
String eczSabit = sa.getItem(position).getValue();
if(!Util.IsNullOrEmpty(eczSabit)){
sabit = Long.parseLong(eczSabit);
Intent intent = new Intent(eczaneSegmentasyon.this,eczaneSegmentasyon.class);
intent.putExtra("sabit", sabit);
startActivity(intent);
}
I found the answer. IE stores passwords in two different locations based on the password type:
%APPDATA%\Microsoft\Credentials
, in encrypted filesHKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\IntelliForms\Storage2
, encrypted with the urlFrom a very good page on NirSoft.com:
Starting from version 7.0 of Internet Explorer, Microsoft completely changed the way that passwords are saved. In previous versions (4.0 - 6.0), all passwords were saved in a special location in the Registry known as the "Protected Storage". In version 7.0 of Internet Explorer, passwords are saved in different locations, depending on the type of password. Each type of passwords has some limitations in password recovery:
AutoComplete Passwords: These passwords are saved in the following location in the Registry:
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\IntelliForms\Storage2
The passwords are encrypted with the URL of the Web sites that asked for the passwords, and thus they can only be recovered if the URLs are stored in the history file. If you clear the history file, IE PassView won't be able to recover the passwords until you visit again the Web sites that asked for the passwords. Alternatively, you can add a list of URLs of Web sites that requires user name/password into the Web sites file (see below).HTTP Authentication Passwords: These passwords are stored in the Credentials file under
Documents and Settings\Application Data\Microsoft\Credentials
, together with login passwords of LAN computers and other passwords. Due to security limitations, IE PassView can recover these passwords only if you have administrator rights.
In my particular case it answers the question of where; and I decided that I don't want to duplicate that. I'll continue to use CredRead
/CredWrite
, where the user can manage their passwords from within an established UI system in Windows.
Many ways to do this. ismember is the first that comes to mind, since it is a set membership action you wish to take. Thus
X = primes(20);
ismember([15 17],X)
ans =
0 1
Since 15 is not prime, but 17 is, ismember has done its job well here.
Of course, find (or any) will also work. But these are not vectorized in the sense that ismember was. We can test to see if 15 is in the set represented by X, but to test both of those numbers will take a loop, or successive tests.
~isempty(find(X == 15))
~isempty(find(X == 17))
or,
any(X == 15)
any(X == 17)
Finally, I would point out that tests for exact values are dangerous if the numbers may be true floats. Tests against integer values as I have shown are easy. But tests against floating point numbers should usually employ a tolerance.
tol = 10*eps;
any(abs(X - 3.1415926535897932384) <= tol)
This is how I did it for one of my projects:
const markdownSaveActionCreator = (newMarkdownLocation, newMarkdownToSave) => ({
type: MARKDOWN_SAVE,
saveLocation: newMarkdownLocation,
savedMarkdownInLocation: newMarkdownToSave
});
const markdownSaveReducer = (state = MARKDOWN_SAVED_ARRAY_DEFAULT, action) => {
let objTemp = {
saveLocation: action.saveLocation,
savedMarkdownInLocation: action.savedMarkdownInLocation
};
switch(action.type) {
case MARKDOWN_SAVE:
return(
state.map(i => {
if (i.saveLocation === objTemp.saveLocation) {
return Object.assign({}, i, objTemp);
}
return i;
})
);
default:
return state;
}
};
Rows("2:2").Select
ActiveWindow.FreezePanes = True
This is the easiest way to freeze the top row. The rule for FreezePanes
is it will freeze the upper left corner from the cell you selected. For example, if you highlight C10, it will freeze between columns B and C, rows 9 and 10. So when you highlight Row 2, it actually freeze between Rows 1 and 2 which is the top row.
Also, the .SplitColumn
or .SplitRow
will split your window once you unfreeze it which is not the way I like.
I don't know if this solves your problem but instead of:
$("#tbIntervalos").find("td").attr("id", horaInicial);
you can just do:
$("#tbIntervalos td#" + horaInicial);
It's just what it says:
inputFile = open((x), encoding = "utf8", "r")
You have specified encoding
as a keyword argument, but "r"
as a positional argument. You can't have positional arguments after keyword arguments. Perhaps you wanted to do:
inputFile = open((x), "r", encoding = "utf8")
I would add the CSS property of float left as seen below. That gets rid of the extra space.
ul li {
float:left;
}
df = pd.DataFrame({'movie': ['thg', 'thg', 'mol', 'mol', 'lob', 'lob'],'rating': [3., 4., 5., np.nan, np.nan, np.nan],'name': ['John','James', np.nan, np.nan, np.nan,np.nan]})
for col in df.columns:
df = df[~pd.isnull(df[col])]
At last! I got the answer to this, the size to edit it in photoshop is: 379x674
You are welcome
You're doing it the right way. Class methods (similar to 'static' methods in C++ or Java) aren't part of the instance, so they have to be referenced directly.
On that note, in your example you'd be better served making 'default_make' a regular method:
#!/usr/bin/ruby
class Truck
def default_make
# Class method.
"mac"
end
def initialize
# Instance method.
puts default_make # gets the default via the class's method.
end
end
myTruck = Truck.new()
Class methods are more useful for utility-type functions that use the class. For example:
#!/usr/bin/ruby
class Truck
attr_accessor :make
def default_make
# Class method.
"mac"
end
def self.buildTrucks(make, count)
truckArray = []
(1..count).each do
truckArray << Truck.new(make)
end
return truckArray
end
def initialize(make = nil)
if( make == nil )
@make = default_make()
else
@make = make
end
end
end
myTrucks = Truck.buildTrucks("Yotota", 4)
myTrucks.each do |truck|
puts truck.make
end
Try this rule before your other rules:
RewriteRule ^(admin|user)($|/) - [L]
This will end the rewriting process.
No special escape sequence is required: you can just type the space directly:
if (char_i_want_to_test == ' ') {
// Do something because it is space
}
In ASCII, space is code 32, so you could specify space by '\x20'
or even 32
, but you really shouldn't do that.
Aside: the word "whitespace" is a catch all for space, tab, newline, and all of that. When you're referring specifically to the ordinary space character, you shouldn't use the term.
You can write directly to an event log. Check the following links:
http://support.microsoft.com/kb/307024
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx
And here's the sample from MSDN:
using System;
using System.Diagnostics;
using System.Threading;
class MySample{
public static void Main(){
// Create the source, if it does not already exist.
if(!EventLog.SourceExists("MySource"))
{
//An event log source should not be created and immediately used.
//There is a latency time to enable the source, it should be created
//prior to executing the application that uses the source.
//Execute this sample a second time to use the new source.
EventLog.CreateEventSource("MySource", "MyNewLog");
Console.WriteLine("CreatedEventSource");
Console.WriteLine("Exiting, execute the application a second time to use the source.");
// The source is created. Exit the application to allow it to be registered.
return;
}
// Create an EventLog instance and assign its source.
EventLog myLog = new EventLog();
myLog.Source = "MySource";
// Write an informational entry to the event log.
myLog.WriteEntry("Writing to event log.");
}
}
Using absolute
as position
is not responsive + mobile friendly. I would suggest using a div
with a background-image
and then placing text in the div
will place text over the image. Depending on your html, you might need to use height
with vh
value
I think something like this should work
-- drop current primary key constraint
ALTER TABLE dbo.persion
DROP CONSTRAINT PK_persionId;
GO
-- add new auto incremented field
ALTER TABLE dbo.persion
ADD pmid BIGINT IDENTITY;
GO
-- create new primary key constraint
ALTER TABLE dbo.persion
ADD CONSTRAINT PK_persionId PRIMARY KEY NONCLUSTERED (pmid, persionId);
GO
Above answers are pretty sufficient. Additional to the onChange
, if you upload a file using drag and drop events, you can get the file in drop
event by accessing eventArgs.dataTransfer.files
.
You can change this in preferences:
DD-MON-RR HH24:MI:SS
into the Date Format field.Here is a screenshot:
Take a look at the FormData object: https://developer.mozilla.org/en/docs/Web/API/FormData
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
If you're using PhpMyAdmin, you can now:
I had over 250 tables to convert. It took a little over 5 minutes.
I found the solution. The answer is very simple. write the below code in your constructor.
import { Component, OnInit, OnDestroy, Input } from "@angular/core";
// Import this, and write at the top of your .ts file
import { HostListener } from "@angular/core";
@Component({
selector: "app-login",
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit, OnDestroy {
// Declare height and width variables
scrHeight:any;
scrWidth:any;
@HostListener('window:resize', ['$event'])
getScreenSize(event?) {
this.scrHeight = window.innerHeight;
this.scrWidth = window.innerWidth;
console.log(this.scrHeight, this.scrWidth);
}
// Constructor
constructor() {
this.getScreenSize();
}
}
====== Working Code (Another) ======
export class Dashboard {
mobHeight: any;
mobWidth: any;
constructor(private router:Router, private http: Http){
this.mobHeight = (window.screen.height) + "px";
this.mobWidth = (window.screen.width) + "px";
console.log(this.mobHeight);
console.log(this.mobWidth)
}
}
[EDIT: this was a stupid suggestion from a time I did not know Vim well enough. Please don't use tabs instead of buffers; tabs are Vim's "window layouts"]
Maybe switch to using tabs?
vim -p a/*.php
opens the same files in tabs
gt
and gT
switch tabs back and forth
:q
closes only the current tab
:qa
closes everything and exits
:tabo
closes everything but the current tab
Take care of performance:
I experienced that at least with EF Core the different answers given here might result in different performance. I'm aware that the OP asked about Linq to SQL, but it seems to me that the same questions occur also with EF Core.
In a specific case I had to handle, the (syntactically nicer) suggestion by Marc Gravell resulted in left joins inside a cross apply -- similarly to what Mike U described -- which had the result that the estimated costs for this specific query were two times as high compared to a query with no cross joins. The server execution times differed by a factor of 3. [1]
The solution by Marc Gravell resulted in a query without cross joins.
Context: I essentially needed to perform two left joins on two tables each of which again required a join to another table. Furthermore, there I had to specify other where-conditions on the tables on which I needed to apply the left join. In addition, I had two inner joins on the main table.
Estimated operator costs:
Server execution times in ms (queries executed 10 times; measured using SET STATISTICS TIME ON):
(The very first run was slower for both queries; seems that something is cached.)
Table sizes:
EF Core version: 2.2.1.
SQL Server version: MS SQL Server 2017 - 14... (on Windows 10).
All relevant tables had indexes on the primary keys only.
My conclusion: it's always recommended to look at the generated SQL since it can really differ.
[1] Interestingly enough, when setting the 'Client statistics' in MS SQL Server Management Studio on, I could see an opposite trend; namely that last run of the solution without cross apply took more than 1s. I suppose that something was going wrong here - maybe with my setup.
IMO, you cannot create an empty Date(java.util)
. You can create a Date
object with null
value and can put a null check.
Date date = new Date(); // Today's date and current time
Date date2 = new Date(0); // Default date and time
Date date3 = null; //Date object with null as value.
if(null != date3) {
// do your work.
}
by not causing the errors:
defined('DIR_FS_CATALOG') || define('DIR_FS_CATALOG', 'whatever');
If you really have to, then change error reporting using error_reporting() to E_ALL^E_NOTICE.
Here is the example in docs:
// with query, resulting in /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
Ref: https://router.vuejs.org/en/essentials/navigation.html
As mentioned in those docs, router.replace
works like router.push
So, you seem to have it right in your sample code in question. But I think you may need to include either name
or path
parameter also, so that the router has some route to navigate to. Without a name
or path
, it does not look very meaningful.
This is my current understanding now:
query
is optional for router - some additional info for the component to construct the viewname
or path
is mandatory - it decides what component to show in your <router-view>
.That might be the missing thing in your sample code.
EDIT: Additional details after comments
Have you tried using named routes in this case? You have dynamic routes, and it is easier to provide params and query separately:
routes: [
{ name: 'user-view', path: '/user/:id', component: UserView },
// other routes
]
and then in your methods:
this.$router.replace({ name: "user-view", params: {id:"123"}, query: {q1: "q1"} })
Technically there is no difference between the above and this.$router.replace({path: "/user/123", query:{q1: "q1"}})
, but it is easier to supply dynamic params on named routes than composing the route string. But in either cases, query params should be taken into account. In either case, I couldn't find anything wrong with the way query params are handled.
After you are inside the route, you can fetch your dynamic params as this.$route.params.id
and your query params as this.$route.query.q1
.
If you're using IntelliJ, you can simply go to Preferences -> Build, Execution, Deployment -> Build Tools -> Maven and check/uncheck Work offline.
In VB.NET, you can apply multiple conditions even if the other conditions don't apply to the Select parameter. See below:
Select Case parameter
Case "userID"
' does something here.
Case "packageID"
' does something here.
Case "mvrType" And otherFactor
' does something here.
Case Else
' does some processing...
End Select
SELECT distinct
group,
max_date = MAX(date) OVER (PARTITION BY group), checks
FROM table
Should work.
You don't actually need to run a command from an xterm session, you can run it directly:
String[] arguments = new String[] {"/path/to/executable", "arg0", "arg1", "etc"};
Process proc = new ProcessBuilder(arguments).start();
If the process responds interactively to the input stream, and you want to inject values, then do what you did before:
OutputStream out = proc.getOutputStream();
out.write("command\n");
out.flush();
Don't forget the '\n' at the end though as most apps will use it to identify the end of a single command's input.
Typically you model the enum itself as a class with the enum
stereotype
You have installed the incorrect package named 'serial'.
pip uninstall serial
for python 2.x or pip3 uninstall serial
for python 3.x pip install pyserial
for python 2.x orpip3 install pyserial
for python 3.x.With <iomanip>
, you can use std::fixed
and std::setprecision
Here is an example
#include <iostream>
#include <iomanip>
int main()
{
double d = 122.345;
std::cout << std::fixed;
std::cout << std::setprecision(2);
std::cout << d;
}
And you will get output
122.34
You can set up logrotate to clear the logs periodically.
Example file in /etc/logrotate.d/docker-logs
/var/lib/docker/containers/*/*.log {
rotate 7
daily
compress
size=50M
missingok
delaycompress
copytruncate
}
You can locate a file named listener.ora
under the installation folder oraclexe\app\oracle\product\11.2.0\server\network\ADMIN
It contains the following entries
SID_LIST_LISTENER =
(SID_LIST =
(SID_DESC =
(SID_NAME = PLSExtProc)
(ORACLE_HOME = C:\oraclexe\app\oracle\product\11.2.0\server)
(PROGRAM = extproc)
)
(SID_DESC =
(SID_NAME = CLRExtProc)
(ORACLE_HOME = C:\oraclexe\app\oracle\product\11.2.0\server)
(PROGRAM = extproc)
)
)
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
(ADDRESS = (PROTOCOL = TCP)(HOST = Codemaker-PC)(PORT = 1521))
)
)
DEFAULT_SERVICE_LISTENER = (XE)
You should verify the HOST (Here it is Codemaker-PC) should be the computer name. If it's not correct the change it as computer name.
then try the following command on the command prompt run as administrator,
lsnrctl start
I realise this is a little late but you could add the following to your code. This won't work for transparent pngs though, you'd need a cropping mask for that. Which I'm now going to see about.
outerLink {
overflow: hidden;
position: relative;
}
outerLink:hover:after {
background: #000;
content: "";
display: block;
height: 100%;
left: 0;
opacity: 0.5;
position: absolute;
top: 0;
width: 100%;
}
I use EasyGit (a.k.a. "eg") as a super lightweight wrapper on top of (or along side of) Git. EasyGit has an "info" subcommand that gives you all kinds of super useful information, including the current branches remote tracking branch. Here's an example (where the current branch name is "foo"):
pknotz@s883422: (foo) ~/workspace/bd $ eg info Total commits: 175 Local repository: .git Named remote repositories: (name -> location) origin -> git://sahp7577/home/pknotz/bd.git Current branch: foo Cryptographic checksum (sha1sum): bd248d1de7d759eb48e8b5ff3bfb3bb0eca4c5bf Default pull/push repository: origin Default pull/push options: branch.foo.remote = origin branch.foo.merge = refs/heads/aal_devel_1 Number of contributors: 3 Number of files: 28 Number of directories: 20 Biggest file size, in bytes: 32473 (pygooglechart-0.2.0/COPYING) Commits: 62
UPDATE table_name SET attrs = jsonb_set(cast(attrs as jsonb), '{key}', '"new_value"', true) WHERE id = 'some_id';
This what worked for me, attrs is a json type field. first cast to jsonb then update.
or
UPDATE table_name SET attrs = jsonb_set(cast(attrs as jsonb), '{key}', '"new_value"', true) WHERE attrs->>key = 'old_value';
if you don't need variable, you can define text in
translations/messages.en.yaml :
CiteExampleHtmlCode: "<b> my static text </b>"
then use it with twig:
templates/about/index.html.twig
… {{ 'CiteExampleHtmlCode' }}
or if you need multilangages like me:
… {{ 'CiteExampleHtmlCode' | trans }}
Let's have a look of https://symfony.com/doc/current/translation.html for more information about translations use.
This is what I'm using:
var ua = navigator.userAgent;
var info = {
browser: /Edge\/\d+/.test(ua) ? 'ed' : /MSIE 9/.test(ua) ? 'ie9' : /MSIE 10/.test(ua) ? 'ie10' : /MSIE 11/.test(ua) ? 'ie11' : /MSIE\s\d/.test(ua) ? 'ie?' : /rv\:11/.test(ua) ? 'ie11' : /Firefox\W\d/.test(ua) ? 'ff' : /Chrom(e|ium)\W\d|CriOS\W\d/.test(ua) ? 'gc' : /\bSafari\W\d/.test(ua) ? 'sa' : /\bOpera\W\d/.test(ua) ? 'op' : /\bOPR\W\d/i.test(ua) ? 'op' : typeof MSPointerEvent !== 'undefined' ? 'ie?' : '',
os: /Windows NT 10/.test(ua) ? "win10" : /Windows NT 6\.0/.test(ua) ? "winvista" : /Windows NT 6\.1/.test(ua) ? "win7" : /Windows NT 6\.\d/.test(ua) ? "win8" : /Windows NT 5\.1/.test(ua) ? "winxp" : /Windows NT [1-5]\./.test(ua) ? "winnt" : /Mac/.test(ua) ? "mac" : /Linux/.test(ua) ? "linux" : /X11/.test(ua) ? "nix" : "",
touch: 'ontouchstart' in document.documentElement,
mobile: /IEMobile|Windows Phone|Lumia/i.test(ua) ? 'w' : /iPhone|iP[oa]d/.test(ua) ? 'i' : /Android/.test(ua) ? 'a' : /BlackBerry|PlayBook|BB10/.test(ua) ? 'b' : /Mobile Safari/.test(ua) ? 's' : /webOS|Mobile|Tablet|Opera Mini|\bCrMo\/|Opera Mobi/i.test(ua) ? 1 : 0,
tablet: /Tablet|iPad/i.test(ua),
};
info
properties:
browser
: gc
for Google Chrome; ie9
-ie11
for IE; ie?
for old or unknown IE; ed
for Edge; ff
for Firefox; sa
for Safari; op
for Opera.os
: mac
win7
win8
win10
winnt
winxp
winvista
linux
nix
mobile
: a
for Android; i
for iOS (iPhone iPad); w
for Windows Phone; b
for Blackberry; s
for undetected mobile running Safari; 1
for other undetected mobile; 0
for non-mobiletouch
: true
for touch enabled devices, including touch laptops/notebooks that has both mouse and touch together; false
for no touch supporttablet
: true
or false
in an actual SQL query, you just add a newline
INSERT INTO table (text) VALUES ('hi this is some text
and this is a linefeed.
and another');
you can init placeholder in you select html code in two level such as:
<select class="form-control select2" style="width: 100%;" data-placeholder="Select a State">
<option></option>
<option>?????</option>
<option>????</option>
<option>??????</option>
<option>?????</option>
<option>?????</option>
<option>?????</option>
<option>???</option>
</select>
1.set data-placeholder attribute in your select tag 2.set empty tag in first of your select tag
I got the same "No Android SDK Found" error message... plus no rendering for Design window, no little cellphone screen.
My SDK path was correct, pointing to where the (downloaded during setup) SDK lives.
During Setup of the SDK Mgr, I didn't download the latest "preview edition (version 20)"...(I thought it better to use the next most recent version (19)) Later I found, there was no dropdown choice in the AVD Manager to pick Version 19, only the default value of the preview, 20.
I thought "Maybe the rendering was based on a version that wasn't present yet." So, I downloaded all the "preview edition's (version 20)" SDK Platform (2) and system images (4)...
Once download/install completed, RESTARTED Android Studio and Viola! success... error message gone, rendering ok.
There may be two causes:
It is case-sensitive: DataFrame .... Dataframe, dataframe will not work.
You have not install pandas (pip install pandas
) in the python path.
Use the ALLOW_PAGE_LOCKS clause of ALTER/CREATE INDEX:
ALTER INDEX indexname ON tablename SET (ALLOW_PAGE_LOCKS = OFF);
The problem is described (among other) in this article.
#box
is relatively positioned, which makes it part of the "flow" of the page. Your other divs are absolutely positioned, so they are removed from the page's "flow".
Page flow means that the positioning of an element effects other elements in the flow.
In other words, as #box
now sees the dom, .a and .b are no longer "inside" #box
.
To fix this, you would want to make everything relative, or everything absolute.
One way would be:
.a {
position:relative;
margin-top:10px;
margin-left:10px;
background-color:red;
width:210px;
padding: 5px;
}
I adjusted the code from Miguel to make it easier to understand and I want to share it with people who have problems like me.
Try this for easy and quick way
$("#datePicker").on("change", function(e) {
displayDateFormat($(this), '#datePickerLbl', $(this).val());
});
function displayDateFormat(thisElement, datePickerLblId, dateValue) {
$(thisElement).css("color", "rgba(0,0,0,0)")
.siblings(`${datePickerLblId}`)
.css({
position: "absolute",
left: "10px",
top: "3px",
width: $(this).width()
})
.text(dateValue.length == 0 ? "" : (`${getDateFormat(new Date(dateValue))}`));
}
function getDateFormat(dateValue) {
let d = new Date(dateValue);
// this pattern dd/mm/yyyy
// you can set pattern you need
let dstring = `${("0" + d.getDate()).slice(-2)}/${("0" + (d.getMonth() + 1)).slice(-2)}/${d.getFullYear()}`;
return dstring;
}
_x000D_
.date-selector {
position: relative;
}
.date-selector>input[type=date] {
text-indent: -500px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="date-selector">
<input id="datePicker" class="form-control" type="date" onkeydown="return false" />
<span id="datePickerLbl" style="pointer-events: none;"></span>
</div>
_x000D_
I found two pages that seem helpful, it's written for ASP.Net, but the same stuff should apply:
The answer here worked better for me as it isolates the search on the hashtag, not just returning results that contain the search string. In the answer above you would still need to parse the JSON response to see if the entities.hashtags array is not empty.
In ANSI C:
char* strings[3];
strings[0] = "foo";
strings[1] = "bar";
strings[2] = "baz";
You could also use the __getitem__
method combined with map
like the following:
L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Idx = [0, 3, 7]
res = list(map(L.__getitem__, Idx))
print(res)
# ['a', 'd', 'h']
The CSS Writing Modes module introduces orthogonal flows with vertical text.
Just use the writing-mode
property with the desired value.
span { margin: 20px; }_x000D_
#vertical-lr { writing-mode: vertical-lr; }_x000D_
#vertical-rl { writing-mode: vertical-rl; }_x000D_
#sideways-lr { writing-mode: sideways-lr; }_x000D_
#sideways-rl { writing-mode: sideways-rl; }
_x000D_
<span id="vertical-lr">_x000D_
? (1) vertical-lr ?<br />_x000D_
? (2) vertical-lr ?<br />_x000D_
? (3) vertical-lr ?_x000D_
</span>_x000D_
<span id="vertical-rl">_x000D_
? (1) vertical-rl ?<br />_x000D_
? (2) vertical-rl ?<br />_x000D_
? (3) vertical-rl ?_x000D_
</span>_x000D_
<span id="sideways-lr">_x000D_
? (1) sideways-lr ?<br />_x000D_
? (2) sideways-lr ?<br />_x000D_
? (3) sideways-lr ?_x000D_
</span>_x000D_
<span id="sideways-rl">_x000D_
? (1) sideways-rl ?<br />_x000D_
? (2) sideways-rl ?<br />_x000D_
? (3) sideways-rl ?_x000D_
</span>
_x000D_
The API of java.io.File
only supports getting the last modified time. And the Internet is very quiet on this topic as well.
Unless I missed something significant, the Java library as is (up to but not yet including Java 7) does not include this capability. So if you were desperate for this, one solution would be to write some C(++) code to call system routines and call it using JNI. Most of this work seems to be already done for you in a library called JNA, though.
You may still need to do a little OS specific coding in Java for this, though, as you'll probably not find the same system calls available in Windows and Unix/Linux/BSD/OS X.
Weird, just had simmilar issue, went here http://www.microsoft.com/en-us/download/confirmation.aspx?id=30679 downloaded and installed vcredist_x86 (i'm using 32bit apache) and it works like a charm.
For anyone using WebdriverIO, you can disable extensions by creating your client like this:
var driver = require('webdriverio');
var client = driver.remote({
desiredCapabilities: {
browserName: 'chrome',
chromeOptions: {
args: [
'disable-extensions'
]
}
}
});
You can try this
SELECT * FROM Buses
WHERE BusID
in (1,2,3,4,...)
Well theres a lot of different ways but if you only want to DISPLAY the text and not STORE it anywhere then you just use: findstr /v "randomtextthatnoonewilluse" filename.txt
Note: I found this question looking for one of the steps in the answer to how to resize an existing array.
So I thought I would add that information here, in case anyone else was searching for how to do a ranged copy as a partial answer to the question of resizing an array.
For anyone else finding this question looking for the same thing I was, it is very simple:
Array.Resize<T>(ref arrayVariable, newSize);
where T is the type, i.e. where arrayVariable is declared:
T[] arrayVariable;
That method handles null checks, as well as newSize==oldSize having no effect, and of course silently handles the case where one of the arrays is longer than the other.
See the MSDN article for more.
As mentioned by Frank, you can use Firebase Cloud Messaging (FCM) HTTP API to trigger push notification from your own back-end. But you won't be able to
Meaning: you'll have to store FCM/GCM registration ids (push tokens) yourself or use FCM topics to subscribe users. Keep also in mind that FCM is not an API for Firebase Notifications, it's a lower-level API without scheduling or open-rate analytics. Firebase Notifications is build on top on FCM.
You could use the String Convert.ToBase64String(byte[]) to encode the byte array into a base64 string, then Byte[] Convert.FromBase64String(string) to convert the resulting string back into a byte array.
According to the documentation:
$validator = Validator::make($request->all(), [
'file' => 'max:500000',
]);
The value is in kilobytes. I.e. max:10240
= max 10 MB.
My take on it...obviously, you've got to do something with the data you read in. If it involves writing it to the sheet, that'll be deadly slow with a normal For Loop. I came up with the following based upon a rehash of some of the items there, plus some help from the Chip Pearson website.
Reading in the text file (assuming you don't know the length of the range it will create, so only the startingCell is given):
Public Sub ReadInPlainText(startCell As Range, Optional textfilename As Variant)
If IsMissing(textfilename) Then textfilename = Application.GetOpenFilename("All Files (*.*), *.*", , "Select Text File to Read")
If textfilename = "" Then Exit Sub
Dim filelength As Long
Dim filenumber As Integer
filenumber = FreeFile
filelength = filelen(textfilename)
Dim text As String
Dim textlines As Variant
Open textfilename For Binary Access Read As filenumber
text = Space(filelength)
Get #filenumber, , text
'split the file with vbcrlf
textlines = Split(text, vbCrLf)
'output to range
Dim outputRange As Range
Set outputRange = startCell
Set outputRange = outputRange.Resize(UBound(textlines), 1)
outputRange.Value = Application.Transpose(textlines)
Close filenumber
End Sub
Conversely, if you need to write out a range to a text file, this does it quickly in one print statement (note: the file 'Open' type here is in text mode, not binary..unlike the read routine above).
Public Sub WriteRangeAsPlainText(ExportRange As Range, Optional textfilename As Variant)
If IsMissing(textfilename) Then textfilename = Application.GetSaveAsFilename(FileFilter:="Text Files (*.txt), *.txt")
If textfilename = "" Then Exit Sub
Dim filenumber As Integer
filenumber = FreeFile
Open textfilename For Output As filenumber
Dim textlines() As Variant, outputvar As Variant
textlines = Application.Transpose(ExportRange.Value)
outputvar = Join(textlines, vbCrLf)
Print #filenumber, outputvar
Close filenumber
End Sub
Try to use this xPath expression:
//book/title[@lang='it']/..
That should give you all book nodes in "it" lang
try using table structure, it's more back compatible. Check this outHorizontal Scrolling using Tables
Declare your function pointer like this:
bool (*f)();
f = A;
f();
This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:
<table>
<tr>
<td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
Hello World
</td>
</tr>
</table>
JSTransform is deprecated , please use babel instead.
<script type="text/babel" src="./lander.js"></script>
Using the syntax that you used,
int array[100] = {-1};
says "set the first element to -1
and the rest to 0
" since all omitted elements are set to 0
.
In C++, to set them all to -1
, you can use something like std::fill_n
(from <algorithm>
):
std::fill_n(array, 100, -1);
In portable C, you have to roll your own loop. There are compiler-extensions or you can depend on implementation-defined behavior as a shortcut if that's acceptable.
unset
is the command you're looking for.
unset GNUPLOT_DRIVER_DIR
I've more recently found a much cleaner approach to this, which can be executed at any time, rather than being forced to do it synchronously when the script loads.
Use stackinfo to get a stacktrace at a current location, and grab the info.file
name off the top of the stack.
info = stackinfo()
console.log('This is the url of the script '+info[0].file)
# *** the shortest and best way ***
# getmtime --> sort by modified time
# getctime --> sort by created time
import glob,os
lst_files = glob.glob("*.txt")
lst_files.sort(key=os.path.getmtime)
print("\n".join(lst_files))
Java Escape Sequences:
\u{0000-FFFF} /* Unicode [Basic Multilingual Plane only, see below] hex value
does not handle unicode values higher than 0xFFFF (65535),
the high surrogate has to be separate: \uD852\uDF62
Four hex characters only (no variable width) */
\b /* \u0008: backspace (BS) */
\t /* \u0009: horizontal tab (HT) */
\n /* \u000a: linefeed (LF) */
\f /* \u000c: form feed (FF) */
\r /* \u000d: carriage return (CR) */
\" /* \u0022: double quote (") */
\' /* \u0027: single quote (') */
\\ /* \u005c: backslash (\) */
\{0-377} /* \u0000 to \u00ff: from octal value
1 to 3 octal digits (variable width) */
The Basic Multilingual Plane is the unicode values from 0x0000 - 0xFFFF (0 - 65535). Additional planes can only be specified in Java by multiple characters: the egyptian heiroglyph A054 (laying down dude) is U+1303F
/ 𓀿
and would have to be broken into "\uD80C\uDC3F"
(UTF-16) for Java strings. Some other languages support higher planes with "\U0001303F"
.
In our case, deletion was not possible due to already having an app that we were in pre-release. The fix was not to delete but rather to edit each section, including version number, that needed to change for the new candidate.
Here's the current (September 2018) extensions for running Python code:
Official Python extension: This is a must install.
Code Runner: Incredibly useful for all sorts of languages, not just Python. I would highly recommend installing.
AREPL: Real-time Python scratchpad that displays your variables in a side window. I'm the creator of this, so obviously I think it's great, but I can't give a unbiased opinion ¯\(?)/¯
Wolf: Real-time Python scratchpad that displays results inline
And of course if you use the integrated terminal you can run Python code in there and not have to install any extensions.
i use these three lines of code to print out the column names which contain at least one null value:
for column in dataframe:
if dataframe[column].isnull().any():
print('{0} has {1} null values'.format(column, dataframe[column].isnull().sum()))
I want to be able to change the background color to white in my android app in the simplest way possible.
Set parentViewStyle
in all your parent views. Like most parent view of your activity, fragment and dialogs.
<LinearLayout style="@style/parentViewStyle">
... other components inside
</LinearLayout>
Just put this style inside res>values>styles.xml
<style name="parentViewStyle">
<item name="android:layout_height">match_parent</item>
<item name="android:layout_width">match_parent</item>
<item name="android:background">@color/white</item> // set your color here.
<item name="android:orientation">vertical</item>
</style>
By this way, you don't have to change background color many times in future.
For the text after the first =
and before the next =
cut -d "=" -f2 <<< "$your_str"
or
sed -e 's#.*=\(\)#\1#' <<< "$your_str"
For all text after the first =
regardless of if there are multiple =
cut -d "=" -f2- <<< "$your_str"
Hope this piece of code give you an idea of changing jPanels inside a JFrame.
public class PanelTest extends JFrame {
Container contentPane;
public PanelTest() {
super("Changing JPanel inside a JFrame");
contentPane=getContentPane();
}
public void createChangePanel() {
contentPane.removeAll();
JPanel newPanel=new JPanel();
contentPane.add(newPanel);
System.out.println("new panel created");//for debugging purposes
validate();
setVisible(true);
}
}
As an alternative to the default title
attribute tooltips, you can make your own custom CSS tooltips using :before
/:after
pseudo elements and HTML5 data-*
attributes.
Using the provided CSS, you can add a tooltip to an element using the data-tooltip
attribute.
You can also control the position of the custom tooltip using the data-tooltip-position
attribute (accepted values: top
/right
/bottom
/left
).
For instance, the following will add a tooltop positioned at the bottom of the span element.
<span data-tooltip="Custom tooltip text." data-tooltip-position="bottom">Custom bottom tooltip.</span>
You can display the custom tooltips with pseudo elements by retrieving the custom attribute values using the attr()
function.
[data-tooltip]:before {
content: attr(data-tooltip);
}
In terms of positioning the tooltip, just use the attribute selector and change the placement based on the attribute's value.
Full CSS used in the example - customize this to your needs.
[data-tooltip] {
display: inline-block;
position: relative;
cursor: help;
padding: 4px;
}
/* Tooltip styling */
[data-tooltip]:before {
content: attr(data-tooltip);
display: none;
position: absolute;
background: #000;
color: #fff;
padding: 4px 8px;
font-size: 14px;
line-height: 1.4;
min-width: 100px;
text-align: center;
border-radius: 4px;
}
/* Dynamic horizontal centering */
[data-tooltip-position="top"]:before,
[data-tooltip-position="bottom"]:before {
left: 50%;
-ms-transform: translateX(-50%);
-moz-transform: translateX(-50%);
-webkit-transform: translateX(-50%);
transform: translateX(-50%);
}
/* Dynamic vertical centering */
[data-tooltip-position="right"]:before,
[data-tooltip-position="left"]:before {
top: 50%;
-ms-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
}
[data-tooltip-position="top"]:before {
bottom: 100%;
margin-bottom: 6px;
}
[data-tooltip-position="right"]:before {
left: 100%;
margin-left: 6px;
}
[data-tooltip-position="bottom"]:before {
top: 100%;
margin-top: 6px;
}
[data-tooltip-position="left"]:before {
right: 100%;
margin-right: 6px;
}
/* Tooltip arrow styling/placement */
[data-tooltip]:after {
content: '';
display: none;
position: absolute;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
/* Dynamic horizontal centering for the tooltip */
[data-tooltip-position="top"]:after,
[data-tooltip-position="bottom"]:after {
left: 50%;
margin-left: -6px;
}
/* Dynamic vertical centering for the tooltip */
[data-tooltip-position="right"]:after,
[data-tooltip-position="left"]:after {
top: 50%;
margin-top: -6px;
}
[data-tooltip-position="top"]:after {
bottom: 100%;
border-width: 6px 6px 0;
border-top-color: #000;
}
[data-tooltip-position="right"]:after {
left: 100%;
border-width: 6px 6px 6px 0;
border-right-color: #000;
}
[data-tooltip-position="bottom"]:after {
top: 100%;
border-width: 0 6px 6px;
border-bottom-color: #000;
}
[data-tooltip-position="left"]:after {
right: 100%;
border-width: 6px 0 6px 6px;
border-left-color: #000;
}
/* Show the tooltip when hovering */
[data-tooltip]:hover:before,
[data-tooltip]:hover:after {
display: block;
z-index: 50;
}
A very easy solution from cssportal.com
If pressed [show], the text [show] will be hidden and other way around.
This example does not work in Chrome, I don't why...
.show {_x000D_
display: none;_x000D_
}_x000D_
.hide:focus + .show {_x000D_
display: inline;_x000D_
}_x000D_
.hide:focus {_x000D_
display: none;_x000D_
}_x000D_
.hide:focus ~ #list { display:none; }_x000D_
@media print {_x000D_
.hide, .show {_x000D_
display: none;_x000D_
}_x000D_
}
_x000D_
<div><a class="hide" href="#">[hide]</a> <a class="show" href="#">[show]</a>_x000D_
<ol id="list">_x000D_
<li>item 1</li>_x000D_
<li>item 2</li>_x000D_
<li>item 3</li>_x000D_
</ol>_x000D_
</div>
_x000D_
Not saying this is better, just another way:
$("#elem")[0].style.fontSize="20px";
I think this will help you... Creating Threads and Passing Data at Start Time!
Imports System.Threading
' The ThreadWithState class contains the information needed for
' a task, and the method that executes the task.
Public Class ThreadWithState
' State information used in the task.
Private boilerplate As String
Private value As Integer
' The constructor obtains the state information.
Public Sub New(text As String, number As Integer)
boilerplate = text
value = number
End Sub
' The thread procedure performs the task, such as formatting
' and printing a document.
Public Sub ThreadProc()
Console.WriteLine(boilerplate, value)
End Sub
End Class
' Entry point for the example.
'
Public Class Example
Public Shared Sub Main()
' Supply the state information required by the task.
Dim tws As New ThreadWithState( _
"This report displays the number {0}.", 42)
' Create a thread to execute the task, and then
' start the thread.
Dim t As New Thread(New ThreadStart(AddressOf tws.ThreadProc))
t.Start()
Console.WriteLine("Main thread does some work, then waits.")
t.Join()
Console.WriteLine( _
"Independent task has completed main thread ends.")
End Sub
End Class
' The example displays the following output:
' Main thread does some work, then waits.
' This report displays the number 42.
' Independent task has completed; main thread ends.
Cohesion refers to what the class (or module) can do. Low cohesion would mean that the class does a great variety of actions - it is broad, unfocused on what it should do. High cohesion means that the class is focused on what it should be doing, i.e. only methods relating to the intention of the class.
Example of Low Cohesion:
-------------------
| Staff |
-------------------
| checkEmail() |
| sendEmail() |
| emailValidate() |
| PrintLetter() |
-------------------
Example of High Cohesion:
----------------------------
| Staff |
----------------------------
| -salary |
| -emailAddr |
----------------------------
| setSalary(newSalary) |
| getSalary() |
| setEmailAddr(newEmail) |
| getEmailAddr() |
----------------------------
As for coupling, it refers to how related or dependent two classes/modules are toward each other. For low coupled classes, changing something major in one class should not affect the other. High coupling would make it difficult to change and maintain your code; since classes are closely knit together, making a change could require an entire system revamp.
Good software design has high cohesion and low coupling.
is there a possibility that casting a double created via
Math.round()
will still result in a truncated down number
No, round()
will always round your double to the correct value, and then, it will be cast to an long
which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining.
Here are the docs from Math.round(double)
:
Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:
(long)Math.floor(a + 0.5d)
Can you do the string conversion while the List(of object) is being built? This would be the only way to avoid enumerating the whole list after the List(of object) was created.
For anyone using AngularJS, a simple solution is to filter the value with the date API, which converts milliseconds to a string based on the requested format. Example:
<div>Offer ends in {{ timeRemaining | date: 'HH:mm:ss' }}</div>
Note that this expects milliseconds, so you may want to multiply timeRemaining by 1000 if you are converting from seconds (as the original question was formulated).
For viewers who got this error after upgrading React Native to 0.40+, you may need to run react-native upgrade
on the command line.
run the below command in command prompt
tnsping Datasource
This should give a response like below
C:>tnsping *******
TNS Ping Utility for *** Windows: Version *** - Production on *****
Copyright (c) 1997, 2014, Oracle. All rights reserved.
Used parameter files: c:\oracle*****
Used **** to resolve the alias Attempting to contact (description=(address_list=(address=(protocol=tcp)(host=)(port=)))(connect_data=(server=)(service_name=)(failover_mode=(type=)(method=)(retries=)(delay=))))** OK (**** msec)
Add the text 'Datasource=' in beginning and credentials at the end. the final string should be
Data Source=(description=(address_list=(address=(protocol=tcp)(host=)(port=)))(connect_data=(server=)(service_name=)(failover_mode=(type=)(method=)(retries=)(delay=))));User Id=;Password=;**
Use this as the connection string to connect to oracle db.
You need to set the text after the replace call:
$('.element span').each(function() {_x000D_
console.log($(this).text());_x000D_
var text = $(this).text().replace('N/A, ', '');_x000D_
$(this).text(text);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="element">_x000D_
<span>N/A, Category</span>_x000D_
</div>
_x000D_
Here's another cool way you can do it (hat tip @Felix King):
$(".element span").text(function(index, text) {
return text.replace("N/A, ", "");
});
First of all, you would have to allocate memory:
char * S = new char[R.length() + 1];
then you can use strcpy
with S
and R.c_str()
:
std::strcpy(S,R.c_str());
You can also use R.c_str()
if the string doesn't get changed or the c string is only used once. However, if S
is going to be modified, you should copy the string, as writing to R.c_str()
results in undefined behavior.
Note: Instead of strcpy
you can also use str::copy
.
The solution is the /Y
switch:
xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y
Using split()
will be the most Pythonic way of splitting on a string.
It's also useful to remember that if you use split()
on a string that does not have a whitespace then that string will be returned to you in a list.
Example:
>>> "ark".split()
['ark']
In Laravel 5.6, you will need to set it as
session(['variableName'=>$value]);
To retrieve it is as simple as
$variableName = session('variableName')
Another tip that would help a lot is that to set the current directory to a different drive one would have to use %~d0
first, then cd %~dp0
. This will change the directory to the batch file's drive, then change to its folder.
Alternatively, for #oneLinerLovers, as @Omni pointed out in the comments cd /d %~dp0
will change both the drive and directory :)
Hope this helps someone.
This might be your problem:
height: .05em;
Chrome is a bit funky with decimals, so try a fixed-pixel height:
height: 2px;
I usually use Task
to interact with Winforms and simple background worker to make it not freezing the UI. here an example when I prefer using Task
private async void buttonDownload_Click(object sender, EventArgs e)
{
buttonDownload.Enabled = false;
await Task.Run(() => {
using (var client = new WebClient())
{
client.DownloadFile("http://example.com/file.mpeg", "file.mpeg");
}
})
buttonDownload.Enabled = true;
}
VS
private void buttonDownload_Click(object sender, EventArgs e)
{
buttonDownload.Enabled = false;
Thread t = new Thread(() =>
{
using (var client = new WebClient())
{
client.DownloadFile("http://example.com/file.mpeg", "file.mpeg");
}
this.Invoke((MethodInvoker)delegate()
{
buttonDownload.Enabled = true;
});
});
t.IsBackground = true;
t.Start();
}
the difference is you don't need to use MethodInvoker
and shorter code.
$("#FormId").validate().element('#FieldId');
There is no concept of a "background image" in a JPanel
, so one would have to write their own way to implement such a feature.
One way to achieve this would be to override the paintComponent
method to draw a background image on each time the JPanel
is refreshed.
For example, one would subclass a JPanel
, and add a field to hold the background image, and override the paintComponent
method:
public class JPanelWithBackground extends JPanel {
private Image backgroundImage;
// Some code to initialize the background image.
// Here, we use the constructor to load the image. This
// can vary depending on the use case of the panel.
public JPanelWithBackground(String fileName) throws IOException {
backgroundImage = ImageIO.read(new File(fileName));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw the background image.
g.drawImage(backgroundImage, 0, 0, this);
}
}
(Above code has not been tested.)
The following code could be used to add the JPanelWithBackground
into a JFrame
:
JFrame f = new JFrame();
f.getContentPane().add(new JPanelWithBackground("sample.jpeg"));
In this example, the ImageIO.read(File)
method was used to read in the external JPEG file.
Right-click on your project's name in Eclipse's Project Explorer, then click Run As followed by Run on Server. Click the Next button. Make sure your project's name is listed in the Configured: column on the right. If it is, then you should be able to access it with this URL:
http://localhost:8085/projectname/
Additionally, whenever you make new additions (such as new JSPs, graphics or other resources) to your project, be sure to refresh the project by clicking on its name and then hitting F5. Otherwise Eclipse does not know that those new resources are available and will not make them available to Tomcat to serve.
to pass the event
object:
<p id="p" onclick="doSomething(event)">
to get the clicked child element
(should be used with event
parameter:
function doSomething(e) {
e = e || window.event;
var target = e.target || e.srcElement;
console.log(target);
}
to pass the element
itself (DOMElement):
<p id="p" onclick="doThing(this)">
see live example on jsFiddle.
You can specify the name of the event
as above, but alternatively your handler can access the event
parameter as described here: "When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters". There's much more additional documentation at the link.
Actually, I found a somewhat quirky way to do this. Add the protocol to your web.config, but inside a location element. Specify the webservice location as the path attribute, like so:
<location path="YourWebservice.asmx">
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
</location>
The problem with information_schema is that it can be terribly slow. It is faster to use the SHOW commands.
After you select the database you first send the query SHOW TABLES. And then you do SHOW COLUMNS for each of the tables.
In PHP that would look something like
$res = mysqli_query("SHOW TABLES"); while($row = mysqli_fetch_array($res)) { $rs2 = mysqli_query("SHOW COLUMNS FROM ".$row[0]); while($rw2 = mysqli_fetch_array($rs2)) { if($rw2[0] == $target) .... } }
Here is a code snip to do exactly that.
public void scaleView(View v, float startScale, float endScale) {
Animation anim = new ScaleAnimation(
1f, 1f, // Start and end values for the X axis scaling
startScale, endScale, // Start and end values for the Y axis scaling
Animation.RELATIVE_TO_SELF, 0f, // Pivot point of X scaling
Animation.RELATIVE_TO_SELF, 1f); // Pivot point of Y scaling
anim.setFillAfter(true); // Needed to keep the result of the animation
anim.setDuration(1000);
v.startAnimation(anim);
}
The ScaleAnimation constructor used here takes 8 args, 4 related to handling the X-scale which we don't care about (1f, 1f, ... Animation.RELATIVE_TO_SELF, 0f, ...)
.
The other 4 args are for the Y-scaling we do care about.
startScale, endScale
- In your case, you'd use 0f, 0.6f
.
Animation.RELATIVE_TO_SELF, 1f
- This specifies where the shrinking of the view collapses to (referred to as the pivot in the documentation). Here, we set the float value to 1f
because we want the animation to start growing the bar from the bottom. If we wanted it to grow downward from the top, we'd use 0f
.
Finally, and equally important, is the call to anim.setFillAfter(true)
. If you want the result of the animation to stick around after the animation completes, you must run this on the animator before executing the animation.
So in your case, you can do something like this:
View v = findViewById(R.id.viewContainer);
scaleView(v, 0f, .6f);
In Bootstrap 3 you can reset your form after your modal window has been closed as follows:
$('.modal').on('hidden.bs.modal', function(){
$(this).find('form')[0].reset();
});
Im prefer this one.
INSERT INTO 'DB_NAME'
(SELECT * from 'DB_NAME@DB_LINK')
MINUS
(SELECT * FROM 'DB_NAME');
Which means will insert whatsoever that not included on DB_NAME
but included at DB_NAME@DB_LINK
. Hope this help.
A subquery is a select statement that is embedded in a clause of another select statement.
EX:
select ename, sal
from emp where sal > (select sal
from emp where ename ='FORD');
A Correlated subquery is a subquery that is evaluated once for each row processed by the outer query or main query. Execute the Inner query based on the value fetched by the Outer query all the values returned by the main query are matched. The INNER Query is driven by the OUTER Query.
Ex:
select empno,sal,deptid
from emp e
where sal=(select avg(sal)
from emp where deptid=e.deptid);
DIFFERENCE
The inner query executes first and finds a value, the outer query executes once using the value from the inner query (subquery)
Fetch by the outer query, execute the inner query using the value of the outer query, use the values resulting from the inner query to qualify or disqualify the outer query (correlated)
For more information : http://www.oraclegeneration.com/2014/01/sql-interview-questions.html
Create a Back up your mysql folder from C:\xampp\mysql
.
Then go to C:\xampp\mysql\backup
Copy all the files and paste it into C:\xampp\mysql\data
.
Then from your old backup folder see for ibdata1
file you can find it in C:\xampp\mysql\data
. Copy this file and paste in into C:\xampp\mysql\data
.
Now restart xampp and it should work.
Use like this,
$( "#id" ).prop( "disabled", true );
$( "#id" ).prop( "disabled", false );
This is indeed rather odd.
If aSourceDictionary
were a dictionary, I don't believe it is possible for your code to fail in the manner you describe.
This leads to two hypotheses:
The code you're actually running is not identical to the code in your question (perhaps an earlier or later version?)
aSourceDictionary
is in fact not a dictionary, but is some other structure (for example, a list).
First, you use include_directories()
to tell CMake to add the directory as -I
to the compilation command line. Second, you list the headers in your add_executable()
or add_library()
call.
As an example, if your project's sources are in src
, and you need headers from include
, you could do it like this:
include_directories(include)
add_executable(MyExec
src/main.c
src/other_source.c
include/header1.h
include/header2.h
)
For printing the Name column
df['Name']
In ---- model:
Add use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
Change the class ----- extends Model
to class ----- extends Eloquent
You can use:
(int)(your value);
Or you can use:
intval(string)
I would like to add an example of prototypical inheritance with javascript to @Scott Driscoll answer. We'll be using classical inheritance pattern with Object.create() which is a part of EcmaScript 5 specification.
First we create "Parent" object function
function Parent(){
}
Then add a prototype to "Parent" object function
Parent.prototype = {
primitive : 1,
object : {
one : 1
}
}
Create "Child" object function
function Child(){
}
Assign child prototype (Make child prototype inherit from parent prototype)
Child.prototype = Object.create(Parent.prototype);
Assign proper "Child" prototype constructor
Child.prototype.constructor = Child;
Add method "changeProps" to a child prototype, which will rewrite "primitive" property value in Child object and change "object.one" value both in Child and Parent objects
Child.prototype.changeProps = function(){
this.primitive = 2;
this.object.one = 2;
};
Initiate Parent (dad) and Child (son) objects.
var dad = new Parent();
var son = new Child();
Call Child (son) changeProps method
son.changeProps();
Check the results.
Parent primitive property did not change
console.log(dad.primitive); /* 1 */
Child primitive property changed (rewritten)
console.log(son.primitive); /* 2 */
Parent and Child object.one properties changed
console.log(dad.object.one); /* 2 */
console.log(son.object.one); /* 2 */
Working example here http://jsbin.com/xexurukiso/1/edit/
More info on Object.create here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/create
On Windows, pip
lives in C:\[pythondir]\scripts
.
So you'll need to add that to your system path in order to run it from the command prompt. You could alternatively cd
into that directory each time, but that's a hassle.
See the top answer here for info on how to do that: Adding Python Path on Windows 7
Also, that is a terrifying way to install pip
. Grab it from Christophe Gohlke. Grab everything else from there for that matter.
http://www.lfd.uci.edu/~gohlke/pythonlibs/
Object[] possibleValues = enumValue.getDeclaringClass().getEnumConstants();
If you like to use a GUI, you can perform the entire operation with gitk.
gitk --reflog
This will allow you to see the branch's commit history as if the branch hadn't been deleted. Now simply right click on the most recent commit to the branch and select the menu option Create new branch
.
UPDATE: I have created a video on sending multipart/form-data requests to explain this better.
Actually, Postman can do this. Here is a screenshot
Newer version : Screenshot captured from postman chrome extension
Another version
Older version
Make sure you check the comment from @maxkoryukov
Be careful with explicit Content-Type header. Better - do not set it's value, the Postman is smart enough to fill this header for you. BUT, if you want to set the Content-Type: multipart/form-data - do not forget about boundary field.
You should write your own stream manipulator
cout << multi(5) << "whatever" << "lolcat";
Here is a concise way using lambdas and JDK 8 Supplier to fit everything in the outer try:
try (Connection con = DriverManager.getConnection(JDBC_URL, prop);
PreparedStatement stmt = ((Supplier<PreparedStatement>)() -> {
try {
PreparedStatement s = con.prepareStatement("SELECT userid, name, features FROM users WHERE userid = ?");
s.setInt(1, userid);
return s;
} catch (SQLException e) { throw new RuntimeException(e); }
}).get();
ResultSet resultSet = stmt.executeQuery()) {
}
And on Windows:
FOR /F "tokens=*" %G IN ('dir /b *.flac') DO ffmpeg -i "%G" -acodec mp3 "%~nG.mp3"
This console warning is not an error or an actual problem — Chrome is just spreading the word about this new standard to increase developer adoption.
It has nothing to do with your code. It is something their web servers will have to support.
Release date for a fix is February 4, 2020 per: https://www.chromium.org/updates/same-site
February, 2020: Enforcement rollout for Chrome 80 Stable: The SameSite-by-default and SameSite=None-requires-Secure behaviors will begin rolling out to Chrome 80 Stable for an initial limited population starting the week of February 17, 2020, excluding the US President’s Day holiday on Monday. We will be closely monitoring and evaluating ecosystem impact from this initial limited phase through gradually increasing rollouts.
For the full Chrome release schedule, see here.
I solved same problem by adding in response header
response.setHeader("Set-Cookie", "HttpOnly;Secure;SameSite=Strict");
SameSite
prevents the browser from sending the cookie along with cross-site requests. The main goal is mitigating the risk of cross-origin information leakage. It also provides some protection against cross-site request forgery attacks. Possible values for the flag are Lax or Strict.
SameSite cookies explained here
Please refer this before applying any option.
Hope this helps you.
That's also my last problem. Here my solution I use data Model and adapter for my RecyclerView
/*Firstly, register your new data to your model*/
DataModel detail = new DataModel(id, name, sat, image);
/*after that, use set to replace old value with the new one*/
int index = 4;
mData.set(index, detail);
/*finally, refresh your adapter*/
if(adapter!=null)
adapter.notifyItemChanged(index);
It's important to point out that all of the above solutions map the port to every interface on your machine. This is less than desirable if you have a public IP address, or your machine has an IP on a large network. Your application may be exposed to a much wider audience than you'd hoped.
redis:
build:
context:
dockerfile: Dockerfile-redis
ports:
- "127.0.0.1:3901:3901"
127.0.0.1
is the ip address that maps to the hostname localhost
on your machine. So now your application is only exposed over that interface and since 127.0.0.1
is only accessible via your machine, you're not exposing your containers to the entire world.
The documentation explains this further and can be found here: https://docs.docker.com/compose/compose-file/#ports
Note: If you're using Docker for mac this will make the container listen on 127.0.0.1 on the Docker for Mac VM and will not be accessible from your localhost. If I recall correctly.
enum
type in Java 5 and onwards for the purpose you have described. It is type safe.If you are talking about the difference between instance variable and class variable, instance variable exist per object created. While class variable has only one copy per class loader regardless of the number of objects created.
Java 5 and up enum
type
public enum Color{
RED("Red"), GREEN("Green");
private Color(String color){
this.color = color;
}
private String color;
public String getColor(){
return this.color;
}
public String toString(){
return this.color;
}
}
If you wish to change the value of the enum you have created, provide a mutator method.
public enum Color{
RED("Red"), GREEN("Green");
private Color(String color){
this.color = color;
}
private String color;
public String getColor(){
return this.color;
}
public void setColor(String color){
this.color = color;
}
public String toString(){
return this.color;
}
}
Example of accessing:
public static void main(String args[]){
System.out.println(Color.RED.getColor());
// or
System.out.println(Color.GREEN);
}
An update for Rails 5:
gem 'protected_attributes'
doesn't seem to work anymore. But give:
gem 'protected_attributes_continued'
a try.
Using generator:
def primes(num):
if 2 <= num:
yield 2
for i in range(3, num + 1, 2):
if all(i % x != 0 for x in range(3, int(math.sqrt(i) + 1))):
yield i
Usage:
for i in primes(10):
print(i)
2, 3, 5, 7
Your method should work fine on a Mac, but on Windows, two additional steps are necessary.
Saving the id_rsa key in this location should solve the permission error.
moment
is a third party global resource. The moment object lives on window
in the browser. Therefor it is not correct to import
it in your angular2 application. Instead include the <script>
tag in your html that will load the moment.js file.
To make TypeScript happy you can add
declare var moment: any;
at the top of your files where you use it to stop the compilation errors, or you can use
///<reference path="./path/to/moment.d.ts" />
or use tsd to install the moment.d.ts file which TypeScript might find on it's own.
Example
import {Component} from 'angular2/core';
declare var moment: any;
@Component({
selector: 'example',
template: '<h1>Today is {{today}}</h1>'
})
export class ExampleComponent{
today: string = moment().format('D MMM YYYY');
}
Just be sure to add the script tag in your html or moment won't exist.
<script src="node_modules/moment/moment.js" />
Module loading moment
First you would need to setup a module loader such as System.js to load the moment commonjs files
System.config({
...
packages: {
moment: {
map: 'node_modules/moment/moment.js',
type: 'cjs',
defaultExtension: 'js'
}
}
});
Then to import moment into the file where needed use
import * as moment from 'moment';
or
import moment = require('moment');
EDIT:
There are also options with some bundlers such as Webpack or SystemJS builder or Browserify that will keep moment off of the window object. For more information on these, please visit their respective websites for instruction.
In bash $1
is the first argument passed to the script, $2
second and so on
/usr/local/bin/abbyyocr9 -rl Swedish -if "$1" -of "$2" 2>&1
So you can use:
./your_script.sh some_source_file.png destination_file.txt
Explanation on double quotes;
consider three scripts:
# foo.sh
bash bar.sh $1
# cat foo2.sh
bash bar.sh "$1"
# bar.sh
echo "1-$1" "2-$2"
Now invoke:
$ bash foo.sh "a b"
1-a 2-b
$ bash foo2.sh "a b"
1-a b 2-
When you invoke foo.sh "a b"
then it invokes bar.sh a b
(two arguments), and with foo2.sh "a b"
it invokes bar.sh "a b"
(1 argument). Always have in mind how parameters are passed and expaned in bash, it will save you a lot of headache.
We should always go for equals() method for comparison for two integers.Its the recommended practice.
If we compare two integers using == that would work for certain range of integer values (Integer from -128 to 127) due to JVM's internal optimisation.
Please see examples:
Case 1:
Integer a = 100; Integer b = 100;
if (a == b) { System.out.println("a and b are equal"); } else { System.out.println("a and b are not equal"); }
In above case JVM uses value of a and b from cached pool and return the same object instance(therefore memory address) of integer object and we get both are equal.Its an optimisation JVM does for certain range values.
Case 2: In this case, a and b are not equal because it does not come with the range from -128 to 127.
Integer a = 220; Integer b = 220;
if (a == b) { System.out.println("a and b are equal"); } else { System.out.println("a and b are not equal"); }
Proper way:
Integer a = 200;
Integer b = 200;
System.out.println("a == b? " + a.equals(b)); // true
I hope this helps.
Finding all possible paths is a hard problem, since there are exponential number of simple paths. Even finding the kth shortest path [or longest path] are NP-Hard.
One possible solution to find all paths [or all paths up to a certain length] from s
to t
is BFS, without keeping a visited
set, or for the weighted version - you might want to use uniform cost search
Note that also in every graph which has cycles [it is not a DAG] there might be infinite number of paths between s
to t
.
If your class2 looks like this having static members
public class2
{
static int var = 1;
public static void myMethod()
{
// some code
}
}
Then you can simply call them like
class2.myMethod();
class2.var = 1;
If you want to access non-static members then you would have to instantiate an object.
class2 object = new class2();
object.myMethod(); // non static method
object.var = 1; // non static variable
How about this in your .htaccess:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
Simply pass the desired value as first argument, like 0
, math.inf
or, here, np.nan
. The constructor then initializes and fills the value array to the size specified by arguments index
and columns
:
>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame(np.nan, index=[0, 1, 2, 3], columns=['A', 'B'])
>>> df.dtypes
A float64
B float64
dtype: object
>>> df.values
array([[nan, nan],
[nan, nan],
[nan, nan],
[nan, nan]])
I think the answers above are missing a simple approach that I've found very useful.
When I have a file that is too large to load in memory, I break up the file into multiple smaller files (either by row or cols)
Example: In case of 30 days worth of trading data of ~30GB size, I break it into a file per day of ~1GB size. I subsequently process each file separately and aggregate results at the end
One of the biggest advantages is that it allows parallel processing of the files (either multiple threads or processes)
The other advantage is that file manipulation (like adding/removing dates in the example) can be accomplished by regular shell commands, which is not be possible in more advanced/complicated file formats
This approach doesn't cover all scenarios, but is very useful in a lot of them
Dynamic Programming
Definition
Dynamic programming (DP) is a general algorithm design technique for solving problems with overlapping sub-problems. This technique was invented by American mathematician “Richard Bellman” in 1950s.
Key Idea
The key idea is to save answers of overlapping smaller sub-problems to avoid recomputation.
Dynamic Programming Properties
It's pretty straightforward using [
to extract:
grep
will give you the position in which it matched your search pattern (unless you use value = TRUE
).
grep("^G45", My.Data$x)
# [1] 2
Since you're searching within the values of a single column, that actually corresponds to the row index. So, use that with [
(where you would use My.Data[rows, cols]
to get specific rows and columns).
My.Data[grep("^G45", My.Data$x), ]
# x y
# 2 G459 2
The help-page for subset
shows how you can use grep
and grepl
with subset
if you prefer using this function over [
. Here's an example.
subset(My.Data, grepl("^G45", My.Data$x))
# x y
# 2 G459 2
As of R 3.3, there's now also the startsWith
function, which you can again use with subset
(or with any of the other approaches above). According to the help page for the function, it's considerably faster than using substring
or grepl
.
subset(My.Data, startsWith(as.character(x), "G45"))
# x y
# 2 G459 2
I do not believe there is a way to do this strictly with CSS. The reason is your "important" qualifier to the question: forcing the parent element to expand with the contents of its child.
My guess is that you will have to use some bits of JavaScript to find the height of the child, and make adjustments.
So, with this HTML:
<div class="parentElement">
<div class="childElement">
...Some Contents...
</div>
</div>
This CSS:
.parentElement { position:relative; width:960px; } .childElement { position:absolute; top:50%; left:50%; }
This jQuery might be useful:
$('.childElement').each(function(){
// determine the real dimensions of the element: http://api.jquery.com/outerWidth/
var x = $(this).outerWidth();
var y = $(this).outerHeight();
// adjust parent dimensions to fit child
if($(this).parent().height() < y) {
$(this).parent().css({height: y + 'px'});
}
// offset the child element using negative margins to "center" in both axes
$(this).css({marginTop: 0-(y/2)+'px', marginLeft: 0-(x/2)+'px'});
});
Remember to load the jQ properly, either in the body below the affected elements, or in the head inside of $(document).ready(...)
.
I'm the OP
With the help of answer from fcalderan I was able to form a solution. I leave my solution here as it brings clarity to how to use it, and adds a very crucial detail, width: 100%;
I add this class
body.noscroll
{
position: fixed;
overflow-y: scroll;
width: 100%;
}
this worked for me and I was using Fancyapp.
Here's a solution, too:
int main()
{
QUuid uuid;
while ( (uuid = QUuid::createUuid()) != QUuid::createUuid() ) { }
std::cout << "Aha! I've found one! " << qPrintable( uuid.toString() ) << std::endl;
}
Note: requires Qt, but I guarantee that if you let it run long enough, it might find one.
(Note note: actually, now that I'm looking at it, there may be something about the generation algorithm that prevents two subsequently generated uuids that collide--but I kinda doubt it).
The method suggested by @roe and @MohitNanda work, but if the right div is set as float:right;
, then it must come first in the HTML source. This breaks the left-to-right read order, which could be confusing if the page is displayed with styles turned off. If that's the case, it might be better to use a wrapper div and absolute positioning:
<div id="wrap" style="position:relative;">
<div id="left" style="margin-right:201px;border:1px solid red;">left</div>
<div id="right" style="position:absolute;width:200px;right:0;top:0;border:1px solid blue;">right</div>
</div>
Demonstrated:
left rightEdit: Hmm, interesting. The preview window shows the correctly formatted divs, but the rendered post item does not. Sorry then, you'll have to try it for yourself.
One of the putty tools is pscp.exe; it will allow you to copy files from your remote host.
If the "many" model does not justify the creation of a model per-se (not the case here, but it might benefits other people), another alternative would be to rely on specific PostgreSQL data types, via the Django Contrib package
Postgres can deal with Array or JSON data types, and this may be a nice workaround to handle One-To-Many when the many-ies can only be tied to a single entity of the one.
Postgres allows you to access single elements of the array, which means that queries can be really fast, and avoid application-level overheads. And of course, Django implements a cool API to leverage this feature.
It obviously has the disadvantage of not being portable to others database backend, but I thougt it still worth mentionning.
Hope it may help some people looking for ideas.
GPS is generally more accurate than network but sometimes GPS is not available, therefore you might need to switch between the two.
A good start might be to look at the android dev site. They had a section dedicated to determining user location and it has all the code samples you need.
http://developer.android.com/guide/topics/location/obtaining-user-location.html
adb kill-server
and adb start-server
only control the adb
daemon on the PC side. You need to restart adbd
daemon on the device itself after reverting the service.adb.root
property change done by adb root
:
~$ adb shell id
uid=2000(shell) gid=2000(shell)
~$ adb root
restarting adbd as root
~$ adb shell id
uid=0(root) gid=0(root)
~$ adb shell 'setprop service.adb.root 0; setprop ctl.restart adbd'
~$ adb shell id
uid=2000(shell) gid=2000(shell)
normally, Maxim Donnie's method can find the reason. But I encountered one 400 bad request will not log to err_log. I found the reason with the help with tcpdump
For those who are using .NET WebForms a full page submit may not be desired. Instead, use the same onchange
idea to have javascript click a hidden button (e.g. <asp:Button...) and the hidden button can take of the rest. Make sure you are doing a display: none;
on the button and not Visible="false"
.
This issue occurred for me after editing the Homestead.yaml. I resolved this issue by
homestead destroy
homestead up
Is a JNDI problem. You will see that exception if the InitialContext
class has neither default properties for the JNDI service provider nor explicitly configured server properties.
Set the Context.INITIAL_CONTEXT_FACTORY
environment property to the class name of the initial context implementation that you are using. This class must be available to your program in the classpath.
Check:
Change display:inline to display:inline-block
.test {
width:200px;
display:inline-block;
overflow: auto;
white-space: nowrap;
margin:0px auto;
border:1px red solid;
}
You can use hexdump
's
import hexdump
hexdump.dump("Hello World", sep=":")
(append .lower()
if you require lower-case). This works for both Python 2 & 3.