If the response is in json then it would be like:
alert(response.id);
Otherwise
var str='{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';
Shortly speaking, have you tried to check "Enable Bitcode=NO". It works for me.
In my case, my project was written in Object-C and includes one 3rd party framework written in swift. I can run my APP on both simulator and real device in developer mode. However, once I achieved the APP with Ad-hoc provision profile and installed this ipa OTA on real device, it crashed. Not even mention upload to store. Hope this information can help.
You can approach this a number of ways. If order is important you can do this:
for key in sorted(d.keys()):
item = d.pop(key)
If order isn't a concern you can do this:
for i in range(4):
item = d.popitem()
I'm surprised no one's mentioned calc()
yet.
I wasn't able to make-out your specific case from your fiddles, but I understand your problem: you want a height: 100%
container that can still use overflow-y: auto
.
This doesn't work out of the box because overflow
requires some hard-coded size constraint to know when it ought to start handling overflow. So, if you went with height: 100px
, it'd work as expected.
The good news is that calc()
can help, but it's not as simple as height: 100%
.
calc()
lets you combine arbitrary units of measure.
So, for the situation you describe in the picture you include:
Since all the elements above and below the pink div are of a known height (let's say, 200px
in total height), you can use calc
to determine the height of ole pinky:
height: calc(100vh - 200px);
or, 'height is 100% of the view height minus 200px.'
Then, overflow-y: auto
should work like a charm.
It seems that there is a typo, since 1104*1104*50=60940800
and you are trying to reshape to dimensions 50,1104,104
. So it seems that you need to change 104 to 1104.
If you've accidentally or not mixed integers with text data you should at first execute below update command (if not above alter table will fail):
UPDATE the_table SET col_name = replace(col_name, 'some_string', '');
I quickly found out there's someone already made a helper: slack-cleaner for this.
And for me it's just:
slack-cleaner --token=<TOKEN> --message --channel jenkins --user "*" --perform
$.ajax({
type: "POST",
url: "url to hit on servelet",
data: JSON.stringify(json),
dataType: "json",
success: function(response){
// we have the response
if(response.status == "SUCCESS"){
$('#info').html("Info has been added to the list successfully.<br>"+
"The Details are as follws : <br> Name : ");
}else{
$('#info').html("Sorry, there is some thing wrong with the data provided.");
}
},
error: function(e){
alert('Error: ' + e);
}
});
Maybe this post is too old but it may help as a suggestion for someone looking around on this : Instead of using:
print_r($this->pdo->errorInfo());
Use PHP implode() function:
echo 'Error occurred:'.implode(":",$this->pdo->errorInfo());
This should print the error code, detailed error information etc. that you would usually get if you were using some SQL User interface.
Hope it helps
Immediately after the object is instantiatd, you can attach a property, say name
, to the object and assign the string value you expect to it:
var myObj = new someClass();
myObj.name="myObj";
document.write(myObj.name);
Alternatively, the assignment can be made inside the codes of the class, i.e.
var someClass = function(P)
{ this.name=P;
// rest of the class definition...
};
var myObj = new someClass("myObj");
document.write(myObj.name);
Tried with sudo and it worked !!
sudo npm install --global gulp-cli
As you mentioned, the easiest way is to use raw_input()
(or simply input()
for Python 3). There is no built-in way to do this. From Recipe 577058:
import sys
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is True for "yes" or False for "no".
"""
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = raw_input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n")
Usage example:
>>> query_yes_no("Is cabbage yummier than cauliflower?")
Is cabbage yummier than cauliflower? [Y/n] oops
Please respond with 'yes' or 'no' (or 'y' or 'n').
Is cabbage yummier than cauliflower? [Y/n] [ENTER]
>>> True
>>> query_yes_no("Is cabbage yummier than cauliflower?", None)
Is cabbage yummier than cauliflower? [y/n] [ENTER]
Please respond with 'yes' or 'no' (or 'y' or 'n').
Is cabbage yummier than cauliflower? [y/n] y
>>> True
You shouldn't use CascadeType.ALL
on @ManyToOne
since entity state transitions should propagate from parent entities to child ones, not the other way around.
The @ManyToOne
side is always the Child association since it maps the underlying Foreign Key column.
Therefore, you should move the CascadeType.ALL
from the @ManyToOne
association to the @OneToMany
side, which should also use the mappedBy
attribute since it's the most efficient one-to-many table relationship mapping.
I have created my personal batch file for this, mine is a little different but feel free to modify as you see fit. I created this a little while ago because I was bored and wanted to make a simple way for people to be able to input ending, starting, stopping, or setting to auto. This BAT file simply requests that you input the service name and it will do the rest for you. I didn't realize that he was looking for something that stated any error, I must have misread that part. Though typically this can be done by inputting >> output.txt on the end of the line.
The %var% is just a way for the user to be able to input their own service into this, instead of having to go modify the bat file every time that you want to start/stop a different service.
If I am wrong, anyone can feel free to correct me on this.
@echo off
set /p c= Would you like to start a service [Y/N]?
if /I "%c%" EQU "Y" goto :1
if /I "%c%" EQU "N" goto :2
:1
set /p var= Service name:
:2
set /p c= Would you like to stop a service [Y/N]?
if /I "%c%" EQU "Y" goto :3
if /I "%c%" EQU "N" goto :4
:3
set /p var1= Service name:
:4
set /p c= Would you like to disable a service [Y/N]?
if /I "%c%" EQU "Y" goto :5
if /I "%c%" EQU "N" goto :6
:5
set /p var2= Service name:
:6
set /p c= Would you like to set a service to auto [Y/N]?
if /I "%c%" EQU "Y" goto :7
if /I "%c%" EQU "N" goto :10
:7
set /p var3= Service name:
:10
sc start %var%
sc stop %var1%
sc config %var2% start=disabled
sc config %var3% start=auto
I found this very helpful if you are a beginner read this
Update:
In Linux or Unix System there are two places programs send output to: Standard output (stdout) and Standard Error (stderr).You can redirect these output to any file.
Like if you do this ls -a > output.txt
Nothing will be printed in console all output (stdout) is redirected to output file.
And if you try print the content of any file that does not exits means output will be an error like if you print test.txt that not present in current directory
cat test.txt > error.txt
Output will be
cat: test.txt :No such file or directory
But error.txt file will be empty because we redirecting the stdout to a file not stderr.
so we need file descriptor( A file descriptor is nothing more that a positive integer that represents an open file. You can say descriptor is unique id of file) to tell shell which type of output we are sending to file .In Unix /Linux system 1 is for stdout and 2 for stderr.
so now if you do this
ls -a 1> output.txt
means you are sending Standard output (stdout) to output.txt.
and if you do this cat test.txt 2> error.txt
means you are sending Standard Error (stderr) to error.txt .
&1
is used to reference the value of the file descriptor 1 (stdout).
Now to the point 2>&1
means “Redirect the stderr to the same place we are redirecting the stdout”
Now you can do this
cat maybefile.txt > output.txt 2>&1
both Standard output (stdout) and Standard Error (stderr) will redirected to output.txt.
Thanks to Ondrej K. for pointing out
try
raw_input('Enter your input:') # If you use Python 2
input('Enter your input:') # If you use Python 3
and if you want to have a numeric value just convert it:
try:
mode=int(raw_input('Input:'))
except ValueError:
print "Not a number"
From the @param wiki page:
If a parameter is expected to have a particular property, you can document that immediately after the @param tag for that parameter, like so:
/**
* @param userInfo Information about the user.
* @param userInfo.name The name of the user.
* @param userInfo.email The email of the user.
*/
function logIn(userInfo) {
doLogIn(userInfo.name, userInfo.email);
}
There used to be a @config tag which immediately followed the corresponding @param, but it appears to have been deprecated (example here).
You will have to split this into multiple statements. Here is one way to do that:
if (!obj.isPresent()) {
logger.fatal("Object not available");
}
obj.ifPresent(o -> o.setAvailable(true));
return obj;
Another way (possibly over-engineered) is to use map
:
if (!obj.isPresent()) {
logger.fatal("Object not available");
}
return obj.map(o -> {o.setAvailable(true); return o;});
If obj.setAvailable
conveniently returns obj
, then you can simply the second example to:
if (!obj.isPresent()) {
logger.fatal("Object not available");
}
return obj.map(o -> o.setAvailable(true));
You will need to pad with "0" if its a single digit & note getMonth
returns 0..11 not 1..12
function printDate() {
var temp = new Date();
var dateStr = padStr(temp.getFullYear()) +
padStr(1 + temp.getMonth()) +
padStr(temp.getDate()) +
padStr(temp.getHours()) +
padStr(temp.getMinutes()) +
padStr(temp.getSeconds());
debug (dateStr );
}
function padStr(i) {
return (i < 10) ? "0" + i : "" + i;
}
To generate a random value between rangeMin
and rangeMax
:
Random r = new Random();
double randomValue = rangeMin + (rangeMax - rangeMin) * r.nextDouble();
I can't get that constructor to work either. This however seems to work:
# $temp = Get-ResourceFiles
$resourceFiles = New-Object System.Collections.ArrayList($null)
$resourceFiles.AddRange($temp)
You can also pass an integer in the constructor to set an initial capacity.
What do you mean when you say you want to enumerate the files? Why can't you just filter the wanted values into a fresh array?
Edit:
It seems that you can use the array constructor like this:
$resourceFiles = New-Object System.Collections.ArrayList(,$someArray)
Note the comma. I believe what is happening is that when you call a .NET method, you always pass parameters as an array. PowerShell unpacks that array and passes it to the method as separate parameters. In this case, we don't want PowerShell to unpack the array; we want to pass the array as a single unit. Now, the comma operator creates arrays. So PowerShell unpacks the array, then we create the array again with the comma operator. I think that is what is going on.
Altenative one-liners in plain-old java:
String.format("The date: %tY-%tm-%td", date, date, date);
String.format("The date: %1$tY-%1$tm-%1$td", date);
String.format("Time with tz: %tY-%<tm-%<td %<tH:%<tM:%<tS.%<tL%<tz", date);
String.format("The date and time in ISO format: %tF %<tT", date);
This uses Formatter and relative indexing instead of SimpleDateFormat
which is not thread-safe, btw.
Slightly more repetitive but needs just one statement. This may be handy in some cases.
There is also a convenient shortcut to get all elements of the array starting with specified index. For example "${A[@]:1}" would be the "tail" of the array, that is the array without its first element.
version=4.7.1
A=( ${version//\./ } )
echo "${A[@]}" # 4 7 1
B=( "${A[@]:1}" )
echo "${B[@]}" # 7 1
You can handle the AppDomain.UnhandledException
event
EDIT: actually, this event is probably more adequate: Application.DispatcherUnhandledException
This might help
lsof -n -i4TCP:8080
The PID is the second field in the output.
Or try:
lsof -i -P
You seem to be looking for range()
:
>>> x1=11
>>> x2=16
>>> range(x1, x2+1)
[11, 12, 13, 14, 15, 16]
>>> list1 = range(x1, x2+1)
>>> list1
[11, 12, 13, 14, 15, 16]
For incrementing by 0.5
instead of 1
, say:
>>> list2 = [x*0.5 for x in range(2*x1, 2*x2+1)]
>>> list2
[11.0, 11.5, 12.0, 12.5, 13.0, 13.5, 14.0, 14.5, 15.0, 15.5, 16.0]
I am adding another answer for other solution I am using now because Android Query is so big and unmaintained to stay healthy. So i moved to this https://github.com/amitshekhariitbhu/Fast-Android-Networking.
AndroidNetworking.download(url,dirPath,fileName).build()
.setDownloadProgressListener(new DownloadProgressListener() {
public void onProgress(long bytesDownloaded, long totalBytes) {
bar.setMax((int) totalBytes);
bar.setProgress((int) bytesDownloaded);
}
}).startDownload(new DownloadListener() {
public void onDownloadComplete() {
...
}
public void onError(ANError error) {
...
}
});
I had the same problem. I called my own custom logger in the log4j.properties file from code when using log4j api directly. If you are using the slf4j api calls, you are probably using the default root logger so you must configure that to be associated with an appender in the log4j.properties:
# Set root logger level to DEBUG and its only appender to A1. log4j.rootLogger=DEBUG, A1 # A1 is set to be a ConsoleAppender. log4j.appender.A1=org.apache.log4j.ConsoleAppender
If a GPU device has, for example, 4 multiprocessing units, and they can run 768 threads each: then at a given moment no more than 4*768 threads will be really running in parallel (if you planned more threads, they will be waiting their turn).
threads are organized in blocks. A block is executed by a multiprocessing unit. The threads of a block can be indentified (indexed) using 1Dimension(x), 2Dimensions (x,y) or 3Dim indexes (x,y,z) but in any case xyz <= 768 for our example (other restrictions apply to x,y,z, see the guide and your device capability).
Obviously, if you need more than those 4*768 threads you need more than 4 blocks. Blocks may be also indexed 1D, 2D or 3D. There is a queue of blocks waiting to enter the GPU (because, in our example, the GPU has 4 multiprocessors and only 4 blocks are being executed simultaneously).
Suppose we want one thread to process one pixel (i,j).
We can use blocks of 64 threads each. Then we need 512*512/64 = 4096 blocks (so to have 512x512 threads = 4096*64)
It's common to organize (to make indexing the image easier) the threads in 2D blocks having blockDim = 8 x 8 (the 64 threads per block). I prefer to call it threadsPerBlock.
dim3 threadsPerBlock(8, 8); // 64 threads
and 2D gridDim = 64 x 64 blocks (the 4096 blocks needed). I prefer to call it numBlocks.
dim3 numBlocks(imageWidth/threadsPerBlock.x, /* for instance 512/8 = 64*/
imageHeight/threadsPerBlock.y);
The kernel is launched like this:
myKernel <<<numBlocks,threadsPerBlock>>>( /* params for the kernel function */ );
Finally: there will be something like "a queue of 4096 blocks", where a block is waiting to be assigned one of the multiprocessors of the GPU to get its 64 threads executed.
In the kernel the pixel (i,j) to be processed by a thread is calculated this way:
uint i = (blockIdx.x * blockDim.x) + threadIdx.x;
uint j = (blockIdx.y * blockDim.y) + threadIdx.y;
I've actually found that in most of my cases, just stripping out those characters is much simpler:
s = mystring.decode('ascii', 'ignore')
I had a situation where I needed to update or insert on a table according to two fields (both foreign keys) on which I couldn't set a UNIQUE constraint (so INSERT ... ON DUPLICATE KEY UPDATE won't work). Here's what I ended up using:
replace into last_recogs (id, hasher_id, hash_id, last_recog)
select l.* from
(select id, hasher_id, hash_id, [new_value] from last_recogs
where hasher_id in (select id from hashers where name=[hasher_name])
and hash_id in (select id from hashes where name=[hash_name])
union
select 0, m.id, h.id, [new_value]
from hashers m cross join hashes h
where m.name=[hasher_name]
and h.name=[hash_name]) l
limit 1;
This example is cribbed from one of my databases, with the input parameters (two names and a number) replaced with [hasher_name], [hash_name], and [new_value]. The nested SELECT...LIMIT 1 pulls the first of either the existing record or a new record (last_recogs.id is an autoincrement primary key) and uses that as the value input into the REPLACE INTO.
You could use actionLayout
from the support library.
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/button_item"
android:title=""
app:actionLayout="@layout/button_layout"
app:showAsAction="always"
/>
</menu>
button_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
Activity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem item = menu.findItem(R.id.button_item);
Button btn = item.getActionView().findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Toolbar Button Clicked!", Toast.LENGTH_SHORT).show();
}
});
return true;
}
As mentioned by Niels, this happens because the server process user can't write to the Wordpress folder.
But here's the thing a lot of articles don't explain. It's the owner of the php process, not the nginx process. If you try to change the nginx owner, it won't solve this.
To solve it, try running ps aux
to see which user owns the php-fpm process. Then check that user is the same user as the owner of the wordpress folder, or can at least write to it. If the user can't write to it, you'll need to change permissions and/or ownership of the folder; or put the two users (server owner and wordpress folder owner) in a common group which can write to the folder; or change php.ini "user" property to a user that can write to the folder.
You can use:
SELECT COUNT(1) FROM MyTable WHERE ...
or
WHERE [NOT] EXISTS
( SELECT 1 FROM MyTable WHERE ... )
This will be more efficient than SELECT *
since you're simply selecting the value 1 for each row, rather than all the fields.
There's also a subtle difference between COUNT(*) and COUNT(column name):
COUNT(*)
will count all rows, including nullsCOUNT(column name)
will only count non null occurrences of column nameFaced same issue and solved by :
remove.packages("ggplot2")
install.packages('ggplot2', dependencies = TRUE)
First of all, I wouldn't use a multi-dimensional array. Only ever seen bad things come of it.
Set up your variable like this:
IEnumerable<IEnumerable<string>> data = new[] {
new[]{"...", "...", "..."},
... etc ...
};
Then you'd simply go:
var firsts = data.Select(x => x.FirstOrDefault()).Where(x => x != null);
The Where makes sure it prunes any nulls if you have an empty list as an item inside.
Alternatively you can implement it as:
string[][] = new[] {
new[]{"...","...","..."},
new[]{"...","...","..."},
... etc ...
};
This could be used similarly to a [x,y]
array but it's used like this: [x][y]
It doesn't recognize that you have a master branch, but I found a way to get around it. I found out that there's nothing special about a master branch, you can just create another branch and call it master branch and that's what I did.
To create a master branch:
git checkout -b master
And you can work off of that.
Jest will use what you pass as a regular expression pattern. That it will match for.
If you want to run a specific test file, then the best way to do it is to use the precise full path to it. (You can too specify a certain relative path like (src/XFolder/index.spec.ts)).
The easiest way to provide the full path being in the directory and in Linux is:
jest $PWD/index.spec.ts
Note the use of the variable $PWD.
For Windows! (to be updated)
div#father {
position: relative;
}
div#son1 {
position: absolute;
/* put your coords here */
}
div#son2 {
position: absolute;
/* put your coords here */
}
doAnswer
and thenReturn
do the same thing if:
Let's mock this BookService
public interface BookService {
String getAuthor();
void queryBookTitle(BookServiceCallback callback);
}
You can stub getAuthor() using doAnswer
and thenReturn
.
BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return "Joshua";
}
}).when(service).getAuthor();
Note that when using doAnswer
, you can't pass a method on when
.
// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());
So, when would you use doAnswer
instead of thenReturn
? I can think of two use cases:
Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.
BookServiceCallback callback = new BookServiceCallback() {
@Override
public void onSuccess(String bookTitle) {
assertEquals("Effective Java", bookTitle);
}
};
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
callback.onSuccess("Effective Java");
// return null because queryBookTitle is void
return null;
}
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:
List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));
Using doAnswer we can stub it safely.
List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));
Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn
.
List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));
To add some clarification here, when you create your service, the service class uses the default 'wsdlLocation', which was inserted into it when the class was built from the wsdl. So if you have a service class called SomeService, and you create an instance like this:
SomeService someService = new SomeService();
If you look inside SomeService, you will see that the constructor looks like this:
public SomeService() {
super(__getWsdlLocation(), SOMESERVICE_QNAME);
}
So if you want it to point to another URL, you just use the constructor that takes a URL argument (there are 6 constructors for setting qname and features as well). For example, if you have set up a local TCP/IP monitor that is listening on port 9999, and you want to redirect to that URL:
URL newWsdlLocation = new URL("http://theServerName:9999/somePath");
SomeService someService = new SomeService(newWsdlLocation);
and that will call this constructor inside the service:
public SomeService(URL wsdlLocation) {
super(wsdlLocation, SOMESERVICE_QNAME);
}
From the link Jweede posted:
exception socket.timeout:
This exception is raised when a timeout occurs on a socket which has had timeouts enabled via a prior call to settimeout(). The accompanying value is a string whose value is currently always “timed out”.
Here are the demo server and client programs for the socket module from the python docs
# Echo server program
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
And the client:
# Echo client program
import socket
HOST = 'daring.cwi.nl' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
On the docs example page I pulled these from, there are more complex examples that employ this idea, but here is the simple answer:
Assuming you're writing the client program, just put all your code that uses the socket when it is at risk of being dropped, inside a try block...
try:
s.connect((HOST, PORT))
s.send("Hello, World!")
...
except socket.timeout:
# whatever you need to do when the connection is dropped
ProductionWorker
extends Employee
, thus it is said that it has all the capabilities of an Employee. In order to accomplish that, Java automatically puts a super();
call in each constructor's first line, you can put it manually but usually it is not necessary. In your case, it is necessary because the call to super();
cannot be placed automatically due to the fact that Employee's constructor has parameters.
You either need to define a default constructor in your Employee
class, or call super('Erkan', 21, new Date());
in the first line of the constructor in ProductionWorker.
My recommendation is TORA
You could also use
ImageIcon background = new ImageIcon("Background/background.png");
JLabel label = new JLabel();
label.setBounds(0, 0, x, y);
label.setIcon(background);
JPanel panel = new JPanel();
panel.setLayout(null);
panel.add(label);
if your working with a absolut value as layout.
You can't search a text field without converting it from text to varchar.
declare @table table (a text)
insert into @table values ('a')
insert into @table values ('a')
insert into @table values ('b')
insert into @table values ('c')
insert into @table values ('d')
select *
from @table
where a ='a'
This give an error:
The data types text and varchar are incompatible in the equal to operator.
Wheras this does not:
declare @table table (a varchar(max))
Interestingly, LIKE
still works, i.e.
where a like '%a%'
cgi.escape
should be good to escape HTML in the limited sense of escaping the HTML tags and character entities.
But you might have to also consider encoding issues: if the HTML you want to quote has non-ASCII characters in a particular encoding, then you would also have to take care that you represent those sensibly when quoting. Perhaps you could convert them to entities. Otherwise you should ensure that the correct encoding translations are done between the "source" HTML and the page it's embedded in, to avoid corrupting the non-ASCII characters.
DELETE FROM tableName WHERE ROWID NOT IN (SELECT MIN (ROWID) FROM table GROUP BY columnname);
I struggled with this for a while and implemented the PL/SQL solution, but later realized that in Toad you can simply double click on the results grid cell, and it brings up an editor with contents in text. (i'm on Toad v11)
int rows, cols , i, j;
printf("Enter number of rows and cols for the matrix: \n");
scanf("%d %d",&rows, &cols);
int mat[rows][cols];
printf("enter the matrix:");
for(i = 0; i < rows ; i++)
for(j = 0; j < cols; j++)
scanf("%d", &mat[i][j]);
printf("\nThe Matrix is:\n");
for(i = 0; i < rows ; i++)
{
for(j = 0; j < cols; j++)
{
printf("%d",mat[i][j]);
printf("\t");
}
printf("\n");
}
}
Below is the code for ImageFullViewActivity
Class
public class ImageFullViewActivity extends AppCompatActivity {
private ScaleGestureDetector mScaleGestureDetector;
private float mScaleFactor = 1.0f;
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_fullview);
mImageView = (ImageView) findViewById(R.id.imageView);
mScaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());
}
@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
mScaleGestureDetector.onTouchEvent(motionEvent);
return true;
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector scaleGestureDetector) {
mScaleFactor *= scaleGestureDetector.getScaleFactor();
mScaleFactor = Math.max(0.1f,
Math.min(mScaleFactor, 10.0f));
mImageView.setScaleX(mScaleFactor);
mImageView.setScaleY(mScaleFactor);
return true;
}
}
}
The expression df1$id %in% idNums1
produces a logical vector. To negate it, you need to negate the whole vector:
!(df1$id %in% idNums1)
"set -e
" is probably the easiest way to do this. Just put that before any commands in your program.
So many answers here, and I hope I might contribute with my own version, which is based on the original answer (by the way), but with a more graphical perspective, also using context for each zipfile
setup and sorting os.walk()
, in order to have a ordered output.
Having these folders and them files (among other folders), I wanted to create a .zip
for each cap_
folder:
$ tree -d
.
+-- cap_01
| +-- 0101000001.json
| +-- 0101000002.json
| +-- 0101000003.json
|
+-- cap_02
| +-- 0201000001.json
| +-- 0201000002.json
| +-- 0201001003.json
|
+-- cap_03
| +-- 0301000001.json
| +-- 0301000002.json
| +-- 0301000003.json
|
+-- docs
| +-- map.txt
| +-- main_data.xml
|
+-- core_files
+-- core_master
+-- core_slave
Here's what I applied, with comments for better understanding of the process.
$ cat zip_cap_dirs.py
""" Zip 'cap_*' directories. """
import os
import zipfile as zf
for root, dirs, files in sorted(os.walk('.')):
if 'cap_' in root:
print(f"Compressing: {root}")
# Defining .zip name, according to Capítulo.
cap_dir_zip = '{}.zip'.format(root)
# Opening zipfile context for current root dir.
with zf.ZipFile(cap_dir_zip, 'w', zf.ZIP_DEFLATED) as new_zip:
# Iterating over os.walk list of files for the current root dir.
for f in files:
# Defining relative path to files from current root dir.
f_path = os.path.join(root, f)
# Writing the file on the .zip file of the context
new_zip.write(f_path)
Basically, for each iteration over os.walk(path)
, I'm opening a context for zipfile
setup and afterwards, iterating iterating over files
, which is a list
of files from root
directory, forming the relative path for each file based on the current root
directory, appending to the zipfile
context which is running.
And the output is presented like this:
$ python3 zip_cap_dirs.py
Compressing: ./cap_01
Compressing: ./cap_02
Compressing: ./cap_03
To see the contents of each .zip
directory, you can use less
command:
$ less cap_01.zip
Archive: cap_01.zip
Length Method Size Cmpr Date Time CRC-32 Name
-------- ------ ------- ---- ---------- ----- -------- ----
22017 Defl:N 2471 89% 2019-09-05 08:05 7a3b5ec6 cap_01/0101000001.json
21998 Defl:N 2471 89% 2019-09-05 08:05 155bece7 cap_01/0101000002.json
23236 Defl:N 2573 89% 2019-09-05 08:05 55fced20 cap_01/0101000003.json
-------- ------- --- -------
67251 7515 89% 3 files
There is no way to gracefully kill a thread.
You can try to interrupt the thread, one commons strategy is to use a poison pill to message the thread to stop itself
public class CancelSupport {
public static class CommandExecutor implements Runnable {
private BlockingQueue<String> queue;
public static final String POISON_PILL = “stopnow”;
public CommandExecutor(BlockingQueue<String> queue) {
this.queue=queue;
}
@Override
public void run() {
boolean stop=false;
while(!stop) {
try {
String command=queue.take();
if(POISON_PILL.equals(command)) {
stop=true;
} else {
// do command
System.out.println(command);
}
} catch (InterruptedException e) {
stop=true;
}
}
System.out.println(“Stopping execution”);
}
}
}
BlockingQueue<String> queue=new LinkedBlockingQueue<String>();
Thread t=new Thread(new CommandExecutor(queue));
queue.put(“hello”);
queue.put(“world”);
t.start();
Thread.sleep(1000);
queue.put(“stopnow”);
As a variation on the accepted answer you could also use the change_column_default
method in your migrations:
def up
change_column_default :profiles, :show_attribute, true
end
def down
change_column_default :profiles, :show_attribute, nil
end
Derived from Denis Tulskiy's answer, this method generates the seed.
public static long generateSeed(String goal, long start, long finish) {
char[] input = goal.toCharArray();
char[] pool = new char[input.length];
label:
for (long seed = start; seed < finish; seed++) {
Random random = new Random(seed);
for (int i = 0; i < input.length; i++)
pool[i] = (char) (random.nextInt(27)+'`');
if (random.nextInt(27) == 0) {
for (int i = 0; i < input.length; i++) {
if (input[i] != pool[i])
continue label;
}
return seed;
}
}
throw new NoSuchElementException("Sorry :/");
}
I am not quite sure if it works with ROW FORMAT serde 'com.bizo.hive.serde.csv.CSVSerde' but I guess that it should be similar to ROW FORMAT DELIMITED FIELDS TERMINATED BY ','.
In your case first row will be treated like normal row. But first field fails to be INT so all fields, for first row, will be set as NULL. You need only one intermediate step to fix it:
INSERT OVERWRITE TABLE Test
SELECT * from Test WHERE RecordId IS NOT NULL
Only one drawback is that your original csv file will be modified. I hope it helps. GL!
Lambdas are now available within Java 8 in the form of JSR-335 - Lambda Expressions for the JavaTM Programming Language
UPDATE: JDK8 has now been released which contains project lambda. It's worth grabbing a copy of Java 8 in Action currently still MEAP.
Have a read of Brian Goetz articles relating to lambdas for a decent understanding of how lambdas are implemented within JDK8 while also gaining an understanding of streams, internal iteration, short-circuiting and constructor references.. Also check out the JSR's above to get further examples.
I've written a blog on some of the advantages of using lambdas in JDK8 called The Power of the Arrow, also NetBeans 8 has great support for converting constructs to JDK8 which I've also blogged about Migrating to JDK 8 with NetBeans.
There are multiple remote linux machines, and I need to write a shell script which will execute the same set of commands in each machine. (Including some sudo operations). How can this be done using shell scripting?
You can do this with ssh, for example:
#!/bin/bash
USERNAME=someUser
HOSTS="host1 host2 host3"
SCRIPT="pwd; ls"
for HOSTNAME in ${HOSTS} ; do
ssh -l ${USERNAME} ${HOSTNAME} "${SCRIPT}"
done
When ssh'ing to the remote machine, how to handle when it prompts for RSA fingerprint authentication.
You can add the StrictHostKeyChecking=no
option to ssh:
ssh -o StrictHostKeyChecking=no -l username hostname "pwd; ls"
This will disable the host key check and automatically add the host key to the list of known hosts. If you do not want to have the host added to the known hosts file, add the option -o UserKnownHostsFile=/dev/null
.
Note that this disables certain security checks, for example protection against man-in-the-middle attack. It should therefore not be applied in a security sensitive environment.
In Bootstrap 3 they do not have separate classes for different styles of labels.
http://getbootstrap.com/components/
However, you can customize bootstrap classes that way. In your css file
.lb-sm {
font-size: 12px;
}
.lb-md {
font-size: 16px;
}
.lb-lg {
font-size: 20px;
}
Alternatively, you can use header tags to change the sizes. For example, here is a medium sized label and a small-sized label
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<h3>Example heading <span class="label label-default">New</span></h3>_x000D_
<h6>Example heading <span class="label label-default">New</span></h6>
_x000D_
They might add size classes for labels in future Bootstrap versions.
Enable Pytest for you project
If you would like to stop jenkins and all its services on the server using Linux console (e.g. Ubuntu), run:
service jenkins start/stop/restart
This is useful when you need to make an image/volume snapshot and you want all services to stop writing to the disk/volume.
Just to update this thread, here is how to add a list (as a json array) into JSONObject. Plz substitute YourClass with your class name;
List<YourClass> list = new ArrayList<>();
JSONObject jsonObject = new JSONObject();
org.codehaus.jackson.map.ObjectMapper objectMapper = new
org.codehaus.jackson.map.ObjectMapper();
org.codehaus.jackson.JsonNode listNode = objectMapper.valueToTree(list);
org.json.JSONArray request = new org.json.JSONArray(listNode.toString());
jsonObject.put("list", request);
Tell the command to automatically stage files that have been modified and deleted, but new files you have not told Git about are not affected:
-a
--all
git add . && git commit -m -a "Your commit"
or
git add --all && git commit -m "Your commit"
Short answer No. CSS is not specific to brands.
Below are the articles to implement for iOS using media only.
https://css-tricks.com/snippets/css/media-queries-for-standard-devices/
http://stephen.io/mediaqueries/
Infact you can use PHP, Javascript to detect the iOS browser and according to that you can call CSS file. For instance
The accepted answer works for me.
Also, in MSSQLMS, you can browse the tree in the Object Explorer to the table you want to query.
[Server] -> Server Objects -> Linked Servers -> [Linked server] -> Catalogs -> [Database] -> [table]
then Right click, Script Table as, SELECT To, New Query Window
And the query will be generated for you with the right FROM, which you can use in your JOIN
ByteArrayInputStream
extends InputStream
:
InputStream myInputStream = new ByteArrayInputStream(myBytes);
1st of all, when you declare a variable in java, you should declare it using Interfaces even if you specify the implementation when instantiating it
ArrayList<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();
should be written
List<List<String>> listOfLists = new ArrayList<List<String>>(size);
Then you will have to instantiate all columns of your 2d array
for(int i = 0; i < size; i++) {
listOfLists.add(new ArrayList<String>());
}
And you will use it like this :
listOfLists.get(0).add("foobar");
But if you really want to "create a 2D array that each cell is an ArrayList!"
Then you must go the dijkstra way.
This is a long standing issue with chromedriver(still present in 2020).
In Chrome I changed from a zoom of 90% to 100% and that solved the problem. ref
I find TheLifeOfSteve's answer more reliable.
If your string is
foo="US/Central - 10:26 PM (CST)"
then
echo "${foo}" | cut -d ' ' -f3
will do the job.
This is because .
is a reserved character in regular expression, representing any character.
Instead, we should use the following statement:
String extensionRemoved = filename.split("\\.")[0];
I've a way and work like this:
<'a href="FOLDER_PATH" target="_explorer.exe">Link Text<'/a>
The simplest solution would be to open Visual Studio, deactivate the TFS Plugin in Tools > Options > Source control and reopen the solution you want to clean. Visual Studio will ask to remove source controls bindings
Code: for row in data:
Error message: TypeError: 'NoneType' object is not iterable
Which object is it complaining about? Choice of two, row
and data
.
In for row in data
, which needs to be iterable? Only data
.
What's the problem with data
? Its type is NoneType
. Only None
has type NoneType
. So data is None
.
You can verify this in an IDE, or by inserting e.g. print "data is", repr(data)
before the for
statement, and re-running.
Think about what you need to do next: How should "no data" be represented? Do we write an empty file? Do we raise an exception or log a warning or keep silent?
You can also use text()
to set or get the text content of selected elements
var text1 = $("#idName").text();
Taken from another post
$checktable = mysql_query("SHOW TABLES LIKE '$this_table'");
$table_exists = mysql_num_rows($checktable) > 0;
@@
denotes a class variable, i.e. it can be inherited.
This means that if you create a subclass of that class, it will inherit the variable. So if you have a class Vehicle
with the class variable @@number_of_wheels
then if you create a class Car < Vehicle
then it too will have the class variable @@number_of_wheels
If you are looking for a very extensible option or have a specific problem domain you could consider rolling your own using the Java Object Oriented Neural Engine. Another JOONE reference.
I used it successfully in a personal project to identify the letter from an image such as this, you can find all the source for the OCR component of my application on github, here.
The key is to add your project directory to sys.path
without considering about the env variable.
For someone who use VSCode, here's a one-line solution for you if there's a base directory of your project:
[MASTER]
init-hook='base_dir="my_spider"; import sys,os,re; _re=re.search(r".+\/" + base_dir, os.getcwd()); project_dir = _re.group() if _re else os.path.join(os.getcwd(), base_dir); sys.path.append(project_dir)'
Let me explain it a little bit:
re.search(r".+\/" + base_dir, os.getcwd()).group()
: find base directory according to the editing file
os.path.join(os.getcwd(), base_dir)
: add cwd
to sys.path
to meet command line environment
FYI, here's my .pylintrc:
https://gist.github.com/chuyik/f0ffc41a6948b6c87c7160151ffe8c2f
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class FrequenceyOfCharacters {
public static void main(String[] args) {
System.out.println("Please enter the string to count each character frequencey: ");
Scanner sc=new Scanner(System.in);
String s =sc.nextLine();
String input = s.replaceAll("\\s",""); // To remove space.
frequenceyCount(input);
}
private static void frequenceyCount(String input) {
Map<Character,Integer> hashCount=new HashMap<>();
Character c;
for(int i=0; i<input.length();i++)
{
c =input.charAt(i);
if(hashCount.get(c)!=null){
hashCount.put(c, hashCount.get(c)+1);
}else{
hashCount.put(c, 1);
}
}
Iterator it = hashCount.entrySet().iterator();
System.out.println("char : frequency");
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " : " + pairs.getValue());
it.remove();
}
}
}
There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml
. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml
mediatype.
I'm surprised nobody has mentioned explicit conversion flag yet
>>> print('{!r}'.format('a word that needs quotation marks'))
'a word that needs quotation marks'
The flag !r
is a shorthand of the repr()
built-in function1. It is used to print the object representation object.__repr__()
instead of object.__str__()
.
There is an interesting side-effect though:
>>> print("{!r} \t {!r} \t {!r} \t {!r}".format("Buzz'", 'Buzz"', "Buzz", 'Buzz'))
"Buzz'" 'Buzz"' 'Buzz' 'Buzz'
Notice how different composition of quotation marks are handled differenty so that it fits a valid string representation of a Python object 2.
1 Correct me if anybody knows otherwise.
2 The question's original example " "word" "
is not a valid representation in Python
Use People implements Comparable<People>
instead; this defines the natural ordering for People
.
A Comparator<People>
can also be defined in addition, but People implements Comparator<People>
is not the right way of doing things.
The two overloads for Collections.sort
are different:
<T extends Comparable<? super T>> void sort(List<T> list)
Comparable
objects using their natural ordering<T> void sort(List<T> list, Comparator<? super T> c)
Comparator
You're confusing the two by trying to sort a Comparator
(which is again why it doesn't make sense that Person implements Comparator<Person>
). Again, to use Collections.sort
, you need one of these to be true:
Comparable
(use the 1-arg sort
)Comparator
for the type must be provided (use the 2-args sort
)Also, do not use raw types in new code. Raw types are unsafe, and it's provided only for compatibility.
That is, instead of this:
ArrayList peps = new ArrayList(); // BAD!!! No generic safety!
you should've used the typesafe generic declaration like this:
List<People> peps = new ArrayList<People>(); // GOOD!!!
You will then find that your code doesn't even compile!! That would be a good thing, because there IS something wrong with the code (Person
does not implements Comparable<Person>
), but because you used raw type, the compiler didn't check for this, and instead you get a ClassCastException
at run-time!!!
This should convince you to always use typesafe generic types in new code. Always.
you can use this.finish() if you want to close current activity.
this.finish()
Use :
instead of =
see the example below that gives an error
app.post('/mews', (req, res) => {
if (isValidMew(req.body)) {
// insert into db
const mew = {
name = filter.clean(req.body.name.toString()),
content = filter.clean(req.body.content.toString()),
created: new Date()
};
That gives Syntex Error: invalid shorthand proprty initializer.
Then i replace =
with :
that's solve this error.
app.post('/mews', (req, res) => {
if (isValidMew(req.body)) {
// insert into db
const mew = {
name: filter.clean(req.body.name.toString()),
content: filter.clean(req.body.content.toString()),
created: new Date()
};
You could use it in conjunction with backticks (``
) to execute a command without displaying its output, like this:
: `some_command`
Of course you could just do some_command > /dev/null
, but the :
-version is somewhat shorter.
That being said I wouldn't recommend actually doing that as it would just confuse people. It just came to mind as a possible use-case.
I would aim at covering a subset of possible "Content-type" values, you question seems to focus on identifying known content types.
@Jeroen RFC 1341 reference is great, but for an fairly exhaustive list IANA keeps a web page of officially registered media types here.
For those who are using Jquery
$("*").each(function(i,e){console.log(i+' '+e)});
First you convert VARCHAR to DATE and then back to CHAR. I do this almost every day and never found any better way.
select TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') from EmpTable
If anyone can't build their downloaded source code (probably google codelabs source code) with Android Studio, try simply remove the buildToolsVersion
from the build.gradle
file, and Android Studio
will build the project with it's default latest buildToolVersion
¯_(?)_/¯
Posting answer to my own question as I found it here and was hidden in bottom somewhere -
This is because the OS failed to install the required update Windows8.1-KB2999226-x64.msu.
However, you can install it by extracting that update to a folder (e.g. XXXX), and execute following cmdlet. You can find the Windows8.1-KB2999226-x64.msu at below.
C:\ProgramData\Package Cache\469A82B09E217DDCF849181A586DF1C97C0C5C85\packages\Patch\amd64\Windows8.1-KB2999226-x64.msu
copy this file to a folder you like, and
Create a folder XXXX in that and execute following commands from Admin command propmt
wusa.exe Windows8.1-KB2999226-x64.msu /extract:XXXX
DISM.exe /Online /Add-Package /PackagePath:XXXX\Windows8.1-KB2999226-x64.cab
vc_redist.x64.exe /repair
(last command need not be run. Just execute vc_redist.x64.exe once again)
this worked for me.
There is also the InStrRev function which does the same type of thing, but starts searching from the end of the text to the beginning.
Per @rene's answer...
Dim pos As Integer
pos = InStrRev("find the comma, in the string", ",")
...would still return 15 to pos, but if the string has more than one of the search string, like the word "the", then:
Dim pos As Integer
pos = InStrRev("find the comma, in the string", "the")
...would return 20 to pos, instead of 6.
On the selector .nav-tabs > li > a:hover
add !important
to the background-color
.
.nav-tabs{_x000D_
background-color:#161616;_x000D_
}_x000D_
.tab-content{_x000D_
background-color:#303136;_x000D_
color:#fff;_x000D_
padding:5px_x000D_
}_x000D_
.nav-tabs > li > a{_x000D_
border: medium none;_x000D_
}_x000D_
.nav-tabs > li > a:hover{_x000D_
background-color: #303136 !important;_x000D_
border: medium none;_x000D_
border-radius: 0;_x000D_
color:#fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<ul class="nav nav-tabs" id="myTab">_x000D_
<li class="active"><a data-toggle="tab" href="#search">SEARCH</a></li>_x000D_
<li><a data-toggle="tab" href="#advanced">ADVANCED</a></li>_x000D_
</ul>_x000D_
<div class="tab-content">_x000D_
<div id="search" class="tab-pane fade in active">_x000D_
Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel,_x000D_
butcher voluptate nisi qui._x000D_
</div>_x000D_
<div id="advanced" class="tab-pane fade">_x000D_
Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna._x000D_
</div>_x000D_
</div>
_x000D_
domContentLoaded: marks the point when both the DOM is ready and there are no stylesheets that are blocking JavaScript execution - meaning we can now (potentially) construct the render tree. Many JavaScript frameworks wait for this event before they start executing their own logic. For this reason the browser captures the EventStart and EventEnd timestamps to allow us to track how long this execution took.
loadEvent: as a final step in every page load the browser fires an “onload” event which can trigger additional application logic.
Building off @ted.strauss
's answer, you can select SSH
and MyIP
from the drop down menu instead of navigating to a third party site.
You can use Getfv.co :
To retrieve a favicon you can hotlink it at... http://g.etfv.co/[URL]
Example for this page : http://g.etfv.co/https://stackoverflow.com/questions/5119041/how-can-i-get-a-web-sites-favicon
Download content and let's go !
Edit :
Getfv.co and fvicon.com look dead. If you want I found a non free alternative : grabicon.com.
As others have suggested that you should look into MERGE statement but nobody provided a solution using it I'm adding my own answer with this particular TSQL construct. I bet you'll like it.
Your code has a typo in your if
statement in not exists(select...)
part. Inner select
statement has only one where
condition while UserName condition is excluded from the not exists
due to invalid brace completion. In any case you cave too many closing braces.
I assume this based on the fact that you're using two where
conditions in update
statement later on in your code.
Let's continue to my answer...
MERGE statement is a beautiful TSQL gem very well suited for "insert or update" situations. In your case it would look similar to the following code. Take into consideration that I'm declaring variables what are likely stored procedure parameters (I suspect).
declare @clockDate date = '08/10/2012';
declare @userName = 'test';
merge Clock as target
using (select @clockDate, @userName) as source (ClockDate, UserName)
on (target.ClockDate = source.ClockDate and target.UserName = source.UserName)
when matched then
update
set BreakOut = getdate()
when not matched then
insert (ClockDate, UserName, BreakOut)
values (getdate(), source.UserName, getdate());
It is.
test.hpp:
class A {
public:
static int a(int i);
};
test.cpp:
#include <iostream>
#include "test.hpp"
int A::a(int i) {
return i + 2;
}
using namespace std;
int main() {
cout << A::a(4) << endl;
}
They're not always inline, no, but the compiler can make them.
Late to the trim party
Features:
1. Trim the beginning quickly, as in a number of other answers.
2. After going to the end, trimming the right with only 1 test per loop. Like @jfm3, but works for an all white-space string)
3. To avoid undefined behavior when char
is a signed char
, cast *s
to unsigned char
.
Character handling "In all cases the argument is an
int
, the value of which shall be representable as anunsigned char
or shall equal the value of the macroEOF
. If the argument has any other value, the behavior is undefined." C11 §7.4 1
#include <ctype.h>
// Return a pointer to the trimmed string
char *string_trim_inplace(char *s) {
while (isspace((unsigned char) *s)) s++;
if (*s) {
char *p = s;
while (*p) p++;
while (isspace((unsigned char) *(--p)));
p[1] = '\0';
}
// If desired, shift the trimmed string
return s;
}
@chqrlie commented the above does not shift the trimmed string. To do so....
// Return a pointer to the (shifted) trimmed string
char *string_trim_inplace(char *s) {
char *original = s;
size_t len = 0;
while (isspace((unsigned char) *s)) {
s++;
}
if (*s) {
char *p = s;
while (*p) p++;
while (isspace((unsigned char) *(--p)));
p[1] = '\0';
// len = (size_t) (p - s); // older errant code
len = (size_t) (p - s + 1); // Thanks to @theriver
}
return (s == original) ? s : memmove(original, s, len + 1);
}
The character in question 
is the Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF). It may be that you copied it into your code via a copy/paste without realizing it. The fact that it's not visible makes it hard to tell if you're using an editor that displays actual unicode characters.
One option is to open the file in a very basic text editor that doesn't understand unicode, or one that understands it but has the ability to display any non-ascii characters using their actual codes.
Once you locate it, you can delete the small block of text around it and retype that text manually.
Building upon @Mark D's answer I would use web.config transforms to set all the various cookies to Secure. This includes setting anonymousIdentification cookieRequireSSL
and httpCookies requireSSL
.
To that end you'd setup your web.Release.config as:
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<system.web>
<httpCookies xdt:Transform="SetAttributes(httpOnlyCookies)" httpOnlyCookies="true" />
<httpCookies xdt:Transform="SetAttributes(requireSSL)" requireSSL="true" />
<anonymousIdentification xdt:Transform="SetAttributes(cookieRequireSSL)" cookieRequireSSL="true" />
</system.web>
</configuration>
If you're using Roles and Forms Authentication with the ASP.NET Membership Provider
(I know, it's ancient) you'll also want to set the roleManager cookieRequireSSL
and the forms requireSSL
attributes as secure too. If so, your web.release.config might look like this (included above plus new tags for membership API):
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<system.web>
<httpCookies xdt:Transform="SetAttributes(httpOnlyCookies)" httpOnlyCookies="true" />
<httpCookies xdt:Transform="SetAttributes(requireSSL)" requireSSL="true" />
<anonymousIdentification xdt:Transform="SetAttributes(cookieRequireSSL)" cookieRequireSSL="true" />
<roleManager xdt:Transform="SetAttributes(cookieRequireSSL)" cookieRequireSSL="true" />
<authentication>
<forms xdt:Transform="SetAttributes(requireSSL)" requireSSL="true" />
</authentication>
</system.web>
</configuration>
Background on web.config transforms here: http://go.microsoft.com/fwlink/?LinkId=125889
Obviously this goes beyond the original question of the OP but if you don't set them all to secure you can expect that a security scanning tool will notice and you'll see red flags appear on the report. Ask me how I know. :)
I don't know anything about EF really, but in LINQ to SQL you usually express a LIKE clause using String.Contains:
where entity.Name.Contains("xyz")
translates to
WHERE Name LIKE '%xyz%'
(Use StartsWith
and EndsWith
for other behaviour.)
I'm not entirely sure whether that's helpful, because I don't understand what you mean when you say you're trying to implement LIKE. If I've misunderstood completely, let me know and I'll delete this answer :)
You can use partial value of an attribute to detect a DOM element using (^) sign. For example you have divs like this:
<div id="abc_1"></div>
<div id="abc_2"></div>
<div id="xyz_3"></div>
<div id="xyz_4"></div>...
You can use the code:
var abc = $('div[id^=abc]')
This will return a DOM array of divs which have id starting with abc
:
<div id="abc_1"></div>
<div id="abc_2"></div>
Here is the demo: http://jsfiddle.net/mCuWS/
You need to add an alias for the count to your query and then use the addScalar()
method as the default for list()
method in Hibernate seams to be BigInteger
for numeric SQL types. Here is an example:
List<Long> sqlResult = session.createSQLQuery("SELECT column AS num FROM table")
.addScalar("num", StandardBasicTypes.LONG).list();
Try dbForge Data Compare for SQL Server. It can compare and sync any databases, even very large ones. Quick, easy, always delivers a correct result. Try it on your database and comment upon the product.
We can recommend you a reliable SQL comparison tool that offer 3 time’s faster comparison and synchronization of table data in your SQL Server databases. It's dbForge Data Compare for SQL Server and dbForge Schema Compare for SQL Server
Main advantages:
Plus free 30-day trial and risk-free purchase with 30-day money back guarantee.
You want rows where that condition is true so you need a comma:
data[data$Ozone > 14, ]
There are many possibilities to do this in R. Here are some of them:
df <- read.table(header = TRUE, text = 'Gene Value
A 12
A 10
B 3
B 5
B 6
C 1
D 3
D 4')
# aggregate
aggregate(df$Value, by = list(df$Gene), max)
aggregate(Value ~ Gene, data = df, max)
# tapply
tapply(df$Value, df$Gene, max)
# split + lapply
lapply(split(df, df$Gene), function(y) max(y$Value))
# plyr
require(plyr)
ddply(df, .(Gene), summarise, Value = max(Value))
# dplyr
require(dplyr)
df %>% group_by(Gene) %>% summarise(Value = max(Value))
# data.table
require(data.table)
dt <- data.table(df)
dt[ , max(Value), by = Gene]
# doBy
require(doBy)
summaryBy(Value~Gene, data = df, FUN = max)
# sqldf
require(sqldf)
sqldf("select Gene, max(Value) as Value from df group by Gene", drv = 'SQLite')
# ave
df[as.logical(ave(df$Value, df$Gene, FUN = function(x) x == max(x))),]
I'm surprised no one has suggested this variation:
SELECT SUM(c)
FROM (
SELECT COUNT(*) AS c FROM foo1 WHERE ID = '00123244552000258'
UNION ALL
SELECT COUNT(*) FROM foo2 WHERE ID = '00123244552000258'
UNION ALL
SELECT COUNT(*) FROM foo3 WHERE ID = '00123244552000258'
);
The size arguments are in pixels. So, to double your example's marker size the fifth argument to the MarkerImage constructor would be:
new google.maps.Size(42,68)
I find it easiest to let the map API figure out the other arguments, unless I need something other than the bottom/center of the image as the anchor. In your case you could do:
var pinIcon = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(42, 68)
);
SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.
You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...
From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.
If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/
I find this easier.
sort -u input_filename > output_filename
-u
stands for unique.
location.assign():
To assign a route path by passing a path into it.. Assign will give you a history even after the path was assigned.
Usage Method: value should be passed into it.
For example: location.assign("http://google.com")
location.href
Can define give a path into it... And it will redirect into a given path once it setup, and it will keep history...
Usage Method: value should be assign into it.
For example: location.href = "http://google.com"
location.replace():
It will help to replace a path if you don't want to keep history. It won't give you a history once you replace its path.
Usage Method: value should be pass into it.
For example: location.replace("http://google.com")
assign()
and href
are similar, and both can hold history. assign
will work by passing a value and href works by assigning.
You can achieve it using JavaScript itself without using jQuery by assigning,
window.location = "http://google.com"
location.href = "http://google.com"
You can achieve similar thing using jQuery like below. It will do exactly the same like above,
$(window).attr('location', "http://www.google.com");
$(location).attr('href', "http://www.google.com");
You can easily understand the difference between both...
Here is the Location object,
just remove 'fade' class from modal class
class="modal fade bs-example-modal-lg"
as
class="modal bs-example-modal-lg"
In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager
then find Xml Tools
plugin. Tick the box and click Install
Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now
).
Following dialog will open:
Click on ...
. Point to XSD file and I am pretty sure you'll be able to handle things from here.
Hope this saves you some time.
EDIT:
Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1
plugin manager is back under a different guise... Plugin Admin
so now you can simply update notepad++ and have it back.
var page = "http://somurl.com/asom.php.aspx";
var $dialog = $('<div></div>')
.html('<iframe style="border: 0px; " src="' + page + '" width="100%" height="100%"></iframe>')
.dialog({
autoOpen: false,
modal: true,
height: 625,
width: 500,
title: "Some title"
});
$dialog.dialog('open');
Use this inside a function. This is great if you really want to load an external URL as an IFRAME. Also make sure that in you custom jqueryUI you have the dialog.
open /Users/you/eclipse/java-oxygen
right click on eclipse, click on show package content
Then go to Contents/Eclipse
and select file eclipse.ini, open in text file or in any editor.
search deleted java path and add newer java path till bin /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/bin
The problem with the answer that was chosen here is that when navigating back and forth, the converter will get triggered every time the page is shown.
This causes new file handles to be created continuously and will block any attempt to delete the file because it is still in use. This can be verified by using Process Explorer.
If the image file might be deleted at some point, a converter such as this might be used: using XAML to bind to a System.Drawing.Image into a System.Windows.Image control
The disadvantage with this memory stream method is that the image(s) get loaded and decoded every time and no caching can take place: "To prevent images from being decoded more than once, assign the Image.Source property from an Uri rather than using memory streams" Source: "Performance tips for Windows Store apps using XAML"
To solve the performance issue, the repository pattern can be used to provide a caching layer. The caching could take place in memory, which may cause memory issues, or as thumbnail files that reside in a temp folder that can be cleared when the app exits.
The term "forward declaration" in C++ is mostly only used for class declarations. See (the end of) this answer for why a "forward declaration" of a class really is just a simple class declaration with a fancy name.
In other words, the "forward" just adds ballast to the term, as any declaration can be seen as being forward in so far as it declares some identifier before it is used.
(As to what is a declaration as opposed to a definition, again see What is the difference between a definition and a declaration?)
An example for subtraction is given below:
Select value1 - (select value2 from AnyTable1) from AnyTable2
value1 & value2 can be count,sum,average output etc. But the values should be comapatible
There is a way that's pretty memory inefficient.
single file:
import hashlib
def file_as_bytes(file):
with file:
return file.read()
print hashlib.md5(file_as_bytes(open(full_path, 'rb'))).hexdigest()
list of files:
[(fname, hashlib.md5(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst]
Recall though, that MD5 is known broken and should not be used for any purpose since vulnerability analysis can be really tricky, and analyzing any possible future use your code might be put to for security issues is impossible. IMHO, it should be flat out removed from the library so everybody who uses it is forced to update. So, here's what you should do instead:
[(fname, hashlib.sha256(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst]
If you only want 128 bits worth of digest you can do .digest()[:16]
.
This will give you a list of tuples, each tuple containing the name of its file and its hash.
Again I strongly question your use of MD5. You should be at least using SHA1, and given recent flaws discovered in SHA1, probably not even that. Some people think that as long as you're not using MD5 for 'cryptographic' purposes, you're fine. But stuff has a tendency to end up being broader in scope than you initially expect, and your casual vulnerability analysis may prove completely flawed. It's best to just get in the habit of using the right algorithm out of the gate. It's just typing a different bunch of letters is all. It's not that hard.
Here is a way that is more complex, but memory efficient:
import hashlib
def hash_bytestr_iter(bytesiter, hasher, ashexstr=False):
for block in bytesiter:
hasher.update(block)
return hasher.hexdigest() if ashexstr else hasher.digest()
def file_as_blockiter(afile, blocksize=65536):
with afile:
block = afile.read(blocksize)
while len(block) > 0:
yield block
block = afile.read(blocksize)
[(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.md5()))
for fname in fnamelst]
And, again, since MD5 is broken and should not really ever be used anymore:
[(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.sha256()))
for fname in fnamelst]
Again, you can put [:16]
after the call to hash_bytestr_iter(...)
if you only want 128 bits worth of digest.
Use the file browser "Total Commander" instead.
You mentioned that you're interested in the equality of the contents of the list (and didn't mention order). So containsExactlyInAnyOrder
from AssertJ is a good fit. It comes packaged with spring-boot-starter-test
, for example.
From the AssertJ docs ListAssert#containsExactlyInAnyOrder:
Verifies that the actual group contains exactly the given values and nothing else, in any order. Example:
// an Iterable is used in the example but it would also work with an array
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya, vilya);
// assertion will pass
assertThat(elvesRings).containsExactlyInAnyOrder(vilya, vilya, nenya, narya);
// assertion will fail as vilya is contained twice in elvesRings.
assertThat(elvesRings).containsExactlyInAnyOrder(nenya, vilya, narya);
Before submitting the form, call tinyMCE.triggerSave();
Use include_once();
- with this, your codes will be included only one time.
It is possible to use your usual System.Configuration
even in .NET Core 2.0 on Linux. Try this test example:
MyLib.dll
)System.Configuration.ConfigurationManager
v4.4.0. This is needed since this package isn't covered by the meta-package NetStandard.Library
v2.0.0 (I hope that changes)ConfigurationSection
or ConfigurationElement
go into MyLib.dll
. For example MyClass.cs
derives from ConfigurationSection
and MyAccount.cs
derives from ConfigurationElement
. Implementation details are out of scope here but Google is your friend.MyApp.dll
). .NET Core apps end with .dll
rather than .exe
in Framework.app.config
in MyApp
with your custom configuration sections. This should obviously match your class designs in #3 above. For example:<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="myCustomConfig" type="MyNamespace.MyClass, MyLib" />
</configSections>
<myCustomConfig>
<myAccount id="007" />
</myCustomConfig>
</configuration>
That's it - you'll find that the app.config is parsed properly within MyApp
and your existing code within MyLib
works just fine. Don't forget to run dotnet restore
if you switch platforms from Windows (dev) to Linux (test).
Additional workaround for test projects
If you're finding that your App.config
is not working in your test projects, you might need this snippet in your test project's .csproj
(e.g. just before the ending </Project>
). It basically copies App.config
into your output folder as testhost.dll.config
so dotnet test
picks it up.
<!-- START: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->
<Target Name="CopyCustomContent" AfterTargets="AfterBuild">
<Copy SourceFiles="App.config" DestinationFiles="$(OutDir)\testhost.dll.config" />
</Target>
<!-- END: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->
This code works too:
$("input[reference=12345].myclass").css('border', '#000 solid 1px');
Right now you're setting the innerHTML to an entire div element; you want to set it to just the innerHTML. Also, I think you want MyDiv2.innerHTML = MyDiv 1 .innerHTML. Also, I think the argument to document.getElementById
is case sensitive. You were passing Div2
when you wanted DIV2
var MyDiv1 = Document.getElementById('DIV1');
var MyDiv2 = Document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
Also, this code will run before your DOM is ready. You can either put this script at the bottom of your body like paislee said, or put it in your body's onload function
<body onload="loadFunction()">
and then
function loadFunction(){
var MyDiv1 = Document.getElementById('DIV1');
var MyDiv2 = Document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
}
An alternative solution is to execute an external command, obviously, this solution limits the portability of the application.
For example, for an application that runs on Windows, a PowerShell command can be executed through jPowershell, as shown in the following code:
public String getMyPublicIp() {
// PowerShell command
String command = "(Invoke-WebRequest ifconfig.me/ip).Content.Trim()";
String powerShellOut = PowerShell.executeSingleCommand(command).getCommandOutput();
// Connection failed
if (powerShellOut.contains("InvalidOperation")) {
powerShellOut = null;
}
return powerShellOut;
}
HTML Form Element Validation
Run Function
<script>
$("#validationForm").validation({
button: "#btnGonder",
onSubmit: function () {
alert("Submit Process");
},
onCompleted: function () {
alert("onCompleted");
},
onError: function () {
alert("Error Process");
}
});
</script>
Go to example and download https://github.com/naimserin/Validation.
Improving Suman.hassan95's answer by adding a link to subcategory as well. Replace the following code:
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo $sub_category->name ;
}
}
with:
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
}
}
or if you also wish a counter for each subcategory, replace with this:
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
echo apply_filters( 'woocommerce_subcategory_count_html', ' <span class="cat-count">' . $sub_category->count . '</span>', $category );
}
}
Expanding on Blender's answer, this happens in a number of situations. The most common ones I run into are:
User-Agent
.socketCloseListener
, as outlined in Blender's answer, is not the only place that hangup errors are created.
For example, found here:
function socketOnEnd() {
var socket = this;
var req = this._httpMessage;
var parser = this.parser;
if (!req.res) {
// If we don't have a response then we know that the socket
// ended prematurely and we need to emit an error on the request.
req.emit('error', createHangUpError());
req._hadError = true;
}
if (parser) {
parser.finish();
freeParser(parser, req);
}
socket.destroy();
}
You could try curl
with the headers and such that are being sent out from Node and see if you get a response there. If you don't get a response with curl
, but you do get a response in your browser, then your User-Agent
header is most likely being blocked.
All new activities/intents by default have back/previous behavior, unless you have coded a finish()
on the calling activity.
I built this off of the answer by @Matt Greer
He answered the OP's question perfectly.
I wanted something like this while maintaining the original capabilities of Any while also checking for null. I'm posting this in case anyone else needs something similar.
Specifically I wanted to still be able to pass in a predicate.
public static class Utilities
{
/// <summary>
/// Determines whether a sequence has a value and contains any elements.
/// </summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <param name="source">The <see cref="System.Collections.Generic.IEnumerable"/> to check for emptiness.</param>
/// <returns>true if the source sequence is not null and contains any elements; otherwise, false.</returns>
public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source)
{
return source?.Any() == true;
}
/// <summary>
/// Determines whether a sequence has a value and any element of a sequence satisfies a condition.
/// </summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <param name="source">An <see cref="System.Collections.Generic.IEnumerable"/> whose elements to apply the predicate to.</param>
/// <param name="predicate">A function to test each element for a condition.</param>
/// <returns>true if the source sequence is not null and any elements in the source sequence pass the test in the specified predicate; otherwise, false.</returns>
public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
return source?.Any(predicate) == true;
}
}
The naming of the extension method could probably be better.
This seems to be a bit of a generic message. I'm sure many of the answers are correct. For me it was a mismatch between the entitlements and settings for the app in the member portal. My solution was this:
The type comes after the name in TypeScript, partly because types are optional.
So your line:
HTMLElement el = document.getElementById('content');
Needs to change to:
const el: HTMLElement = document.getElementById('content');
Back in 2013, the type HTMLElement
would have been inferred from the return value of getElementById
, this is still the case if you aren't using strict null checks (but you ought to be using the strict modes in TypeScript). If you are enforcing strict null checks you will find the return type of getElementById
has changed from HTMLElement
to HTMLElement | null
. The change makes the type more correct, because you don't always find an element.
So when using type mode, you will be encouraged by the compiler to use a type assertion to ensure you found an element. Like this:
const el: HTMLElement | null = document.getElementById('content');
if (el) {
const definitelyAnElement: HTMLElement = el;
}
I have included the types to demonstrate what happens when you run the code. The interesting bit is that el
has the narrower type HTMLElement
within the if
statement, due to you eliminating the possibility of it being null.
You can do exactly the same thing, with the same resulting types, without any type annotations. They will be inferred by the compiler, thus saving all that extra typing:
const el = document.getElementById('content');
if (el) {
const definitelyAnElement = el;
}
Good news! A pull request adding System.Globalization.ISOWeek
to .NET Core was just merged and is currently slated for the 3.0 release. Hopefully it will propagate to the other .NET platforms in a not-too-distant future.
The type has the following signature, which should cover most ISO week needs:
namespace System.Globalization
{
public static class ISOWeek
{
public static int GetWeekOfYear(DateTime date);
public static int GetWeeksInYear(int year);
public static int GetYear(DateTime date);
public static DateTime GetYearEnd(int year);
public static DateTime GetYearStart(int year);
public static DateTime ToDateTime(int year, int week, DayOfWeek dayOfWeek);
}
}
You can find the source code here.
UPDATE: These APIs have also been included in the 2.1 version of .NET Standard.
You're trying to invoke an instance method on the class it self.
You should do:
Random rand = new Random();
int a = 0 ;
while (!done) {
int a = rand.nextInt(10) ;
....
Instead
As I told you here stackoverflow.com/questions/2694470/whats-wrong...
A note for others who may be using Owl Carousel v 1.3.2:
You can replace the navigation text in the settings where you're enabling the navigation.
navigation:true,
navigationText: [
"<i class='fa fa-chevron-left'></i>",
"<i class='fa fa-chevron-right'></i>"
]
There are two commands which will work in this situation,
root>git reset --hard HEAD~1
root>git push -f
For more git commands refer this page
string::c.str()
returns a string of type const char *
as seen here
A quick fix: try casting printfunc(num,addr,(char *)data.str().c_str())
;
While the above may work, it is undefined behaviour, and unsafe.
Here's a nicer solution using templates:
char * my_argument = const_cast<char*> ( ...c_str() );
I've found out the solution! Thanks to Firebug ;)
//"markers" is an array that I declared which contains all the marker of the map
//"i" is the index of the marker in the array that I want to trigger the OnClick event
//V2 version is:
GEvent.trigger(markers[i], 'click');
//V3 version is:
google.maps.event.trigger(markers[i], 'click');
We can bypass execution policy in a nice way (inside command prompt):
type file.ps1 | powershell -command -
Or inside powershell:
gc file.ps1|powershell -c -
The related name parameter is actually an option. If we do not set it, Django
automatically creates the other side of the relation for us. In the case of the Map model,
Django would have created a map_set
attribute, allowing access via m.map_set
in your
example(m being your class instance). The formula Django uses is the name of the model followed by the
string _set
. The related name parameter thus simply overrides Django’s default rather
than providing new behavior.
Temporary Solution
Maybe someone facing this problem. I am using Mysql Workbench on Ubuntu 14 and got this error.
mysqldump: Got error: 2002: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) when trying to connect
Find your socket file by running sudo find / -type s
, in my case it was /run/mysqld/mysqld.sock
So, I just created a link to this file in tmp
directory.
sudo ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock
Please note that this is a temporary solution since the file created will be under /tmp
. See other answers for a permanent solution.
Note: Not in boolean
WebDriver driver=new FirefoxDriver();
driver.get("http://www.gmail.com");
if(driver.getPageSource().contains("Ur message"))
{
System.out.println("Pass");
}
else
{
System.out.println("Fail");
}
You need to add your tiles into your resource bundle. I mean add all those files to your project make sure to copy all files to project directory option checked.
I solved this issue editing both /etc/yum.repos.d/epel.repo
and /etc/yum.repos.d/epel-testing.repo
files, commenting all entries starting with mirrorlist=...
and uncommenting all the entries starting with baseurl=...
.
Have you confirmed that you are passing actual values and not None
?
from django.shortcuts import render
def createUser(request):
userName = request.REQUEST.get('username', None)
userPass = request.REQUEST.get('password', None)
userMail = request.REQUEST.get('email', None)
# TODO: check if already existed
if userName and userPass and userMail:
u,created = User.objects.get_or_create(userName, userMail)
if created:
# user was created
# set the password here
else:
# user was retrieved
else:
# request was empty
return render(request,'home.html')
There are no unsigned integers in Java. All integers are signed and in big endian.
On the C side the each byte has tne LSB at the start is on the left and the MSB at the end.
It sounds like you are using LSB as Least significant bit, are you? LSB usually stands for least significant byte. Endianness is not bit based but byte based.
To convert from unsigned byte to a Java integer:
int i = (int) b & 0xFF;
To convert from unsigned 32-bit little-endian in byte[] to Java long (from the top of my head, not tested):
long l = (long)b[0] & 0xFF;
l += ((long)b[1] & 0xFF) << 8;
l += ((long)b[2] & 0xFF) << 16;
l += ((long)b[3] & 0xFF) << 24;
<input type="text" class="number_only" />
<script>
$(document).ready(function() {
$('.number_only').keypress(function (event) {
return isNumber(event, this)
});
});
function isNumber(evt, element) {
var charCode = (evt.which) ? evt.which : event.keyCode
if ((charCode != 45 || $(element).val().indexOf('-') != -1) && (charCode != 46 || $(element).val().indexOf('.') != -1) && ((charCode < 48 && charCode != 8) || charCode > 57)){
return false;
}
else {
return true;
}
}
</script>
http://www.encodedna.com/2013/05/enter-only-numbers-using-jquery.htm
public Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
Tested answer:
In the .view-row css, change:
display:table-row;
to:
display:table
and get rid of "float". Everything will work as expected.
As it has been suggested in the comments, there is no need for a wrapping table. CSS allows for omitting levels of the tree structure (in this case rows) that are implicit. The reason your code doesn't work is that "width" can only be interpreted at the table level, not at the table-row level. When you have a "table" and then "table-cell"s directly underneath, they're implicitly interpreted as sitting in a row.
Working example:
<div class="view">
<div>Type</div>
<div>Name</div>
</div>
with css:
.view {
width:100%;
display:table;
}
.view > div {
width:50%;
display: table-cell;
}
If you have a build.gradle.kts
written in Kotlin DSL you can print test results with (I was developing a kotlin multi-platform project, with no "java" plugin applied):
tasks.withType<AbstractTestTask> {
afterSuite(KotlinClosure2({ desc: TestDescriptor, result: TestResult ->
if (desc.parent == null) { // will match the outermost suite
println("Results: ${result.resultType} (${result.testCount} tests, ${result.successfulTestCount} successes, ${result.failedTestCount} failures, ${result.skippedTestCount} skipped)")
}
}))
}
No need to use expensive regex
, if barely needed then try-
Use r'(/)(?=$)'
pattern that is capture last /
and replace with r''
i.e. blank character.
>>>re.sub(r'(/)(?=$)',r'','/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg/')
>>>'/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg'
If you want a no-bullet list (or any other non-standard usage) or more lines in a cell use <br />
| Event | Platform | Description |
| ------------- |-----------| -----:|
| `message_received`| `facebook-messenger`<br/>`skype`|
@Lucius and @zyrolasting have it right.
However, you will probably need to give the form a specified width
for it to work properly.
form {
margin: 0 auto;
width:250px;
}
This wll work.
public class CryptoUtils {
private final String TRANSFORMATION = "AES";
private final String encodekey = "1234543444555666";
public String encrypt(String inputFile)
throws CryptoException {
return doEncrypt(encodekey, inputFile);
}
public String decrypt(String input)
throws CryptoException {
// return doCrypto(Cipher.DECRYPT_MODE, key, inputFile);
return doDecrypt(encodekey,input);
}
private String doEncrypt(String encodekey, String inputStr) throws CryptoException {
try {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
byte[] key = encodekey.getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] inputBytes = inputStr.getBytes();
byte[] outputBytes = cipher.doFinal(inputBytes);
return Base64Utils.encodeToString(outputBytes);
} catch (NoSuchPaddingException | NoSuchAlgorithmException
| InvalidKeyException | BadPaddingException
| IllegalBlockSizeException | IOException ex) {
throw new CryptoException("Error encrypting/decrypting file", ex);
}
}
public String doDecrypt(String encodekey,String encrptedStr) {
try {
Cipher dcipher = Cipher.getInstance(TRANSFORMATION);
dcipher = Cipher.getInstance("AES");
byte[] key = encodekey.getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
dcipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
// decode with base64 to get bytes
byte[] dec = Base64Utils.decode(encrptedStr.getBytes());
byte[] utf8 = dcipher.doFinal(dec);
// create new string based on the specified charset
return new String(utf8, "UTF8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
If you want to disable all the div's controls, you can try adding a transparent div on the div to disable, you gonna make it unclickable, also use fadeTo to create a disable appearance.
try this.
$('#DisableDiv').fadeTo('slow',.6);
$('#DisableDiv').append('<div style="position: absolute;top:0;left:0;width: 100%;height:100%;z-index:2;opacity:0.4;filter: alpha(opacity = 50)"></div>');
WordNet database might be helpful. I once worked on a Firefox add-on which deals with words and all kinds of simple to complicated associations between them and stuff. Looks like WordNet will be very much useful to you.
Here it is in MySQL format. And this one (web-archived link) uses Wordnet v3.0 data, rather than the older Wordnet 2.0 data.
if exist <insert file name here> (
rem file exists
) else (
rem file doesn't exist
)
Or on a single line (if only a single action needs to occur):
if exist <insert file name here> <action>
for example, this opens notepad on autoexec.bat, if the file exists:
if exist c:\autoexec.bat notepad c:\autoexec.bat
This is all you need.
rsync -e ssh file host:/directory/.
I see no one mentioned the diamond problem, which might arise with inheritance.
In a glance, if classes B and C inherit A and both override method X, and a fourth class D, inherits from both B and C, and does not override X, which implementation of X D is supposed to use?
Wikipedia offers a nice overview of the topic being discussed in this question.
It also can be achieved in a little safer way using String.valueOf()
like so
Spinner sp = (Spinner) findViewById(R.id.sp_id);
String selectedText = String.valueOf(sp.getSelectedItem());
without crashing the app when all hell breaks loose.
The reason behind its safeness is having the capability of dealing with null
objects as the argument. The documentation says
if the argument is
null
, then a string equal to"null"
; otherwise, the value ofobj.toString()
is returned.
So, some insurance there in case of having an empty Spinner
for example, which the currently selected item has to be converted to String
.
return
returns a value. It doesn't matter what name you gave to that value. Returning it just "passes it out" so that something else can use it. If you want to use it, you have to grab it from outside:
lst = defineAList()
useTheList(lst)
Returning list
from inside defineAList
doesn't mean "make it so the whole rest of the program can use that variable". It means "pass this variable out and give the rest of the program one chance to grab it and use it". You need to assign that value to something outside the function in order to make use of it. Also, because of this, there is no need to define your list ahead of time with list = []
. Inside defineAList
, you create a new list and return it; this list has no relationship to the one you defined with list = []
at the beginning.
Incidentally, I changed your variable name from list
to lst
. It's not a good idea to use list
as a variable name because that is already the name of a built-in Python type. If you make your own variable called list
, you won't be able to access the builtin one anymore.
If you are passing id through url please use below
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot([
{ path: 'Employees', component: EmployeesComponent, pathMatch: 'full' },
{ path: 'Add', component: EmployeeAddComponent, pathMatch: 'full' },
**{ path: 'Edit/:id', component: EmployeeEditComponent },
{ path: 'Edit', component: EmployeeEditComponent },**
{ path: '', redirectTo: 'Employees', pathMatch: 'full' }
]),
],
i.e If you are passing any id we need to both url edit with id and edit url alone
for completeness, taken from this solution:
You could use toDateString:
var today = new Date();
var isToday = (today.toDateString() == otherDate.toDateString());
no library dependencies, and looking cleaner than the 'setHours()' approach shown in a previous answer, imho
Services and factories are similar to one another. Both will yield a singleton object that can be injected into other objects, and so are often used interchangeably.
They are intended to be used semantically to implement different design patterns.
A service pattern is one in which your application is broken into logically consistent units of functionality. An example might be an API accessor, or a set of business logic.
This is especially important in Angular because Angular models are typically just JSON objects pulled from a server, and so we need somewhere to put our business logic.
Here is a Github service for example. It knows how to talk to Github. It knows about urls and methods. We can inject it into a controller, and it will generate and return a promise.
(function() {
var base = "https://api.github.com";
angular.module('github', [])
.service('githubService', function( $http ) {
this.getEvents: function() {
var url = [
base,
'/events',
'?callback=JSON_CALLBACK'
].join('');
return $http.jsonp(url);
}
});
)();
Factories, on the other hand are intended to implement a factory pattern. A factory pattern in one in which we use a factory function to generate an object. Typically we might use this for building models. Here is a factory which returns an Author constructor:
angular.module('user', [])
.factory('User', function($resource) {
var url = 'http://simple-api.herokuapp.com/api/v1/authors/:id'
return $resource(url);
})
We would make use of this like so:
angular.module('app', ['user'])
.controller('authorController', function($scope, User) {
$scope.user = new User();
})
Note that factories also return singletons.
Because a factory simply returns an object, it can return any type of object you like, including a constructor function, as we see above.
Another technical difference is in the way services and factories are composed. A service function will be newed to generate the object. A factory function will be called and will return the object.
This means that in a service, we append to "this" which, in the context of a constructor, will point to the object under construction.
To illustrate this, here is the same simple object created using a service and a factory:
angular.module('app', [])
.service('helloService', function() {
this.sayHello = function() {
return "Hello!";
}
})
.factory('helloFactory', function() {
return {
sayHello: function() {
return "Hello!";
}
}
});
You can specify the CFBundleShortVersionString
string in your plist.info and read that programmatically using the provided API.
UPDATE:
Starting from CLI v6 you can just run ng update
in order to get your dependencies updated automatically to a new version.
With
ng update
sometimes you might want to add--force
flag. If you do so make sure that the version of typescript you got installed this way is supported by your current angular version, otherwise you might need to downgrade the typescript version.
Also checkout this guide Updating your Angular projects
If you are on are on Mac/Linux
or running bash on Windows
(that wont work in default Windows CMD
) you can run that oneliner:
npm install @angular/{animations,common,compiler,core,forms,http,platform-browser,platform-browser-dynamic,router,compiler-cli}@4.4.5 --save
yarn add @angular/{animations,common,compiler,core,forms,http,platform-browser,platform-browser-dynamic,router,compiler-cli}@4.4.5
Just specify version you wan't e.g @4.4.5 or put @latest to get the latest
Check your
package.json
just to make sure you are updating all@angular/*
packages that you app is relying on
@angular
version in your project run:npm ls @angular/compiler
or yarn list @angular/compiler
@angular
version available on npm run:npm show @angular/compiler version
Its Ctrl + Shift + r
For me, there was only one option to discard all.
The ALL_CAPS is taken from the C and C++ way of working I believe. This article here explains how the style differences came about.
In the new IDE's such as Visual Studio it is easy to identify the types, scope and if they are constant so it is not strictly necessary.
The FxCop and Microsoft StyleCop software will help give you guidelines and check your code so everyone works the same way.
Encountered the same issue and was able to fix it by the following the steps listed below:
As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().
Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static
for the example. Once it's done, add this line in your server code:
app.use("/static", express.static('./static/'));
This will effectively serve every file in your "static" folder via the /static route.
Querying your index.js file in the client thus becomes:
<script src="static/index.js"></script>
A callback is a method that is scheduled to be executed when a condition is met.
An "real world" example is a local video game store. You are waiting for Half-Life 3. Instead of going to the store every day to see if it is in, you register your email on a list to be notified when the game is available. The email becomes your "callback" and the condition to be met is the game's availability.
A "programmers" example is a web page where you want to perform an action when a button is clicked. You register a callback method for a button and continue doing other tasks. When/if the user cicks on the button, the browser will look at the list of callbacks for that event and call your method.
A callback is a way to handle events asynchronously. You can never know when the callback will be executed, or if it will be executed at all. The advantage is that it frees your program and CPU cycles to perform other tasks while waiting for the reply.
Check this page out: http://matplotlib.org/examples/pylab_examples/subplots_demo.html
plt.subplots
is similar. I think it's better since it's easier to set parameters of the figure. The first two arguments define the layout (in your case 1 row, 2 columns), and other parameters change features such as figure size:
import numpy as np
import matplotlib.pyplot as plt
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(5, 3))
axes[0].plot(x1, y1)
axes[1].plot(x2, y2)
fig.tight_layout()
What is the best approach to do this JAVA?
I would personally NOT use Axis 2, even for client side development only. Here is why I stay away from it:
The only reason Axis is still around is IMO because it's used in Eclipse since ages. Thanks god, this has been fixed in Eclipse Helios and I hope Axis2 will finally die. There are just much better stacks.
I read about SAAJ, looks like that will be more granular level of approach?
To do what?
Is there any other way than using the WSDL2Java tool, to generate the code. Maybe wsimport in another option. What are the pros and cons?
Yes! Prefer a JAX-WS stack like CXF or JAX-WS RI (you might also read about Metro, Metro = JAX-WS RI + WSIT), they are just more elegant, simpler, easier to use. In your case, I would just use JAX-WS RI which is included in Java 6 and thus wsimport
.
Can someone send the links for some good tutorials on these topics?
That's another pro, there are plenty of (good quality) tutorials for JAX-WS, see for example:
What are the options we need to use while generating the code using the WSDL2Java?
No options, use wsimport
:)
Old post but as it comes up for what I was searching for I thought I'd add some information to this topic. I was going to add a comment but I don't have enough rep.
As others have said:
connection.ConnectionTimeout is used for the initial connection
command.CommandTimeout is used for individual searches, updates, etc.
But:
connection.ConnectionTimeout is also used for committing and rolling back transactions.
Yes, this is an absolutely insane design decision.
So, if you are running into a timeout on commit or rollback you'll need to increase this value through the connection string.
The HAVING option can be used for this purpose and query should be
SELECT word, COUNT(*) FROM words
GROUP BY word
HAVING COUNT(*) > 1;
To check configuration files for syntax errors:
# Red Hat-based (Fedora, CentOS) and OSX
httpd -t
# Debian-based (Ubuntu)
apache2ctl -t
# MacOS
apachectl -t
To list all virtual hosts, and their locations:
# Red Hat-based (Fedora, CentOS) and OSX
httpd -S
# Debian-based (Ubuntu)
apache2ctl -S
# MacOS
apachectl -S
For Windows:
Method 1 (Two keys pressed at a time)
Method 2 (3 keys pressed at a time)
Please note: If you press and hold Ctrl+K for more than two seconds it will start deleting text so try to be quick with it.
I use the above shortcuts, and they work on my Windows system.
If you need to print the number you can use printf
System.out.printf("%02d", num);
You can use
String.format("%02d", num);
or
(num < 10 ? "0" : "") + num;
or
(""+(100+num)).substring(1);
This expression 12-4-2005
is a calculated int and the value is -1997
. You should do like this instead '2005-04-12'
with the '
before and after.
What you are trying to do is an extension of string slicing in Python:
Say all strings are of length 10, last char to be removed:
>>> st[:9]
'abcdefghi'
To remove last N
characters:
>>> N = 3
>>> st[:-N]
'abcdefg'
If this class is only a utility class, you should make the class final and define a private constructor:
public final class FilePathHelper {
private FilePathHelper() {
//not called
}
}
This prevents the default parameter-less constructor from being used elsewhere in your code. Additionally, you can make the class final, so that it can't be extended in subclasses, which is a best practice for utility classes. Since you declared only a private constructor, other classes wouldn't be able to extend it anyway, but it is still a best practice to mark the class as final.
You should be able to do something like this:
int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
View radioButton = radioButtonGroup.findViewById(radioButtonID);
int idx = radioButtonGroup.indexOfChild(radioButton);
If the RadioGroup
contains other Views (like a TextView
) then the indexOfChild()
method will return wrong index.
To get the selected RadioButton
text on the RadioGroup
:
RadioButton r = (RadioButton) radioButtonGroup.getChildAt(idx);
String selectedtext = r.getText().toString();
I think your date format does not make sense. There is no 13:00 PM. Remove the "aaa" at the end of your format or turn the HH into hh.
Nevertheless, this works fine for me:
String testDate = "29-Apr-2010,13:00:14 PM";
DateFormat formatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa");
Date date = formatter.parse(testDate);
System.out.println(date);
It prints "Thu Apr 29 13:00:14 CEST 2010".
I'd do this:
add the dependency as you like in your pom:
<dependency>
<groupId>com.stackoverflow...</groupId>
<artifactId>artifactId...</artifactId>
<version>1.0</version>
</dependency>
run mvn install
it will try to download the jar and fail. On the process, it
will give you the complete command of installing the jar with the error message. Copy that command and run it! easy huh?!
My solution to this problem is:
document.onkeypress = function (event) {
event = (event || window.event);
if (event.keyCode == 123) {
return false;
}
}
With the magic number 123
which is the key F12.
Run dos2unix or similar utility on it to remove the carriage returns (^M).
This message indicates that your file has dos-style lineendings:
-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory
Utilities like dos2unix
will fix it:
dos2unix <backup.bash >improved-backup.sh
Or, if no such utility is installed, you can accomplish the same thing with translate:
tr -d "\015\032" <backup.bash >improved-backup.sh
As for how those characters got there in the first place, @MadPhysicist had some good comments.
For your stated desire to "check if a property exists" you can directly use Lo-Dash's has
.
var exists = _.has(myObject, propertyNameToCheck);
See my code which may help you. models.py
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
password = models.CharField(max_length=100)
instrument_purchase = models.CharField(max_length=100)
house_no = models.CharField(max_length=100)
address_line1 = models.CharField(max_length=100)
address_line2 = models.CharField(max_length=100)
telephone = models.CharField(max_length=100)
zip_code = models.CharField(max_length=20)
state = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def __str__(self):
return self.name
forms.py
from django import forms
from models import *
class CustomerForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = Customer
fields = ('name', 'email', 'password', 'instrument_purchase', 'house_no', 'address_line1', 'address_line2', 'telephone', 'zip_code', 'state', 'country')
If I've understood your problem correctly, there are two possible problems here:
resultset
is null
- I assume that this can't be the case as if it was you'd get an exception in your while loop and nothing would be output.resultset.getString(i++)
will get columns 1,2,3 and so on from each subsequent row.I think that the second point is probably your problem here.
Lets say you only had 1 row returned, as follows:
Col 1, Col 2, Col 3
A , B, C
Your code as it stands would only get A - it wouldn't get the rest of the columns.
I suggest you change your code as follows:
ResultSet resultset = ...;
ArrayList<String> arrayList = new ArrayList<String>();
while (resultset.next()) {
int i = 1;
while(i <= numberOfColumns) {
arrayList.add(resultset.getString(i++));
}
System.out.println(resultset.getString("Col 1"));
System.out.println(resultset.getString("Col 2"));
System.out.println(resultset.getString("Col 3"));
System.out.println(resultset.getString("Col n"));
}
Edit:
To get the number of columns:
ResultSetMetaData metadata = resultset.getMetaData();
int numberOfColumns = metadata.getColumnCount();
iOS 10
Use app-prefs:
App-prefs:root=MOBILE_DATA_SETTINGS_ID
See gist
The new Mavericks (10.9) showed me the "Requesting install", but nothing happened.
The solution was to manually download and install the official Java package for OS X, which is in Java for OS X 2013-005.
Update: As mentioned in the comments below, there is a newer version of this same package:
Java for OS X 2014-001 (Correcting dead line above)
Java for OS X 2014-001 includes installation improvements, and supersedes all previous versions of Java for OS X. This package installs the same version of Java 6 included in Java for OS X 2013-005.