This works on a Mac as noted by Alex Moore-Niemi:
set backupdir=$TMPDIR//
set directory=$TMPDIR//
Make sure to use TMPDIR
and not TEMPDIR
.
You can use the cache dir using context.getCacheDir().
File temp=File.createTempFile("prefix","suffix",context.getCacheDir());
On Windows add following lines to _vimrc
" store backup, undo, and swap files in temp directory
set directory=$HOME/temp//
set backupdir=$HOME/temp//
set undodir=$HOME/temp//
More Suggestive answer supporting rmaddy's answer as our primary purpose is to delete unnecessary file and folder:
Delete this folder after every few days interval. Most of the time, it occupy huge space!
~/Library/Developer/Xcode/DerivedData
All your targets are kept in the archived form in Archives folder. Before you decide to delete contents of this folder, here is a warning - if you want to be able to debug deployed versions of your App, you shouldn’t delete the archives. Xcode will manage of archives and creates new file when new build is archived.
~/Library/Developer/Xcode/Archives
iOS Device Support folder creates a subfolder with the device version as an identifier when you attach the device. Most of the time it’s just old stuff. Keep the latest version and rest of them can be deleted (if you don’t have an app that runs on 5.1.1, there’s no reason to keep the 5.1.1 directory/directories). If you really don't need these, delete. But we should keep a few although we test app from device mostly.
~/Library/Developer/Xcode/iOS DeviceSupport
Core Simulator folder is familiar for many Xcode users. It’s simulator’s territory; that's where it stores app data. It’s obvious that you can toss the older version simulator folder/folders if you no longer support your apps for those versions. As it is user data, no big issue if you delete it completely but it’s safer to use ‘Reset Content and Settings’ option from the menu to delete all of your app data in a Simulator.
~/Library/Developer/CoreSimulator
(Here's a handy shell command for step 5: xcrun simctl delete unavailable
)
Caches are always safe to delete since they will be recreated as necessary. This isn’t a directory; it’s a file of kind Xcode Project. Delete away!
~/Library/Caches/com.apple.dt.Xcode
Additionally, Apple iOS device automatically syncs specific files and settings to your Mac every time they are connected to your Mac machine. To be on safe side, it’s wise to use Devices pane of iTunes preferences to delete older backups; you should be retaining your most recent back-ups off course.
~/Library/Application Support/MobileSync/Backup
Source: https://ajithrnayak.com/post/95441624221/xcode-users-can-free-up-space-on-your-mac
I got back about 40GB!
Guaranteed to be (statistically) unique:
string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".csv";
(To quote from the wiki article on the probabilty of a collision:
...one's annual risk of being hit by a meteorite is estimated to be one chance in 17 billion [19], that means the probability is about 0.00000000006 (6 × 10-11), equivalent to the odds of creating a few tens of trillions of UUIDs in a year and having one duplicate. In other words, only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%. The probability of one duplicate would be about 50% if every person on earth owns 600 million UUIDs
EDIT: Please also see JaredPar's comments.
To expand on another answer, here is a fairly complete example which can cleanup the tmpdir even on exceptions:
import contextlib
import os
import shutil
import tempfile
@contextlib.contextmanager
def cd(newdir, cleanup=lambda: True):
prevdir = os.getcwd()
os.chdir(os.path.expanduser(newdir))
try:
yield
finally:
os.chdir(prevdir)
cleanup()
@contextlib.contextmanager
def tempdir():
dirpath = tempfile.mkdtemp()
def cleanup():
shutil.rmtree(dirpath)
with cd(dirpath, cleanup):
yield dirpath
def main():
with tempdir() as dirpath:
pass # do something here
On platforms where they both have the same size the answer is nothing. They both represent signed 4 byte values.
However you cannot depend on this being true. The size of long and int are not definitively defined by the standard. It's possible for compilers to give the types different sizes and hence break this assumption.
< img style="vertical-align: bottom" src="blah.png" >
Works for me. Inside a parallax div as well.
Try to use keyup.enter
but make sure to use it inside your input
tag
<input
matInput
placeholder="enter key word"
[(ngModel)]="keyword"
(keyup.enter)="addToKeywords()"
/>
Use the CSS function from jQuery to set styles to your items :
$('#buttonId').css({ "background-color": 'brown'});
I had the same kind of problems. I finally made it to work.
I successfully changed the apache ports to listen to ports not used by other programs Port 443 is used by SSL and Skype
I believe that the XAMPP Control Panel has a bug and I have screen shots in my posts to. I do not have enough credibility on this web site to upload pictures.
I have the whole thing written down with screen shots in the following blog posts:
http://hodentek.blogspot.com/2014/02/one-way-to-handle-port-80-in-use-by.html http://hodentekhelp.blogspot.com/2014/02/on-installing-apache-on-windows-7-64bit.html http://hodentekhelp.blogspot.com/2014/02/do-you-want-to-change-ports-that-skype.html
Note that this can happen even when the user has NOT bookmarked the site to their iOS home screen - for example, any time you open a page using Chrome for iOS, it does a GET "/apple-touch-icon-precomposed.png"
.
I've handled this and other non-HTML 404 requests in my ApplicationController as follows:
respond_to do |format|
format.html { render :template => "error_404", :layout => "errors", :status => 404 }
format.all { render :nothing => true, :status => 404 }
end
The format.all
response takes care of images such as this PNG file (which does not exist for my site).
When loading all names of files in the operating directory you can use
Dir.glob("*)
This will return all files within the context that the application is running in (Note for Rails this is the top level directory of the application)
You can do additional matching and recursive searching found here https://ruby-doc.org/core-2.7.1/Dir.html#method-c-glob
Anything defined as package private can be accessed by the class itself, other classes within the same package, but not outside of the package, and not by sub-classes.
See this page for a handy table of access level modifiers...
To query a large set of text in efficient manner you can use the concept of Edit Distance/ Prefix Edit Distance.
Edit Distance ED(x,y): minimal number of transfroms to get from term x to term y
But computing ED between each term and query text is resource and time intensive. Therefore instead of calculating ED for each term first we can extract possible matching terms using a technique called Qgram Index. and then apply ED calculation on those selected terms.
An advantage of Qgram index technique is it supports for Fuzzy Search.
One possible approach to adapt QGram index is build an Inverted Index using Qgrams. In there we store all the words which consists with particular Qgram, under that Qgram.(Instead of storing full string you can use unique ID for each string). You can use Tree Map data structure in Java for this. Following is a small example on storing of terms
col : colmbia, colombo, gancola, tacolama
Then when querying, we calculate the number of common Qgrams between query text and available terms.
Example: x = HILLARY, y = HILARI(query term)
Qgrams
$$HILLARY$$ -> $$H, $HI, HIL, ILL, LLA, LAR, ARY, RY$, Y$$
$$HILARI$$ -> $$H, $HI, HIL, ILA, LAR, ARI, RI$, I$$
number of q-grams in common = 4
number of q-grams in common = 4.
For the terms with high number of common Qgrams, we calculate the ED/PED against the query term and then suggest the term to the end user.
you can find an implementation of this theory in following project(See "QGramIndex.java"). Feel free to ask any questions. https://github.com/Bhashitha-Gamage/City_Search
To study more about Edit Distance, Prefix Edit Distance Qgram index please watch the following video of Prof. Dr Hannah Bast https://www.youtube.com/embed/6pUg2wmGJRo (Lesson starts from 20:06)
Way late, but I threw this together to be able to do String comparisons using SQL Like style wildcards:
public static class StringLikeExtensions
{
/// <summary>
/// Tests a string to be Like another string containing SQL Like style wildcards
/// </summary>
/// <param name="value">string to be searched</param>
/// <param name="searchString">the search string containing wildcards</param>
/// <returns>value.Like(searchString)</returns>
/// <example>value.Like("a")</example>
/// <example>value.Like("a%")</example>
/// <example>value.Like("%b")</example>
/// <example>value.Like("a%b")</example>
/// <example>value.Like("a%b%c")</example>
/// <remarks>base author -- Ruard van Elburg from StackOverflow, modifications by dvn</remarks>
/// <remarks>converted to a String extension by sja</remarks>
/// <seealso cref="https://stackoverflow.com/questions/1040380/wildcard-search-for-linq"/>
public static bool Like(this String value, string searchString)
{
bool result = false;
var likeParts = searchString.Split(new char[] { '%' });
for (int i = 0; i < likeParts.Length; i++)
{
if (likeParts[i] == String.Empty)
{
continue; // "a%"
}
if (i == 0)
{
if (likeParts.Length == 1) // "a"
{
result = value.Equals(likeParts[i], StringComparison.OrdinalIgnoreCase);
}
else // "a%" or "a%b"
{
result = value.StartsWith(likeParts[i], StringComparison.OrdinalIgnoreCase);
}
}
else if (i == likeParts.Length - 1) // "a%b" or "%b"
{
result &= value.EndsWith(likeParts[i], StringComparison.OrdinalIgnoreCase);
}
else // "a%b%c"
{
int current = value.IndexOf(likeParts[i], StringComparison.OrdinalIgnoreCase);
int previous = value.IndexOf(likeParts[i - 1], StringComparison.OrdinalIgnoreCase);
result &= previous < current;
}
}
return result;
}
/// <summary>
/// Tests a string containing SQL Like style wildcards to be ReverseLike another string
/// </summary>
/// <param name="value">search string containing wildcards</param>
/// <param name="compareString">string to be compared</param>
/// <returns>value.ReverseLike(compareString)</returns>
/// <example>value.ReverseLike("a")</example>
/// <example>value.ReverseLike("abc")</example>
/// <example>value.ReverseLike("ab")</example>
/// <example>value.ReverseLike("axb")</example>
/// <example>value.ReverseLike("axbyc")</example>
/// <remarks>reversed logic of Like String extension</remarks>
public static bool ReverseLike(this String value, string compareString)
{
bool result = false;
var likeParts = value.Split(new char[] {'%'});
for (int i = 0; i < likeParts.Length; i++)
{
if (likeParts[i] == String.Empty)
{
continue; // "a%"
}
if (i == 0)
{
if (likeParts.Length == 1) // "a"
{
result = compareString.Equals(likeParts[i], StringComparison.OrdinalIgnoreCase);
}
else // "a%" or "a%b"
{
result = compareString.StartsWith(likeParts[i], StringComparison.OrdinalIgnoreCase);
}
}
else if (i == likeParts.Length - 1) // "a%b" or "%b"
{
result &= compareString.EndsWith(likeParts[i], StringComparison.OrdinalIgnoreCase);
}
else // "a%b%c"
{
int current = compareString.IndexOf(likeParts[i], StringComparison.OrdinalIgnoreCase);
int previous = compareString.IndexOf(likeParts[i - 1], StringComparison.OrdinalIgnoreCase);
result &= previous < current;
}
}
return result;
}
}
Here's a way that I consider easier: The general idea is that you want to append a text element to a circle element then play around with its "dx" and "dy" attributes until you position the text at the point in the circle that you like. In my example, I used a negative number for the dx since I wanted to have text start towards the left of the centre.
const nodes = [ {id: ABC, group: 1, level: 1}, {id:XYZ, group: 2, level: 1}, ]
const nodeElems = svg.append('g')
.selectAll('circle')
.data(nodes)
.enter().append('circle')
.attr('r',radius)
.attr('fill', getNodeColor)
const textElems = svg.append('g')
.selectAll('text')
.data(nodes)
.enter().append('text')
.text(node => node.label)
.attr('font-size',8)//font size
.attr('dx', -10)//positions text towards the left of the center of the circle
.attr('dy',4)
final
can be used to mark a variable "unchangeable"
private final String name = "foo"; //the reference name can never change
final
can also make a method not "overrideable"
public final String toString() { return "NULL"; }
final
can also make a class not "inheritable". i.e. the class can not be subclassed.
public final class finalClass {...}
public class classNotAllowed extends finalClass {...} // Not allowed
finally
is used in a try/catch statement to execute code "always"
lock.lock();
try {
//do stuff
} catch (SomeException se) {
//handle se
} finally {
lock.unlock(); //always executed, even if Exception or Error or se
}
Java 7 has a new try with resources statement that you can use to automatically close resources that explicitly or implicitly implement java.io.Closeable or java.lang.AutoCloseable
finalize
is called when an object is garbage collected. You rarely need to override it. An example:
protected void finalize() {
//free resources (e.g. unallocate memory)
super.finalize();
}
Here is a code that works for me, which is a part from the website above combined with my early trials: http://www.codeproject.com/KB/system/DriveDetector.aspx
This basically makes your form listen to windows messages, filters for usb drives and (cd-dvds), grabs the lparam structure of the message and extracts the drive letter.
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_DEVICECHANGE)
{
DEV_BROADCAST_VOLUME vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
if ((m.WParam.ToInt32() == DBT_DEVICEARRIVAL) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME) )
{
MessageBox.Show(DriveMaskToLetter(vol.dbcv_unitmask).ToString());
}
if ((m.WParam.ToInt32() == DBT_DEVICEREMOVALCOMPLETE) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME))
{
MessageBox.Show("usb out");
}
}
base.WndProc(ref m);
}
[StructLayout(LayoutKind.Sequential)] //Same layout in mem
public struct DEV_BROADCAST_VOLUME
{
public int dbcv_size;
public int dbcv_devicetype;
public int dbcv_reserved;
public int dbcv_unitmask;
}
private static char DriveMaskToLetter(int mask)
{
char letter;
string drives = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //1 = A, 2 = B, 3 = C
int cnt = 0;
int pom = mask / 2;
while (pom != 0) // while there is any bit set in the mask shift it right
{
pom = pom / 2;
cnt++;
}
if (cnt < drives.Length)
letter = drives[cnt];
else
letter = '?';
return letter;
}
Do not forget to add this:
using System.Runtime.InteropServices;
and the following constants:
const int WM_DEVICECHANGE = 0x0219; //see msdn site
const int DBT_DEVICEARRIVAL = 0x8000;
const int DBT_DEVICEREMOVALCOMPLETE = 0x8004;
const int DBT_DEVTYPVOLUME = 0x00000002;
It is working. I just added square brackets to JSON data. The data is:
var data = [
{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "[email protected]"
},
{
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "[email protected]"
}
]
And the loop is:
for (var key in data) {
if (data.hasOwnProperty(key)) {
alert(data[key].id);
}
}
ASIHTTPRequest is a great wrapper around the network APIs and makes it very easy to upload a file. Here's their example (but you can do this on the iPhone too - we save images to "disk" and later upload them.
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setPostValue:@"Ben" forKey:@"first_name"];
[request setPostValue:@"Copsey" forKey:@"last_name"];
[request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];
As Jose answered, screen -d -r
should do the trick. This is a combination of two commands, as taken from the man page.
screen -d
detaches the already-running screen session, and screen -r
reattaches the existing session. By running screen -d -r
, you force screen to detach it and then resume the session.
If you use the capital -D -RR
, I quote the man page because it's too good to pass up.
Attach here and now. Whatever that means, just do it.
Note: It is always a good idea to check the status of your sessions by means of "screen -list".
Expanding from Andriy M, and yes you can do this from a file, even one with multiple lines
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "INTEXTFILE=test.txt"
set "OUTTEXTFILE=test_out.txt"
set "SEARCHTEXT=bath"
set "REPLACETEXT=hello"
for /f "delims=" %%A in ('type "%INTEXTFILE%"') do (
set "string=%%A"
set "modified=!string:%SEARCHTEXT%=%REPLACETEXT%!"
echo !modified!>>"%OUTTEXTFILE%"
)
del "%INTEXTFILE%"
rename "%OUTTEXTFILE%" "%INTEXTFILE%"
endlocal
EDIT
Thanks David Nelson, I have updated the script so it doesn't have the hard coded values anymore.
Following worked for me by mounting the file during docker run instead of docker build
docker service create --name <name> --mount type=bind,source=/etc/hosts,dst=/etc/hosts <image>
which(df==my.val, arr.ind=TRUE)
I also ran into this fault when I used open(file_path)
. My reason for this fault was that my file_path
had a special character like "?"
or "<"
.
Did you try assigning it back to the column?
df['column'] = df['column'].astype('str')
Referring to this question, the pandas dataframe stores the pointers to the strings and hence it is of type 'object'. As per the docs ,You could try:
df['column_new'] = df['column'].str.split(',')
Maybe this would help:
String[] some_array = getResources().getStringArray(R.array.your_string_array)
So you get the array-list as a String[] and then choose any i, some_array[i].
Before using plugin NOTE plugins are usually in notepad 32 bit , 32 bit plugin is not compatible with 64 bit and vice versa(Recommendation use Notepad++ 32 bit)
Using Import in Notepad++
I tried Import plugin : https://stackoverflow.com/a/54873143/3266623
However it didnt worked for me
Manual way
1. Download and extract .zip file having all .dll plugin files under the path
C:\ProgramData\Notepad++\plugins\
To download use following link or google the same
http://docs.notepad-plus-plus.org/index.php/Plugin_Central
2. For placing inside plugins - Make sure to create a separated folder for each plugin
\plugins
+ DSpellCheck
+ MIME Tools
+ Converter (etc.)
3. (if plugin contains ext_libs folder) Copy ext_libs to the root notepad folder,Usually contains few ddl files i.e.
C:\Program Files (x86)\Notepad++
I posted a fix for this here
You can use this function to modify JSON.stringify
to encode arrays
, just post it near the beginning of your script (check the link above for more detail):
// Upgrade for JSON.stringify, updated to allow arrays
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
To convert a valid JSON string back, you can use the json_decode()
method.
To convert it back to an object use this method:
$jObj = json_decode($jsonString);
And to convert it to a associative array, set the second parameter to true
:
$jArr = json_decode($jsonString, true);
By the way to convert your mentioned string back to either of those, you should have a valid JSON string. To achieve it, you should do the following:
Coords
array, remove the two "
(double quote marks) from the start and end of the object.,
), so add commas between the objects in the Coords
array..And you will have a valid JSON String..
Here is your JSON String I converted to a valid one: http://pastebin.com/R16NVerw
You can use document.write
or even console.write
(this is good for debugging).
But your best bet and it gives you more control is to use DOM to update the page.
I was able to handle this in Spring 2 as following
private boolean isInPath(ServletRequest request) {
String PATH_TO_VALIDATE = "/path/";
String path = ((HttpServletRequest) request).getRequestURI();
return path != null && path.toLowerCase().contains(PATH_TO_VALIDATE);
}
have MinGW compiler bin directory added to path.
use mingw32-g++ -s -c source_file_name.cpp -o output_file_name.o
to compile
then mingw32-g++ -o executable_file_name.exe output_file_name.o
to build exe
finally, you run with executable_file_name.exe
As an alternative to sed or perl you may consider to use ed(1) and POSIX character classes.
Note: ed(1) reads the entire file into memory to edit it in-place, so for really large files you should use sed -i ..., perl -i ...
# see:
# - http://wiki.bash-hackers.org/doku.php?id=howto:edit-ed
# - http://en.wikipedia.org/wiki/Regular_expression#POSIX_character_classes
# test
echo $'aaa \177 bbb \200 \214 ccc \254 ddd\r\n' > testfile
ed -s testfile <<< $',l'
ed -s testfile <<< $'H\ng/[^[:graph:][:space:][:cntrl:]]/s///g\nwq'
ed -s testfile <<< $',l'
Something else to check: if your site is using MVC, this can happen if you added [Authorize] to your login controller class. It can't access the login method because it's not authorized so it redirects to the login method --> boom.
1)
select *
from employee em
where CONCAT(em.firstname, ' ', em.lastname) like '%parth pa%';
2)
select *
from employee em
where CONCAT_ws('-', em.firstname, em.lastname) like '%parth-pa%';
First is usefull when we have data like : 'firstname lastname'.
e.g
Second is usefull when we have data like : 'firstname-lastname'. In it you can also use special characters.
e.g
You need to convert the string to date using the to_date()
function
SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31-Dec-2014','DD-MON-YYYY');
OR
SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014','DD MON YYYY');
OR
SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('2014-12-31','yyyy-MM-dd');
This will work only if OrderDate
is stored in Date format
. If it is Varchar
you should apply to_date()
func on that column also like
SELECT * FROM OrderArchive
WHERE to_date(OrderDate,'yyyy-Mm-dd') <= to_date('2014-12-31','yyyy-MM-dd');
1-liner, takes a XML string text
and YourType
as the expected object type. not very different from other answers, just compressed to 1 line:
var result = (YourType)new XmlSerializer(typeof(YourType)).Deserialize(new StringReader(text));
If you've created more than one emulators or if you have an Android device plugged in, adb will complain with
error: more than one device and emulator
adb help
is not extremely clear on what to do:
-d - directs command to the only connected USB device...
-e - directs command to the only running emulator...
-s <serial number> ...
-p <product name or path> ...
The flag you decide to use has to come before the actual adb command:
adb -e install path/to/app.apk
You can use the is_a?
method
>> 1.is_a? Integer
=> true
>> "[email protected]".is_a? Integer
=> false
>> nil.is_a? Integer
=> false
export class GenericValidator {
constructor(private validationMessages: { [key: string]: { [key: string]: string } }) {
}
processMessages(container: FormGroup): { [key: string]: string } {
const messages = {};
for (const controlKey in container.controls) {
if (container.controls.hasOwnProperty(controlKey)) {
const c = container.controls[controlKey];
if (c instanceof FormGroup) {
const childMessages = this.processMessages(c);
// handling formGroup errors messages
const formGroupErrors = {};
if (this.validationMessages[controlKey]) {
formGroupErrors[controlKey] = '';
if (c.errors) {
Object.keys(c.errors).map((messageKey) => {
if (this.validationMessages[controlKey][messageKey]) {
formGroupErrors[controlKey] += this.validationMessages[controlKey][messageKey] + ' ';
}
})
}
}
Object.assign(messages, childMessages, formGroupErrors);
} else {
// handling control fields errors messages
if (this.validationMessages[controlKey]) {
messages[controlKey] = '';
if ((c.dirty || c.touched) && c.errors) {
Object.keys(c.errors).map((messageKey) => {
if (this.validationMessages[controlKey][messageKey]) {
messages[controlKey] += this.validationMessages[controlKey][messageKey] + ' ';
}
})
}
}
}
}
}
return messages;
}
}
I took it from Deborahk and modified it a little bit.
You can do this in XAML easily enough:
<TextBlock>
Hello <Bold>my</Bold> faithful <Underline>computer</Underline>.<Italic>You rock!</Italic>
</TextBlock>
LINQ provides Last():
csharp> int[] nums = {1,2,3,4,5};
csharp> nums.Last();
5
This is handy when you don't want to make a variable unnecessarily.
string lastName = "Abraham Lincoln".Split().Last();
Let eclipse use your java vm directly!
Put these lines at the end of eclipse.ini (located in the directory where eclipse.exe is present):
-vm
<your path to jdk|jre>/bin/javaw.exe
Pay attention that there are two lines. Also make sure that the -vm option is before the -vmargs option (and of course after "openFile").
Useful link Eclispe.ini at wiki.eclipse.org
Do search with LEFT OUTER JOIN
. I don't know if MySQL allows inline VALUES
in join clauses but you can have predefined table for this purposes.
Erland Sommarskog has an exhaustive post about passing data in SQL Server located here:
http://www.sommarskog.se/share_data.html
He covers SQL Server 2000, 2005, and 2008, and it should probably be read in its full detail as there is ample coverage of each method's advantages and drawbacks. However, here are the highlights of the article (frozen in time as of July 2015) for the sake of providing search terms that can be used to look greater details:
This article tackles two related questions:
- How can I use the result set from one stored procedure in another, also expressed as How can I use the result set from a stored
procedure in a SELECT statement?- How can I pass a table data in a parameter from one stored procedure to another?
OUTPUT Parameters
- Not generally applicable, but sometimes overlooked.
Table-valued Functions
- Often the best choice for output-only, but there are several restrictions.
- Examples:
- Inline Functions: Use this to reuse a single SELECT.
- Multi-statement Functions: When you need to encapsulate more complex logic.
Using a Table
- The most general solution. My favoured choice for input/output scenarios.
- Examples:
- Sharing a Temp Table: Mainly for a single pair of caller/callee.
- Process-keyed Table: Best choice for many callers to the same callee.
- Global Temp Tables: A variation of process-keyed.
Table-valued Parameters
- Req. Version: SQL 2008
- Mainly useful when passing data from a client.
INSERT-EXEC
- Deceivingly appealing, but should be used sparingly.
Using the CLR
- Req. Version: SQL 2005
- Complex, but useful as a last resort when INSERT-EXEC does not work.
OPENQUERY
- Tricky with many pitfalls. Discouraged.
Using XML
- Req. Version: SQL 2005
- A bit of a kludge, but not without advantages.
Using Cursor Variables
- Not recommendable.
Better yet, consider sp_getapplock
which is designed for this. Or use SET LOCK_TIMEOUT
Otherwise, you'd have to do something with sys.dm_tran_locks
which I'd use only for DBA stuff: not for user defined concurrency.
I was having the same problems and believe I have solved it. I used the link meta tag as mentioned here to point to the image I wanted, but the key is that if you do that FB won't pull any other images as choices. Also if your image is too big, you won't have any choices at all.
Here's how I fixed my site http://gnorml.com/blog/facebook-link-thumbnails/
For indexed arrays, you can reference them like so:
foo=(a b c)
bar=(d e f)
for arr_var in 'foo' 'bar'; do
declare -a 'arr=("${'"$arr_var"'[@]}")'
# do something with $arr
echo "\$$arr_var contains:"
for char in "${arr[@]}"; do
echo "$char"
done
done
Associative arrays can be referenced similarly but need the -A
switch on declare
instead of -a
.
If the problem is happening on a specific computer,then please try the following fix provided you have Internet Explorer 11.
Please open regedit.exe as an Administrator. Navigate to the following path/paths:
For 32 bit machine:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION
For 64 bit machine:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION &
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION
And delete the REG_DWORD
value iexplore.exe
.
Please close and relaunch the website using Internet Explorer 11, it will default to Edge as Document Mode.
HTML
<div id='a'>
<div>
<a class='click'>abc</a>
</div>
</div>
You could use the XPATH as :
//div[@id='a']//a[@class='click']
output
<a class="click">abc</a>
That said your Python code should be as :
driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")
If you want to plot a single line connecting all the points in the list
plt.plot(li[:])
plt.show()
This will plot a line connecting all the pairs in the list as points on a Cartesian plane from the starting of the list to the end. I hope that this is what you wanted.
here is the easiest way to add progress bar in android Web View.
Add a boolean field in your activity/fragment
private boolean isRedirected;
This boolean will prevent redirection of web pages cause of dead links.Now you can just pass your WebView object and web Url into this method.
private void startWebView(WebView webView,String url) {
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
isRedirected = true;
return false;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
isRedirected = false;
}
public void onLoadResource (WebView view, String url) {
if (!isRedirected) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(SponceredDetailsActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
}
public void onPageFinished(WebView view, String url) {
try{
isRedirected=true;
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
Here when start loading it will call onPageStarted
. Here i setting Boolean field is false. But when page load finish it will come to onPageFinished
method and here Boolean field is set to true. Sometimes if url is dead it will redirected and it will come to onLoadResource()
before onPageFinished
method. For this reason it will not hiding the progress bar. To prevent this i am checking if (!isRedirected)
in onLoadResource()
in onPageFinished()
method before dismissing the Progress Dialog you can write your 10 second time delay code
That's it. Happy coding :)
I've just put together what you may be looking for: http://www.graphdracula.net
It's JavaScript with directed graph layouting, SVG and you can even drag the nodes around. Still needs some tweaking, but is totally usable. You create nodes and edges easily with JavaScript code like this:
var g = new Graph();
g.addEdge("strawberry", "cherry");
g.addEdge("cherry", "apple");
g.addEdge("id34", "cherry");
I used the previously mentioned Raphael JS library (the graffle example) plus some code for a force based graph layout algorithm I found on the net (everything open source, MIT license). If you have any remarks or need a certain feature, I may implement it, just ask!
You may want to have a look at other projects, too! Below are two meta-comparisons:
SocialCompare has an extensive list of libraries, and the "Node / edge graph" line will filter for graph visualization ones.
DataVisualization.ch has evaluated many libraries, including node/graph ones. Unfortunately there's no direct link so you'll have to filter for "graph":
Here's a list of similar projects (some have been already mentioned here):
vis.js supports many types of network/edge graphs, plus timelines and 2D/3D charts. Auto-layout, auto-clustering, springy physics engine, mobile-friendly, keyboard navigation, hierarchical layout, animation etc. MIT licensed and developed by a Dutch firm specializing in research on self-organizing networks.
Cytoscape.js - interactive graph analysis and visualization with mobile support, following jQuery conventions. Funded via NIH grants and developed by by @maxkfranz (see his answer below) with help from several universities and other organizations.
The JavaScript InfoVis Toolkit - Jit, an interactive, multi-purpose graph drawing and layout framework. See for example the Hyperbolic Tree. Built by Twitter dataviz architect Nicolas Garcia Belmonte and bought by Sencha in 2010.
D3.js Powerful multi-purpose JS visualization library, the successor of Protovis. See the force-directed graph example, and other graph examples in the gallery.
Plotly's JS visualization library uses D3.js with JS, Python, R, and MATLAB bindings. See a nexworkx example in IPython here, human interaction example here, and JS Embed API.
sigma.js Lightweight but powerful library for drawing graphs
jsPlumb jQuery plug-in for creating interactive connected graphs
Springy - a force-directed graph layout algorithm
Processing.js Javascript port of the Processing library by John Resig
JS Graph It - drag'n'drop boxes connected by straight lines. Minimal auto-layout of the lines.
RaphaelJS's Graffle - interactive graph example of a generic multi-purpose vector drawing library. RaphaelJS can't layout nodes automatically; you'll need another library for that.
JointJS Core - David Durman's MPL-licensed open source diagramming library. It can be used to create either static diagrams or fully interactive diagramming tools and application builders. Works in browsers supporting SVG. Layout algorithms not-included in the core package
mxGraph Previously commercial HTML 5 diagramming library, now available under Apache v2.0. mxGraph is the base library used in draw.io.
GoJS Interactive graph drawing and layout library
yFiles for HTML Commercial graph drawing and layout library
KeyLines Commercial JS network visualization toolkit
ZoomCharts Commercial multi-purpose visualization library
Syncfusion JavaScript Diagram Commercial diagram library for drawing and visualization.
Cytoscape Web Embeddable JS Network viewer (no new features planned; succeeded by Cytoscape.js)
Canviz JS renderer for Graphviz graphs. Abandoned in Sep 2013.
arbor.js Sophisticated graphing with nice physics and eye-candy. Abandoned in May 2012. Several semi-maintained forks exist.
jssvggraph "The simplest possible force directed graph layout algorithm implemented as a Javascript library that uses SVG objects". Abandoned in 2012.
jsdot Client side graph drawing application. Abandoned in 2011.
Protovis Graphical Toolkit for Visualization (JavaScript). Replaced by d3.
Moo Wheel Interactive JS representation for connections and relations (2008)
JSViz 2007-era graph visualization script
dagre Graph layout for JavaScript
Graphviz Sophisticated graph visualization language
Flare Beautiful and powerful Flash based graph drawing
NodeBox Python Graph Visualization
At least in Firefox (v3.5), cache seems to be disabled rather than simply cleared. If there are multiple instances of the same image on a page, it will be transferred multiple times. That is also the case for img
tags that are added subsequently via Ajax/JavaScript.
So in case you're wondering why the browser keeps downloading the same little icon a few hundred times on your auto-refresh Ajax site, it's because you initially loaded the page using CTRL-F5.
You can convert it to char* if you don't need a modifiable string by using:
(char*) yourString.c_str();
This would be very useful when you want to publish a String variable via MQTT in arduino.
@IBOutlet weak var constraintTxtV: NSLayoutConstraint!
func TextViewDynamicallyIncreaseSize() {
let contentSize = self.txtVDetails.sizeThatFits(self.txtVDetails.bounds.size)
let higntcons = contentSize.height
constraintTxtV.constant = higntcons
}
Batch file to copy folder is easy.
xcopy /Y C:\Source\*.* C:\NewFolder
Save the above as a batch file, and get Windows to run it on start up.
To do the same thing when folder is updated is trickier, you'll need a program that monitors the folder every x time and check for changes. You can write the program in VB/Java/whatever then schedule it to run every 30mins.
set PATH=c:\Program Files\Java\jdk1.6.0_45\bin;%PATH%
this will work if you are working on command prompt
alt text http://img17.imageshack.us/img17/879/billgateslastmoments.jpg
You'll have to create your own chooser dialog merging both intent resolution results.
To do this, you will need to query the PackageManager with PackageManager.queryIntentActivities() for both original intents and create the final list of possible Intents with one new Intent for each retrieved activity like this:
List<Intent> yourIntentsList = new ArrayList<Intent>();
List<ResolveInfo> listCam = packageManager.queryIntentActivities(camIntent, 0);
for (ResolveInfo res : listCam) {
final Intent finalIntent = new Intent(camIntent);
finalIntent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
yourIntentsList.add(finalIntent);
}
List<ResolveInfo> listGall = packageManager.queryIntentActivities(gallIntent, 0);
for (ResolveInfo res : listGall) {
final Intent finalIntent = new Intent(gallIntent);
finalIntent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
yourIntentsList.add(finalIntent);
}
(I wrote this directly here so this may not compile)
Then, for more info on creating a custom dialog from a list see https://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog
Q1) Here are couple things to read or google more :
Main differences between SOAP and RESTful web services in java http://www.ajaxonomy.com/2008/xml/web-services-part-1-soap-vs-rest
It's up to you what do you want to learn first. I'd recommend you take a look at the CXF framework. You can build both rest/soap services.
Q2) Here are couple of good tutorials for soap (I had them bookmarked) :
http://www.benmccann.com/blog/web-services-tutorial-with-apache-cxf/
http://www.mastertheboss.com/web-interfaces/337-apache-cxf-interceptors.html
Best way to learn is not just reading tutorials. But you would first go trough tutorials to get a basic idea so you can see that you're able to produce something(or not) and that would get you motivated.
SO is great way to learn particular technology (or more), people ask lot of wierd questions, and there are ever weirder answers. But overall you'll learn about ways to solve issues on other way. Maybe you didn't know of that way, maybe you couldn't thought of it by yourself.
Subscribe to couple of tags that are interesting to you and be persistent, ask good questions and try to give good answers and I guarantee you that you'll learn this as time passes (if you're persistent that is).
Q3) You will have to answer this one yourself. First by deciding what you're going to build, after all you will need to think of some mini project or something and take it from there.
If you decide to use CXF as your framework for building either REST/SOAP services I'd recommend you look up this book Apache CXF Web Service Development
.
It's fantastic, not hard to read and not too big either (win win).
Try details: use any option..
MessageBox.Show("your message",
"window title",
MessageBoxButtons.OK,
MessageBoxIcon.Warning // for Warning
//MessageBoxIcon.Error // for Error
//MessageBoxIcon.Information // for Information
//MessageBoxIcon.Question // for Question
);
You can use Modernizr to detect simply IE or not IE, by checking for SVG SMIL animation support.
If you've included SMIL feature detection in your Modernizr setup, you can use a simple CSS approach, and target the .no-smil class that Modernizr applies to the html element:
html.no-smil {
/* IE/Edge specific styles go here - hide HTML5 content and show Flash content */
}
Alternatively, you could use Modernizr with a simple JavaScript approach, like so:
if ( Modernizr.smil ) {
/* set HTML5 content */
} else {
/* set IE/Edge/Flash content */
}
Bear in mind, IE/Edge might someday support SMIL, but there are currently no plans to do so.
For reference, here's a link to the SMIL compatibility chart at caniuse.com.
Have you tried to overlay one gradient with a nearly-transparent opacity for the highlight on top of another image with an opaque opacity for the green gradient?
You may wonder, why the syntax is valid (but not working as expected):
var func = p => { foo: "bar" }
It's because of JavaScript's label syntax:
So if you transpile the above code to ES5, it should look like:
var func = function (p) {
foo:
"bar"; //obviously no return here!
}
Ran into this exact problem.
What I ended up doing:
# starting with date string
sdt = "20190901"
std_format = '%Y%m%d'
# create naive datetime object
from datetime import datetime
dt = datetime.strptime(sdt, sdt_format)
# extract the relevant date time items
dt_formatters = ['%Y','%m','%d']
dt_vals = tuple(map(lambda formatter: int(datetime.strftime(dt,formatter)), dt_formatters))
# set timezone
import pendulum
tz = pendulum.timezone('utc')
dt_tz = datetime(*dt_vals,tzinfo=tz)
ln -s /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk '/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk'
might help you. It fixed my problem.
Check the items in forEach
<c:forEach items="${pools}" var="pool">
${pool.name}
</c:forEach>
Some times items="${pools}" has an extra space or it acts like string, retyping it should solve the issue.
for me it was that i had "ENGINE=MyISAM" kind of tables , once i changed it to "ENGINE=InnoDB" it worked:) in PhpMyAdmin on Azure App Service :)
SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;
:- In MySQL, you can get the concatenated values of expression combinations . To eliminate duplicate values, use the DISTINCT clause. To sort values in the result, use the ORDER BY clause. To sort in reverse order, add the DESC (descending) keyword to the name of the column you are sorting by in the ORDER BY clause. The default is ascending order; this may be specified explicitly using the ASC keyword. The default separator between values in a group is comma (“,”). To specify a separator explicitly, use SEPARATOR followed by the string literal value that should be inserted between group values. To eliminate the separator altogether, specify SEPARATOR ''.
GROUP_CONCAT([DISTINCT] expr [,expr ...]
[ORDER BY {unsigned_integer | col_name | expr}
[ASC | DESC] [,col_name ...]]
[SEPARATOR str_val])
OR
mysql> SELECT student_name,
-> GROUP_CONCAT(DISTINCT test_score
-> ORDER BY test_score DESC SEPARATOR ' ')
-> FROM student
-> GROUP BY student_name;
I will correct usage for that method that @BullyWillPlaza suggested. Reason is that when I try to add add textArea to only contextMenu it's not visible, and if i add it to both to contextMenu and some panel it ecounters: Different parent double association if i try to switch to Design editor.
TexetObjcet.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)){
contextmenu.add(TexetObjcet);
contextmenu.show(TexetObjcet, 0, 0);
}
}
});
Make mouse listener like this for text object you need to have popup on. What this will do is when you right click on your text object it will then add that popup and display it. This way you don't encounter that error. Solution that @BullyWillPlaza made is very good, rich and fast to implement in your program so you should try it our see how you like it.
This is my simple solution
var arr = ["you", "are", "the", "love", "of", "my", "life"];
var sorted = arr.sort(function (a, b){
return b.length - a.length;
});
console.log(sorted[0])
Here's an accessible solution
label {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
label input {_x000D_
position: absolute;_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
label:focus-within {_x000D_
outline: 1px solid orange;_x000D_
}
_x000D_
<div class="radio-toolbar">_x000D_
<label><input type="radio" value="all" checked>All</label>_x000D_
<label><input type="radio" value="false">Open</label>_x000D_
<label><input type="radio" value="true">Archived</label>_x000D_
</div>
_x000D_
The answer from ks1322 helped me to identify the issue while using docker-compose exec
:
If you omit the -T
flag, docker-compose exec
add a special character that break output, we see b
instead of 1b
:
$ test=$(/usr/local/bin/docker-compose exec db bash -c "echo 1")
$ echo "${test}b"
b
echo "${test}" | cat -vte
1^M$
With -T
flag, docker-compose exec
works as expected:
$ test=$(/usr/local/bin/docker-compose exec -T db bash -c "echo 1")
$ echo "${test}b"
1b
In a terminal window, you can type:
kill -9 $(ps -p $PPID -o ppid=)
This will kill the Terminal application process, which is the parent of the parent of the current process, as seen by the kill command.
To close a Terminal window from within a running script, you need to go up one more level in the process hierarchy like this:
kill -9 $(ps -p $(ps -p $PPID -o ppid=) -o ppid=)
this is error in some answers for replace |
var mystring = "this|is|a|test";
mystring = mystring.replace(/|/g, "");
alert(mystring);
this correction is correct but the | In the end it should look like this \|
var mystring = "this|is|a|test";
mystring = mystring.replace(/\|/g, "");
alert(mystring);
/path/to/project
Copy projects into workspace
and Add project to working sets
On ASP.net web forms use in the @page AspCompat="true", add the system.windows.forms to you project. At your web.config add:
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" />
</appSettings>
Then you can use:
Clipboard.SetText(CreateDescription());
I've noticed that if you set the theme in the AndroidManifest, it seems to get rid of that short time where you can see the action bar. So, try adding this to your manifest:
<android:theme="@android:style/Theme.NoTitleBar">
Just add it to your application
tag to apply it app-wide.
Yeah, as others have said, there's no convenient 'DELETE FROM my_table ... CASCADE' (or equivalent). To delete non-cascading foreign key-protected child records and their referenced ancestors, your options include:
It's on purpose that circumventing foreign key constraints isn't made convenient, I assume; but I do understand why in particular circumstances you'd want to do it. If it's something you'll be doing with some frequency, and if you're willing to flout the wisdom of DBAs everywhere, you may want to automate it with a procedure.
I came here a few months ago looking for an answer to the "CASCADE DELETE just once" question (originally asked over a decade ago!). I got some mileage out of Joe Love's clever solution (and Thomas C. G. de Vilhena's variant), but in the end my use case had particular requirements (handling of intra-table circular references, for one) that forced me to take a different approach. That approach ultimately became recursively_delete (PG 10.10).
I've been using recursively_delete in production for a while, now, and finally feel (warily) confident enough to make it available to others who might wind up here looking for ideas. As with Joe Love's solution, it allows you to delete entire graphs of data as if all foreign key constraints in your database were momentarily set to CASCADE, but offers a couple additional features:
Use a Java 8 Stream
.
myString.chars().mapToObj(i -> (char) i).collect(Collectors.toList());
Breakdown:
myString
.chars() // Convert to an IntStream
.mapToObj(i -> (char) i) // Convert int to char, which gets boxed to Character
.collect(Collectors.toList()); // Collect in a List<Character>
(I have absolutely no idea why String#chars()
returns an IntStream
.)
Use this method to convert from NSString
to NSdate
:
-(NSDate *)getDateFromString:(NSString *)pstrDate
{
NSDateFormatter* myFormatter = [[NSDateFormatter alloc] init];
[myFormatter setDateFormat:@"dd/MM/yyyy"];
NSDate* myDate = [myFormatter dateFromString:pstrDate];
return myDate;
}
If you have an Asp.Net web application, you can also set it in the web.config
so that it is the same throughout the whole web application
<system.web>
...
<globalization
requestEncoding="utf-8"
responseEncoding="utf-8"
culture="en-GB"
uiCulture="en-GB"
enableClientBasedCulture="false"/>
...
</system.web>
Correct me if wrong...I think request does persist between consecutive pages..
Think you traverse from page 1--> page 2-->page 3.
You have some value set in the request object using setAttribute from page 1, which you retrieve in page 2 using getAttribute,then if you try setting something again in same request object to retrieve it in page 3 then it fails giving you null value as "the request that created the JSP, and the request that gets generated when the JSP is submitted are completely different requests and any attributes placed on the first one will not be available on the second".
I mean something like this in page 2 fails:
Where as the same thing has worked in case of page 1 like:
So I think I would need to proceed with either of the two options suggested by Phill.
I would suggest the following:
String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName);
Maintain a set
and remove a randomly picked-up element (with choice
) until the list is empty:
s = set(range(1, 6))
import random
while len(s) > 0:
s.remove(random.choice(list(s)))
print(s)
Three runs give three different answers:
>>>
set([1, 3, 4, 5])
set([3, 4, 5])
set([3, 4])
set([4])
set([])
>>>
set([1, 2, 3, 5])
set([2, 3, 5])
set([2, 3])
set([2])
set([])
>>>
set([1, 2, 3, 5])
set([1, 2, 3])
set([1, 2])
set([1])
set([])
A general answer involves using a Manager
object. Adapted from the docs:
from multiprocessing import Process, Manager
def f(d):
d[1] += '1'
d['2'] += 2
if __name__ == '__main__':
manager = Manager()
d = manager.dict()
d[1] = '1'
d['2'] = 2
p1 = Process(target=f, args=(d,))
p2 = Process(target=f, args=(d,))
p1.start()
p2.start()
p1.join()
p2.join()
print d
Output:
$ python mul.py
{1: '111', '2': 6}
In matrix multiplication there are 3 for loop, we are using since execution of each for loop requires time complexity O(n)
. So for three loops it becomes O(n^3)
<GridViewName>.ClearSelection(); ----------------------------------------------------1
foreach(var item in itemList) -------------------------------------------------------2
{
rowHandle =<GridViewName>.LocateByValue("UniqueProperty_Name", item.unique_id );--3
if (rowHandle != GridControl.InvalidRowHandle)------------------------------------4
{
<GridViewName>.SelectRow(rowHandle);------------------------------------ -----5
}
}
Where itemList is list of rows to be selected in the grid view.
I have fixed this issue with mine as well, but I had to change a couple of things. I require that on my Windows 10 machine I keep my C# and Visual Studio development environment, so I didn't want to tinker with any services. All I had to do was download the latest version of XAMPP and change the listening ports for 80 and 443. They were located in two files:
C:\xampp\apache\conf\httpd.conf
Listen 122
ServerName localhost:122
C:\xampp\apache\conf\extra\httpd-ssl.conf
Listen 444
Changing the above from port 80 to 122 and 443 to 444 allowed me to have Apache run and serve pages while keeping everything else the same for my ASP.NET development. Hopefully this helps someone out there. In the end this is a very simple fix.
Direct your browser to: http://localhost:122
I'm not sure how necessary this is, and it adds a call to getElementById
, but if you're really keen on getting inline JavaScript out of your code, you can pass it as an HTML attribute, namely:
<span class="metadata" id="metadata-size-of-widget" title="<?php echo json_encode($size_of_widget) ?>"></span>
And then in your JavaScript:
var size_of_widget = document.getElementById("metadata-size-of-widget").title;
You didn't call the function and you have other errors, should be:
function checkFilled() {
var inputVal = document.getElementById("subEmail");
if (inputVal.value == "") {
inputVal.style.backgroundColor = "yellow";
}
}
checkFilled();
You were setting inputVal
to the string value of the input, but then you tried to set style.backgroundColor
on it, which won't work because it's a string, not the element. I changed your variable to store the element object instead of its value.
My suggestion:
using System.Linq;
string myStringOutput = String.Join(",", myArray.Select(p => p.ToString()).ToArray());
reference: https://coderwall.com/p/oea7uq/convert-simple-int-array-to-string-c
You have to replace YourID and value="3" for your current ones.
$(document).ready(function() {_x000D_
$('#YourID option[value="3"]').attr("selected", "selected");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
<select id="YourID">_x000D_
<option value="1">A</option>_x000D_
<option value="2">B</option>_x000D_
<option value="3">C</option>_x000D_
<option value="4">D</option>_x000D_
</select>
_x000D_
and value="3" for your current ones.
$('#YourID option[value="3"]').attr("selected", "selected");
<select id="YourID" >
<option value="1">A </option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
I think maybe you can try
python manage.py syncdb
Even sqlite3 need syncdb
sencondly, you can check your sql file name
it should look like xxx.s3db
Add your multiple columns with comma separations:
UPDATE settings SET postsPerPage = $postsPerPage, style= $style WHERE id = '1'
However, you're not sanitizing your inputs?? This would mean any random hacker could destroy your database. See this question: What's the best method for sanitizing user input with PHP?
Also, is style a number or a string? I'm assuming a string, so it would need to be quoted.
This works for me:
try {
$statusUpdate = $facebook->api('/me/feed', 'post',
array('name'=>'My APP on Facebook','message'=> 'I am here working',
'privacy'=> array('value'=>'CUSTOM','friends'=>'SELF'),
'description'=>'testing my description',
'picture'=>'https://fbcdn-photos-a.akamaihd.net/mypicture.gif',
'caption'=>'apps.facebook.com/myapp','link'=>'http://apps.facebook.com/myapp'));
} catch (FacebookApiException $e) {
d($e);
}
great answer from @David, here is for Python 3 without the generic try-except:
def send_email(user, password, recipient, subject, body):
gmail_user = user
gmail_pwd = password
FROM = user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd)
server.sendmail(FROM, TO, message)
server.close()
I do this as a side-effect of pushing with the -u
option as in
$ git push -u origin branch-name
The equivalent long option is --set-upstream
.
The git-branch
command also understands --set-upstream
, but its use can be confusing. Version 1.8.0 modifies the interface.
git branch --set-upstream
is deprecated and may be removed in a relatively distant future.git branch [-u|--set-upstream-to]
has been introduced with a saner order of arguments.…
It was tempting to say
git branch --set-upstream origin/master
, but that tells Git to arrange the local branch "origin/master" to integrate with the currently checked out branch, which is highly unlikely what the user meant. The option is deprecated; use the new--set-upstream-to
(with a short-and-sweet-u
) option instead.
Say you have a local foo
branch and want it to treat the branch by the same name as its upstream. Make this happen with
$ git branch foo
$ git branch --set-upstream-to=origin/foo
or just
$ git branch --set-upstream-to=origin/foo foo
I think the best way to solve this is to follow the error advice, hence looking for server logs. To enable logs I added
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
<listeners>
<add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="c:\logs\TracesServ_ce.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>
Then you go to c:\logs\TracesServ_ce.svclog open it with microsoft service trace viewer. And see what the problem really is.
Quote_Month (Worksheet!$D:$D) contains a formula (=TEXT(Worksheet!$E:$E,"mmm-yy"))to convert a date/time number from another column into a text based month reference.
You can use OR
by adding +
in Sumproduct
. See this
=SUMPRODUCT((Quote_Value)*(Salesman="JBloggs")*(Days_To_Close<=90)*((Quote_Month="Cond1")+(Quote_Month="Cond2")+(Quote_Month="Cond3")))
ScreenShot
In core_test.py, do the following:
import sys
sys.path.append('../components')
from core import GameLoopEvents
Env: macOS Mojave 10.14.4
Install: homebrew
Location:/usr/local/Cellar/mongodb/4.0.3_1
Note :If update version by
brew upgrade mongo
,the folder 4.0.4_1
will be removed and replace with the new version folder
HashMap<Integer,Player> hash = new HashMap<Integer,Player>();
Set keys = hash.keySet();
Iterator itr = keys.iterator();
while(itr.hasNext()){
Integer key = itr.next();
Player objPlayer = (Player) hash.get(key);
System.out.println("The player "+objPlayer.getName()+" has "+objPlayer.getScore()+" points");
}
You can use this code to print all scores in your format.
You can do this (YAML block):
~~~
# This is a
# multiline
# comment
...
I tried with latex output only, please confirm for others.
If there are duplicate keys in the first list that map to different values in the second list, like a 1-to-many relationship, but you need the values to be combined or added or something instead of updating, you can do this:
i = iter(["a", "a", "b", "c", "b"])
j = iter([1,2,3,4,5])
k = list(zip(i, j))
for (x,y) in k:
if x in d:
d[x] = d[x] + y #or whatever your function needs to be to combine them
else:
d[x] = y
In that example, d == {'a': 3, 'c': 4, 'b': 8}
use the helper function in laravel 5.1 instead:
return response()->json(['name' => 'Abigail', 'state' => 'CA']);
This will create an instance of \Illuminate\Routing\ResponseFactory
. See the phpDocs for possible parameters below:
/**
* Return a new JSON response from the application.
*
* @param string|array $data
* @param int $status
* @param array $headers
* @param int $options
* @return \Symfony\Component\HttpFoundation\Response
* @static
*/
public static function json($data = array(), $status = 200, $headers = array(), $options = 0){
return \Illuminate\Routing\ResponseFactory::json($data, $status, $headers, $options);
}
You can use the WSDL2JAVA Codegen (or) You can simply use the 'Web Service/WebServiceClient' Wizard available in the Eclipse IDE. Open the IDE and press 'Ctrl+N', selectfor 'Web Service/WebServiceClient', specify the wsdl URL, ouput folder and select finish.
It creates the complete source files that you would need.
All of these are good answers, but I would like to suggest one more that I feel is a better code standard. You may choose to use a flag in the loop condition that indicates whether or not to continue looping and avoid using break
all together.
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
$length = count($arr);
$found = false;
for ($i = 0; $i < $length && !$found; $i++) {
$val = $arr[$i];
if ($val == 'stop') {
$found = true; // this will cause the code to
// stop looping the next time
// the condition is checked
}
echo "$val<br />\n";
}
I consider this to be better code practice because it does not rely on the scope that break
is used. Rather, you define a variable that indicates whether or not to break a specific loop. This is useful when you have many loops that may or may not be nested or sequential.
For others needing a key binding:
{ "keys": ["ctrl+="], "command": "upper_case" },
{ "keys": ["ctrl+-"], "command": "lower_case" }
Nope, you cannot just change it, you would have to upload a new package as a new app. Have a look at the Google's app Talk
, its name was changed to Hangouts
, but the package name is still com.google.android.talk
. Because it is not doable :) Cheers.
You just have to replace the break
with a return
statement.
Think of the code inside the Foreach-Object
as an anonymous function. If you have loops inside the function, just use the control keywords applying to the construction (continue
, break
, ...).
I'm using react-native CLI and I just restart rn-cli, ctrl+c
to stop the process then npx react-native start
The best way to solve this problem would be by starting with customizing Bootstrap using their customization tools.
http://getbootstrap.com/customize/
Go down to @headings-color and change it from "inherit" to something that you would like your headers to be across the site (if you like the default just change it to #333).
Note that this will keep all your headings the same color, as you requested.
Now in order to accomplish what you want that after you make this change you can now overwrite them specifically in your own CSS to apply your own color to them. The "inherit" keyword I always have found to be a pain in frameworks.
The Java Virtual Machine takes two command line arguments which set the initial and maximum heap sizes: -Xms and -Xmx. You can add a system environment variable named _JAVA_OPTIONS, and set the heap size values there.
For example if you want a 512Mb initial and 1024Mb maximum heap size you could use:
under Windows:
SET _JAVA_OPTIONS = -Xms512m -Xmx1024m
under Linux:
export _JAVA_OPTIONS="-Xms512m -Xmx1024m"
It is possible to read the default JVM heap size programmatically by using totalMemory() method of Runtime class. Use following code to read JVM heap size.
public class GetHeapSize {
public static void main(String[]args){
//Get the jvm heap size.
long heapSize = Runtime.getRuntime().totalMemory();
//Print the jvm heap size.
System.out.println("Heap Size = " + heapSize);
}
}
You use new
to perform dynamic allocation. It returns a pointer that points to the dynamically allocated object.
You have no reason to use new
, since A
is an automatic variable. You can simply initialise A
using its constructor:
vector<vector<int> > A(dimension, vector<int>(dimension));
Like said Gumbo,
<?php
$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry
?>
The syntax you're after is possible with a little helper function that converts a Runnable
into Action<Void, Void>
(you can place it in Action
for example):
public static Action<Void, Void> action(Runnable runnable) {
return (v) -> {
runnable.run();
return null;
};
}
// Somewhere else in your code
Action<Void, Void> action = action(() -> System.out.println("foo"));
Create a "module" object and declare variables in there. Unlike class-objects that have to be instantiated each time, the module objects are always available. Therefore, a public variable, function, or property in a "module" will be available to all the other objects in the VBA project, macro, Excel formula, or even within a MS Access JET-SQL query def.
You can get the Parent of a control via
myControl.Parent
See MSDN: Control.Parent
Just another way to use Git's awesomeness...
git difftool HEAD HEAD@{N} /PATH/FILE.ext
In C# 7:
(startAngle, stopAngle) = (stopAngle, startAngle);
I will go for Inner Join in this context. If I would have used contains, it would iterate 6 times despite if the fact that there are just one match.
var desiredNames = new[] { "Pankaj", "Garg" };
var people = new[]
{
new { FirstName="Pankaj", Surname="Garg" },
new { FirstName="Marc", Surname="Gravell" },
new { FirstName="Jeff", Surname="Atwood" }
};
var records = (from p in people join filtered in desiredNames on p.FirstName equals filtered select p.FirstName).ToList();
Suppose I have two list objects.
List 1 List 2
1 12
2 7
3 8
4 98
5 9
6 10
7 6
Using Contains, it will search for each List 1 item in List 2 that means iteration will happen 49 times !!!
I recommend a clean shutdown with the exit(0) builtin rather than using sys.exit()
I'm not sure if this is good advice.
The very documentation mentioned reads:
The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace. They are useful for the interactive interpreter shell and should not be used in programs.
Then:
exit(code=None)
Objects that when printed, print a message like “Use quit() or Ctrl-D (i.e. EOF) to exit”, and when called, raise SystemExit with the specified exit code.
If we compare it to sys.exit() documentation, it's using the same mechanism which is raising a SystemExit
exception.
Your code is way more cluttered than necessary.
Replace (Not (X Is Nothing))
with X IsNot Nothing
and omit the outer parentheses:
If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
For i As Integer = 0 To comp.Container.Components.Count() - 1
fixUIIn(comp.Container.Components(i), style)
Next
End If
Much more readable. … Also notice that I’ve removed the redundant Step 1
and the probably redundant .Item
.
But (as pointed out in the comments), index-based loops are out of vogue anyway. Don’t use them unless you absolutely have to. Use For Each
instead:
If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
For Each component In comp.Container.Components
fixUIIn(component, style)
Next
End If
CentOs 6.5+ & PHP 5.6:
sudo yum install php56-gd
service httpd restart
Six years on, this is still at the top for some searches. Things have changed a lot since then. Now the defacto standard is more or less to use Volley and the NetworkImageView which takes care of the heavy lifting for you.
Assuming that you already have your Apaters, Loaders and ListFragments setup properly, this official google tutorial explains how to use NetworkImageView to load the images. Images are automatically loaded in a background thread and the view updated on the UI thread. It even supports caching.
Not very technical answer but just letting you know.
For easy stuff like printing you can define a sort of function in your preprocessors like
#define print(x) cout << x << endl
One simple solution:
cond1 <- df$sub == 1 & df$day == 2
cond2 <- df$sub == 3 & df$day == 4
df <- df[!(cond1 | cond2),]
$('#div-id').click(function(){
location.reload();
});
This is the correct syntax.
$('#div-id').html(newContent); //This doesnt work
The problem with the former is that what you're doing is USE 'myDB'
rather than USE myDB
.
you're passing a string; but USE is looking for an explicit reference.
The latter example works for me.
declare @sql varchar(20)
select @sql = 'USE myDb'
EXEC sp_sqlexec @Sql
-- also works
select @sql = 'USE [myDb]'
EXEC sp_sqlexec @Sql
I know when you said "contents" you didn't mean this, but if you want to find all the values of all the attributes of a webelement this is a pretty nifty way to do that with javascript in python:
everything = b.execute_script(
'var element = arguments[0];'
'var attributes = {};'
'for (index = 0; index < element.attributes.length; ++index) {'
' attributes[element.attributes[index].name] = element.attributes[index].value };'
'var properties = [];'
'properties[0] = attributes;'
'var element_text = element.textContent;'
'properties[1] = element_text;'
'var styles = getComputedStyle(element);'
'var computed_styles = {};'
'for (index = 0; index < styles.length; ++index) {'
' var value_ = styles.getPropertyValue(styles[index]);'
' computed_styles[styles[index]] = value_ };'
'properties[2] = computed_styles;'
'return properties;', element)
you can also get some extra data with element.__dict__
.
I think this is about all the data you'd ever want to get from a webelement.
Had the same issue and all solutions didn't work. Found this gem and thought I'd pass along if it helps someone else. Install on Server 2012 R2 getting the DLL missing error, try to reinstall VS C++ 2015 and get an error. Fix is to do the following:
Seems the file
C:\ProgramData\Package Cache\...\packages\Patch\x64\Windows8.1-KB2999226-x64.msu
has problems being installed.
Open admin command prompt do:
c:
mkdir tmp
mkdir tmp\tmp
move "C:\ProgramData\Package Cache\...\packages\Patch\x64\Windows8.1-KB2999226-x64.msu" c:\tmp
expand -F:* c:\tmp\Windows8.1-KB2999226-x64.msu c:\tmp\tmp
dism /online /add-package /packagepath:c:\tmp\tmp\Windows8.1-KB2999226-x64.cab
NOTE: replace the "..." with the correct folder name. After this reinstall the VS C++ 2015 package.
there you go
date('d.m.Y',strtotime("-1 days"));
this will work also if month change
File > Project Structure > Build Variants > Select release > Make sure 'Signing Config' is not empty > if it is select from the drop window the $signingConfigs.release
I did this with Android Studio 3.1.4 and it allowed me to create a release apk after following all the steps above of creating the release apk and release key and adding the info to the app gradle. Cheers!
You can't resolve a promise with multiple properties just like you can't return multiple values from a function. A promise conceptually represents a value over time so while you can represent composite values you can't put multiple values in a promise.
A promise inherently resolves with a single value - this is part of how Q works, how the Promises/A+ spec works and how the abstraction works.
The closest you can get is use Q.spread
and return arrays or use ES6 destructuring if it's supported or you're willing to use a transpilation tool like BabelJS.
As for passing context down a promise chain please refer to Bergi's excellent canonical on that.
EDIT: the following is wrong, because Cell("width") returns the width of the last modified cell.
Cell("width")
returns the width of the current cell, so you don't need a reference to the current cell. If you need one, though, cell("address")
returns the address of the current cell, so if you need a reference to the current cell, use indirect(cell("address"))
. See the documentation: http://www.techonthenet.com/excel/formulas/cell.php
From the Postgres documentation page:
sudo mkdir -p /etc/paths.d && echo /Applications/Postgres.app/Contents/Versions/latest/bin | sudo tee /etc/paths.d/postgresapp
restart your terminal and you will have it in your path.
From: Developer > reference - Application
There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.
If they are in the same controller class, it would be:
foreach ( $characters as $character) {
$num += $this->getFactorial($index) * $index;
$index ++;
}
Otherwise you need to create a new instance of the class, and call the method, ie:
$controller = new MyController();
foreach ( $characters as $character) {
$num += $controller->getFactorial($index) * $index;
$index ++;
}
double d = 1.234;
int i = Convert.ToInt32(d);
Handles rounding like so:
rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.
TextView
comes with 4 compound drawables, one for each of left, top, right and bottom.
In your case, you do not need the LinearLayout
and ImageView
at all. Just add android:drawableLeft="@drawable/up_count_big"
to your TextView
.
See TextView#setCompoundDrawablesWithIntrinsicBounds for more info.
All you need to do is to include the following libraries in tour app.module.ts and also include it in your imports:
import { HttpModule } from '@angular/http';
@NgModule({
imports: [ HttpModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
If I understand what you need, try this:
SELECT id, pass, AVG(val) AS val_1
FROM data_r1
GROUP BY id, pass;
Or, if you want just one row for every id, this:
SELECT d1.id,
(SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2
WHERE d2.id = d1.id AND pass = 1) as val_1,
(SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2
WHERE d2.id = d1.id AND pass = 2) as val_2,
(SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2
WHERE d2.id = d1.id AND pass = 3) as val_3,
(SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2
WHERE d2.id = d1.id AND pass = 4) as val_4,
(SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2
WHERE d2.id = d1.id AND pass = 5) as val_5,
(SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2
WHERE d2.id = d1.id AND pass = 6) as val_6,
(SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2
WHERE d2.id = d1.id AND pass = 7) as val_7
from data_r1 d1
GROUP BY d1.id
I was working with statistics in Java 2 years ago and I still got the codes of a function that allows you to round a number to the number of decimals that you want. Now you need two, but maybe you would like to try with 3 to compare results, and this function gives you this freedom.
/**
* Round to certain number of decimals
*
* @param d
* @param decimalPlace
* @return
*/
public static float round(float d, int decimalPlace) {
BigDecimal bd = new BigDecimal(Float.toString(d));
bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
return bd.floatValue();
}
You need to decide if you want to round up or down. In my sample code I am rounding up.
Hope it helps.
EDIT
If you want to preserve the number of decimals when they are zero (I guess it is just for displaying to the user) you just have to change the function type from float to BigDecimal, like this:
public static BigDecimal round(float d, int decimalPlace) {
BigDecimal bd = new BigDecimal(Float.toString(d));
bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
return bd;
}
And then call the function this way:
float x = 2.3f;
BigDecimal result;
result=round(x,2);
System.out.println(result);
This will print:
2.30
This worked on my test file (note the index in VBA starts from zero):
Sub DV_Test()
Dim ValidationList(5) As Variant, i As Integer
For i = 0 To UBound(ValidationList)
ValidationList(i) = i + 1
Next
With Range("A1").Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlEqual, Formula1:=Join(ValidationList, ",")
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End Sub
I used xlEqual
because that's what I think you are trying to get people to select one of the list.
Perhaps try:
var body = document.getElementsByTagName('body')[0];
body.setAttribute("data-body","");
Here is a link from developer.nokia.com wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator
And another link here
AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).
For SQL Server 2000 and above, I prefer the following parsing of Joe's answer:
declare @sqlVers numeric(4,2)
select @sqlVers = left(cast(serverproperty('productversion') as varchar), 4)
Gives results as follows:
Result Server Version 8.00 SQL 2000 9.00 SQL 2005 10.00 SQL 2008 10.50 SQL 2008R2 11.00 SQL 2012 12.00 SQL 2014
Basic list of version numbers here, or exhaustive list from Microsoft here.
In addition to the other answer, I would like to point out that this reasoning is also known as the De Morgan's law. It's actually more about mathematics than programming, but it is so fundamental that every programmer should know about it.
Your problem started like this:
enabled = A and B
disabled = not ( A and B )
So far so good, but you went one step further and tried to remove the braces.
And that's a little tricky, because you have to replace the and
/&&
with an or
/||
.
not ( A and B ) = not(A) OR not(B)
Or in a more mathematical notation:
I always keep this law in mind whenever I simplify conditions or work with probabilities.
You could also use CEILING
which rounds up to an integer or desired multiple of significance
ie
=CEILING(A1,10)
rounds up to a multiple of 10
12340.0001
will become 12350
Assuming the type is CV_8UC3 you would do this:
for(int i = 0; i < foo.rows; i++)
{
for(int j = 0; j < foo.cols; j++)
{
Vec3b bgrPixel = foo.at<Vec3b>(i, j);
// do something with BGR values...
}
}
Here is the documentation for Vec3b. Hope that helps! Also, don't forget OpenCV stores things internally as BGR not RGB.
EDIT :
For performance reasons, you may want to use direct access to the data buffer in order to process the pixel values:
Here is how you might go about this:
uint8_t* pixelPtr = (uint8_t*)foo.data;
int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;
for(int i = 0; i < foo.rows; i++)
{
for(int j = 0; j < foo.cols; j++)
{
bgrPixel.val[0] = pixelPtr[i*foo.cols*cn + j*cn + 0]; // B
bgrPixel.val[1] = pixelPtr[i*foo.cols*cn + j*cn + 1]; // G
bgrPixel.val[2] = pixelPtr[i*foo.cols*cn + j*cn + 2]; // R
// do something with BGR values...
}
}
Or alternatively:
int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;
for(int i = 0; i < foo.rows; i++)
{
uint8_t* rowPtr = foo.row(i);
for(int j = 0; j < foo.cols; j++)
{
bgrPixel.val[0] = rowPtr[j*cn + 0]; // B
bgrPixel.val[1] = rowPtr[j*cn + 1]; // G
bgrPixel.val[2] = rowPtr[j*cn + 2]; // R
// do something with BGR values...
}
}
I ran into the same problem. Here's how I solved it:
find . -name '*FoooBar*' | sed 's/.*/"&"/' | xargs cp ~/foo/bar
I used sed
to substitute each line of input with the same line, but surrounded by double quotes. From the sed
man page, "...An ampersand (``&'') appearing in the replacement is replaced by the string matching the RE..." -- in this case, .*
, the entire line.
This solves the xargs: unterminated quote
error.
In Visual Studio 2019- Tools > Command Line > Developer Command Prompt.enter image description here
Here's a useful little function, which makes using/creating iOS folders a little easier.
You pass it the name of a subfolder, it'll return the full path back to you, and make sure the directory exists.
(Personally, I stick this static function in my AppDelete class, but perhaps this isn't the smartest place to put it.)
Here's how you would call it, to get the "full path" of a MySavedImages subdirectory:
NSString* fullPath = [AppDelegate getFullPath:@"MySavedImages"];
And here's the full function:
+(NSString*)getFullPath:(NSString*)folderName
{
// Check whether a subdirectory exists in our sandboxed Documents directory.
// Returns the full path of the directory.
//
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if (paths.count < 1)
return nil;
NSString *rootFolder = [paths firstObject];
NSString* fullFolderPath = [rootFolder stringByAppendingPathComponent:folderName];
BOOL isDirectory;
NSFileManager* manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:fullFolderPath isDirectory:&isDirectory] || !isDirectory) {
NSError *error = nil;
NSDictionary *attr = [NSDictionary dictionaryWithObject:NSFileProtectionComplete
forKey:NSFileProtectionKey];
[manager createDirectoryAtPath:fullFolderPath
withIntermediateDirectories:YES
attributes:attr
error:&error];
if (error) {
NSLog(@"Error creating directory path: %@", [error localizedDescription]);
return nil;
}
}
return fullFolderPath;
}
Using this little function, it's easy to create a directory in your app's Documents directory (if it doesn't already exist), and to write a file into it.
Here's how I would create the directory, and write the contents of one of my image files into it:
// Let's create a "MySavedImages" subdirectory (if it doesn't already exist)
NSString* fullPath = [AppDelegate getFullPath:@"MySavedImages"];
// As an example, let's load the data in one of my images files
NSString* imageFilename = @"icnCross.png";
UIImage* image = [UIImage imageNamed:imageFilename];
NSData *imageData = UIImagePNGRepresentation(image);
// Obtain the full path+filename where we can write this .png to, in our new MySavedImages directory
NSString* imageFilePathname = [fullPath stringByAppendingPathComponent:imageFilename];
// Write the data
[imageData writeToFile:imageFilePathname atomically:YES];
Hope this helps !
Go to file ---> switch workspace .It will work
In my case I was trying to connect to a remote mysql server on cent OS. After going through a lot of solutions (granting all privileges, removing ip bindings,enabling networking) problem was still not getting solved.
As it turned out, while looking into various solutions,I came across iptables, which made me realize mysql port 3306 was not accepting connections.
Here is a small note on how I checked and resolved this issue.
telnet (mysql server ip) [portNo]
iptables -A INPUT -i eth0 -p tcp -m tcp --dport 3306 -j ACCEPT
service iptables stop
Hope this helps.
The files selected are stored in an array: [input].files
For example, you can access the items
// assuming there is a file input with the ID `my-input`...
var files = document.getElementById("my-input").files;
for (var i = 0; i < files.length; i++)
{
alert(files[i].name);
}
For jQuery-comfortable people, it's similarly easy
// assuming there is a file input with the ID `my-input`...
var files = $("#my-input")[0].files;
for (var i = 0; i < files.length; i++)
{
alert(files[i].name);
}
jQuery might be missing.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
for IE9 I found that a meta tag was required to set the mode
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
<video width="400" height="300" preload controls>
<source src="movie.mp4" type="video/mp4" />
Your browser does not support the video tag
</video>
You need to define a class for the bullets you want to hide. For examples
.no-bullets {
list-style-type: none;
}
Then apply it to the list you want hidden bullets:
<ul class="no-bullets">
All other lists (without a specific class) will show the bulltets as usual.
There is a simple way to align vertically and horizontally a div in css.
Just put a height to your div and apply this style
.hv-center {
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}
Hope this helped.
To specify a port for a Web application project that uses IIS Express
In Solution Explorer, right-click the name of the application and then select Properties. Click the Web tab.
In the Servers section, under Use Local IIS Web server, in the Project URL box change the port number.
To the right of the Project URL box, click Create Virtual Directory, and then click OK.
In the File menu, click Save Selected Items.
To verify the change, press CTRL+F5 to run the project. The new port number appears in the address bar of the browser.
From How to: Specify a Port for the Development Server (archive.org backup here).
Simple and easy to understand.
var mySearchTimeout;
$('#ctl00_mainContent_CaseSearch').keyup(function () {
clearTimeout(mySearchTimeout);
var filter = $(this).val();
mySearchTimeout = setTimeout(function () { myAjaxCall(filter); }, 700);
return true;
});
There is a pretty good example on https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple
To shorten it up a little:
geocoder = new google.maps.Geocoder();
function codeAddress() {
//In this case it gets the address from an element on the page, but obviously you could just pass it to the method instead
var address = document.getElementById( 'address' ).value;
geocoder.geocode( { 'address' : address }, function( results, status ) {
if( status == google.maps.GeocoderStatus.OK ) {
//In this case it creates a marker, but you can get the lat and lng from the location.LatLng
map.setCenter( results[0].geometry.location );
var marker = new google.maps.Marker( {
map : map,
position: results[0].geometry.location
} );
} else {
alert( 'Geocode was not successful for the following reason: ' + status );
}
} );
}
For ubuntu with Plesk installed run apt-get install plesk-php56-dev
, for other versions just change XX in phpXX (without the dot)
try something like
public static Document loadXML(String xml) throws Exception
{
DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
DocumentBuilder bldr = fctr.newDocumentBuilder();
InputSource insrc = new InputSource(new StringReader(xml));
return bldr.parse(insrc);
}
Is there any other way to convert that array into string ?
You don't want to convert the array to a string, you want to get the value of the array's sole element, if I read it correctly.
<?php
$foo = array( 18 => 'Something' );
$value = array_shift( $foo );
echo $value; // 'Something'.
?>
Using array_shift you don't have to worry about the index.
EDIT: Mind you, array_shift is not the only function that will return a single value. array_pop( ), current( ), end( ), reset( ), they will all return that one single element. All of the posted solutions work. Using array shift though, you can be sure that you'll only ever get the first value of the array, even when there are multiple.
Script are executed sequentially only if they do not have either a "defer" or an "async" attribute. Knowing one of the possible ID/SRC/TITLE attributes of the script tag could work also in those cases. So both Greg and Justin suggestions are correct.
There is already a proposal for a document.currentScript
on the WHATWG lists.
EDIT: Firefox > 4 already implement this very useful property but it is not available in IE11 last I checked and only available in Chrome 29 and Safari 8.
EDIT: Nobody mentioned the "document.scripts" collection but I believe that the following may be a good cross browser alternative to get the currently running script:
var me = document.scripts[document.scripts.length -1];
The verbose option is handy, but if you want to see everything that curl does (including the HTTP body that is transmitted, and not just the headers), I suggest using one of the below options:
--trace-ascii -
# stdout--trace-ascii output_file.txt
# fileThis one worked for me.
public void RestrictNumbersOnly(TextField tf){
tf.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue,
String newValue) {
if (!newValue.matches("|[-\\+]?|[-\\+]?\\d+\\.?|[-\\+]?\\d+\\.?\\d+")){
tf.setText(oldValue);
}
}
});
}
Unordered lists are often created with the intent of using them as a menu, but an li
list item is text. Because the list li
item is text, the mouse pointer will not be an arrow, but an "I cursor". Users are accustomed to seeing a pointing finger for a mouse pointer when something is clickable. Using an anchor tag a
inside of the li
tag causes the mouse pointer to change to a pointing finger. The pointing finger is a lot better for using the list as a menu.
<ul id="menu">
<li><a href="#">Menu Item 1</a></li>
<li><a href="#">Menu Item 2</a></li>
<li><a href="#">Menu Item 3</a></li>
<li><a href="#">Menu Item 4</a></li>
</ul>
If the list is being used for a menu, and doesn't need a link, then a URL doesn't need to be designated. But the problem is that if you leave out the href
attribute, text in the <a>
tag is seen as text, and therefore the mouse pointer is back to an I-cursor. The I-cursor might make the user think that the menu item is not clickable. Therefore, you still need an href
, but you don't need a link to anywhere.
You could use lots of div
or p
tags for a menu list, but the mouse pointer would be an I-cursor for them also.
You could use lots of buttons stacked on top of each other for a menu list, but the list seems to be preferable. And that's probably why the href="#"
that points to nowhere is used in anchor tags inside of list tags.
You can set the pointer style in CSS, so that is another option. The href="#"
to nowhere might just be the lazy way to set some styling.
The DATEDIFF function can give you the number of days between two dates. Which is more accurate, since... how do you define a month? (28, 29, 30, or 31 days?)
duckduckgo.com doesn't ignore special characters, at least if the whole string is between ""
https://duckduckgo.com/?q=%22*222%23%22
sudo apt-get install php5.6-curl
and restart the web browser.
You can check the modules by running php -m | grep curl
For python 3.5 in case you have multiple python versions and want to install with python3.5:
pip3 install scikit-image --user
Unfortunately you can't use that tuple assignment syntax in (ECMA|Java)Script.
EDIT: Someone linked to Mozilla/JS 1.7 - this wouldn't work cross-browser but if that is not required then there's your answer.
Sorry, there is no operation similar to LIKE IN
in mysql.
If you want to use the LIKE operator without a join, you'll have to do it this way:
(field LIKE value OR field LIKE value OR field LIKE value)
You know, MySQL will not optimize that query, FYI.
You do with this too...
.p{
writing-mode: vertical-rl;
text-orientation: upright;
}
SELECT STRCMP("string1", "string2");
this returns 0 if the strings are equal.
This cross browser code below evaluates all possible heights of the body and html elements and returns the max found:
var body = document.body;
var html = document.documentElement;
var bodyH = Math.max(body.scrollHeight, body.offsetHeight, body.getBoundingClientRect().height, html.clientHeight, html.scrollHeight, html.offsetHeight); // The max height of the body
function getHeight()_x000D_
{_x000D_
var body = document.body;_x000D_
var html = document.documentElement; _x000D_
var bodyH = Math.max(body.scrollHeight, body.offsetHeight, body.getBoundingClientRect().height, html.clientHeight, html.scrollHeight, html.offsetHeight);_x000D_
return bodyH;_x000D_
}_x000D_
_x000D_
document.getElementById('height').innerText = getHeight();
_x000D_
body,html_x000D_
{_x000D_
height: 3000px;_x000D_
}_x000D_
_x000D_
#posbtm_x000D_
{_x000D_
bottom: 0;_x000D_
position: fixed;_x000D_
background-color: Yellow;_x000D_
}
_x000D_
<div id="posbtm">The max Height of this document is: <span id="height"></span> px</div>_x000D_
_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />
_x000D_
If I understand you question correctly, you could create a wrapper around your marquee and then assign a width
(or max-width
) to the wrapping element. For example:
<div id="marquee-wrapper">
<div class="marquee">This is a marquee!</div>
</div>
And then #marquee-wrapper { width: x }
.
The following example Web.config file will configure IIS to deny access for HTTP requests where the length of the "Content-type" header is greater than 100 bytes.
<configuration>
<system.webServer>
<security>
<requestFiltering>
<requestLimits>
<headerLimits>
<add header="Content-type" sizeLimit="100" />
</headerLimits>
</requestLimits>
</requestFiltering>
</security>
</system.webServer>
</configuration>
Source: http://www.iis.net/configreference/system.webserver/security/requestfiltering/requestlimits
$rootScope
basically functions as an event listener and dispatcher.
To answer the question of how it is used, it used in conjunction with rootScope.$on
;
$rootScope.$broadcast("hi");
$rootScope.$on("hi", function(){
//do something
});
However, it is a bad practice to use $rootScope
as your own app's general event service, since you will quickly end up in a situation where every app depends on $rootScope, and you do not know what components are listening to what events.
The best practice is to create a service for each custom event you want to listen to or broadcast.
.service("hiEventService",function($rootScope) {
this.broadcast = function() {$rootScope.$broadcast("hi")}
this.listen = function(callback) {$rootScope.$on("hi",callback)}
})
Basically both ArrayList and Vector both uses internal Object Array.
ArrayList: The ArrayList class extends AbstractList and implements the List interface and RandomAccess (marker interface). ArrayList supports dynamic arrays that can grow as needed. It gives us first iteration over elements. ArrayList uses internal Object Array; they are created with an default initial size of 10. When this size is exceeded, the collection is automatically increases to half of the default size that is 15.
Vector: Vector is similar to ArrayList but the differences are, it is synchronized and its default initial size is 10 and when the size exceeds its size increases to double of the original size that means the new size will be 20. Vector is the only class other than ArrayList to implement RandomAccess. Vector is having four constructors out of that one takes two parameters Vector(int initialCapacity, int capacityIncrement) capacityIncrement is the amount by which the capacity is increased when the vector overflows, so it have more control over the load factor.
Some other differences are:
Using the MaximumSize
and MinimumSize
properties of the form will fix the form size, and prevent the user from resizing the form, while keeping the form default FormBorderStyle
.
this.MaximumSize = new Size(XX, YY);
this.MinimumSize = new Size(X, Y);
This is so called file local variables, that are understood by Emacs and set correspondingly. See corresponding section in Emacs manual - you can define them either in header or in footer of file
New, simplified answer to an old, commonly asked question...
Always (90% important to remember)
Attribute Values (9% important to remember)
attr="
'
Single quotes'
are ok within double quotes."
attr='
"
Double quotes"
are ok within single quotes.'
"
as "
and '
as '
otherwise.Comments, CDATA, and Processing Instructions (0.9% important to remember)
Esoterica (0.1% important to remember)
]]>
as ]]>
unless ]]>
is ending a CDATA section. Using my library at rootbox, it is pretty easy. Check the required code below:
//Pass true to <Shell>.start(...) call to run as superuser
Shell shell = null;
try {
shell = Shell.start(true);
} catch (IOException exception) {
exception.printStackTrace();
}
if (shell == null)
// We failed to execute su binary
return;
if (shell.isRoot()) {
// Verified running as uid 0 (root), can continue with commands
...
} else
throw Exception("Unable to gain root access. Make sure you pressed Allow/Grant in superuser prompt.");
I got this same error when I was trying to import an Eclipse NDK project into Android Studio. It turns out, for NDK support in Android Studio, you need to use a new gradle and android plugin (and gradle version 2.5+ for that matter). This plugin, requires changes in the module's build.gradle file. Specifically the "android{...}" object should be inside "model{...}" object like this:
apply plugin: 'com.android.model.application'
model {
android {
....
}
}
So if you have updated your gradle configuration to use the new gradle plugin, and the new android plugin, but didn't change the module's build.gradle syntax, you could get "Gradle DSL method not found: 'android()'" error.
I prepared a patch file here that has some further explanations in the comments: https://gist.github.com/shumoapp/91d815de6e01f5921d1f These are the changes I had to do after importing the native-audio ndk project into Android Studio.
It's only supposed to send the information to the server. The reason that it must preceed the file field is that it has to come before the file payload in the request for the server to be able to use it to check the size of the upload.
How the value is used on the server depends on what you use to take care of the upload. The code is supposedly intended for a specific upload component that specifically looks for that value.
It seems that the built in upload support in PHP is one to use this field value.
I think your answer can be found on this page. From the page:
This Folder, Subfolders and Files:
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit PropagationFlags.None
Use a parameterized query to prevent Sql injections (secutity problem)
Use the using statement so the connection will be closed and resources will be disposed.
using(var connection = new SqlConnection("connectionString"))
{
connection.Open();
var sql = "INSERT INTO Main(FirstName, SecondName) VALUES(@FirstName, @SecondName)";
using(var cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.AddWithValue("@FirstName", txFirstName.Text);
cmd.Parameters.AddWithValue("@SecondName", txSecondName.Text);
cmd.ExecuteNonQuery();
}
}
Just throw some light in to some issues related to this control.
Date picker is not a standard control that comes with office package. So developers encountered issues like missing date picker controls when application deployed in some other machiens/versions of office. In order to use it you have to activate the reference to the .dll, .ocx file that contains it.
In the event of a missing date picker, you have to replace MSCOMCT2.OCX file in System or System32 directory and register it properly. Try this link to do the proper replacement of the file.
In the VBA editor menu bar-> select tools-> references and then find the date picker reference and check it.
If you need the file, download MSCOMCT2.OCX from here.
The opposite of this is to flatten a column into a csv eg
SELECT STRING_AGG ([value],',') FROM STRING_SPLIT('Akio,Hiraku,Kazuo', ',')
I encountered this issue too. I'm using Git Bash, hence the Unix-style $ prompt on Windows.
$ rails db
Couldn't find database client: psql, psql.exe. Check your $PATH and try again.
Here's what I did:
In Windows 7, navigate to:
Control Panel
All Control Panel Items
System
Advanced System Settings
Environment Variables
from the System Variables box select "PATH"
Edit...
Then append this string to the existing PATH Variable Value:
;C:\Program Files\PostgreSQL\9.2\bin
and click "OK" three times to exit the menus.
Now, close the console and restart it.
Navigate back to the directory of your Rails app. In my case, this is accomplished with:
$ cd rails_projects/sample_app
Then, try again:
$ rails db
sources:
How do I put PostgreSQL /bin directory on my path in Windows?
http://railscasts.com/episodes/342-migrating-to-postgresql?view=asciicast
If you have skype
installed, close it completely.
If you have sql server
installed, go to:
Control panel
-> Administrative Tools
-> Services
And stop SQL Server Reporting Services
Port 80 must be free now. Click on Wamp icon -> Restart All Services
I do the following in Mint 15 through 17, also works on ubuntu server 12.04 and above:
sudo vi /etc/bash.bashrc
scroll to the bottom, and add:
export LD_LIBRARY_PATH=.
All users have the environment variable added.
If you are using Java8 or + version, JDBC and MySql8 and facing this issue then try this:
Add parameter to connection string:
jdbc:mysql://localhost:3306/tempDB?allowLoadLocalInfile=true
Also, set
local_infile = 1
in my.cnf file.
The latest version of mysql-java-connector might be wont allow directly to connect to local file. So with this parameter, you can able to enable it. This works for me.
You can just display both the text and image as inline-blocks so that they dont stack. using floats like pull-left/pull-right can cause undesired issues so they should be used sparingly
<a class="navbar-brand" href="#">
<img src="mylogo.png" style="display: inline-block;">
<span style="display: inline-block;">My Company</span>
</a>
It is possible to increase heap size allocated by the Java Virtual Machine (JVM) by using command line options.
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
-Xss<size> set java thread stack size
If you are using the tomcat server, you can change the heap size by going to Eclipse/Run/Run Configuration and select Apache Tomcat/your_server_name/Arguments and under VM arguments section use the following:
-XX:MaxPermSize=256m
-Xms256m -Xmx512M
If you are not using any server, you can type the following on the command line before you run your code:
java -Xms64m -Xmx256m HelloWorld
More information on increasing the heap size can be found here
well it's deprecated in android M so you must make exception for android M and lower. Just add current theme on getColor
function. You can get current theme with getTheme()
.
This will do the trick in fragment, you can replace getActivity()
with getBaseContext()
, yourContext
, etc which hold your current context
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white, getActivity().getTheme()));
}else {
yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white));
}
*p.s : color is deprecated in M, but drawable is deprecated in L
You want to do $arrayOfString[0].Title -eq $myPbiject.item(0).Title
-match
is for regex matching ( the second argument is a regex )