One-liner:
$ python -c "import urllib2; print urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)).open(urllib2.Request('http://google.com'))"
Any CPU means that it will work on any platform. This is because managed code is similar to Java. Think of it as being compiled to a byte code that is interpreted by the .NET Framework at run-time.
C++ does not have this option because it is compiled to machine code that is platform specific.
I had gotten frustrated with this problem myself and so I modified the filter that was created by @Trevor Senior as I was running into an issue with my console saying that it could not use the reverse method. I also, wanted to keep the integrity of the object because this is what Angular is originally using in a ng-repeat directive. In this case I used the input of stupid (key) because the console will get upset saying there are duplicates and in my case I needed to track by $index.
Filter:
angular.module('main').filter('reverse', function() {
return function(stupid, items) {
var itemss = items.files;
itemss = itemss.reverse();
return items.files = itemss;
};
});
HTML:
<div ng-repeat="items in items track by $index | reverse: items">
I think I had a better output, especially for a double datatype sorting.
Though this question has been marked answered, perhaps this will help someone else;
Arrays.sort(newTag, new Comparator<String[]>() {
@Override
public int compare(final String[] entry1, final String[] entry2) {
final Integer time1 = (int)Integer.valueOf((int) Double.parseDouble(entry1[2]));
final Integer time2 = (int)Integer.valueOf((int) Double.parseDouble(entry2[2]));
return time1.compareTo(time2);
}
});
DECLARE @start [datetime] = 2010/4/1;
Should be...
DECLARE @start [datetime] = '2010-04-01';
The one you have is dividing 2010 by 4, then by 1, then converting to a date. Which is the 57.5th day from 1900-01-01.
Try SELECT @start
after your initialisation to check if this is correct.
This worked for me:
#!/bin/bash
#Variables
FILELOCAL=/var/www/folder/$(date +'%Y%m%d_%H-%M-%S').csv
SFTPHOSTNAME="myHost.com"
SFTPUSERNAME="myUser"
SFTPPASSWORD="myPass"
FOLDER="myFolderIfNeeded"
FILEREMOTE="fileNameRemote"
#SFTP CONNECTION
sshpass -p $SFTPPASSWORD sftp $SFTPUSERNAME@$SFTPHOSTNAME << !
cd $FOLDER
get $FILEREMOTE $FILELOCAL
ls
bye
!
Probably you have to install sshpass:
sudo apt-get install sshpass
csvreader.next() Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.
You can generate NPM dependency trees without the need of installing a dependency by using the command
npm list
This will generate a dependency tree for the project at the current directory and print it to the console.
You can get the dependency tree of a specific dependency like so:
npm list [dependency]
You can also set the maximum depth level by doing
npm list --depth=[depth]
Note that you can only view the dependency tree of a dependency that you have installed either globally, or locally to the NPM project.
Why don't you just apply the div submit styles to a submit button? I'm sure there's a javascript for this but that would be easier.
You cannot have spaces around the =
sign.
When you write:
STR = "foo"
bash tries to run a command named STR
with 2 arguments (the strings =
and foo
)
When you write:
STR =foo
bash tries to run a command named STR
with 1 argument (the string =foo
)
When you write:
STR= foo
bash tries to run the command foo
with STR set to the empty string in its environment.
I'm not sure if this helps to clarify or if it is mere obfuscation, but note that:
STR "=" "foo"
,STR "=foo"
,STR="" foo
.The relevant section of the sh language spec, section 2.9.1 states:
A "simple command" is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator.
In that context, a word
is the command that bash is going to run. Any string containing =
(in any position other than at the beginning of the string) which is not a redirection and in which the portion of the string before the =
is a valid variable name is a variable assignment, while any string that is not a redirection or a variable assignment is a command. In STR = "foo"
, STR
is not a variable assignment.
Find all word and space characters up to and including a -
^[\w ]+-
For those using nginx with unicorn and rails, most likely the timeout is in your unicorn.rb
file
put a large timeout in unicorn.rb
timeout 500
if you're still facing issues, try having fail_timeout=0 in your upstream in nginx and see if this fixes your issue. This is for debugging purposes and might be dangerous in a production environment.
upstream foo_server {
server 127.0.0.1:3000 fail_timeout=0;
}
We can get a list of files inside a folder on the file system using various golang standard library functions.
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
)
func main() {
var (
root string
files []string
err error
)
root := "/home/manigandan/golang/samples"
// filepath.Walk
files, err = FilePathWalkDir(root)
if err != nil {
panic(err)
}
// ioutil.ReadDir
files, err = IOReadDir(root)
if err != nil {
panic(err)
}
//os.File.Readdir
files, err = OSReadDir(root)
if err != nil {
panic(err)
}
for _, file := range files {
fmt.Println(file)
}
}
The
path/filepath
package provides a handy way to scan all the files in a directory, it will automatically scan each sub-directories in the directory.
func FilePathWalkDir(root string) ([]string, error) {
var files []string
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if !info.IsDir() {
files = append(files, path)
}
return nil
})
return files, err
}
ioutil.ReadDir
reads the directory named by dirname and returns a list of directory entries sorted by filename.
func IOReadDir(root string) ([]string, error) {
var files []string
fileInfo, err := ioutil.ReadDir(root)
if err != nil {
return files, err
}
for _, file := range fileInfo {
files = append(files, file.Name())
}
return files, nil
}
Readdir reads the contents of the directory associated with file and returns a slice of up to n FileInfo values, as would be returned by Lstat, in directory order. Subsequent calls on the same file will yield further FileInfos.
func OSReadDir(root string) ([]string, error) {
var files []string
f, err := os.Open(root)
if err != nil {
return files, err
}
fileInfo, err := f.Readdir(-1)
f.Close()
if err != nil {
return files, err
}
for _, file := range fileInfo {
files = append(files, file.Name())
}
return files, nil
}
Benchmark results.
Get more details on this Blog Post
SQL> select substr('999123456789', greatest (-9, -length('999123456789')), 9) as value from dual;
VALUE
---------
123456789
SQL> select substr('12345', greatest (-9, -length('12345')), 9) as value from dual;
VALUE
----
12345
The call to greatest (-9, -length(string))
limits the starting offset either 9 characters left of the end or the beginning of the string.
I just want to bring up a valid point to anyone searching for this. If you are going to work with .NET versions before 4.0 (VS2010), please be advised that you have to create constructor chains as shown above.
However, if you're staying in 4.0, I have good news. You can now have a single constructor with optional arguments! I'll simplify the Foo class example:
class Foo {
private int id;
private string name;
public Foo(int id = 0, string name = "") {
this.id = id;
this.name = name;
}
}
class Main() {
// Foo Int:
Foo myFooOne = new Foo(12);
// Foo String:
Foo myFooTwo = new Foo(name:"Timothy");
// Foo Both:
Foo myFooThree = new Foo(13, name:"Monkey");
}
When you implement the constructor, you can use the optional arguments since defaults have been set.
I hope you enjoyed this lesson! I just can't believe that developers have been complaining about construct chaining and not being able to use default optional arguments since 2004/2005! Now it has taken SO long in the development world, that developers are afraid of using it because it won't be backwards compatible.
Sorry to say that there is no print function in sublimetext2, may be 3 will fix this?
Anyway there are a few plugins that are floating about, the most helpful for you might be print-to-HTML https://github.com/joelpt/sublimetext-print-to-html .
Thanks for everyone who answered, and thanks for those who gave me the function-format idea, i'll really study it for future using.
But for this explicit case, the 'special yyyymm field' is not to be considered as a date field, but just as a tag, o whatever would be used for matching the exactly year-month researched value; there is already another date field, with the full timestamp, but if i need all the rows of january 2008, i think that is faster a select like
SELECT [columns] FROM table WHERE yearmonth = '200801'
instead of
SELECT [columns] FROM table WHERE date BETWEEN DATE('2008-01-01') AND DATE('2008-01-31')
Simplest:
Form form = new Form();
form.add("id", "1");
form.add("name", "supercobra");
ClientResponse response = webResource
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, form);
You can use one of the following:
DateTime.current.midnight
DateTime.current.beginning_of_day
DateTime.current.to_date
Yes, .length
(property-like, not a method):
String[] array = new String[10];
int size = array.length;
Generally, you can use the func(*tuple)
syntax. You can even pass a part of the tuple, which seems like what you're trying to do here:
t = (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(*t[0:7])
This is called unpacking a tuple, and can be used for other iterables (such as lists) too. Here's another example (from the Python tutorial):
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]
Both of the examples are in VB.NET.
Debug path:
TextBox1.Text = My.Application.Info.DirectoryPath
EXE path:
TextBox2.Text = IO.Path.GetFullPath(Application.ExecutablePath)
For example:
you can use:
df %>% filter(!is.na(a))
to remove the NA in column a.
per @Kevin-Reid's answer, here's an alternative to the "I ended up doing the following" example that avoids needing to name and then lookup the form object again by constructing the form specifically (using jQuery)..
var url = 'http://example.com/vote/' + Username;
var form = $('<form action="' + url + '" method="post">' +
'<input type="text" name="api_url" value="' + Return_URL + '" />' +
'</form>');
$('body').append(form);
form.submit();
Just to add to the other answers, I found that the simplest solution to achieve the rounded corners was to set the following as a background to your Edittext.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@android:color/white"/>
<corners android:radius="8dp"/>
</shape>
As mentioned above if you wish to as a new element your queried collection you can use:
$items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.' ;'));
foreach($items as $item){
$product = DB::select(DB::raw(' select * from product
where product_id = '. $id.';' ));
$items->push($product);
// or
// $items->put('products', $product);
}
but if you wish to add new element to each queried element you need to do like:
$items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.' ;'));
foreach($items as $item){
$product = DB::select(DB::raw(' select * from product
where product_id = '. $id.';' ));
$item->add_whatever_element_you_want = $product;
}
add_whatever_element_you_want
can be whatever you wish that your element is named (like product for example).
You can find something about this in the Adobe Developer FAQ. (It's a PDF document rather than a web page, which I guess is unsurprising in this particular case.)
The FAQ notes that the use of the command line switches is unsupported.
To open a file it's:
AcroRd32.exe <filename>
The following switches are available:
/n
- Launch a new instance of Reader even if one is already open/s
- Don't show the splash screen/o
- Don't show the open file dialog/h
- Open as a minimized window/p <filename>
- Open and go straight to the print dialog/t <filename> <printername> <drivername> <portname>
- Print the file the specified printer.Sometimes an algorithm is easiest to understand top-down, starting with the overall structure and drilling down into the details.
You can do so without forward declarations:
def main():
make_omelet()
eat()
def make_omelet():
break_eggs()
whisk()
fry()
def break_eggs():
for egg in carton:
break(egg)
# ...
main()
The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[]
with an index read from stream. Try vector::at()
instead of vector::operator[]
. This won't solve your problem, but will show which assignment to the vector causes error.
Try launching the Emulator from the command line as follows:
emulator -verbose -avd <AVD name>
This will give you detailed output and may show the error that's preventing the emulator from connecting to the Internet.
It's worth noting that if you want a currently-focused field to update the keyboard type immediately, there's one extra step:
// textField is set to a UIKeyboardType other than UIKeyboardTypeEmailAddress
[textField setKeyboardType:UIKeyboardTypeEmailAddress];
[textField reloadInputViews];
Without the call to reloadInputViews
, the keyboard will not change until the selected field (the first responder) loses and regains focus.
A full list of the UIKeyboardType
values can be found here, or:
typedef enum : NSInteger {
UIKeyboardTypeDefault,
UIKeyboardTypeASCIICapable,
UIKeyboardTypeNumbersAndPunctuation,
UIKeyboardTypeURL,
UIKeyboardTypeNumberPad,
UIKeyboardTypePhonePad,
UIKeyboardTypeNamePhonePad,
UIKeyboardTypeEmailAddress,
UIKeyboardTypeDecimalPad,
UIKeyboardTypeTwitter,
UIKeyboardTypeWebSearch,
UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable
} UIKeyboardType;
VB 6 provides a Clipboard
object that makes all of this extremely simple and convenient, but unfortunately that's not available from VBA.
If it were me, I'd go the API route. There's no reason to be scared of calling native APIs; the language provides you with the ability to do that for a reason.
However, a simpler alternative is to use the DataObject
class, which is part of the Forms library. I would only recommend going this route if you are already using functionality from the Forms library in your app. Adding a reference to this library only to use the clipboard seems a bit silly.
For example, to place some text on the clipboard, you could use the following code:
Dim clipboard As MSForms.DataObject
Set clipboard = New MSForms.DataObject
clipboard.SetText "A string value"
clipboard.PutInClipboard
Or, to copy text from the clipboard into a string variable:
Dim clipboard As MSForms.DataObject
Dim strContents As String
Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
strContents = clipboard.GetText
I normally have them in an array and call writeBooleanArray
and readBooleanArray
If it's a single boolean you need to pack, you could do this:
parcel.writeBooleanArray(new boolean[] {myBool});
Open Notepad and write this
@echo off
:A
Cls
echo MESSENGER
set /p n=User:
set /p m=Message:
net send %n% %m%
Pause
Goto A
and then save as "Messenger.bat
" and close the Notepad
Step 1:
when you open that saved notepad file it will open as a file Messenger command prompt with this details.
Messenger
User:
after "User
" write the ip of the computer you want to contact and then press enter.
import java.util.ArrayList;
public class TestClass {
public static void main(String[] args) {
ArrayList<ArrayList<String>> listOLists = new ArrayList<ArrayList<String>>();
ArrayList<String> List_1 = new ArrayList<String>();
List_1.add("1");
List_1.add("2");
listOLists.add(List_1);
ArrayList<String> List_2 = new ArrayList<String>();
List_2.add("4");
List_2.add("5");
List_2.add("10");
List_2.add("11");
listOLists.add(List_2);
for (int i = 0; i < listOLists.size(); i++) {
System.out.print("list " + i + " :");
for (int j = 0; j < listOLists.get(i).size(); j++) {
System.out.print(listOLists.get(i).get(j) + " ;");
}
System.out.println();
}
}
}
Another solution, besides the ondes already mentioned (using layout
or par(xpd=TRUE)
) is to overlay your plot with a transparent plot over the entire device and then add the legend to that.
The trick is to overlay a (empty) graph over the complete plotting area and adding the legend to that. We can use the par(fig=...)
option. First we instruct R to create a new plot over the entire plotting device:
par(fig=c(0, 1, 0, 1), oma=c(0, 0, 0, 0), mar=c(0, 0, 0, 0), new=TRUE)
Setting oma
and mar
is needed since we want to have the interior of the plot cover the entire device. new=TRUE
is needed to prevent R from starting a new device. We can then add the empty plot:
plot(0, 0, type='n', bty='n', xaxt='n', yaxt='n')
And we are ready to add the legend:
legend("bottomright", ...)
will add a legend to the bottom right of the device. Likewise, we can add the legend to the top or right margin. The only thing we need to ensure is that the margin of the original plot is large enough to accomodate the legend.
Putting all this into a function;
add_legend <- function(...) {
opar <- par(fig=c(0, 1, 0, 1), oma=c(0, 0, 0, 0),
mar=c(0, 0, 0, 0), new=TRUE)
on.exit(par(opar))
plot(0, 0, type='n', bty='n', xaxt='n', yaxt='n')
legend(...)
}
And an example. First create the plot making sure we have enough space at the bottom to add the legend:
par(mar = c(5, 4, 1.4, 0.2))
plot(rnorm(50), rnorm(50), col=c("steelblue", "indianred"), pch=20)
Then add the legend
add_legend("topright", legend=c("Foo", "Bar"), pch=20,
col=c("steelblue", "indianred"),
horiz=TRUE, bty='n', cex=0.8)
Resulting in:
Ok. I found a program buried deep in other files from the beginning of the year that does what I want. I can't really comment on the suggestions offered because I'm not an experienced spim or low level programmer.Here it is:
.text
.globl __start
__start:
la $a0,str1 #Load and print string asking for string
li $v0,4
syscall
li $v0,8 #take in input
la $a0, buffer #load byte space into address
li $a1, 20 # allot the byte space for string
move $t0,$a0 #save string to t0
syscall
la $a0,str2 #load and print "you wrote" string
li $v0,4
syscall
la $a0, buffer #reload byte space to primary address
move $a0,$t0 # primary address = t0 address (load pointer)
li $v0,4 # print string
syscall
li $v0,10 #end program
syscall
.data
buffer: .space 20
str1: .asciiz "Enter string(max 20 chars): "
str2: .asciiz "You wrote:\n"
###############################
#Output:
#Enter string(max 20 chars): qwerty 123
#You wrote:
#qwerty 123
#Enter string(max 20 chars): new world oreddeYou wrote:
# new world oredde //lol special character
###############################
Maybe you can use this properties:
ActiveCell.Interior.ColorIndex - one of 56 preset colors
and
ActiveCell.Interior.Color - RGB color, used like that:
ActiveCell.Interior.Color = RGB(255,255,255)
In the case where you presented a UIViewController
from within a UIViewController
i.e...
// Main View Controller
self.present(otherViewController, animated: true)
Simply call the dismiss
function:
// Other View Controller
self.dismiss(animated: true)
@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
text.set_fontsize('x-large')
plt.savefig('leg_example')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()
The above two methods produce the same output image:
Other option using apache-commons:
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
...
File file = new File( "path" );
byte[] bytes = Base64.decodeBase64( "base64" );
FileUtils.writeByteArrayToFile( file, bytes );
Eclipse Oxygen - after installation of Lombok according to the process described on the Lombok page, still could not use @Log annotation.
Solution : Project --> Properties - Enable annotation processing
If you have MATLAB Compiler installed, there's a GUI option for compiling. Try entering
deploytool
in the command line. Mathworks does a pretty good job documenting how to use it in this video tutorial: http://www.mathworks.com/products/demos/compiler/deploytool/index.html
Also, if you want to include user input such as choosing a file or directory, look into
uigetfile % or uigetdir if you need every file in a directory
for use in conjunction with
guide
The fact that the previously accepted answer refers to php 5.3.6, while the current version of MAMP ships with 7.2.1 as the default (as of early 2018), points out that this is not a very sustainable solution. You can make your path update automatically by adding an extra line to your .bash_profile
or .zshrc
to get the latest version of PHP from /Applications/MAMP/bin/php/
and export that to your path. Here’s how I do it:
# Use MAMP version of PHP
PHP_VERSION=`command ls /Applications/MAMP/bin/php/ | sort -n | tail -1`
export PATH=/Applications/MAMP/bin/php/${PHP_VERSION}/bin:$PATH
(Use source ~/.bash_profile
after making your changes to make sure they take effect.)
As others have mentioned, you will likely also want to modify your shell to use MAMP’s mysql executable, which is located in /Applications/MAMP/Library/bin
. However, I do not recommend exporting that folder, because there are a bunch of other executables there, like libtool
, that you probably don’t want to be giving priority to over your system installed versions. This issue prevented me from installing a node package recently (libxmljs), as documented here.
My solution was to define and export mysql
and mysqladmin
as functions:
# Export MAMP MySQL executables as functions
# Makes them usable from within shell scripts (unlike an alias)
mysql() {
/Applications/MAMP/Library/bin/mysql "$@"
}
mysqladmin() {
/Applications/MAMP/Library/bin/mysqladmin "$@"
}
export -f mysql
export -f mysqladmin
I used functions instead of aliases, because aliases don’t get passed to child processes, or at least not in the context of a shell script. The only downside I’ve found is that running which mysql
and which mysqladmin
will no longer return anything, which is a bummer. If you want to check which mysql is being used and make sure everything is copacetic, use mysql --version
instead.
Note: @julianromera points out that zsh doesn’t support exporting functions, so in that case, you’re best off using an alias, like alias mysql='/Applications/MAMP/Library/bin/mysql'
. Just be aware that your aliases might not be available from subshells (like when executing a shell script).
You can rename/remove master on remote, but this will be an issue if lots of people have based their work on the remote master branch and have pulled that branch in their local repo.
That might not be the case here since everyone seems to be working on branch 'seotweaks
'.
In that case you can:
git remote --show may not work.
(Make a git remote show
to check how your remote is declared within your local repo. I will assume 'origin
')
(Regarding GitHub, house9 comments: "I had to do one additional step, click the 'Admin
' button on GitHub and set the 'Default Branch
' to something other than 'master
', then put it back afterwards")
git branch -m master master-old # rename master on local
git push origin :master # delete master on remote
git push origin master-old # create master-old on remote
git checkout -b master seotweaks # create a new local master on top of seotweaks
git push origin master # create master on remote
But again:
reset --hard
their local master to the remote/master branch they will fetch, and forget about their current master.While you can alias your tables within your query (i.e., "SELECT u.username FROM users u;"), you have to use the actual names of the columns you're referencing. AS only impacts how the fields are returned.
You can pass the element into the function <input type="button" value="mybutton1" onclick="dosomething(this)">test
by passing this. Then in the function you can access the value like this:
function dosomething(element) {
console.log(element.value);
}
One of the difference is Null termination (\0).
In C and C++, char* or char[] will take a pointer to a single char as a parameter and will track along the memory until a 0 memory value is reached (often called the null terminator).
C++ strings can contain embedded \0 characters, know their length without counting.
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
void NullTerminatedString(string str){
int NUll_term = 3;
str[NUll_term] = '\0'; // specific character is kept as NULL in string
cout << str << endl <<endl <<endl;
}
void NullTerminatedChar(char *str){
int NUll_term = 3;
str[NUll_term] = 0; // from specific, all the character are removed
cout << str << endl;
}
int main(){
string str = "Feels Happy";
printf("string = %s\n", str.c_str());
printf("strlen = %d\n", strlen(str.c_str()));
printf("size = %d\n", str.size());
printf("sizeof = %d\n", sizeof(str)); // sizeof std::string class and compiler dependent
NullTerminatedString(str);
char str1[12] = "Feels Happy";
printf("char[] = %s\n", str1);
printf("strlen = %d\n", strlen(str1));
printf("sizeof = %d\n", sizeof(str1)); // sizeof char array
NullTerminatedChar(str1);
return 0;
}
Output:
strlen = 11
size = 11
sizeof = 32
Fee s Happy
strlen = 11
sizeof = 12
Fee
A simpler SHA-1 method: (updated from the commenter's suggestions, also using a massively more efficient byte->string algorithm)
String sha1Hash( String toHash )
{
String hash = null;
try
{
MessageDigest digest = MessageDigest.getInstance( "SHA-1" );
byte[] bytes = toHash.getBytes("UTF-8");
digest.update(bytes, 0, bytes.length);
bytes = digest.digest();
// This is ~55x faster than looping and String.formating()
hash = bytesToHex( bytes );
}
catch( NoSuchAlgorithmException e )
{
e.printStackTrace();
}
catch( UnsupportedEncodingException e )
{
e.printStackTrace();
}
return hash;
}
// http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex( byte[] bytes )
{
char[] hexChars = new char[ bytes.length * 2 ];
for( int j = 0; j < bytes.length; j++ )
{
int v = bytes[ j ] & 0xFF;
hexChars[ j * 2 ] = hexArray[ v >>> 4 ];
hexChars[ j * 2 + 1 ] = hexArray[ v & 0x0F ];
}
return new String( hexChars );
}
If you already know the indices:
list1 = ['x','y','z','a','b','c','d','e','f','g']
indices = [(0, 4), (5, 9)]
print [list1[s:e+1] for s,e in indices]
Note that we're adding +1 to the end to make the range inclusive...
It turns out that my understanding of the error message was wrong. I'd say it features very poor choice of words. Googling around shown me someone else misunderstood the message exactly like I did - see PHP bug #66763.
After totally unhelpful "This is the way the RMs wanted it to be." response to that bug by Mike, Tyrael explains that setting it to "-1" doesn't make just the warning to go away. It does the right thing, i.e. it completely disables populating the culprit variable. Turns out that having it set to 0 STILL populates data under some circumstances. Talk about bad design! To cite PHP RFC:
Change always_populate_raw_post_data INI setting to accept three values instead of two.
- -1: The behavior of master; don't ever populate $GLOBALS[HTTP_RAW_POST_DATA]
- 0/off/whatever: BC behavior (populate if content-type is not registered or request method is other than POST)
- 1/on/yes/true: BC behavior (always populate $GLOBALS[HTTP_RAW_POST_DATA])
So yeah, setting it to -1 not only avoids the warning, like the message said, but it also finally disables populating this variable, which is what I wanted.
How to do it without using cURL with straight-up PHP: http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
Codified version of all other answers (at the time of writing):
import java.io.*;
/**
* This class is based on <a href="http://stackoverflow.com/users/2478930/cheneym">cheneym</a>'s
* <a href="http://stackoverflow.com/a/18375641/253468">awesome interpretation</a>
* of the Java {@link Runtime}'s memory query methods, which reflects intuitive thinking.
* Also includes comments and observations from others on the same question, and my own experience.
* <p>
* <img src="https://i.stack.imgur.com/GjuwM.png" alt="Runtime's memory interpretation">
* <p>
* <b>JVM memory management crash course</b>:
* Java virtual machine process' heap size is bounded by the maximum memory allowed.
* The startup and maximum size can be configured by JVM arguments.
* JVMs don't allocate the maximum memory on startup as the program running may never require that.
* This is to be a good player and not waste system resources unnecessarily.
* Instead they allocate some memory and then grow when new allocations require it.
* The garbage collector will be run at times to clean up unused objects to prevent this growing.
* Many parameters of this management such as when to grow/shrink or which GC to use
* can be tuned via advanced configuration parameters on JVM startup.
*
* @see <a href="http://stackoverflow.com/a/42567450/253468">
* What are Runtime.getRuntime().totalMemory() and freeMemory()?</a>
* @see <a href="http://www.oracle.com/technetwork/java/javase/memorymanagement-whitepaper-150215.pdf">
* Memory Management in the Sun Java HotSpot™ Virtual Machine</a>
* @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/windows/java.html">
* Full VM options reference for Windows</a>
* @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html">
* Full VM options reference for Linux, Mac OS X and Solaris</a>
* @see <a href="http://www.oracle.com/technetwork/articles/java/vmoptions-jsp-140102.html">
* Java HotSpot VM Options quick reference</a>
*/
public class SystemMemory {
// can be white-box mocked for testing
private final Runtime runtime = Runtime.getRuntime();
/**
* <b>Total allocated memory</b>: space currently reserved for the JVM heap within the process.
* <p>
* <i>Caution</i>: this is not the total memory, the JVM may grow the heap for new allocations.
*/
public long getAllocatedTotal() {
return runtime.totalMemory();
}
/**
* <b>Current allocated free memory</b>: space immediately ready for new objects.
* <p>
* <i>Caution</i>: this is not the total free available memory,
* the JVM may grow the heap for new allocations.
*/
public long getAllocatedFree() {
return runtime.freeMemory();
}
/**
* <b>Used memory</b>:
* Java heap currently used by instantiated objects.
* <p>
* <i>Caution</i>: May include no longer referenced objects, soft references, etc.
* that will be swept away by the next garbage collection.
*/
public long getUsed() {
return getAllocatedTotal() - getAllocatedFree();
}
/**
* <b>Maximum allocation</b>: the process' allocated memory will not grow any further.
* <p>
* <i>Caution</i>: This may change over time, do not cache it!
* There are some JVMs / garbage collectors that can shrink the allocated process memory.
* <p>
* <i>Caution</i>: If this is true, the JVM will likely run GC more often.
*/
public boolean isAtMaximumAllocation() {
return getAllocatedTotal() == getTotal();
// = return getUnallocated() == 0;
}
/**
* <b>Unallocated memory</b>: amount of space the process' heap can grow.
*/
public long getUnallocated() {
return getTotal() - getAllocatedTotal();
}
/**
* <b>Total designated memory</b>: this will equal the configured {@code -Xmx} value.
* <p>
* <i>Caution</i>: You can never allocate more memory than this, unless you use native code.
*/
public long getTotal() {
return runtime.maxMemory();
}
/**
* <b>Total free memory</b>: memory available for new Objects,
* even at the cost of growing the allocated memory of the process.
*/
public long getFree() {
return getTotal() - getUsed();
// = return getAllocatedFree() + getUnallocated();
}
/**
* <b>Unbounded memory</b>: there is no inherent limit on free memory.
*/
public boolean isBounded() {
return getTotal() != Long.MAX_VALUE;
}
/**
* Dump of the current state for debugging or understanding the memory divisions.
* <p>
* <i>Caution</i>: Numbers may not match up exactly as state may change during the call.
*/
public String getCurrentStats() {
StringWriter backing = new StringWriter();
PrintWriter out = new PrintWriter(backing, false);
out.printf("Total: allocated %,d (%.1f%%) out of possible %,d; %s, %s %,d%n",
getAllocatedTotal(),
(float)getAllocatedTotal() / (float)getTotal() * 100,
getTotal(),
isBounded()? "bounded" : "unbounded",
isAtMaximumAllocation()? "maxed out" : "can grow",
getUnallocated()
);
out.printf("Used: %,d; %.1f%% of total (%,d); %.1f%% of allocated (%,d)%n",
getUsed(),
(float)getUsed() / (float)getTotal() * 100,
getTotal(),
(float)getUsed() / (float)getAllocatedTotal() * 100,
getAllocatedTotal()
);
out.printf("Free: %,d (%.1f%%) out of %,d total; %,d (%.1f%%) out of %,d allocated%n",
getFree(),
(float)getFree() / (float)getTotal() * 100,
getTotal(),
getAllocatedFree(),
(float)getAllocatedFree() / (float)getAllocatedTotal() * 100,
getAllocatedTotal()
);
out.flush();
return backing.toString();
}
public static void main(String... args) {
SystemMemory memory = new SystemMemory();
System.out.println(memory.getCurrentStats());
}
}
Assuming you are a PyCharm User, its pretty easy to install Flask This will help users without shell pip access also.
Cases in which flask is not shown in pip: Open Manage Repository>> Add(+) >> Add this following url
Now back to pip, it will show related packages of flask,
Voila!!!
Had same problem - it was somewhere in the ca certificate, so I used the ca bundle used for curl, and it worked. You can download the curl ca bundle here: https://curl.haxx.se/docs/caextract.html
For encryption and security issues see this helpful article:
https://www.venditan.com/labs/2014/06/26/ssl-and-php-streams-part-1-you-are-doing-it-wrongtm/432
Here is the example:
$url = 'https://www.example.com/api/list';
$cn_match = 'www.example.com';
$data = array (
'apikey' => '[example api key here]',
'limit' => intval($limit),
'offset' => intval($offset)
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
, 'ssl' => array(
'verify_peer' => true,
'cafile' => [path to file] . "cacert.pem",
'ciphers' => 'HIGH:TLSv1.2:TLSv1.1:TLSv1.0:!SSLv3:!SSLv2',
'CN_match' => $cn_match,
'disable_compression' => true,
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
Hope that helps
In your entity for that table, add the DatabaseGenerated
attribute above the column for which identity insert is set:
Example:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int TaskId { get; set; }
Segmentation fault is a generic one, there are many possible reasons for this:
String[] strings = new String[25000];
for (int i = 0; i < 25000; i++) strings[i] = '1234567';
String result;
result = "";
for (String s : strings) result += s;
//linear +: 5s
result = "";
for (String s : strings) result = result.concat(s);
//linear .concat: 2.5s
result = String.join("", strings);
//Java 8 .join: 3ms
Public String join(String delimiter, String[] s)
{
int ls = s.length;
switch (ls)
{
case 0: return "";
case 1: return s[0];
case 2: return s[0].concat(delimiter).concat(s[1]);
default:
int l1 = ls / 2;
String[] s1 = Arrays.copyOfRange(s, 0, l1);
String[] s2 = Arrays.copyOfRange(s, l1, ls);
return join(delimiter, s1).concat(delimiter).concat(join(delimiter, s2));
}
}
result = join("", strings);
// Divide&Conquer join: 7ms
If you don't have the choise but to use Java 6 or 7 then you should use Divide&Conquer join.
I see the subList answer is already here, but here's code that demonstrates that it's a true sublist, not a copy:
public class SubListTest extends TestCase {
public void testSubarray() throws Exception {
Integer[] array = {1, 2, 3, 4, 5};
List<Integer> list = Arrays.asList(array);
List<Integer> subList = list.subList(2, 4);
assertEquals(2, subList.size());
assertEquals((Integer) 3, subList.get(0));
list.set(2, 7);
assertEquals((Integer) 7, subList.get(0));
}
}
I don't believe there's a good way to do this directly with arrays, however.
Like this.
import java.util.Date;
import java.util.GregorianCalendar;
/**
* DateDiff -- compute the difference between two dates.
*/
public class DateDiff {
public static void main(String[] av) {
/** The date at the end of the last century */
Date d1 = new GregorianCalendar(2000, 11, 31, 23, 59).getTime();
/** Today's date */
Date today = new Date();
// Get msec from each, and subtract.
long diff = today.getTime() - d1.getTime();
System.out.println("The 21st century (up to " + today + ") is "
+ (diff / (1000 * 60 * 60 * 24)) + " days old.");
}
}
Here is an article on Java date arithmetic.
I agree with Paolo that we need to see more code. I tested this overly simplified example and it worked. This means that it is able to change the form action on the fly.
<script type="text/javascript">
function submitForm(){
var form_url = $("#openid_form").attr("action");
alert("Before - action=" + form_url);
//changing the action to google.com
$("#openid_form").attr("action","http://google.com");
alert("After - action = "+$("#openid_form").attr("action"));
//submit the form
$("#openid_form").submit();
}
</script>
<form id="openid_form" action="test.html">
First Name:<input type="text" name="fname" /><br/>
Last Name: <input type="text" name="lname" /><br/>
<input type="button" onclick="submitForm()" value="Submit Form" />
</form>
EDIT: I tested the updated code you posted and found a syntax error in the declaration of providers_large
. There's an extra comma. Firefox ignores the issue, but IE8 throws an error.
var providers_large = {
google: {
name: 'Google',
url: 'https://www.google.com/accounts/o8/id'
},
facebook: {
name: 'Facebook',
form_url: 'http://wikipediamaze.rpxnow.com/facebook/start?token_url=http://www.wikipediamaze.com/Accounts/Logon'
}, //<-- Here's the problem. Remove that comma
};
In Xcode 4 search for "Product Name" under "Build Settings" tab of the target.
For Mac OS X, I really like LaunchRocket for this and other background services I used in development.
This site has nice instructions on installation.
This gives you a nice screen in your System Preferences that allows you to launch, reboot, root, and launch at login.
It sounds to me like you want to be able to easily pass a string created using printf-style formatting to the function you already have that takes a simple string. You can create a wrapper function using stdarg.h
facilities and vsnprintf()
(which may not be readily available, depending on your compiler/platform):
#include <stdarg.h>
#include <stdio.h>
// a function that accepts a string:
void foo( char* s);
// You'd like to call a function that takes a format string
// and then calls foo():
void foofmt( char* fmt, ...)
{
char buf[100]; // this should really be sized appropriately
// possibly in response to a call to vsnprintf()
va_list vl;
va_start(vl, fmt);
vsnprintf( buf, sizeof( buf), fmt, vl);
va_end( vl);
foo( buf);
}
int main()
{
int val = 42;
foofmt( "Some value: %d\n", val);
return 0;
}
For platforms that don't provide a good implementation (or any implementation) of the snprintf()
family of routines, I've successfully used a nearly public domain snprintf()
from Holger Weiss.
Most answers said that how to set #ifdef DEBUG and none of them saying how to determinate debug/release build.
My opinion:
Iterating over a dictionary object itself actually gives you an iterator over its keys. Python is trying to unpack keys, which you get from m.type + m.purity
into (m, k)
.
My crystal ball says m.type
and m.purity
are both strings, so your keys are also strings. Strings are iterable, so they can be unpacked; but iterating over the string gives you an iterator over its characters. So whenever m.type + m.purity
is more than two characters long, you have too many values to unpack. (And whenever it's shorter, you have too few values to unpack.)
To fix this, you can iterate explicitly over the items
of the dict, which are the (key, value) pairs that you seem to be expecting. But if you only want the values, then just use the values.
(In 2.x, itervalues
, iterkeys
, and iteritems
are typically a better idea; the non-iter
versions create a new list object containing the values/keys/items. For large dictionaries and trivial tasks within the iteration, this can be a lot slower than the iter
versions which just set up an iterator.)
I had this error with VS 2015, in my case going to the project properties page, Web tab, and clicking on Create Virtual Directory
button in Servers section solved it
I realize this is a rather late post but still a possible solution for the OP. I use IE9 on Win 7 and have been having Adobe Reader's grey screen issues for several months when trying to open pdf bank and credit card statements online. I could open everything in Firefox or Opera but not IE. I finally tried PDF-Viewer, set it as the default pdf viewer in its preferences and no more problems. I'm sure there are other free viewers out there, like Foxit, PDF-Xchange, etc., that will give better results than Reader with less headaches. Adobe is like some of the other big companies that develop software on a take it or leave it basis ... so I left it.
You can use this
<button type="submit" class="btn btn-primary btn-block w-50 mx-auto">Search</button>
Complete Form code -
<form id="submit">
<input type="text" class="form-control mt-5" id="search-city"
placeholder="Search City">
<button type="submit" class="btn btn-primary mt-3 btn-sm btn-block w-50
mx-auto">Search</button>
</form>
On my network just setting http_proxy didn't work for me. The following points were relevant.
1 Setting http_proxy for your user wont be preserved when you execute sudo - to preserve it, do:
sudo -E yourcommand
I got my install working by first installing cntlm local proxy. The instructions here is succinct : http://www.leg.uct.ac.za/howtos/use-isa-proxies
Instead of student number, you'd put your domain username
2 To use the cntlm local proxy, exec:
pip install --proxy localhost:3128 pygments
click here for good explaination!
All you need to know about relative file paths:
Starting with "/" returns to the root directory and starts there
Starting with "../" moves one directory backward and starts there
Starting with "../../" moves two directories backward and starts there (and so on...)
To move forward, just start with the first subdirectory and keep moving forward
See the answer by @david-east for the correct way to handle the issue
This answer is only relevant to a bug with jQuery 1.5 when using the file: protocol.
I had a similar problem recently when upgrading to jQuery 1.5. Despite getting a correct response the error handler fired. I resolved it by using the complete
event and then checking the status value. e.g:
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
handleError();
}
else {
var data = xhr.responseText;
//...
}
}
In my case, I am using homestead.
cd ~/Homestead
and run composer install
.
So I get you are using Eclipse with the M2E plugin. Try to update your Maven configuration : In the Project Explorer, right-click on the project, Maven -> Update project.
If the problem still remains, try to clean your project: right-click on your pom.xml, Run as -> Maven build (the second one). Enter "clean package" in the Goals fields. Check the Skip Tests box. Click on the Run button.
Edit: For your new problem, you need to add Spring MVC to your pom.xml. Add something like the following:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
Maybe you have to change the version to match the version of your Spring framework. Take a look here:
http://mvnrepository.com/artifact/org.springframework/spring-webmvc
Request.Url.Host
HTML5 has provided new attribute multiple for input element whose type attribute is file. So you can select multiple files and IE9 and previous versions does not support this.
NOTE: be carefull with the name of the input element. when you want to upload multiple file you should use array and not string as the value of the name attribute.
ex:
input type="file" name="myPhotos[]" multiple="multiple"
and if you are using php then you will get the data in $_FILES and use var_dump($_FILES) and see output and do processing Now you can iterate over and do the rest
Surround the script call with ""
, generally it's good practices to do so with filepath.
"C:\Program Files"
Although for this particular name you probably should use environment variable like this :
"%ProgramFiles%\batch.cmd"
or for 32 bits program on 64 bit windows :
"%ProgramFiles(x86)%\batch.cmd"
I have this error as well after upgrading MySQL from 5.6 to 5.7
I figured out that the best solution for me was to combine some of the solutions here and make something of it that worked with the minimum of input.
I use MyPHPAdmin for the simplicity of sending the queries through the interface because then I can check the structure and all that easily. You might use ssh directly or some other interface. The method should be similar or same anyway.
...
1.
First check out the actual error when trying to repair the db:
joomla.jos_menu Note : TIME/TIMESTAMP/DATETIME columns of old format have been upgraded to the new format.
Warning : Incorrect datetime value: '0000-00-00 00:00:00' for column 'checked_out_time' at row 1
Error : Invalid default value for 'checked_out_time'
status : Operation failed
This tells me the column checked_out_time in the table jos_menu needs to have all bad dates fixed as well as the "default" changed.
...
2.
I run the SQL query based on the info in the error message:
UPDATE jos_menu SET checked_out_time = '1970-01-01 08:00:00' WHERE checked_out_time = 0
If you get an error you can use the below query instead that seems to always work:
UPDATE jos_menu SET checked_out_time = '1970-01-01 08:00:00' WHERE CAST(checked_out_time AS CHAR(20)) = '0000-00-00 00:00:00'
...
3.
Then once that is done I run the second SQL query:
ALTER TABLE `jos_menu` CHANGE `checked_out_time` `checked_out_time` DATETIME NULL DEFAULT CURRENT_TIMESTAMP;
Or in the case it is a date that has to be NULL
ALTER TABLE `jos_menu` CHANGE `checked_out_time` `checked_out_time` DATETIME NULL DEFAULT NULL;
...
If I run repair database now I get:
joomla.jos_menu OK
...
Works just fine :)
table td{
color:#0000ff;
}
<table>
<tbody>
<tr>
<td>
<select name="test">
<option value="Basic">Basic : $30.00 USD - yearly</option>
<option value="Sustaining">Sustaining : $60.00 USD - yearly</option>
<option value="Supporting">Supporting : $120.00 USD - yearly</option>
</select>
</td>
</tr>
</tbody>
</table>
sed
doesn't recognize \d
, use [[:digit:]]
instead. You will also need to escape the +
or use the -r
switch (-E
on OS X).
Note that [0-9]
works as well for Arabic-Hindu numerals.
java.exe
is the console app while javaw.exe
is windows app (console-less). You can't have Console
with javaw.exe
.
You can escape it by preceding it with a \
(making it \/
), or you could use new RegExp('/')
to avoid escaping the regex.
See example in JSFiddle.
'/'.match(/\//) // matches /
'/'.match(new RegExp('/') // matches /
Yes, although it uses the same syntax as a for loop.
for x in ['a', 'b']: print(x)
GitHub is a great tool in-all for making repositories. However, it does not do good with private repositories.
You're forced to pay for private repositories unless you get some sort of plan. I have a couple of projects so far, and if GitHub doesn't do what I want I just go to Bitbucket. It's a bit harder to work with than GitHub, however it's unlimited free repositories.
I am posting this answer to provide a script with explanations that covers three different scenarios of creating a local repo that has a local remote. You can run the entire script and it will create the test repos in your home folder (tested on windows git bash). The explanations are inside the script for easier saving to your personal notes, its very readable from, e.g. Visual Studio Code.
I would also like to thank Jack for linking to this answer where adelphus has good, detailed, hands on explanations on the topic.
This is my first post here so please advise what should be improved.
## SETUP LOCAL GIT REPO WITH A LOCAL REMOTE
# the main elements:
# - remote repo must be initialized with --bare parameter
# - local repo must be initialized
# - local repo must have at least one commit that properly initializes a branch(root of the commit tree)
# - local repo needs to have a remote
# - local repo branch must have an upstream branch on the remote
{ # the brackets are optional, they allow to copy paste into terminal and run entire thing without interruptions, run without them to see which cmd outputs what
cd ~
rm -rf ~/test_git_local_repo/
## Option A - clean slate - you have nothing yet
mkdir -p ~/test_git_local_repo/option_a ; cd ~/test_git_local_repo/option_a
git init --bare local_remote.git # first setup the local remote
git clone local_remote.git local_repo # creates a local repo in dir local_repo
cd ~/test_git_local_repo/option_a/local_repo
git remote -v show origin # see that git clone has configured the tracking
touch README.md ; git add . ; git commit -m "initial commit on master" # properly init master
git push origin master # now have a fully functional setup, -u not needed, git clone does this for you
# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branches and their respective remote upstream branches with the initial commit
git remote -v show origin # see all branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote
## Option B - you already have a local git repo and you want to connect it to a local remote
mkdir -p ~/test_git_local_repo/option_b ; cd ~/test_git_local_repo/option_b
git init --bare local_remote.git # first setup the local remote
# simulate a pre-existing git local repo you want to connect with the local remote
mkdir local_repo ; cd local_repo
git init # if not yet a git repo
touch README.md ; git add . ; git commit -m "initial commit on master" # properly init master
git checkout -b develop ; touch fileB ; git add . ; git commit -m "add fileB on develop" # create develop and fake change
# connect with local remote
cd ~/test_git_local_repo/option_b/local_repo
git remote add origin ~/test_git_local_repo/option_b/local_remote.git
git remote -v show origin # at this point you can see that there is no the tracking configured (unlike with git clone), so you need to push with -u
git push -u origin master # -u to set upstream
git push -u origin develop # -u to set upstream; need to run this for every other branch you already have in the project
# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branch(es) and its remote upstream with the initial commit
git remote -v show origin # see all remote branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote
## Option C - you already have a directory with some files and you want it to be a git repo with a local remote
mkdir -p ~/test_git_local_repo/option_c ; cd ~/test_git_local_repo/option_c
git init --bare local_remote.git # first setup the local remote
# simulate a pre-existing directory with some files
mkdir local_repo ; cd local_repo ; touch README.md fileB
# make a pre-existing directory a git repo and connect it with local remote
cd ~/test_git_local_repo/option_c/local_repo
git init
git add . ; git commit -m "inital commit on master" # properly init master
git remote add origin ~/test_git_local_repo/option_c/local_remote.git
git remote -v show origin # see there is no the tracking configured (unlike with git clone), so you need to push with -u
git push -u origin master # -u to set upstream
# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branch and its remote upstream with the initial commit
git remote -v show origin # see all remote branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote
}
Try using How to recover a dropped stash in Git? to find the stash you popped. I think there are always two commits for a stash, since it preserves the index and the working copy (so often the index commit will be empty). Then git show
them to see the diff and use patch -R
to unapply them.
The three possible solutions suggested here have different use cases.
Use .equals when comparing ObjectID on two mongoDocuments like this
results.userId.equals(AnotherMongoDocument._id)
Use .toString() when comparing a string representation of ObjectID to an ObjectID of a mongoDocument. like this
results.userId === AnotherMongoDocument._id.toString()
And if you want to search and replace based on the value of another field you could do a CONCAT:
update table_name set `field_name` = replace(`field_name`,'YOUR_OLD_STRING',CONCAT('NEW_STRING',`OTHER_FIELD_VALUE`,'AFTER_IF_NEEDED'));
Just to have this one here so that others will find it at once.
Total no of Binary Trees are =
Summing over i gives the total number of binary search trees with n nodes.
The base case is t(0) = 1 and t(1) = 1, i.e. there is one empty BST and there is one BST with one node.
So, In general you can compute total no of Binary Search Trees using above formula. I was asked a question in Google interview related on this formula. Question was how many total no of Binary Search Trees are possible with 6 vertices. So Answer is t(6) = 132
I think that I gave you some idea...
NewScores is an alias to Scores table - it looks like you can combine the queries as follows:
SELECT
ROW_NUMBER() OVER( ORDER BY NETT) AS Rank,
Name,
FlagImg,
Nett,
Rounds
FROM (
SELECT
Members.FirstName + ' ' + Members.LastName AS Name,
CASE
WHEN MenuCountry.ImgURL IS NULL THEN
'~/images/flags/ismygolf.png'
ELSE
MenuCountry.ImgURL
END AS FlagImg,
AVG(CAST(NewScores.NetScore AS DECIMAL(18, 4))) AS Nett,
COUNT(Score.ScoreID) AS Rounds
FROM
Members
INNER JOIN
Score NewScores
ON Members.MemberID = NewScores.MemberID
LEFT OUTER JOIN MenuCountry
ON Members.Country = MenuCountry.ID
WHERE
Members.Status = 1
AND NewScores.InsertedDate >= DATEADD(mm, -3, GETDATE())
GROUP BY
Members.FirstName + ' ' + Members.LastName,
MenuCountry.ImgURL
) AS Dertbl
ORDER BY;
So I figured out what is wrong with this statement:
Import-Csv H:\Programs\scripts\SomeText.csv |`
(Original)
Import-Csv H:\Programs\scripts\SomeText.csv -Delimiter "|"
(Proposed, You must use quotations; otherwise, it will not work and ISE will give you an error)
It requires the -Delimiter "|"
, in order for the variable to be populated with an array of items. Otherwise, Powershell ISE does not display the list of items.
I cannot say that I would recommend the |
operator, since it is used to pipe cmdlets into one another.
I still cannot get the if statement to return true and output the values entered via the prompt.
If anyone else can help, it would be great. I still appreciate the post, it has been very helpful!
Simply can be used:
SELECT RIGHT('0' + CAST(MONTH(@Date) AS NVARCHAR(2)), 2)
In addition to existing good answers, note that Jackson 1.9 improved handling by adding "property unification", meaning that ALL annotations from difference parts of a logical property are combined, using (hopefully) intuitive precedence.
In Jackson 1.8 and prior, only field and getter annotations were used when determining what and how to serialize (writing JSON); and only and setter annotations for deserialization (reading JSON). This sometimes required addition of "extra" annotations, like annotating both getter and setter.
With Jackson 1.9 and above these extra annotations are NOT needed. It is still possible to add those; and if different names are used, one can create "split" properties (serializing using one name, deserializing using other): this is occasionally useful for sort of renaming.
What seems to be needed is to actually define the button as a button widget.
I had the same problem (in beta 1)
I did
$("#submitButton").button();
in my window ready handler, after that it worked to do as it is said in the docs, i.e.:
$("#submitButton").button('disable');
I guess this has to do with that jqm is converting the markup, but isnt actually instatiating a real button widget for buttons and link buttons.
When I started to use Latex, I used Eclipse with the texlipse plugin. That allowed me to use the same environment in Linux and Windows, has some auto completion features and runs all tools (latex, bibtex, makeindex, ...) automatically to fully build the project.
But now I switched. Eclipse is large and slow on my PCs, crashes often and shows some weird behaviour here and there. Now I use vim for editing and make in collaboration with a self written perl script to build my projects. Using cygwin I am still able to use the same work flows under Linux and Windows.
A little late to the party, found this while looking for an example of the marker click event. The undefined error the original poster got is because the onClick function is referred to before it's defined. Swap line 2 and 3 and it should work.
Using the index:
df[1:4,]
Where the values in the parentheses can be interpreted as either logical, numeric, or character (matching the respective names):
df[row.index, column.index]
Read help(`[`) for more detail on this subject, and also read about index matrices in the Introduction to R.
byte[] byteArray = new byte[102400];
base64String = Base64.encode(byteArray);
That code will encode 102400 bytes, no matter how much data you actually use in the array.
while ((bytesRead = fis.read(byteArray)) != -1)
You need to use the value of bytesRead somewhere.
Also, this may not read the whole file into the array in one go (it only reads as much as is in the I/O buffer), so your loop will probably not work, you may end up with half an image in your array.
I'd use Apache Commons IOUtils here:
Base64.encode(FileUtils.readFileToByteArray(file));
netstat -ano|grep 443|grep LISTEN
will tell you whether a process is listening on port 443 (you might have to replace LISTEN with a string in your language, though, depending on your system settings).
You can pass any number of arguments to the function that apply
is calling through either unnamed arguments, passed as a tuple to the args
parameter, or through other keyword arguments internally captured as a dictionary by the kwds
parameter.
For instance, let's build a function that returns True for values between 3 and 6, and False otherwise.
s = pd.Series(np.random.randint(0,10, 10))
s
0 5
1 3
2 1
3 1
4 6
5 0
6 3
7 4
8 9
9 6
dtype: int64
s.apply(lambda x: x >= 3 and x <= 6)
0 True
1 True
2 False
3 False
4 True
5 False
6 True
7 True
8 False
9 True
dtype: bool
This anonymous function isn't very flexible. Let's create a normal function with two arguments to control the min and max values we want in our Series.
def between(x, low, high):
return x >= low and x =< high
We can replicate the output of the first function by passing unnamed arguments to args
:
s.apply(between, args=(3,6))
Or we can use the named arguments
s.apply(between, low=3, high=6)
Or even a combination of both
s.apply(between, args=(3,), high=6)
Don't call methods within the Fragment that require getActivity() until onStart in the parent Activity.
private MyFragment myFragment;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
myFragment = new MyFragment();
ft.add(android.R.id.content, youtubeListFragment).commit();
//Other init calls
//...
}
@Override
public void onStart()
{
super.onStart();
//Call your Fragment functions that uses getActivity()
myFragment.onPageSelected();
}
#!/bin/sh
sed '1,2d' "$0"|$(which groovy) /dev/stdin; exit;
println("hello");
The newest version of BlueStacks has the ability to rotate the screen. Open the app and there's an icon in the lower right to rotate.
In my case ASP.NET not registered on server. try to execute this in command prompt:
Windows 32bit
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir
Windows 64bit
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir
SLaks has the right answer... but let me be a bit more specific for people, like me, who are annoyed by this and can't find it right away :
Project -> Properties -> Application -> Target Framework -> select ".Net Framework 4"
the project will then save and reload.
This exception raised on API 19, 21 (but not new). In Kotlin coroutine I loaded data (in background thread) and in UI thread added and showed them:
adapter.addItem(item)
Adapter:
var list: MutableList<Item> = mutableListOf()
init {
this.setHasStableIds(true)
}
open fun addItem(item: Item) {
list.add(item)
notifyItemInserted(list.lastIndex)
}
For some reason Android doesn't render quick enough or something else, so, I update a list in post
method of the RecyclerView
(add, remove, update events of items):
view.recycler_view.post { adapter.addItem(item) }
This exception is similar to "Cannot call this method in a scroll callback. Scroll callbacks mightbe run during a measure & layout pass where you cannot change theRecyclerView data. Any method call that might change the structureof the RecyclerView or the adapter contents should be postponed tothe next frame.": Recyclerview - cannot call this method in a scroll callback.
Hi if you are going to subtract only Integer value from DateTime then you have to write code like this
DateTime.Now.AddHours(-2)
Here I am subtracting 2 hours from the current date and time
I faced this issue while using Android SDK for x86 in a Windows 7 64-bit machine. I downloaded the Android SDK 64-bit version, made Eclipse see it in Window > Preferences > Android > SDK location and the issue stopped occurring.
// define
var foo = {
bar: ['foo', 'bar', 'baz']
};
// access
foo.bar[2]; // will give you 'baz'
My case is a little different, I'm trying to create a mask from a power, but I thought I'd share the solution I found anyway.
Obviously, it only works for powers of 2.
Mask1 = 1 << (Exponent - 1);
Mask2 = Mask1 - 1;
return Mask1 + Mask2;
I think doing this way is much simpler:
button.setBackgroundColor(Color.BLACK);
And you need to import android.graphics.Color;
not: import android.R.color;
Or you can just write the 4-byte hex code (not 3-byte) 0xFF000000
where the first byte is setting the alpha.
Besides using multiple proxies or proxy-networks, you might want to try the planet-lab. (And probably there are other similar institutions around).
The social solution would be to post a question on some board that you are searching for volunteers that proxy your requests. (They only have to allow for one destination in their proxy config thus the danger of becoming spam-whores is relatively low.) You should prepare credentials that ensure your partners of the authenticity of the claim that the destination is indeed your computer.
What is wrong -
The most elegant for me is using DateTime
I wonder I do not see DateTime::createFromFormat
, one-liner
$lastDay = \DateTime::createFromFormat("Y-m-d", "2009-11-23")->format("Y-m-t");
+
means "one or more characters" and without the plus it means "one character." In your case both result in the same output.
By default, inheritance is private. You have to explicitly use public
:
class Bar : public Foo
<input type="checkbox" checked="checked" />
or simply
<input type="checkbox" checked />
for checked checkbox.
No checked attribute (<input type="checkbox" />
) for unchecked checkbox.
reference: http://www.w3.org/TR/html-markup/input.checkbox.html#input.checkbox.attrs.checked
You have to run 'bibtex':
latex paper.tex
bibtex paper
latex paper.tex
latex paper.tex
dvipdf paper.dvi
This should work:
s=json.dumps(variables)
variables2=json.loads(s)
assert(variables==variables2)
Looks like it is a known problem with EdmGen: http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/12aaac4d-2be8-44f3-9448-d7c659585945/
I think that's another case of git error messages being misleading. Usually when I've seen that error it's due to ssh problems. Did you add your public ssh key to your github account?
Edit: Also, the xinet.d forum post is referring to running the git-daemon as a service so that people could pull from your system. It's not necessary to run git-daemon to push to github.
declare @listOfIDs table (id int);
insert @listOfIDs(id) values(1),(2),(3);
select *
from TabA
where TabA.ID in (select id from @listOfIDs)
or
declare @listOfIDs varchar(1000);
SET @listOfIDs = ',1,2,3,'; --in this solution need put coma on begin and end
select *
from TabA
where charindex(',' + CAST(TabA.ID as nvarchar(20)) + ',', @listOfIDs) > 0
You can use NestedScrollView
instead of ScrollView
. However, when using a Kotlin Lambda, it won't know you want NestedScrollView's setOnScrollChangeListener
instead of the one at View (which is API level 23). You can fix this by specifying the first parameter as a NestedScrollView.
nestedScrollView.setOnScrollChangeListener { _: NestedScrollView, scrollX: Int, scrollY: Int, _: Int, _: Int ->
Log.d("ScrollView", "Scrolled to $scrollX, $scrollY")
}
Here you go: ES5
var test = 'Hello World';
if( test.indexOf('World') >= 0){
// Found world
}
With ES6 best way would be to use includes
function to test if the string contains the looking work.
const test = 'Hello World';
if (test.includes('World')) {
// Found world
}
This works as you wish:
<html>
<head>
<style type="text/css">
ul
{
overflow-x:hidden;
white-space:nowrap;
height: 1em;
width: 100%;
}
li
{
display:inline;
}
</style>
</head>
<body>
<ul>
<li>abcdefghijklmonpqrstuvwxyz</li>
<li>abcdefghijklmonpqrstuvwxyz</li>
<li>abcdefghijklmonpqrstuvwxyz</li>
<li>abcdefghijklmonpqrstuvwxyz</li>
<li>abcdefghijklmonpqrstuvwxyz</li>
<li>abcdefghijklmonpqrstuvwxyz</li>
<li>abcdefghijklmonpqrstuvwxyz</li>
</ul>
</body>
</html>
Try this:
find . -name .svn -exec rm -rf '{}' \;
Before running a command like that, I often like to run this first:
find . -name .svn -exec ls '{}' \;
concat()
function because this function only applies to a string, not on a integer. but we can concatenate a string to a number(integer) using + operator.<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<p>The concat() method joins two or more strings</p>_x000D_
_x000D_
_x000D_
<p id="demo"></p>_x000D_
<p id="demo1"></p>_x000D_
_x000D_
<script>_x000D_
var text1 = 4;_x000D_
var text2 = "World!";_x000D_
document.getElementById("demo").innerHTML = text1 + text2;_x000D_
//Below Line can't produce result_x000D_
document.getElementById("demo1").innerHTML = text1.concat(text2);_x000D_
</script>_x000D_
<p><strong>The Concat() method can't concatenate a string with a integer </strong></p>_x000D_
</body>_x000D_
</html>
_x000D_
You can use
driver.execute_script("window.scrollTo(0, Y)")
where Y is the height (on a fullhd monitor it's 1080). (Thanks to @lukeis)
You can also use
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
to scroll to the bottom of the page.
If you want to scroll to a page with infinite loading, like social network ones, facebook etc. (thanks to @Cuong Tran)
SCROLL_PAUSE_TIME = 0.5
# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
# Scroll down to bottom
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# Wait to load page
time.sleep(SCROLL_PAUSE_TIME)
# Calculate new scroll height and compare with last scroll height
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
another method (thanks to Juanse) is, select an object and
label.sendKeys(Keys.PAGE_DOWN);
If you want to see a more detailed discussion of differences for the commands, see the Details about Differences section, below.
From the LeMoDa.net website1 (archived), specifically the Windows and Unix command line equivalents page (archived), I found the following2. There's a better/more complete table in the next edit.
Windows command Unix command
rmdir rmdir
rmdir /s rm -r
move mv
I'm interested to hear from @Dave and @javadba to hear how equivalent the commands are - how the "behavior and capabilities" compare, whether quite similar or "woefully NOT equivalent".
All I found out was that when I used it to try and recursively remove a directory and its constituent files and subdirectories, e.g.
(Windows cmd)>rmdir /s C:\my\dirwithsubdirs\
gave me a standard Windows-knows-better-than-you-do-are-you-sure message and prompt
dirwithsubdirs, Are you sure (Y/N)?
and that when I typed Y
, the result was that my top directory and its constituent files and subdirectories went away.
Edit
I'm looking back at this after finding this answer. I retried each of the commands, and I'd change the table a little bit.
Windows command Unix command
rmdir rmdir
rmdir /s /q rm -r
rmdir /s /q rm -rf
rmdir /s rm -ri
move mv
del <file> rm <file>
If you want the equivalent for
rm -rf
you can use
rmdir /s /q
or, as the author of the answer I sourced described,
But there is another "old school" way to do it that was used back in the day when commands did not have options to suppress confirmation messages. Simply
ECHO
the needed response and pipe the value into the command.
echo y | rmdir /s
I tested each of the commands using Windows CMD and Cygwin (with its bash
).
Before each test, I made the following setup.
Windows CMD
>mkdir this_directory
>echo some text stuff > this_directory/some.txt
>mkdir this_empty_directory
Cygwin bash
$ mkdir this_directory
$ echo "some text stuff" > this_directory/some.txt
$ mkdir this_empty_directory
That resulted in the following file structure for both.
base
|-- this_directory
| `-- some.txt
`-- this_empty_directory
Here are the results. Note that I'll not mark each as CMD or bash
; the CMD will have a >
in front, and the bash
will have a $
in front.
RMDIR
>rmdir this_directory
The directory is not empty.
>tree /a /f .
Folder PATH listing for volume Windows
Volume serial number is ¦¦¦¦¦¦¦¦ ¦¦¦¦:¦¦¦¦
base
+---this_directory
| some.txt
|
\---this_empty_directory
> rmdir this_empty_directory
>tree /a /f .
base
\---this_directory
some.txt
$ rmdir this_directory
rmdir: failed to remove 'this_directory': Directory not empty
$ tree --charset=ascii
base
|-- this_directory
| `-- some.txt
`-- this_empty_directory
2 directories, 1 file
$ rmdir this_empty_directory
$ tree --charset=ascii
base
`-- this_directory
`-- some.txt
RMDIR /S /Q and RM -R ; RM -RF
>rmdir /s /q this_directory
>tree /a /f
base
\---this_empty_directory
>rmdir /s /q this_empty_directory
>tree /a /f
base
No subfolders exist
$ rm -r this_directory
$ tree --charset=ascii
base
`-- this_empty_directory
$ rm -r this_empty_directory
$ tree --charset=ascii
base
0 directories, 0 files
$ rm -rf this_directory
$ tree --charset=ascii
base
`-- this_empty_directory
$ rm -rf this_empty_directory
$ tree --charset=ascii
base
0 directories, 0 files
RMDIR /S AND RM -RI
Here, we have a bit of a difference, but they're pretty close.
>rmdir /s this_directory
this_directory, Are you sure (Y/N)? y
>tree /a /f
base
\---this_empty_directory
>rmdir /s this_empty_directory
this_empty_directory, Are you sure (Y/N)? y
>tree /a /f
base
No subfolders exist
$ rm -ri this_directory
rm: descend into directory 'this_directory'? y
rm: remove regular file 'this_directory/some.txt'? y
rm: remove directory 'this_directory'? y
$ tree --charset=ascii
base
`-- this_empty_directory
$ rm -ri this_empty_directory
rm: remove directory 'this_empty_directory'? y
$ tree --charset=ascii
base
0 directories, 0 files
I'M HOPING TO GET A MORE THOROUGH MOVE AND MV TEST
Copyright © Ben Bullock 2009-2018. All rights reserved.
and that there seem to be a bunch of useful programming tips along with some humour (yes, the British spelling) and information on how to fix Japanese toilets. I also found some stuff talking about the "Ibaraki Report", but I don't know if that is the website.
I think I shall go there more often; it's quite useful. Props to Ben Bullock, whose email is on his page. If he wants me to remove this info, I will.
I will include the disclaimer (archived) from the site:
Disclaimer Please read the following disclaimer before using any of the computer program code on this site.
There Is No Warranty For The Program, To The Extent Permitted By Applicable Law. Except When Otherwise Stated In Writing The Copyright Holders And/Or Other Parties Provide The Program “As Is” Without Warranty Of Any Kind, Either Expressed Or Implied, Including, But Not Limited To, The Implied Warranties Of Merchantability And Fitness For A Particular Purpose. The Entire Risk As To The Quality And Performance Of The Program Is With You. Should The Program Prove Defective, You Assume The Cost Of All Necessary Servicing, Repair Or Correction.
In No Event Unless Required By Applicable Law Or Agreed To In Writing Will Any Copyright Holder, Or Any Other Party Who Modifies And/Or Conveys The Program As Permitted Above, Be Liable To You For Damages, Including Any General, Special, Incidental Or Consequential Damages Arising Out Of The Use Or Inability To Use The Program (Including But Not Limited To Loss Of Data Or Data Being Rendered Inaccurate Or Losses Sustained By You Or Third Parties Or A Failure Of The Program To Operate With Any Other Programs), Even If Such Holder Or Other Party Has Been Advised Of The Possibility Of Such Damages.
https://www.google.com/search?q=cmd+equivalent+of+rm
The information I'm sharing came up first.
Here is a production ready pure JavaScript solution:
<View styles={{backgroundColor: `the main color you want`}}>
<Image source={`A white to transparent gradient png`}>
</View>
Here is the source code of a npm package using this solution: https://github.com/flyskywhy/react-native-smooth-slider/blob/0f18a8bf02e2d436503b9a8ba241440247ef1c44/src/Slider.js#L329
Here is the gradient palette screenshot of saturation and brightness using this npm package: https://github.com/flyskywhy/react-native-slider-color-picker
Your Promise is pending, complete it by
userToken.then(function(result){
console.log(result)
})
after your remaining code.
All this code does is that .then()
completes your promise & captures the end result in result variable & print result in console.
Keep in mind, you cannot store the result in global variable.
Hope that explanation might help you.
Using aLearningLady's answer above, you can make your selection range dynamic by looking for the last row with data in it instead of just selecting the entire column.
The below code worked for me.
Dim lastrow as Integer
lastrow = Cells(Rows.Count, 2).End(xlUp).Row
Range("C2:C" & lastrow).Select
With Selection
.NumberFormat = "General"
.Value = .Value
End With
Remove the last commit before push
git reset --soft HEAD~1
1
means the last commit, if you want to remove two last use 2
, and so forth*
With IIS's self-signed certificate feature, you cannot set the common name (CN) for the certificate, and therefore cannot create a certificate bound to your choice of subdomain.
One way around the problem is to use makecert.exe, which is bundled with the .Net 2.0 SDK. On my server it's at:
C:\Program Files\Microsoft.Net\SDK\v2.0 64bit\Bin\makecert.exe
You can create a signing authority and store it in the LocalMachine certificates repository as follows (these commands must be run from an Administrator account or within an elevated command prompt):
makecert.exe -n "CN=My Company Development Root CA,O=My Company,
OU=Development,L=Wallkill,S=NY,C=US" -pe -ss Root -sr LocalMachine
-sky exchange -m 120 -a sha1 -len 2048 -r
You can then create a certificate bound to your subdomain and signed by your new authority:
(Note that the the value of the -in parameter must be the same as the CN value used to generate your authority above.)
makecert.exe -n "CN=subdomain.example.com" -pe -ss My -sr LocalMachine
-sky exchange -m 120 -in "My Company Development Root CA" -is Root
-ir LocalMachine -a sha1 -eku 1.3.6.1.5.5.7.3.1
Your certificate should then appear in IIS Manager to be bound to your site as explained in Tom Hall's post.
All kudos for this solution to Mike O'Brien for his excellent blog post at http://www.mikeobrien.net/blog/creating-self-signed-wildcard
For those of us still stuck on webforms I found the following solution that enables you to only disable the validation on one field! (I would hate to disable it for the whole page.)
VB.NET:
Public Class UnvalidatedTextBox
Inherits TextBox
Protected Overrides Function LoadPostData(postDataKey As String, postCollection As NameValueCollection) As Boolean
Return MyBase.LoadPostData(postDataKey, System.Web.HttpContext.Current.Request.Unvalidated.Form)
End Function
End Class
C#:
public class UnvalidatedTextBox : TextBox
{
protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
return base.LoadPostData(postDataKey, System.Web.HttpContext.Current.Request.Unvalidated.Form);
}
}
Now just use <prefix:UnvalidatedTextBox id="test" runat="server" />
instead of <asp:TextBox
, and it should allow all characters (this is perfect for password fields!)
There is a much easier and more compact solution for multilevel prototype lookup, but it requires Proxy
support. Usage: SUPER(<instance>).<method>(<args>)
, for example, assuming two classes A
and B extends A
with method m
: SUPER(new B).m()
.
function SUPER(instance) {
return new Proxy(instance, {
get(target, prop) {
return Object.getPrototypeOf(Object.getPrototypeOf(target))[prop].bind(target);
}
});
}
This works properly try this code-
selenium.click("xpath=//a[contains(@href,'listDetails.do') and @id='oldcontent']");
<input name="date" type="text" (focus)="focusFunction()" (focusout)="focusOutFunction()">
works for me from Pardeep Jain
Adding this to your iframe might resolve the issue:
frameborder="0" seamless="seamless"
I had a similar task, and was not able to get the above perl solution to work.
Here is my solution:
perl -i -pe "BEGIN{undef $/;} s/^\[mysqld\]$/[mysqld]\n\ncollation-server = utf8_unicode_ci\n/sgm" /etc/mysql/my.cnf
Explanation:
Uses a regular expression to search for a line in my /etc/mysql/my.cnf file that contained only [mysqld]
and replaced it with
[mysqld]
collation-server = utf8_unicode_ci
effectively adding the collation-server = utf8_unicode_ci
line after the line containing [mysqld]
.
if you get the values in int you have to use string for that it is throwing the error
before
holder.villageName.setText(villageModelList.get(position).getVillageName());
holder.villageCount.setText(villageModelList.get(position).getPeopleCount());
holder.peopleCount.setText(villageModelList.get(position).getPeopleCount());
after
holder.villageName.setText(villageModelList.get(position).getVillageName());
holder.villageCount.setText(String.valueOf(villageModelList.get(position).getPeopleCount()));
holder.peopleCount.setText(String.valueOf(villageModelList.get(position).getPeopleCount()));
you can solve the error by adding the String.valueOf
The explanation with the examples was key to helping mine, but the issue that i came was when I copied it didn't work so I had to mess with it in several ways to get it to work right. (I'm super new at R, and had some issues with the third ifelse due to lack of knowledge).
so for those who are super new to R running into issues...
ifelse(x < -2,"pretty negative", ifelse(x < 1,"close to zero", ifelse(x < 3,"in [1, 3)","large")##all one line
)#normal tab
)
(i used this in a function so it "ifelse..." was tabbed over one, but the last ")" was completely to the left)
You can use the Standard PHP Library (SPL) to "hide" the recursion.
$a = array(1,2,array(3,4, array(5,6,7), 8), 9);
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($a));
foreach($it as $v) {
echo $v, " ";
}
prints
1 2 3 4 5 6 7 8 9
spans default to inline style, which you can't specify the width of.
display: inline-block;
would be a good way, except IE doesn't support it
you can, however, hack a multiple browser solution
You can either use a regular tuple
interface IReqularDemo: [number, string];
or if optional parameters support is needed
interface IOptionalDemo: [value1: number, value2?: string]
The error is coming because of the parser you are using. In general, if you have HTML file/code then you need to use html5lib
(documentation can be found here) & in-case you have XML file/data then you need to use lxml
(documentation can be found here). You can use lxml
for HTML file/code also but sometimes it gives an error as above. So, better to choose the package wisely based on the type of data/file. You can also use html_parser
which is built-in module. But, this also sometimes do not work.
For more details regarding when to use which package you can see the details here
It is not possible. Otherwise you may need to use Silverlight or Flash upload control.
Window-->Web Browser--> Firefox
To get the keys:
function GetDictionaryKeysAsArray(dict: {[key: string]: string;}): string[] {
let result: string[] = [];
Object.keys(dict).map((key) =>
result.push(key),
);
return result;
}
Due to https://mywiki.wooledge.org/BashPitfalls#Non-atomic_writes_with_xargs_-P (output from parallel jobs in xargs
risks being mixed), I would use GNU Parallel instead of xargs
to parallelize:
cat url.lst |
parallel -P0 -q curl -o /dev/null --silent --head --write-out '%{url_effective}: %{http_code}\n' > outfile
In this particular case it may be safe to use xargs
because the output is so short, so the problem with using xargs
is rather that if someone later changes the code to do something bigger, it will no longer be safe. Or if someone reads this question and thinks he can replace curl
with something else, then that may also not be safe.
There is an onpaste event that works in modern day browsers. You can access the pasted data using the getData
function on the clipboardData
object.
$("#textareaid").bind("paste", function(e){
// access the clipboard using the api
var pastedData = e.originalEvent.clipboardData.getData('text');
alert(pastedData);
} );
Note that bind and unbind are deprecated as of jQuery 3. The preferred call is to on.
All modern day browsers support the Clipboard API.
See also: In Jquery How to handle paste?
It's netstat -ano|findstr port no
Result would show process id in last column
after your pc connects to other pc use these 4 step:
4 steps:
1- Edit this file: httpd.conf
for that click on wamp server and select Apache and select httpd.conf
2- Find this text: Deny from all
in the below tag:
<Directory "c:/wamp/www"><!-- maybe other url-->
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.4/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# AllowOverride FileInfo AuthConfig Limit
#
AllowOverride All
#
# Controls who can get stuff from this server.
#
# Require all granted
# onlineoffline tag - don't remove
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
</Directory>
3- Change to: Deny from none
like this:
<Directory "c:/wamp/www">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.4/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# AllowOverride FileInfo AuthConfig Limit
#
AllowOverride All
#
# Controls who can get stuff from this server.
#
# Require all granted
# onlineoffline tag - don't remove
Order Deny,Allow
Deny from none
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
4- Restart Apache
Don't forget restart Apache or all servises!!!
The problem with calling async void is that
you don’t even get the task back. You have no way of knowing when the function’s task has completed. —— Crash course in async and await | The Old New Thing
Here are the three ways to call an async function:
async Task<T> SomethingAsync() { ... return t; } async Task SomethingAsync() { ... } async void SomethingAsync() { ... }
In all the cases, the function is transformed into a chain of tasks. The difference is what the function returns.
In the first case, the function returns a task that eventually produces the t.
In the second case, the function returns a task which has no product, but you can still await on it to know when it has run to completion.
The third case is the nasty one. The third case is like the second case, except that you don't even get the task back. You have no way of knowing when the function's task has completed.
The async void case is a "fire and forget": You start the task chain, but you don't care about when it's finished. When the function returns, all you know is that everything up to the first await has executed. Everything after the first await will run at some unspecified point in the future that you have no access to.
Simple
function timeToSeconds($time)
{
$timeExploded = explode(':', $time);
if (isset($timeExploded[2])) {
return $timeExploded[0] * 3600 + $timeExploded[1] * 60 + $timeExploded[2];
}
return $timeExploded[0] * 3600 + $timeExploded[1] * 60;
}
You can use XDocument.Parse(string)
instead of Load(string)
.
Very similar to this question, and I would suggest the same formula in column D, albeit a few changes to the ranges:
=IFERROR(VLOOKUP(C1, A:B, 2, 0), "")
If you wanted to use match, you'd have to use INDEX
as well, like so:
=IFERROR(INDEX(B:B, MATCH(C1, A:A, 0)), "")
but this is really lengthy to me and you need to know how to properly use two functions (or three, if you don't know how IFERROR
works)!
Note: =IFERROR()
can be a substitute of =IF()
and =ISERROR()
in some cases :)
function Index($index) {
$Count = count($YOUR_ARRAY);
if ($index <= $Count) {
$Keys = array_keys($YOUR_ARRAY);
$Value = array_values($YOUR_ARRAY);
return $Keys[$index] . ' = ' . $Value[$index];
} else {
return "Out of the ring";
}
}
echo 'Index : ' . Index(0);
Replace the ( $YOUR_ARRAY )
Well when you are writing a c program and want the output log to stay instead of flickering away you only need to import the stdlib.h header file and type "system("PAUSE");" at the place you want the output screen to halt.Look at the example here.The following simple c program prints the product of 5 and 6 i.e 30 to the output window and halts the output window.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b,c;
a=5;b=6;
c=a*b;
printf("%d",c);
system("PAUSE");
return 0;
}
Hope this helped.
Good News! Basically, Bootstrap 5 can be implemented easily now, and you don't even need jQuery.
From your terminal, just run
npm install bootstrap@next --save
So, Angular uses webpack, therefore, in your app.module.ts, just add:
import "bootstrap";
Or if you want to import them separately, do it like:
import { ModuleToBeImported } from 'bootstrap';
Then to your styles.scss, add:
@import '~bootstrap/scss/bootstrap';
Basically that's it, BUT beware that some components require popper.js. Components requiring bootstrap's js There you'll see the components dependent on popper.js too, which at the time of writing this are Dropdowns for displaying and positioning, and Tooltips and popovers for displaying and positioning.
Therefore, to install popper.js, just run:
npm install @popperjs/core
It prints the byte
in Hexadecimal format.
No format string: 13
'X2' format string: 0D
http://msdn.microsoft.com/en-us/library/aa311428(v=vs.71).aspx
>>> import string
>>> string.ascii_lowercase[:14]
'abcdefghijklmn'
>>> string.ascii_lowercase[:14:2]
'acegikm'
To do the urls, you could use something like this
[i + j for i, j in zip(list_of_urls, string.ascii_lowercase[:14])]
Or you could do it properly:
In your HtmlHelper Extension class:
public static MvcHtmlString FileFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
return helper.FileFor(expression, null);
}
public static MvcHtmlString FileFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
var builder = new TagBuilder("input");
var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
builder.GenerateId(id);
builder.MergeAttribute("name", id);
builder.MergeAttribute("type", "file");
builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
// Render tag
return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
}
This line:
var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
Generates an id unique to the model, you know in lists and stuff. model[0].Name etc.
Create the correct property in the model:
public HttpPostedFileBase NewFile { get; set; }
Then you need to make sure your form will send files:
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
Then here's your helper:
@Html.FileFor(x => x.NewFile)
The suggestion to use .split(/[ ,]+/)
is good, but with natural sentences sooner or later you'll end up getting empty elements in the array. e.g. ['foo', '', 'bar']
.
Which is fine if that's okay for your use case. But if you want to get rid of the empty elements you can do:
var str = 'whatever your text is...';
str.split(/[ ,]+/).filter(Boolean);
Make sure that you don't declare it as a integer, float, string or boolean before. http://php.net/manual/en/function.is-scalar.php
I have three approaches,
Here you can use both <input>
or <textarea>
as per your requirements.
1. Use Input in <td>
.
Using <input>
element in all <td>
s,
<tr><td><input type="text"></td>....</tr>
Also, you might want to resize the input to the size of its td
. ex.,
input { width:100%; height:100%; }
You can additionally change the colour of the border of the input box when it is not being edited.
2. Use contenteditable='true'
attribute. (HTML5)
However, if you want to use contenteditable='true'
, you might also want to save the appropriate values to the database. You can achieve this with ajax.
You can attach keyhandlers keyup
, keydown
, keypress
etc to the <td>
. Also, it is good to use some delay() with those events when user continuously types, the ajax event won't fire with every key user press. for example,
$('table td').keyup(function() {
clearTimeout($.data(this, 'timer'));
var wait = setTimeout(saveData, 500); // delay after user types
$(this).data('timer', wait);
});
function saveData() {
// ... ajax ...
}
3. Append <input>
to <td>
when it is clicked.
Add the input element in td
when the <td>
is clicked, replace its value according to the td
's value. When the input is blurred, change the `td's value with the input's value. All this with javascript.
Why don't you go for awk:
awk '/Start pattern/,/End pattern/' filename
If you set
android:inputType="textPassword"
this property and if you provide number as password example "1234567" it will take it as "123456/" the seventh character is not taken. Thats why instead of this approach use
android:password="true"
property which allows you to enter any type of password without any restriction.
If you want to provide hint use
android:hint="hint text goes here"
example:
android:hint="password"
You can work with the overridable HandleUnauthorizedRequest
inside your custom AuthorizeAttribute
Like this:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
// Returns HTTP 401 by default - see HttpUnauthorizedResult.cs.
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "action", "YourActionName" },
{ "controller", "YourControllerName" },
{ "parameterName", "YourParameterValue" }
});
}
You can also do something like this:
private class RedirectController : Controller
{
public ActionResult RedirectToSomewhere()
{
return RedirectToAction("Action", "Controller");
}
}
Now you can use it in your HandleUnauthorizedRequest
method this way:
filterContext.Result = (new RedirectController()).RedirectToSomewhere();
<?php
header("Location: your url");
exit;
?>
If for any reason, you want to avoid using sed, the following will print the line matching TERMINATE
till the end of the file:
tail -n "+$(grep -n 'TERMINATE' file | head -n 1 | cut -d ":" -f 1)" file
and the following will print from the following line matching TERMINATE
till the end of the file:
tail -n "+$(($(grep -n 'TERMINATE' file | head -n 1 | cut -d ":" -f 1)+1))" file
It takes 2 processes to do what sed can do in one process, and if the file changes between the execution of grep and tail, the result can be incoherent, so I recommend using sed. Moreover, if the file dones not contain TERMINATE
, the 1st command fails.
Use the after
method on the Tk
object:
from tkinter import *
root = Tk()
def task():
print("hello")
root.after(2000, task) # reschedule event in 2 seconds
root.after(2000, task)
root.mainloop()
Here's the declaration and documentation for the after
method:
def after(self, ms, func=None, *args):
"""Call function once after given time.
MS specifies the time in milliseconds. FUNC gives the
function which shall be called. Additional parameters
are given as parameters to the function call. Return
identifier to cancel scheduling with after_cancel."""
Mockito matchers are static methods and calls to those methods, which stand in for arguments during calls to when
and verify
.
Hamcrest matchers (archived version) (or Hamcrest-style matchers) are stateless, general-purpose object instances that implement Matcher<T>
and expose a method matches(T)
that returns true if the object matches the Matcher's criteria. They are intended to be free of side effects, and are generally used in assertions such as the one below.
/* Mockito */ verify(foo).setPowerLevel(gt(9000));
/* Hamcrest */ assertThat(foo.getPowerLevel(), is(greaterThan(9000)));
Mockito matchers exist, separate from Hamcrest-style matchers, so that descriptions of matching expressions fit directly into method invocations: Mockito matchers return T
where Hamcrest matcher methods return Matcher objects (of type Matcher<T>
).
Mockito matchers are invoked through static methods such as eq
, any
, gt
, and startsWith
on org.mockito.Matchers
and org.mockito.AdditionalMatchers
. There are also adapters, which have changed across Mockito versions:
Matchers
featured some calls (such as intThat
or argThat
) are Mockito matchers that directly accept Hamcrest matchers as parameters. ArgumentMatcher<T>
extended org.hamcrest.Matcher<T>
, which was used in the internal Hamcrest representation and was a Hamcrest matcher base class instead of any sort of Mockito matcher.Matchers
calls phrased as intThat
or argThat
wrap ArgumentMatcher<T>
objects that no longer implement org.hamcrest.Matcher<T>
but are used in similar ways. Hamcrest adapters such as argThat
and intThat
are still available, but have moved to MockitoHamcrest
instead.Regardless of whether the matchers are Hamcrest or simply Hamcrest-style, they can be adapted like so:
/* Mockito matcher intThat adapting Hamcrest-style matcher is(greaterThan(...)) */
verify(foo).setPowerLevel(intThat(is(greaterThan(9000))));
In the above statement: foo.setPowerLevel
is a method that accepts an int
. is(greaterThan(9000))
returns a Matcher<Integer>
, which wouldn't work as a setPowerLevel
argument. The Mockito matcher intThat
wraps that Hamcrest-style Matcher and returns an int
so it can appear as an argument; Mockito matchers like gt(9000)
would wrap that entire expression into a single call, as in the first line of example code.
when(foo.quux(3, 5)).thenReturn(true);
When not using argument matchers, Mockito records your argument values and compares them with their equals
methods.
when(foo.quux(eq(3), eq(5))).thenReturn(true); // same as above
when(foo.quux(anyInt(), gt(5))).thenReturn(true); // this one's different
When you call a matcher like any
or gt
(greater than), Mockito stores a matcher object that causes Mockito to skip that equality check and apply your match of choice. In the case of argumentCaptor.capture()
it stores a matcher that saves its argument instead for later inspection.
Matchers return dummy values such as zero, empty collections, or null
. Mockito tries to return a safe, appropriate dummy value, like 0 for anyInt()
or any(Integer.class)
or an empty List<String>
for anyListOf(String.class)
. Because of type erasure, though, Mockito lacks type information to return any value but null
for any()
or argThat(...)
, which can cause a NullPointerException if trying to "auto-unbox" a null
primitive value.
Matchers like eq
and gt
take parameter values; ideally, these values should be computed before the stubbing/verification starts. Calling a mock in the middle of mocking another call can interfere with stubbing.
Matcher methods can't be used as return values; there is no way to phrase thenReturn(anyInt())
or thenReturn(any(Foo.class))
in Mockito, for instance. Mockito needs to know exactly which instance to return in stubbing calls, and will not choose an arbitrary return value for you.
Matchers are stored (as Hamcrest-style object matchers) in a stack contained in a class called ArgumentMatcherStorage. MockitoCore and Matchers each own a ThreadSafeMockingProgress instance, which statically contains a ThreadLocal holding MockingProgress instances. It's this MockingProgressImpl that holds a concrete ArgumentMatcherStorageImpl. Consequently, mock and matcher state is static but thread-scoped consistently between the Mockito and Matchers classes.
Most matcher calls only add to this stack, with an exception for matchers like and
, or
, and not
. This perfectly corresponds to (and relies on) the evaluation order of Java, which evaluates arguments left-to-right before invoking a method:
when(foo.quux(anyInt(), and(gt(10), lt(20)))).thenReturn(true);
[6] [5] [1] [4] [2] [3]
This will:
anyInt()
to the stack.gt(10)
to the stack.lt(20)
to the stack.gt(10)
and lt(20)
and add and(gt(10), lt(20))
.foo.quux(0, 0)
, which (unless otherwise stubbed) returns the default value false
. Internally Mockito marks quux(int, int)
as the most recent call.when(false)
, which discards its argument and prepares to stub method quux(int, int)
identified in 5. The only two valid states are with stack length 0 (equality) or 2 (matchers), and there are two matchers on the stack (steps 1 and 4), so Mockito stubs the method with an any()
matcher for its first argument and and(gt(10), lt(20))
for its second argument and clears the stack.This demonstrates a few rules:
Mockito can't tell the difference between quux(anyInt(), 0)
and quux(0, anyInt())
. They both look like a call to quux(0, 0)
with one int matcher on the stack. Consequently, if you use one matcher, you have to match all arguments.
Call order isn't just important, it's what makes this all work. Extracting matchers to variables generally doesn't work, because it usually changes the call order. Extracting matchers to methods, however, works great.
int between10And20 = and(gt(10), lt(20));
/* BAD */ when(foo.quux(anyInt(), between10And20)).thenReturn(true);
// Mockito sees the stack as the opposite: and(gt(10), lt(20)), anyInt().
public static int anyIntBetween10And20() { return and(gt(10), lt(20)); }
/* OK */ when(foo.quux(anyInt(), anyIntBetween10And20())).thenReturn(true);
// The helper method calls the matcher methods in the right order.
The stack changes often enough that Mockito can't police it very carefully. It can only check the stack when you interact with Mockito or a mock, and has to accept matchers without knowing whether they're used immediately or abandoned accidentally. In theory, the stack should always be empty outside of a call to when
or verify
, but Mockito can't check that automatically.
You can check manually with Mockito.validateMockitoUsage()
.
In a call to when
, Mockito actually calls the method in question, which will throw an exception if you've stubbed the method to throw an exception (or require non-zero or non-null values).
doReturn
and doAnswer
(etc) do not invoke the actual method and are often a useful alternative.
If you had called a mock method in the middle of stubbing (e.g. to calculate an answer for an eq
matcher), Mockito would check the stack length against that call instead, and likely fail.
If you try to do something bad, like stubbing/verifying a final method, Mockito will call the real method and also leave extra matchers on the stack. The final
method call may not throw an exception, but you may get an InvalidUseOfMatchersException from the stray matchers when you next interact with a mock.
InvalidUseOfMatchersException:
Check that every single argument has exactly one matcher call, if you use matchers at all, and that you haven't used a matcher outside of a when
or verify
call. Matchers should never be used as stubbed return values or fields/variables.
Check that you're not calling a mock as a part of providing a matcher argument.
Check that you're not trying to stub/verify a final method with a matcher. It's a great way to leave a matcher on the stack, and unless your final method throws an exception, this might be the only time you realize the method you're mocking is final.
NullPointerException with primitive arguments: (Integer) any()
returns null while any(Integer.class)
returns 0; this can cause a NullPointerException
if you're expecting an int
instead of an Integer. In any case, prefer anyInt()
, which will return zero and also skip the auto-boxing step.
NullPointerException or other exceptions: Calls to when(foo.bar(any())).thenReturn(baz)
will actually call foo.bar(null)
, which you might have stubbed to throw an exception when receiving a null argument. Switching to doReturn(baz).when(foo).bar(any())
skips the stubbed behavior.
Use MockitoJUnitRunner, or explicitly call validateMockitoUsage
in your tearDown
or @After
method (which the runner would do for you automatically). This will help determine whether you've misused matchers.
For debugging purposes, add calls to validateMockitoUsage
in your code directly. This will throw if you have anything on the stack, which is a good warning of a bad symptom.
How about this deliciously evil implementation?
array.h
#define IMPORT_ARRAY(TYPE) \
\
struct TYPE##Array { \
TYPE* contents; \
size_t size; \
}; \
\
struct TYPE##Array new_##TYPE##Array() { \
struct TYPE##Array a; \
a.contents = NULL; \
a.size = 0; \
return a; \
} \
\
void array_add(struct TYPE##Array* o, TYPE value) { \
TYPE* a = malloc((o->size + 1) * sizeof(TYPE)); \
TYPE i; \
for(i = 0; i < o->size; ++i) { \
a[i] = o->contents[i]; \
} \
++(o->size); \
a[o->size - 1] = value; \
free(o->contents); \
o->contents = a; \
} \
void array_destroy(struct TYPE##Array* o) { \
free(o->contents); \
} \
TYPE* array_begin(struct TYPE##Array* o) { \
return o->contents; \
} \
TYPE* array_end(struct TYPE##Array* o) { \
return o->contents + o->size; \
}
main.c
#include <stdlib.h>
#include "array.h"
IMPORT_ARRAY(int);
struct intArray return_an_array() {
struct intArray a;
a = new_intArray();
array_add(&a, 1);
array_add(&a, 2);
array_add(&a, 3);
return a;
}
int main() {
struct intArray a;
int* it;
int* begin;
int* end;
a = return_an_array();
begin = array_begin(&a);
end = array_end(&a);
for(it = begin; it != end; ++it) {
printf("%d ", *it);
}
array_destroy(&a);
getchar();
return 0;
}
From Api level 1, you can use the public void setTextSize (float size)
method.
From the documentation:
Set the default text size to the given value, interpreted as "scaled pixel" units. This size is adjusted based on the current density and user font size preference.
Parameters: size -> float: The scaled pixel size.
So you can simple do:
textView.setTextSize(12); // your size in sp
Seems like the cleanest way in this example is to:
Example adapted from shamanland implementation, use whatever FAB you wish. Assume FAB is 64dp high including shadow:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<View
android:id="@+id/header"
android:layout_width="match_parent"
android:layout_height="120dp"
/>
<View
android:id="@+id/body"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/header"
/>
<fully.qualified.name.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignBottom="@id/header"
android:layout_marginBottom="-32dp"
android:layout_marginRight="20dp"
/>
</RelativeLayout>
To install font-awesome you first should install it with npm. So in your project root directory type:
npm install font-awesome --save
(Of course I assume you have node.js and npm already installed. And you've done npm install
in your projects root directory)
Then edit the resources/assets/sass/app.scss
file and add at the top this line:
@import "node_modules/font-awesome/scss/font-awesome.scss";
Now you can do for example:
npm run dev
This builds unminified versions of the resources in the correct folders. If you wanted to minify them, you would instead run:
npm run production
And then you can use the font.
In Java you can use GET
which shows requested data on URL.But POST
method cannot , because POST
has body but GET
donot have body.
Here is an answer proposal:
http://www.greenvilleweb.us/how-to-web-design/problem-with-ie-9-caching-ajax-get-request/
The idea is to add a parameter to your ajax query containing for example the current date an time, so the browser will not be able to cache it.
Have a look on the link, it is well explained.
tSql escapes a double quote with another double quote. So if you wanted it to be part of your sql string literal you would do this:
declare @xml xml
set @xml = "<transaction><item value=""hi"" /></transaction>"
If you want to include a quote inside a value in the xml itself, you use an entity, which would look like this:
declare @xml xml
set @xml = "<transaction><item value=""hi "mom" lol"" /></transaction>"
Using Neon - just happened to me too. You would have to delete the Eclipse version (not from disk) in your Project Explorer and import the projects as existing projects. Of course, ensure that the project folders as a whole were moved and that the Eclipse meta files are still there as mentioned by @koenpeters.
Refactor does not handle this.
Fiddler's website addresses this question directly.
There are several suggested workarounds, but the most straightforward is simply to use the machine name rather than "localhost" or "127.0.0.1":
http://machinename/mytestpage.aspx
Now that the question is clearer, you can just do this in one grep
grep -R --include "*bills*" "put" .
With relevant flags
-R, -r, --recursive
Read all files under each directory, recursively; this is
equivalent to the -d recurse option.
--include=GLOB
Search only files whose base name matches GLOB (using wildcard
matching as described under --exclude).
Apparently, I needed to run OpenSSL as root in order for it to have permission to the seeding file.
As you probably learned VBA does not natively support multithreading but. There are 3 methods to achieve multithreading:
I compared all thread approaches here: http://analystcave.com/excel-multithreading-vba-vs-vbscript-vs-c-net/
Considering approach #3 I also made a VBA Multithreading Tool that allows you to easily add multithreading to VBA: http://analystcave.com/excel-vba-multithreading-tool/
See the examples below:
Multithreading a For Loop
Sub RunForVBA(workbookName As String, seqFrom As Long, seqTo As Long)
For i = seqFrom To seqTo
x = seqFrom / seqTo
Next i
End Sub
Sub RunForVBAMultiThread()
Dim parallelClass As Parallel
Set parallelClass = New Parallel
parallelClass.SetThreads 4
Call parallelClass.ParallelFor("RunForVBA", 1, 1000)
End Sub
Run an Excel macro asynchronously
Sub RunAsyncVBA(workbookName As String, seqFrom As Long, seqTo As Long)
For i = seqFrom To seqTo
x = seqFrom / seqTo
Next i
End Sub
Sub RunForVBAAndWait()
Dim parallelClass As Parallel
Set parallelClass = New Parallel
Call parallelClass.ParallelAsyncInvoke("RunAsyncVBA", ActiveWorkbook.Name, 1, 1000)
'Do other operations here
'....
parallelClass.AsyncThreadJoin
End Sub
The statement about CMake being a "build generator" is a common misconception.
It's not technically wrong; it just describes HOW it works, but not WHAT it does.
In the context of the question, they do the same thing: take a bunch of C/C++ files and turn them into a binary.
So, what is the real difference?
CMake is much more high-level. It's tailored to compile C++, for which you write much less build code, but can be also used for general purpose build. make
has some built-in C/C++ rules as well, but they are useless at best.
CMake
does a two-step build: it generates a low-level build script in ninja
or make
or many other generators, and then you run it. All the shell script pieces that are normally piled into Makefile
are only executed at the generation stage. Thus, CMake
build can be orders of magnitude faster.
The grammar of CMake
is much easier to support for external tools than make's.
Once make
builds an artifact, it forgets how it was built. What sources it was built from, what compiler flags? CMake
tracks it, make
leaves it up to you. If one of library sources was removed since the previous version of Makefile
, make
won't rebuild it.
Modern CMake
(starting with version 3.something) works in terms of dependencies between "targets". A target is still a single output file, but it can have transitive ("public"/"interface" in CMake terms) dependencies.
These transitive dependencies can be exposed to or hidden from the dependent packages. CMake
will manage directories for you. With make
, you're stuck on a file-by-file and manage-directories-by-hand level.
You could code up something in make
using intermediate files to cover the last two gaps, but you're on your own. make
does contain a Turing complete language (even two, sometimes three counting Guile); the first two are horrible and the Guile is practically never used.
To be honest, this is what CMake
and make
have in common -- their languages are pretty horrible. Here's what comes to mind:
CMake
has three data types: string, list, and a target with properties. make
has one: string;set_property(TARGET helloworld APPEND PROPERTY INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}")
;Note from 2017: File::Slurp is not recommended due to design mistakes and unmaintained errors. Use File::Slurper or Path::Tiny instead.
extending on your answer
use File::Slurp ();
my $value = File::Slurp::slurp($filename);
$value =~ s/\R*//g;
File::Slurp abstracts away the File IO stuff and just returns a string for you.
NOTE
Important to note the addition of /g
, without it, given a multi-line string, it will only replace the first offending character.
Also, the removal of $
, which is redundant for this purpose, as we want to strip all line breaks, not just line-breaks before whatever is meant by $
on this OS.
In a multi-line string, $
matches the end of the string and that would be problematic ).
Point 3 means that point 2 is made with the assumption that you'd also want to use /m
otherwise '$' would be basically meaningless for anything practical in a string with >1 lines, or, doing single line processing, an OS which actually understands $
and manages to find the \R*
that proceed the $
Examples
while( my $line = <$foo> ){
$line =~ $regex;
}
Given the above notation, an OS which does not understand whatever your files '\n' or '\r' delimiters, in the default scenario with the OS's default delimiter set for $/
will result in reading your whole file as one contiguous string ( unless your string has the $OS's delimiters in it, where it will delimit by that )
So in this case all of these regex are useless:
/\R*$//
: Will only erase the last sequence of \R
in the file /\R*//
: Will only erase the first sequence of \R
in the file /\012?\015?//
: When will only erase the first 012\015
, \012
, or \015
sequence, \015\012
will result in either \012
or \015
being emitted.
/\R*$//
: If there happens to be no byte sequences of '\015$OSDELIMITER' in the file, then then NO linebreaks will be removed except for the OS's own ones.
It would appear nobody gets what I'm talking about, so here is example code, that is tested to NOT remove line feeds. Run it, you'll see that it leaves the linefeeds in.
#!/usr/bin/perl
use strict;
use warnings;
my $fn = 'TestFile.txt';
my $LF = "\012";
my $CR = "\015";
my $UnixNL = $LF;
my $DOSNL = $CR . $LF;
my $MacNL = $CR;
sub generate {
my $filename = shift;
my $lineDelimiter = shift;
open my $fh, '>', $filename;
for ( 0 .. 10 )
{
print $fh "{0}";
print $fh join "", map { chr( int( rand(26) + 60 ) ) } 0 .. 20;
print $fh "{1}";
print $fh $lineDelimiter->();
print $fh "{2}";
}
close $fh;
}
sub parse {
my $filename = shift;
my $osDelimiter = shift;
my $message = shift;
print "Parsing $message File $filename : \n";
local $/ = $osDelimiter;
open my $fh, '<', $filename;
while ( my $line = <$fh> )
{
$line =~ s/\R*$//;
print ">|" . $line . "|<";
}
print "Done.\n\n";
}
my @all = ( $DOSNL,$MacNL,$UnixNL);
generate 'Windows.txt' , sub { $DOSNL };
generate 'Mac.txt' , sub { $MacNL };
generate 'Unix.txt', sub { $UnixNL };
generate 'Mixed.txt', sub {
return @all[ int(rand(2)) ];
};
for my $os ( ["$MacNL", "On Mac"], ["$DOSNL", "On Windows"], ["$UnixNL", "On Unix"]){
for ( qw( Windows Mac Unix Mixed ) ){
parse $_ . ".txt", @{ $os };
}
}
For the CLEARLY Unprocessed output, see here: http://pastebin.com/f2c063d74
Note there are certain combinations that of course work, but they are likely the ones you yourself naívely tested.
Note that in this output, all results must be of the form >|$string|<>|$string|<
with NO LINE FEEDS to be considered valid output.
and $string
is of the general form {0}$data{1}$delimiter{2}
where in all output sources, there should be either :
{1}
and {2}
|<>|
between {1}
and {2}
In one line:
$('#selector').clone().attr('id','newid').appendTo('#newPlace');
I wanted to comment on @Ionica Bizau, but I don't have enough reputation.
To give a reply to your question about javascript code:
What you need to do is get the parent's element height (minus any elements that take up space) and apply that to the child elements.
function wrapperHeight(){
var height = $(window).outerHeight() - $('#header').outerHeight(true);
$('.wrapper').css({"max-height":height+"px"});
}
Note
window could be replaced by ".container" if that one has no floated children or has a fix to get the correct height calculated. This solution uses jQuery.
You were close. This will work:
.image { position: relative; border: 1px solid black; width: 200px; height: 200px; }
.image img { max-width: 100%; max-height: 100%; }
.overlay { position: absolute; top: 0; left: 0; right:0; bottom:0; display: none; background-color: rgba(0,0,0,0.5); }
.image:hover .overlay { display: block; }
You needed to put the :hover
on image, and make the .overlay
cover the whole image by adding right:0;
and bottom:0
.
jsfiddle: http://jsfiddle.net/Zf5am/569/
Here is an elegant way to do similar thing. But why do partly JSON unmarshal? That doesn't make sense.
Look below at the working code. Copy and paste it.
import (
"bytes"
"encoding/json" // Encoding and Decoding Package
"fmt"
)
var messeging = `{
"say":"Hello",
"sendMsg":{
"user":"ANisus",
"msg":"Trying to send a message"
}
}`
type SendMsg struct {
User string `json:"user"`
Msg string `json:"msg"`
}
type Chat struct {
Say string `json:"say"`
SendMsg *SendMsg `json:"sendMsg"`
}
func main() {
/** Clean way to solve Json Decoding in Go */
/** Excellent solution */
var chat Chat
r := bytes.NewReader([]byte(messeging))
chatErr := json.NewDecoder(r).Decode(&chat)
errHandler(chatErr)
fmt.Println(chat.Say)
fmt.Println(chat.SendMsg.User)
fmt.Println(chat.SendMsg.Msg)
}
func errHandler(err error) {
if err != nil {
fmt.Println(err)
return
}
}
$('#OvernightOnshore').click(function () {
if ($('#OvernightOnshore').prop("checked") == true) {
if ($('#OvernightOffshore').prop("checked") == true) {
$('#OvernightOffshore').attr('checked', false)
}
}
})
$('#OvernightOffshore').click(function () {
if ($('#OvernightOffshore').prop("checked") == true) {
if ($('#OvernightOnshore').prop("checked") == true) {
$('#OvernightOnshore').attr('checked', false);
}
}
})
This above code snippet will allow you to use checkboxes over radio buttons, but have the same functionality of radio buttons where you can only have one selected.
30-07-2019
In Windows 10 pro:
C:\Program Files\PostgreSQL\11\data
It seems this is true but, personally, it seems to me to be poor design. Sure, have a default name (with extension) but allow other names and have a way of specifying the name of the docker file for commands.
Having an extension is also nice because it allows one to associate applications to that extension type. When I click on a Dockerfile in MacOSX it treats it as a Unix executable and tries to run it.
If Docker files had an extension I could tell the OS to start them with a particular application, e.g. my text editor application. I'm not sure but the current behaviour may also be related to the file permisssions.
I like prettyPhoto, IMHO it's the one that looks the best.
You can easily pick image from asset without UIImage(named: "green-square-Retina")
.
Instead use the image object directly from bundle.
Start typing the image name and you will get suggestions with actual image from bundle. It is advisable practice and less prone to error.
See this Stackoverflow answer for reference.
Going down your list:
Utf32String
class as part of my MiscUtil library, should you ever want it. (It's not been very thoroughly tested, mind you.)There's more on my Unicode page and tips for debugging Unicode problems.
The other big resource of code is unicode.org which contains more information than you'll ever be able to work your way through - possibly the most useful bit is the code charts.
Had an issue where my task was not firing simply because it was running on a laptop without a power cord... Under the conditions tab, by default it is checked so that a task will not run while AC power is not connected.
SET GLOBAL auto_increment_offset=1;
SET GLOBAL auto_increment_increment=5;
auto_increment_offset: interval between successive column values
auto_increment_offset: determines the starting point for the AUTO_INCREMENT column value. The default value is 1.