In C, the order that you define things often matters. Either move the definition of outchar to the top, or provide a prototype at the top, like this:
#include <stdio.h> #include <stdlib.h> void outchar(char ch); int main() { outchar('A'); outchar('B'); outchar('C'); return 0; } void outchar(char ch) { printf("%c", ch); }
Also, you should be specifying the return type of every function. I added that for you.
Just in case you don't want to bump Windows SDK to Windows 10 (you could be for example working on an open source project where the decision isn't yours to make), you can solve this problem in a Windows SDK 8.1 project by navigating Tools -> Get Tools and Features... -> Individual Compontents tab
and installing the individual components "Windows 8.1 SDK" (under SDKs, libraries and frameworks) and "Windows Universal CRT SDK" (under Compilers, build tools and runtimes):
typedef struct{
char name[30];
char surname[30];
int age;
} data;
defines that data
should be a block of memory that fits 60 chars plus 4 for the int (see note)
[----------------------------,------------------------------,----]
^ this is name ^ this is surname ^ this is age
This allocates the memory on the stack.
data s1;
Assignments just copies numbers, sometimes pointers.
This fails
s1.name = "Paulo";
because the compiler knows that s1.name
is the start of a struct 64 bytes long, and "Paulo"
is a char[] 6 bytes long (6 because of the trailing \0 in C strings)
Thus, trying to assign a pointer to a string into a string.
To copy "Paulo" into the struct at the point name
and "Rossi" into the struct at point surname
.
memcpy(s1.name, "Paulo", 6);
memcpy(s1.surname, "Rossi", 6);
s1.age = 1;
You end up with
[Paulo0----------------------,Rossi0-------------------------,0001]
strcpy
does the same thing but it knows about \0
termination so does not need the length hardcoded.
Alternatively you can define a struct which points to char arrays of any length.
typedef struct {
char *name;
char *surname;
int age;
} data;
This will create
[----,----,----]
This will now work because you are filling the struct with pointers.
s1.name = "Paulo";
s1.surname = "Rossi";
s1.age = 1;
Something like this
[---4,--10,---1]
Where 4 and 10 are pointers.
Note: the ints and pointers can be different sizes, the sizes 4 above are 32bit as an example.
This worked for me:
(I don't have enough rep to embed pictures yet -- sorry about this.)
I went into Project --> Properties --> Linker --> System.
IMG: Located here, as of Dec 2019 Visual Studio for Windows
My platform was set to Active(Win32) with the Subsystem as "Windows". I was making a console app, so I set it to "Console".
IMG: Changing "Windows" --> "Console"
Then, I switched my platform to "x64".
No.. It is not proper way. Refer the steps,
For Classpath reference:
Right click on project in Eclipse -> Buildpath -> Configure Build path -> Java Build Path (left Pane) -> Libraries(Tab) -> Add External Jars -> Select your jar and select OK.
For Deployment Assembly:
Right click on WAR in eclipse-> Buildpath -> Configure Build path -> Deployment Assembly (left Pane) -> Add -> External file system -> Add -> Select your jar -> Add -> Finish.
This is the proper way! Don't forget to remove environment variable. It is not required now.
Try this. Surely it will work. Try to use Maven, it will simplify you task.
A possible solution is to think about it backwards: Accept a float as input and reject the input if the float is not an integer:
int n;
float f;
printf("Please enter an integer: ");
while(scanf("%f",&f)!=1 || (int)f != f)
{
...
}
n = f;
Though this does allow the user to enter something like 12.0, or 12e0, etc.
You have to properly understand what is a "stdafx.h", aka precompiled header. Other questions or Wikipedia will answer that. In many cases a precompiled header can be avoided, especially if your project is small and with few dependencies. In your case, as you probably started from a template project, it was used to include Windows.h
only for the _TCHAR
macro.
Then, precompiled header is usually a per-project file in Visual Studio world, so:
#include <stdafx.h>
to #include "stdafx.h"
. It is supposed to be a project local file, not to be resolved in include directories.Secondly: it's inadvisable to include the precompiled header in your own headers, to not clutter namespace of other source that can use your code as a library, so completely remove its inclusion in vector.h
.
@RequestMapping(value="/add/image", method=RequestMethod.POST)
public ResponseEntity upload(@RequestParam("id") Long id, HttpServletResponse response, HttpServletRequest request)
{
try {
MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest)request;
Iterator<String> it=multipartRequest.getFileNames();
MultipartFile multipart=multipartRequest.getFile(it.next());
String fileName=id+".png";
String imageName = fileName;
byte[] bytes=multipart.getBytes();
BufferedOutputStream stream= new BufferedOutputStream(new FileOutputStream("src/main/resources/static/image/book/"+fileName));;
stream.write(bytes);
stream.close();
return new ResponseEntity("upload success", HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity("Upload fialed", HttpStatus.BAD_REQUEST);
}
}
Which is best way to pause the console in C++ programs?
system("pause");
and getch();
(which comes from the DOS world, IIRC) are both unportable.
Is cin.get() is better to use to pause console?
As the only one portable and standard option, I would say it is, but I personally believe one should not write interactive console programs, i.e. programs which actually pause the console or prompt for input (unless there is a really good reason for that, because that makes shell scripting much harder). Console programs should interact with the user via command line arguments (or at least that kind of interaction should be the default one).
Just in case you need pausing the program for the my-program-is-launched-from-the-IDE-and-immediately-closed-but-I-don't-have-enough-time-to-see-the-result reason — don't do that. Just configure your IDE or launch console programs right from the console.
Swift 5.1
Here might be the easiest solution out of all these answers.
Add this extension:
extension String {
func retrieveFirstCharacter() -> String? {
guard self.count > 0 else { return nil }
let numberOfCharacters = self.count
return String(self.dropLast(numberOfCharacters - 1))
}
}
I found solution. It works fine when I throw away next line from form:
enctype="multipart/form-data"
And now it pass all parameters at request ok:
<form action="/registration" method="post">
<%-- error messages --%>
<div class="form-group">
<c:forEach items="${registrationErrors}" var="error">
<p class="error">${error}</p>
</c:forEach>
</div>
I'll join the fray. It's been too long since I've written C. Besides, there's no complete examples here anyway. The OP's code is basically C, so I went ahead and made it work with GCC.
The problems were covered before; the next
pointer wasn't being advanced. That was the crux of the issue.
I also took the opportunity to make a suggested edit; instead of having two funcitons to malloc
, I put it in initNode()
and then used initNode()
to malloc
both (malloc
is "the C new" if you will). I changed initNode()
to return a pointer.
#include <stdlib.h>
#include <stdio.h>
// required to be declared before self-referential definition
struct Node;
struct Node {
int x;
struct Node *next;
};
struct Node* initNode( int n){
struct Node *head = malloc(sizeof(struct Node));
head->x = n;
head->next = NULL;
return head;
}
void addNode(struct Node **head, int n){
struct Node *NewNode = initNode( n );
NewNode -> next = *head;
*head = NewNode;
}
int main(int argc, char* argv[])
{
struct Node* head = initNode(5);
addNode(&head,10);
addNode(&head,20);
struct Node* cur = head;
do {
printf("Node @ %p : %i\n",(void*)cur, cur->x );
} while ( ( cur = cur->next ) != NULL );
}
compilation: gcc -o ll ll.c
output:
Node @ 0x9e0050 : 20
Node @ 0x9e0030 : 10
Node @ 0x9e0010 : 5
you need implements Parcelable in your ContactBean
class, I put one example for you:
public class ContactClass implements Parcelable {
private String id;
private String photo;
private String firstname;
private String lastname;
public ContactClass()
{
}
private ContactClass(Parcel in) {
firstname = in.readString();
lastname = in.readString();
photo = in.readString();
id = in.readString();
}
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(firstname);
dest.writeString(lastname);
dest.writeString(photo);
dest.writeString(id);
}
public static final Parcelable.Creator<ContactClass> CREATOR = new Parcelable.Creator<ContactClass>() {
public ContactClass createFromParcel(Parcel in) {
return new ContactClass(in);
}
public ContactClass[] newArray(int size) {
return new ContactClass[size];
}
};
// all get , set method
}
and this get and set for your code:
Intent intent = new Intent(this,DisplayContact.class);
intent.putExtra("Contact_list", ContactLis);
startActivity(intent);
second class:
ArrayList<ContactClass> myList = getIntent().getParcelableExtra("Contact_list");
NullPointerException
s are among the easier exceptions to diagnose, frequently. Whenever you get an exception in Java and you see the stack trace ( that's what your second quote-block is called, by the way ), you read from top to bottom. Often, you will see exceptions that start in Java library code or in native implementations methods, for diagnosis you can just skip past those until you see a code file that you wrote.
Then you like at the line indicated and look at each of the objects ( instantiated classes ) on that line -- one of them was not created and you tried to use it. You can start by looking up in your code to see if you called the constructor on that object. If you didn't, then that's your problem, you need to instantiate that object by calling new Classname( arguments ). Another frequent cause of NullPointerException
s is accidentally declaring an object with local scope when there is an instance variable with the same name.
In your case, the exception occurred in your constructor for Workshop on line 75. <init>
means the constructor for a class. If you look on that line in your code, you'll see the line
denimjeansButton.addItemListener(this);
There are fairly clearly two objects on this line: denimjeansButton
and this
. this
is synonymous with the class instance you are currently in and you're in the constructor, so it can't be this
. denimjeansButton
is your culprit. You never instantiated that object. Either remove the reference to the instance variable denimjeansButton
or instantiate it.
I create a demo with 7 jQueryUI Slider and ChartJs (with dynamic text inside)
Chart.types.Doughnut.extend({
name: "DoughnutTextInside",
showTooltip: function() {
this.chart.ctx.save();
Chart.types.Doughnut.prototype.showTooltip.apply(this, arguments);
this.chart.ctx.restore();
},
draw: function() {
Chart.types.Doughnut.prototype.draw.apply(this, arguments);
var width = this.chart.width,
height = this.chart.height;
var fontSize = (height / 140).toFixed(2);
this.chart.ctx.font = fontSize + "em Verdana";
this.chart.ctx.textBaseline = "middle";
var red = $( "#red" ).slider( "value" ),
green = $( "#green" ).slider( "value" ),
blue = $( "#blue" ).slider( "value" ),
yellow = $( "#yellow" ).slider( "value" ),
sienna = $( "#sienna" ).slider( "value" ),
gold = $( "#gold" ).slider( "value" ),
violet = $( "#violet" ).slider( "value" );
var text = (red+green+blue+yellow+sienna+gold+violet) + " minutes";
var textX = Math.round((width - this.chart.ctx.measureText(text).width) / 2);
var textY = height / 2;
this.chart.ctx.fillStyle = '#000000';
this.chart.ctx.fillText(text, textX, textY);
}
});
var ctx = $("#myChart").get(0).getContext("2d");
var myDoughnutChart = new Chart(ctx).DoughnutTextInside(data, {
responsive: false
});
You are missing 'json' dataType in the $.post()
method:
$.post('http://www.example.com:PORT_NUMBER/MYSERVLET',{MyParam: 'value'})
.done(function(data){
alert(data);
}, "json");
//-^^^^^^-------here
Updates:
try with this:
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
this type of error usually occur when you try to access data through the index in which data data has not been assign. for example
//assign of data in to array
for(int i=0; i<10; i++){
arr[i]=i;
}
//accessing of data through array index
for(int i=10; i>=0; i--){
cout << arr[i];
}
the code will give error (vector subscript out of range) because you are accessing the arr[10] which has not been assign yet.
To get a definitive reason, you'd need to ask the designer(s) of that API.
But one possible reason is that the intent of a (hypothetical) nextChar
would not fit into the scanning model very well.
If nextChar()
to behaved like read()
on a Reader
and simply returned the next unconsumed character from the scanner, then it is behaving inconsistently with the other next<Type>
methods. These skip over delimiter characters before they attempt to parse a value.
If nextChar()
to behaved like (say) nextInt
then:
the delimiter skipping would be "unexpected" for some folks, and
there is the issue of whether it should accept a single "raw" character, or a sequence of digits that are the numeric representation of a char
, or maybe even support escaping or something1.
No matter what choice they made, some people wouldn't be happy. My guess is that the designers decided to stay away from the tarpit.
1 - Would vote strongly for the raw character approach ... but the point is that there are alternatives that need to be analysed, etc.
for ( i = 0; i < total.length; i++ );
^-- remove the semi-colon here
With this semi-colon, the loop loops until i == total.length
, doing nothing, and then what you thought was the body of the loop is executed.
I bet for sure, that this is because you didn't close the running instance of the program before trying to re-compile it.
Generally, ld.exe
returns 1 when it can't access required files. This usually includes
Access denied
)The program looks completely fine, so the second point should not hit. In usual cases, it's impossible for ld
to fail to open the object file (unless you have a faulty drive and a dirty filesystem), so the first point is also nearly impossible.
Now we get to the third point. Note that Windows not allow writing to a file when it's in use, so the running instance of your program prevents ld.exe
from writing the new linked program to it.
So next time be sure to close running programs before compiling.
The compiler wants to know the function before it can use it
just declare the function before you call it
#include <stdio.h>
int Fibonacci(int number); //now the compiler knows, what the signature looks like. this is all it needs for now
int main(int argc, const char * argv[])
{
int input;
printf("Please give me a number : ");
scanf("%d", &input);
getchar();
printf("The fibonacci number of %d is : %d", input, Fibonacci(input)); //!!!
}/* main */
int Fibonacci(int number)
{
//…
If condition is wrong. Also return type for lower is needed.
#include <stdio.h>
int lower(int a)
{
if ((a >= 65) && (a <= 90))
a = a + 32;
return a;
}
int _tmain(int argc, _TCHAR* argv[])
{
putchar(lower('A'));
return 0;
}
On the latest support library none of the solutions discussed here are necessary anymore. You can play with your Activity
's fragments as you like using the FragmentTransaction
. Just make sure that your fragments can be identified either with an id or tag.
The fragments will be restored automatically as long as you don't try to recreate them on every call to onCreate()
. Instead, you should check if savedInstanceState
is not null and find the old references to the created fragments in this case.
Here is an example:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
myFragment = MyFragment.newInstance();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.my_container, myFragment, MY_FRAGMENT_TAG)
.commit();
} else {
myFragment = (MyFragment) getSupportFragmentManager()
.findFragmentByTag(MY_FRAGMENT_TAG);
}
...
}
Note however that there is currently a bug when restoring the hidden state of a fragment. If you are hiding fragments in your activity, you will need to restore this state manually in this case.
This method would be helpful :
String rightPart(String text,int length)
{
if (text.length()<length) return text;
String raw = "";
for (int i = 1; i <= length; i++) {
raw += text.toCharArray()[text.length()-i];
}
return new StringBuilder(raw).reverse().toString();
}
Setup scanner:
reader.useDelimiter("");
After this reader.next()
will return a single-character string.
Re: textFile.getch()
, did you make that up, or do you have a reference that says it should work? If it's the latter, get rid of it. If it's the former, don't do that. Get a good reference.
char ch;
textFile.unsetf(ios_base::skipws);
textFile >> ch;
Comilation error is due arguments are not properly provided, replaceFirst accepts regx as initial arg. [a-z]{1} will match string of simple alpha characters of length 1.
Try this.
betterIdea = userIdea.replaceFirst("[a-z]{1}", userIdea.substring(0,1).toUpperCase())
VS 2012 applications cannot be run under Windows XP.
See this VC++ blog on why and how to make it work.
It seems to be supported/possible from Feb 2013. See noelicus answer below on how to.
I do not know much about Java but URL query arguments should be separated by "&", not "?"
http://tools.ietf.org/html/rfc3986 is good place for reference using "sub-delim" as keyword. http://en.wikipedia.org/wiki/Query_string is another good source.
public static String abcBase36(int i) {
char[] ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
int quot = i / 36;
int rem = i % 36;
char letter = ALPHABET[rem];
if (quot == 0) {
return "" + letter;
} else {
return abcBase36(quot - 1) + letter;
}
}
Try this
#include <stdio.h>
struct context;
struct funcptrs{
void (*func0)(struct context *ctx);
void (*func1)(void);
};
struct context{
struct funcptrs fps;
};
void func1 (void) { printf( "1\n" ); }
void func0 (struct context *ctx) { printf( "0\n" ); }
void getContext(struct context *con){
con->fps.func0 = func0;
con->fps.func1 = func1;
}
int main(int argc, char *argv[]){
struct context c;
c.fps.func0 = func0;
c.fps.func1 = func1;
getContext(&c);
c.fps.func0(&c);
getchar();
return 0;
}
The program will not work properly because at Line 1, when the user presses Enter, it will leave in the input buffer 2 character: Enter key (ASCII code 13) and \n (ASCII code 10). Therefore, at Line 2, it will read the \n and will not wait for the user to enter a character.
The behavior you see at line 2 is correct, but that's not quite the correct explanation. With text-mode streams, it doesn't matter what line-endings your platform uses (whether carriage return (0x0D) + linefeed (0x0A), a bare CR, or a bare LF). The C runtime library will take care of that for you: your program will see just '\n'
for newlines.
If you typed a character and pressed enter, then that input character would be read by line 1, and then '\n'
would be read by line 2. See I'm using scanf %c
to read a Y/N response, but later input gets skipped. from the comp.lang.c FAQ.
As for the proposed solutions, see (again from the comp.lang.c FAQ):
fflush(stdin)
work? fflush
won't work, what can I use to flush input?which basically state that the only portable approach is to do:
int c;
while ((c = getchar()) != '\n' && c != EOF) { }
Your getchar() != '\n'
loop works because once you call getchar()
, the returned character already has been removed from the input stream.
Also, I feel obligated to discourage you from using scanf
entirely: Why does everyone say not to use scanf
? What should I use instead?
To convert and append an integer, use operator += (or member function concat
):
String stringOne = "A long integer: ";
stringOne += 123456789;
To get the string as type char[]
, use toCharArray():
char charBuf[50];
stringOne.toCharArray(charBuf, 50)
In the example, there is only space for 49 characters (presuming it is terminated by null). You may want to make the size dynamic.
The cost of bringing in String
(it is not included if not used anywhere in the sketch), is approximately 1212 bytes program memory (flash) and 48 bytes RAM.
This was measured using Arduino IDE version 1.8.10 (2019-09-13) for an Arduino Leonardo sketch.
The std::mbstowcs
function is what you are looking for:
char text[] = "something";
wchar_t wtext[20];
mbstowcs(wtext, text, strlen(text)+1);//Plus null
LPWSTR ptr = wtext;
for string
s,
string text = "something";
wchar_t wtext[20];
mbstowcs(wtext, text.c_str(), text.length());//includes null
LPWSTR ptr = wtext;
--> ED: The "L" prefix only works on string literals, not variables. <--
You can't clone it, and how you are going to solve your problem depends on what the source of the data is.
One solution is to read all data from the InputStream into a byte array, and then create a ByteArrayInputStream around that byte array, and pass that input stream into your method.
Edit 1: That is, if the other method also needs to read the same data. I.e you want to "reset" the stream.
you can initialize it to ' ' instead. Also, the reason that you received an error -1 being too many characters is because it is treating '-' and 1 as separate.
in your dispatcher servlet context xml, you have to add a propertie
"<property name="contentType" value="text/html;charset=UTF-8" />"
on your viewResolver bean.
we are using freemarker for views.
it looks something like this:
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
...
<property name="contentType" value="text/html;charset=UTF-8" />
...
</bean>
$.fn.extend( {
limiter: function(limit, elem) {
$(this).on("keyup focus", function() {
setCount(this, elem);
});
function setCount(src, elem) {
var chars = src.value.length;
if (chars > limit) {
src.value = src.value.substr(0, limit);
chars = limit;
}
elem.html( limit - chars );
}
setCount($(this)[0], elem);
}
});
var elem = $("#cntr");
$("#status_txt").limiter(160, elem);
I'm not fully sure that this is what you're looking for, but if your question is how to read an integer using <stdio.h>
, then the proper syntax is
int myInt;
scanf("%d", &myInt);
You'll need to do a lot of error-handling to ensure that this works correctly, of course, but this should be a good start. In particular, you'll need to handle the cases where
stdin
file is closed or broken, so you get nothing at all.To check for this, you can capture the return code from scanf
like this:
int result = scanf("%d", &myInt);
If stdin
encounters an error while reading, result
will be EOF
, and you can check for errors like this:
int myInt;
int result = scanf("%d", &myInt);
if (result == EOF) {
/* ... you're not going to get any input ... */
}
If, on the other hand, the user enters something invalid, like a garbage text string, then you need to read characters out of stdin
until you consume all the offending input. You can do this as follows, using the fact that scanf
returns 0 if nothing was read:
int myInt;
int result = scanf("%d", &myInt);
if (result == EOF) {
/* ... you're not going to get any input ... */
}
if (result == 0) {
while (fgetc(stdin) != '\n') // Read until a newline is found
;
}
Hope this helps!
EDIT: In response to the more detailed question, here's a more appropriate answer. :-)
The problem with this code is that when you write
printf("got the number: %d", scanf("%d", &x));
This is printing the return code from scanf
, which is EOF
on a stream error, 0
if nothing was read, and 1
otherwise. This means that, in particular, if you enter an integer, this will always print 1
because you're printing the status code from scanf
, not the number you read.
To fix this, change this to
int x;
scanf("%d", &x);
/* ... error checking as above ... */
printf("got the number: %d", x);
Hope this helps!
*(myString.end() - 1)
maybe? That's not exactly elegant either.
A python-esque myString.at(-1)
would be asking too much of an already-bloated class.
No, but you can with an if
-else if
-else
chain which achieves the same result:
if (answer >= 1 && answer <= 4)
cout << "You need more cars.";
else if (answer <= 8)
cout << "Now you need a house.";
else
cout << "What are you? A peace-loving hippie freak?";
You may also want to handle the case of 0 cars and then also the unexpected case of a negative number of cars probably by throwing an exception.
PS: I've renamed Answer
to answer
as it's considered bad style to start variables with an uppercase letter.
As a side note, scripting languages such as Python allow for the nice if answer in [1, 2, 3, 4]
syntax which is a flexible way of achieving what you want.
That's a lot of questions.
Why EOF
is -1: usually -1 in POSIX system calls is returned on error, so i guess the idea is "EOF is kind of error"
any boolean operation (including !=) returns 1 in case it's TRUE, and 0 in case it's FALSE, so getchar() != EOF
is 0
when it's FALSE, meaning getchar()
returned EOF
.
in order to emulate EOF
when reading from stdin
press Ctrl+D
The syntax to statically initialize an array uses curly braces, like this:
int array[10] = { 0 };
This will zero-initialize the array.
For multi-dimensional arrays, you need nested curly braces, like this:
int cipher[Array_size][Array_size]= { { 0 } };
Note that Array_size
must be a compile-time constant for this to work. If Array_size
is not known at compile-time, you must use dynamic initialization. (Preferably, an std::vector
).
There is an underlying buffer/stream that getchar()
and friends read from. When you enter text, the text is stored in a buffer somewhere. getchar()
can stream through it one character at a time. Each read returns the next character until it reaches the end of the buffer. The reason it's not asking you for subsequent characters is that it can fetch the next one from the buffer.
If you run your script and type directly into it, it will continue to prompt you for input until you press CTRL+D (end of file). If you call it like ./program < myInput
where myInput
is a text file with some data, it will get the EOF
when it reaches the end of the input. EOF
isn't a character that exists in the stream, but a sentinel value to indicate when the end of the input has been reached.
As an extra warning, I believe getchar()
will also return EOF
if it encounters an error, so you'll want to check ferror()
. Example below (not tested, but you get the idea).
main() {
int c;
do {
c = getchar();
if (c == EOF && ferror()) {
perror("getchar");
}
else {
putchar(c);
}
}
while(c != EOF);
}
sizeof(source)
is returning to you the size of a char*
, not the length of the string. You should be using strlen(source)
, and you should move that out of the loop, or else you'll be recalculating the size of the string every loop.%s
format modifier, printf
is looking for a char*
, but you're actually passing a char
. You should use the %c
modifier.public static String readClob(Clob clob) throws SQLException, IOException {
StringBuilder sb = new StringBuilder((int) clob.length());
Reader r = clob.getCharacterStream();
char[] cbuf = new char[2048];
int n;
while ((n = r.read(cbuf, 0, cbuf.length)) != -1) {
sb.append(cbuf, 0, n);
}
return sb.toString();
}
The above approach is also very efficient.
I've had this problem/question come up in an assignment that I'm currently working on. It also depends on which input you are grabbing from. I am using
/dev/tty
to get input while the program is running, so that needs to be the filestream associated with the command.
On the ubuntu machine I have to test/target, it required more than just
system( "stty -raw" );
or
system( "stty -icanon" );
I had to add the --file flag, as well as path to the command, like so:
system( "/bin/stty --file=/dev/tty -icanon" );
Everything is copacetic now.
#include <stdio.h>
int main() {
int c;
while((c = getchar()) != EOF) {
putchar(c);
}
printf("%d at EOF\n", c);
}
modified the above code to give more clarity on EOF, Press Ctrl+d and putchar is used to print the char avoid using printf within while loop.
check
System.getProperty("sun.jnu.encoding")
it seems to be the same encoding as the one used in your system's command line.
It will be $_COOKIE['CaptchaResponseValue']
, not $_COOKIE('CaptchaResponseValue')
If I understand correctly, you need to convert the type (char value) that you store in Building list to the type (enum) that you store in buildingStatus list.
(For each status in the Building list//character value//, does the status exists in the buildingStatus list//enum value//)
public static IQueryable<Building> WithStatus(this IQueryable<Building> qry,
IList<BuildingStatuses> buildingStatus)
{
return from v in qry
where ContainsStatus(v.Status)
select v;
}
private bool ContainsStatus(v.Status)
{
foreach(Enum value in Enum.GetValues(typeof(buildingStatus)))
{
If v.Status == value.GetCharValue();
return true;
}
return false;
}
"ABCDEFG".chars.each do |char|
puts char
end
also
"ABCDEFG".each_char {|char| p char}
Ruby version >2.5.1
Make sure that your Spring form mentions the modelAttribute="<Model Name"
.
Example:
@Controller
@RequestMapping("/greeting.html")
public class GreetingController {
@ModelAttribute("greeting")
public Greeting getGreetingObject() {
return new Greeting();
}
/**
* GET
*
*
*/
@RequestMapping(method = RequestMethod.GET)
public String handleRequest() {
return "greeting";
}
/**
* POST
*
*
*/
@RequestMapping(method = RequestMethod.POST)
public ModelAndView processSubmit(@ModelAttribute("greeting") Greeting greeting, BindingResult result){
ModelAndView mv = new ModelAndView();
mv.addObject("greeting", greeting);
return mv;
}
}
In your JSP :
<form:form modelAttribute="greeting" method="POST" action="greeting.html">
If I were you I'd just use a scanner and use ".nextByte()". You can cast that to a char and you're good.
Why use freopen()
? The C89 specification has the answer in one of the endnotes for the section on <stdio.h>
:
116. The primary use of the
freopen
function is to change the file associated with a standard text stream (stderr
,stdin
, orstdout
), as those identifiers need not be modifiable lvalues to which the value returned by thefopen
function may be assigned.
freopen
is commonly misused, e.g. stdin = freopen("newin", "r", stdin);
. This is no more portable than fclose(stdin); stdin = fopen("newin", "r");
. Both expressions attempt to assign to stdin
, which is not guaranteed to be assignable.
The right way to use freopen
is to omit the assignment: freopen("newin", "r", stdin);
Another option is to use
#include <process.h>
system("pause");
Though this is not very portable because it will only work on Windows, but it will automatically print
Press any key to continue...
Niyaz is correct, but it's also worth noting that the special + operator can be converted into something more efficient by the Java compiler. Java has a StringBuilder class which represents a non-thread-safe, mutable String. When performing a bunch of String concatenations, the Java compiler silently converts
String a = b + c + d;
into
String a = new StringBuilder(b).append(c).append(d).toString();
which for large strings is significantly more efficient. As far as I know, this does not happen when you use the concat method.
However, the concat method is more efficient when concatenating an empty String onto an existing String. In this case, the JVM does not need to create a new String object and can simply return the existing one. See the concat documentation to confirm this.
So if you're super-concerned about efficiency then you should use the concat method when concatenating possibly-empty Strings, and use + otherwise. However, the performance difference should be negligible and you probably shouldn't ever worry about this.
for a 2-D tensor, you can get the number of rows and columns as int32 using the following code:
rows, columns = map(lambda i: i.value, tensor.get_shape())
In cpp, you need to pay special attention to string types when using execvp
:
#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
#include <unistd.h>
using namespace std;
const size_t MAX_ARGC = 15; // 1 command + # of arguments
char* argv[MAX_ARGC + 1]; // Needs +1 because of the null terminator at the end
// c_str() converts string to const char*, strdup converts const char* to char*
argv[0] = strdup(command.c_str());
// start filling up the arguments after the first command
size_t arg_i = 1;
while (cin && arg_i < MAX_ARGC) {
string arg;
cin >> arg;
if (arg.empty()) {
argv[arg_i] = nullptr;
break;
} else {
argv[arg_i] = strdup(arg.c_str());
}
++arg_i;
}
// Run the command with arguments
if (execvp(command.c_str(), argv) == -1) {
// Print error if command not found
cerr << "command '" << command << "' not found\n";
}
Reference: execlp?execvp?????
First Install Dynamic Tools --> NuGet Package Manager --> Package Manager Console
install-package System.Linq.Dynamic
Add Namespace using System.Linq.Dynamic;
Now you can use OrderBy("Name, Age DESC")
For everyone using Laravel 5, Homestead and Mac try this:
mkdir storage/framework/views
Note : this does not deal with history for sensitive information.
This process definitely takes some undertanding of what is going on with git. Over time, having gained that, I've learned to do processes such as:
.gitignore
to ignore them - in many cases such as yours, the parent directory, e.g. log/
will be the regex to use..gitignore
file change (not sure if push needed mind you, no harm if done).git remove --cached some_dir/
git add .
git commit -m"removal"
I'm not a git expert, but I think this should work:
git clone http://git.abc.net/git/abc.git
cd abc
git checkout my_abc
OR
git clone http://git.abc.net/git/abc.git
cd abc
git checkout -b new_branch my_abc
The second variation establishes a new branch based on the tag, which lets you avoid a 'detached HEAD'. (git-checkout manual)
Every git repo contains the entire revision history, so cloning the repo gives you access to the latest commit, plus everything that came before, including the tag you're looking for.
If you have just added FCM to an existing app, onTokenRefresh()
will NOT be called. I got it to run by uninstalling the app and installing it again.
An all-pairs shortest path algorithm will compute the shortest paths between all vertices in a graph. This will allow paths to be pre-computed instead of requiring a path to be calculated each time someone wants to find the shortest path between a source and a destination. The Floyd-Warshall algorithm is an all-pairs shortest path algorithm.
If you facing grant permission access denied problem, you can try mysql_upgrade to fix the problem:
/usr/bin/mysql_upgrade -u root -p
Login as root:
mysql -u root -p
Run this commands:
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
mysql> FLUSH PRIVILEGES;
These days, you can leverage the .NET library from VBA. The following works for me in Excel 2016. Returns the hash as uppercase hex.
Public Function SHA1(ByVal s As String) As String
Dim Enc As Object, Prov As Object
Dim Hash() As Byte, i As Integer
Set Enc = CreateObject("System.Text.UTF8Encoding")
Set Prov = CreateObject("System.Security.Cryptography.SHA1CryptoServiceProvider")
Hash = Prov.ComputeHash_2(Enc.GetBytes_4(s))
SHA1 = ""
For i = LBound(Hash) To UBound(Hash)
SHA1 = SHA1 & Hex(Hash(i) \ 16) & Hex(Hash(i) Mod 16)
Next
End Function
Alexy's answer almost worked for me except that I was getting this error:
timebase 1/90000 not supported by MPEG 4 standard, the maximum admitted value for the timebase denominator is 65535
I just had to add a parameter (-r 65535/2733) to the command and it worked. The full command was thus:
ffmpeg -i in.mp4 -vf "transpose=1" -r 65535/2733 out.mp4
You partial looks much like an editor template so you could include it as such (assuming of course that your partial is placed in the ~/views/controllername/EditorTemplates
subfolder):
@Html.EditorFor(model => model.SomePropertyOfTypeLocaleBaseModel)
Or if this is not the case simply:
@Html.Partial("nameOfPartial", Model)
v-model
it is two way data binding, it is used to bind html input element when you change input value then bounded data will be change.
v-model is used only for HTML input elements
ex: <input type="text" v-model="name" >
v-bind
it is one way data binding,means you can only bind data to input element but can't change bounded data changing input element.
v-bind is used to bind html attribute
ex:
<input type="text" v-bind:class="abc" v-bind:value="">
<a v-bind:href="home/abc" > click me </a>
On python3, this function will get the outer most name in the stack:
import inspect
def retrieve_name(var):
"""
Gets the name of var. Does it from the out most frame inner-wards.
:param var: variable to get name from.
:return: string
"""
for fi in reversed(inspect.stack()):
names = [var_name for var_name, var_val in fi.frame.f_locals.items() if var_val is var]
if len(names) > 0:
return names[0]
It is useful anywhere on the code. Traverses the reversed stack looking for the first match.
In Javascript, replace function available to replace sub-string from given string with new one. Use:
var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
console.log(new_text);
You can even use regular expression with this function. For example, if want to replace all occurrences of ,
with .
.
var text = "123,123,123";
var new_text = text.replace(/,/g, ".");
console.log(new_text);
Here g
modifier used to match globally all available matches.
$options = array(
'options' => array('min_range' => 0)
);
if (filter_var($int, FILTER_VALIDATE_INT, $options) !== FALSE) {
// you're good
}
We can use params
, new feature of the UI-Router:
API Reference / ui.router.state / $stateProvider
params
A map which optionally configures parameters declared in the url, or defines additional non-url parameters. For each parameter being configured, add a configuration object keyed to the name of the parameter.
See the part: "...or defines additional non-url parameters..."
So the state def would be:
$stateProvider
.state('home', {
url: "/home",
templateUrl: 'tpl.html',
params: { hiddenOne: null, }
})
Few examples form the doc mentioned above:
// define a parameter's default value
params: {
param1: { value: "defaultValue" }
}
// shorthand default values
params: {
param1: "defaultValue",
param2: "param2Default"
}
// param will be array []
params: {
param1: { array: true }
}
// handling the default value in url:
params: {
param1: {
value: "defaultId",
squash: true
} }
// squash "defaultValue" to "~"
params: {
param1: {
value: "defaultValue",
squash: "~"
} }
EXTEND - working example: http://plnkr.co/edit/inFhDmP42AQyeUBmyIVl?p=info
Here is an example of a state definition:
$stateProvider
.state('home', {
url: "/home",
params : { veryLongParamHome: null, },
...
})
.state('parent', {
url: "/parent",
params : { veryLongParamParent: null, },
...
})
.state('parent.child', {
url: "/child",
params : { veryLongParamChild: null, },
...
})
This could be a call using ui-sref:
<a ui-sref="home({veryLongParamHome:'Home--f8d218ae-d998-4aa4-94ee-f27144a21238'
})">home</a>
<a ui-sref="parent({
veryLongParamParent:'Parent--2852f22c-dc85-41af-9064-d365bc4fc822'
})">parent</a>
<a ui-sref="parent.child({
veryLongParamParent:'Parent--0b2a585f-fcef-4462-b656-544e4575fca5',
veryLongParamChild:'Child--f8d218ae-d998-4aa4-94ee-f27144a61238'
})">parent.child</a>
Check the example here
Header header = new Header();
Byte[] headerBytes = new Byte[Marshal.SizeOf(header)];
Marshal.Copy((IntPtr)(&header), headerBytes, 0, headerBytes.Length);
This should do the trick quickly, right?
You can store the promise returned by the interval and use $interval.cancel()
to that promise, which cancels the interval of that promise. To delegate the starting and stopping of the interval, you can create start()
and stop()
functions whenever you want to stop and start them again from a specific event. I have created a snippet below showing the basics of starting and stopping an interval, by implementing it in view through the use of events (e.g. ng-click
) and in the controller.
angular.module('app', [])_x000D_
_x000D_
.controller('ItemController', function($scope, $interval) {_x000D_
_x000D_
// store the interval promise in this variable_x000D_
var promise;_x000D_
_x000D_
// simulated items array_x000D_
$scope.items = [];_x000D_
_x000D_
// starts the interval_x000D_
$scope.start = function() {_x000D_
// stops any running interval to avoid two intervals running at the same time_x000D_
$scope.stop(); _x000D_
_x000D_
// store the interval promise_x000D_
promise = $interval(setRandomizedCollection, 1000);_x000D_
};_x000D_
_x000D_
// stops the interval_x000D_
$scope.stop = function() {_x000D_
$interval.cancel(promise);_x000D_
};_x000D_
_x000D_
// starting the interval by default_x000D_
$scope.start();_x000D_
_x000D_
// stops the interval when the scope is destroyed,_x000D_
// this usually happens when a route is changed and _x000D_
// the ItemsController $scope gets destroyed. The_x000D_
// destruction of the ItemsController scope does not_x000D_
// guarantee the stopping of any intervals, you must_x000D_
// be responsible for stopping it when the scope is_x000D_
// is destroyed._x000D_
$scope.$on('$destroy', function() {_x000D_
$scope.stop();_x000D_
});_x000D_
_x000D_
function setRandomizedCollection() {_x000D_
// items to randomize 1 - 11_x000D_
var randomItems = parseInt(Math.random() * 10 + 1); _x000D_
_x000D_
// empties the items array_x000D_
$scope.items.length = 0; _x000D_
_x000D_
// loop through random N times_x000D_
while(randomItems--) {_x000D_
_x000D_
// push random number from 1 - 10000 to $scope.items_x000D_
$scope.items.push(parseInt(Math.random() * 10000 + 1)); _x000D_
}_x000D_
}_x000D_
_x000D_
});
_x000D_
<div ng-app="app" ng-controller="ItemController">_x000D_
_x000D_
<!-- Event trigger to start the interval -->_x000D_
<button type="button" ng-click="start()">Start Interval</button>_x000D_
_x000D_
<!-- Event trigger to stop the interval -->_x000D_
<button type="button" ng-click="stop()">Stop Interval</button>_x000D_
_x000D_
<!-- display all the random items -->_x000D_
<ul>_x000D_
<li ng-repeat="item in items track by $index" ng-bind="item"></li>_x000D_
</ul>_x000D_
<!-- end of display -->_x000D_
</div>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
_x000D_
I used this
:top
cls
type G:\empty.txt
type I:\empty.txt
timeout /T 500
goto top
If you want to use embedded H2 database from Spring Boot starter add the below dependency to your pom file.
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.156</version>
</dependency>
But as mentioned in comments, the embedded H2 database keeps data in memory and doesn't stores it permanently.
If you want a rounded corner only to one corner or two corners, etc... read this post:
[ObjC] – UIButton with rounded corner - http://goo.gl/kfzvKP
It's a XIB/Storyboard subclass. Import and set borders without write code.
These toolz are great for this kind of simple yet repetitive logic.
http://toolz.readthedocs.org/en/latest/api.html#toolz.dicttoolz.valmap
Gets you right where you want to be.
import toolz
def f(x):
return x+1
toolz.valmap(f, my_list)
Here's one that works for both Mac and Linux:
netstat -aln | awk '$6 == "LISTEN" && $4 ~ "[\\.\:]445$"'
I've seen many of the proposed solutions, but none were quite what I was hoping.
Here's my best hack at this, where the color is transparent, the background and the top text-shadow are the same color with varying opacities, simulating the mask, and the second text-shadow is a darker, more saturated version of the color you actually want (pretty easy to do with HSLA).
(btw, text and styling based upon a dupe thread's OP)
>
is the child combinator, sometimes mistakenly called the direct descendant combinator.1
That means the selector div > p.some_class
only selects paragraphs of .some_class
that are nested directly inside a div
, and not any paragraphs that are nested further within.
An illustration:
div > p.some_class {
background: yellow;
}
_x000D_
<div>
<p class="some_class">Some text here</p> <!-- Selected [1] -->
<blockquote>
<p class="some_class">More text here</p> <!-- Not selected [2] -->
</blockquote>
</div>
_x000D_
What's selected and what's not:
Selected
This p.some_class
is located directly inside the div
, hence a parent-child relationship is established between both elements.
Not selected
This p.some_class
is contained by a blockquote
within the div
, rather than the div
itself. Although this p.some_class
is a descendant of the div
, it's not a child; it's a grandchild.
Consequently, while div > p.some_class
won't match this element, div p.some_class
will, using the descendant combinator instead.
1 Many people go further to call it "direct child" or "immediate child", but that's completely unnecessary (and incredibly annoying to me), because a child element is immediate by definition anyway, so they mean the exact same thing. There's no such thing as an "indirect child".
IMHO, the 'cleanest' way to select the First, visible, enabled text field on the page, is to use jQuery and do something like this:
$(document).ready(function() {
$('input:text[value=""]:visible:enabled:first').focus();
});
Hope that helps...
Thanks...
In my case service address in wsdl is wrong.
My wsdl url is.
https://myweb.com:4460/xxx_webservices/services/ABC.ABC?wsdl
But service address in that xml result is.
<soap:address location="http://myweb.com:8080/xxx_webservices/services/ABC.ABC/"/>
I just save that xml to local file and change service address to.
<soap:address location="https://myweb.com:4460/xxx_webservices/services/ABC.ABC/"/>
Good luck.
Use Directory.GetDirectories
to get the subdirectories of the directory specified by "your_directory_path". The result is an array of strings.
var directories = Directory.GetDirectories("your_directory_path");
By default, that only returns subdirectories one level deep. There are options to return all recursively and to filter the results, documented here, and shown in Clive's answer.
Avoiding an UnauthorizedAccessException
It's easily possible that you'll get an UnauthorizedAccessException
if you hit a directory to which you don't have access.
You may have to create your own method that handles the exception, like this:
public class CustomSearcher
{
public static List<string> GetDirectories(string path, string searchPattern = "*",
SearchOption searchOption = SearchOption.AllDirectories)
{
if (searchOption == SearchOption.TopDirectoryOnly)
return Directory.GetDirectories(path, searchPattern).ToList();
var directories = new List<string>(GetDirectories(path, searchPattern));
for (var i = 0; i < directories.Count; i++)
directories.AddRange(GetDirectories(directories[i], searchPattern));
return directories;
}
private static List<string> GetDirectories(string path, string searchPattern)
{
try
{
return Directory.GetDirectories(path, searchPattern).ToList();
}
catch (UnauthorizedAccessException)
{
return new List<string>();
}
}
}
And then call it like this:
var directories = CustomSearcher.GetDirectories("your_directory_path");
This traverses a directory and all its subdirectories recursively. If it hits a subdirectory that it cannot access, something that would've thrown an UnauthorizedAccessException
, it catches the exception and just returns an empty list for that inaccessible directory. Then it continues on to the next subdirectory.
style.css
is actually being process via fastcgi due to your "location /" directive. So it is fastcgi that is serving up the file (nginx > fastcgi > filesystem
), and not the filesystem directly (nginx > filesystem
).
For a reason I have yet to figure out (I'm sure there's a directive somewhere), NGINX applies the mime type text/html
to anything being served from fastcgi, unless the backend application explicitly says otherwise.
The culprit is this configuration block specifically:
location / {
root /usr/share/nginx/html;
index index.html index.htm index.php;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html$fastcgi_script_name;
include fastcgi_params;
}
It should be:
location ~ \.php$ { # this line
root /usr/share/nginx/html;
index index.html index.htm index.php;
fastcgi_split_path_info ^(.+\.php)(/.+)$; #this line
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; # update this too
include fastcgi_params;
}
This change makes sure only *.php
files are requested from fastcgi. At this point, NGINX will apply the correct MIME type. If you have any URL rewriting happening, you must handle this before the location directive (location ~\.php$
) so that the correct extension is derived and properly routed to fastcgi.
Be sure to check out this article regarding additional security considerations using try_files
. Given the security implications, I consider this a feature and not a bug.
After declaring the array
int boardAux[length][length];
the simplest way to assign the initial values as zero is using for loop, even if it may be a bit lengthy
int i, j;
for (i = 0; i<length; i++)
{
for (j = 0; j<length; j++)
boardAux[i][j] = 0;
}
http://www.useragentstring.com/
Visit that page, it'll give you a good explanation of each element of your user agent.
Mozilla:
MozillaProductSlice. Claims to be a Mozilla based user agent, which is only true for Gecko browsers like Firefox and Netscape. For all other user agents it means 'Mozilla-compatible'. In modern browsers, this is only used for historical reasons. It has no real meaning anymore
On Android, colors are can be specified as RGB or ARGB.
http://en.wikipedia.org/wiki/ARGB
In RGB you have two characters for every color (red, green, blue), and in ARGB you have two additional chars for the alpha channel.
So, if you have 8 characters, it's ARGB, with the first two characters specifying the alpha channel. If you remove the leading two characters it's only RGB (solid colors, no alpha/transparency). If you want to specify a color in your Java source code, you have to use:
int Color.argb (int alpha, int red, int green, int blue)
alpha Alpha component [0..255] of the color
red Red component [0..255] of the color
green Green component [0..255] of the color
blue Blue component [0..255] of the color
Reference: argb
In CSS3 you have:
:nth-last-child(2)
See: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child
nth-last-child Browser Support:
- Chrome 2
- Firefox 3.5
- Opera 9.5, 10
- Safari 3.1, 4
- Internet Explorer 9
You can use forEach method to iterate over array of objects.
data.messages.forEach(function(message){
console.log(message)
});
Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
What does it mean with local variable? Is that a function local variable?
Yes - Non-global, such as a function local variable.
Because there's also that when you declare a function local as static that it is only initialized once, the first time it enters this function.
Right.
It also only talks about storage duration with regards to class members, what about it being non instance specific, that's also a property of static no? Or is that storage duration?
class R { static int a; }; // << static lives for the duration of the program
that is to say, all instances of R
share int R::a
-- int R::a
is never copied.
Now what about the case with static and file scope?
Effectively a global which has constructor/destructor where appropriate -- initialization is not deferred until access.
How does static relate to the linkage of a variable?
For a function local, it is external. Access: It's accessible to the function (unless of course, you return it).
For a class, it is external. Access: Standard access specifiers apply (public, protected, private).
static
can also specify internal linkage, depending on where it's declared (file/namespace).
This whole static keyword is downright confusing
It has too many purposes in C++.
can someone clarify the different uses for it English and also tell me when to initialize a static class member?
It's automatically initialized before main
if it's loaded and has a constructor. That might sound like a good thing, but initialization order is largely beyond your control, so complex initialization becomes very difficult to maintain, and you want to minimize this -- if you must have a static, then function local scales much better across libraries and projects. As far as data with static storage duration, you should try to minimize this design, particularly if mutable (global variables). Initialization 'time' also varies for a number of reasons -- the loader and kernel have some tricks to minimize memory footprints and defer initialization, depending on the data in question.
Following Mike's answer, I'd also add another step. Let's imagine you have your data in column A.
Hope it helps.
Ofc, if the word you want to add will always be the same, you won't need a column B (thus, C1="k"+A1)
Rgds
This may not help answer your question directly but is something I have found useful when trying to work with dynamic ranges that may help you out.
Suppose in your worksheet you have the numbers 100 to 108 in cells A1:C3:
A B C
1 100 101 102
2 103 104 105
3 106 107 108
Then to select all the cells you can use the CurrentRegion
property:
Sub SelectRange()
Dim dynamicRange As Range
Set dynamicRange = Range("A1").CurrentRegion
End Sub
The advantage of this is that if you add new rows or columns to your block of numbers (e.g. 109, 110, 111) then the CurrentRegion will always reference the enlarged range (in this case A1:C4).
I have used CurrentRegion quite a bit in my VBA code and find it is most useful when working with dynmacially sized ranges. Also it avoids having to hard code ranges in your code.
As a final note, in my code you will see that I used A1 as the reference cell for CurrentRegion. It will also work no matter which cell you reference (try: replacing A1 with B2 for example). The reason is that CurrentRegion will select all contiguous cells based on the reference cell.
If your test and webapp are in the same Maven project, you can use a property in the project POM. Then you can filter certain files which will allow Maven to set the property in those files. There are different ways to filter, but the most common is during the resources phase - http://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-description.html
If the test and webapp are in different Maven projects, you can put the property in settings.xml, which is in your maven repository folder (C:\Documents and Settings\username.m2) on Windows. You will still need to use filtering or some other method to read the property into your test and webapp.
JQUERY FORMATCURRENCY PLUGIN
http://code.google.com/p/jquery-formatcurrency/
If you are looking to create a mask for an image and position the image inside the container don't set the 'position: absolute' attribute. All you have to do is change the margin-left and margin-right. Chrome/Opera will adhere to the overflow: hidden and border-radius rules.
// Breaks in Chrome/Opera.
.container {
overflow: hidden;
border-radius: 50%;
img {
position: absolute;
left: 20px;
right: 20px;
}
}
// Works in Chrome/Opera.
.container {
overflow: hidden;
border-radius: 50%;
img {
margin-left: 20px;
margin-right: 20px;
}
}
Since the other answers explained how to do it without actually explaining why it works:
When the switch
executes, it finds the first matching case
statement and then executes each line of code after the switch until it hits either a break
statement or the end of the switch
(or a return
statement to leave the entire containing function). When you deliberately omit the break
so that code under the next case
gets executed too that's called a fall-through. So for the OP's requirement:
switch (pageid) {
case "listing-page":
case "home-page":
alert("hello");
break;
case "details-page":
alert("goodbye");
break;
}
Forgetting to include break
statements is a fairly common coding mistake and is the first thing you should look for if your switch
isn't working the way you expected. For that reason some people like to put a comment in to say "fall through" to make it clear when break statements have been omitted on purpose. I do that in the following example since it is a bit more complicated and shows how some cases can include code to execute before they fall-through:
switch (someVar) {
case 1:
someFunction();
alert("It was 1");
// fall through
case 2:
alert("The 2 case");
// fall through
case 3:
// fall through
case 4:
// fall through
case 5:
alert("The 5 case");
// fall through
case 6:
alert("The 6 case");
break;
case 7:
alert("Something else");
break;
case 8:
// fall through
default:
alert("The end");
break;
}
You can also (optionally) include a default
case, which will be executed if none of the other cases match - if you don't include a default
and no cases match then nothing happens. You can (optionally) fall through to the default case.
So in my second example if someVar
is 1 it would call someFunction()
and then you would see four alerts as it falls through multiple cases some of which have alerts under them. Is someVar
is 3, 4 or 5 you'd see two alerts. If someVar
is 7 you'd see "Something else" and if it is 8 or any other value you'd see "The end".
The filesystem of the emulator doesn't map to a directory on your hard drive. The emulator's disk image is stored as an image file, which you can manage through either Eclipse (look for the G1-looking icon in the toolbar), or through the emulator binary itself (run "emulator -help" for a description of options).
You're best off using adb from the command line to jack into a running emulator. If you can get the specific directory and filename, you can do an "adb pull" to get the database file off of the emulator and onto your regular hard drive.
Edit: Removed suggestion that this works for unrooted devices too - it only works for emulators, and devices where you are operating adb as root.
I know replaceAll method is much easier but I wanted to post this as well.
public static String removeExtraSpace(String input) {
input= input.trim();
ArrayList <String> x= new ArrayList<>(Arrays.asList(input.split("")));
for(int i=0; i<x.size()-1;i++) {
if(x.get(i).equals(" ") && x.get(i+1).equals(" ")) {
x.remove(i);
i--;
}
}
String word="";
for(String each: x)
word+=each;
return word;
}
<input type="password"id="har">
<input type="submit"value="get password"onclick="har()">
<script>
function har() {
var txt_val;
txt_val = document.getElementById("har").value;
alert(txt_val);
}
</script>
You may want to look into the profile modules. You'll get a better read out of where your slowdowns are, and much of your work will be full-on automated.
Simply use mysql_fetch_assoc and count the array using count() function
Use this.dispose
for current window to close and next_window.setVisible(true)
to show next window behind button property ActionPerformed
, Example is shown below in pic for your help.
If you are mocking the behavior (with something like doNothing()
) there should really be no need to call to verify*()
. That said, here's my stab at re-writing your test method:
@PrepareForTest({InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest { //Note the renaming of the test class.
public void testProcessOrder() {
//Variables
InternalService is = new InternalService();
Order order = mock(Order.class);
//Mock Behavior
when(order.isSuccessful()).thenReturn(true);
mockStatic(Internalutils.class);
doNothing().when(InternalUtils.class); //This is the preferred way
//to mock static void methods.
InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());
//Execute
is.processOrder(order);
//Verify
verifyStatic(InternalUtils.class); //Similar to how you mock static methods
//this is how you verify them.
InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());
}
}
I grouped into four sections to better highlight what is going on:
I choose to declare any instance variables / method arguments / mock collaborators here. If it is something used in multiple tests, consider making it an instance variable of the test class.
This is where you define the behavior of all of your mocks. You're setting up return values and expectations here, prior to executing the code under test. Generally speaking, if you set the mock behavior here you wouldn't need to verify the behavior later.
Nothing fancy here; this just kicks off the code being tested. I like to give it its own section to call attention to it.
This is when you call any method starting with verify
or assert
. After the test is over, you check that the things you wanted to have happen actually did happen. That is the biggest mistake I see with your test method; you attempted to verify the method call before it was ever given a chance to run. Second to that is you never specified which static method you wanted to verify.
This is mostly personal preference on my part. There is a certain order you need to do things in but within each grouping there is a little wiggle room. This helps me quickly separate out what is happening where.
I also highly recommend going through the examples at the following sites as they are very robust and can help with the majority of the cases you'll need:
You can get a more detailed list (e.g. structured by defining class) with gems like debugging or looksee.
#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29
assuming v is a ArrayList:
String[] x = (String[]) v.toArray(new String[0]);
You need to rearrange your curly brackets. Your first statement is complete, so R interprets it as such and produces syntax errors on the other lines. Your code should look like:
if (dsnt<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else if (dst<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else {
t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
}
To put it more simply, if you have:
if(condition == TRUE) x <- TRUE
else x <- FALSE
Then R reads the first line and because it is complete, runs that in its entirety. When it gets to the next line, it goes "Else? Else what?" because it is a completely new statement. To have R interpret the else as part of the preceding if statement, you must have curly brackets to tell R that you aren't yet finished:
if(condition == TRUE) {x <- TRUE
} else {x <- FALSE}
OPTION 1: if you want to make a common utility function then you can use this
export function getCurrentDate(separator=''){
let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();
return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}
and use it by just importing it as
import {getCurrentDate} from './utils'
console.log(getCurrentDate())
OPTION 2: or define and use in a class directly
getCurrentDate(separator=''){
let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();
return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}
.env
and .env.production
VUE_APP_
eg: VUE_APP_WHATEVERYOUWANT
.env
and build uses .env.production
process.env.VUE_APP_WHATEVERYOUWANT
to call valueBe sure you are using vue-cli version 3 or above
For more information: https://cli.vuejs.org/guide/mode-and-env.html
You may be trying to use a JSON object:
var myMappings = { "name": "10%", "phone": "10%", "address": "50%", etc.. }
To access:
myMappings.name;
myMappings.phone;
etc..
Simply cleaning the project has worked for me every time this error has come up.
This should get you started: Using VBA in your own Excel workbook, have it prompt the user for the filename of their data file, then just copy that fixed range into your target workbook (that could be either the same workbook as your macro enabled one, or a third workbook). Here's a quick vba example of how that works:
' Get customer workbook...
Dim customerBook As Workbook
Dim filter As String
Dim caption As String
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetWorkbook As Workbook
' make weak assumption that active workbook is the target
Set targetWorkbook = Application.ActiveWorkbook
' get the customer workbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please Select an input file "
customerFilename = Application.GetOpenFilename(filter, , caption)
Set customerWorkbook = Application.Workbooks.Open(customerFilename)
' assume range is A1 - C10 in sheet1
' copy data from customer to target workbook
Dim targetSheet As Worksheet
Set targetSheet = targetWorkbook.Worksheets(1)
Dim sourceSheet As Worksheet
Set sourceSheet = customerWorkbook.Worksheets(1)
targetSheet.Range("A1", "C10").Value = sourceSheet.Range("A1", "C10").Value
' Close customer workbook
customerWorkbook.Close
// $scope.dateField="value" in ctrl
<div ng-bind="dateField | date:'MM/dd/yyyy'"></div>
There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :
Option Explicit
DIM fso
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists("C:\Program Files\conf")) Then
WScript.Echo("File exists!")
WScript.Quit()
Else
WScript.Echo("File does not exist!")
End If
WScript.Quit()
I had the same problem and a simple solution that I found was:
List<Object[]> results = query.getResultList();
for (Object[] result: results) {
SomeClass something = (SomeClass)result[1];
something.doSomething;
}
I know this is defenitly not the most elegant solution nor is it best practice but it works, at least for me.
Always check if your java files are in src/main/java and not on some other directory path.
What i have done is that import a new project into eclipse workspace, and that path of that was be
android-sdk-macosx/extras/google/google_play_services/libproject/google-play-services_lib
and add as library in your project.. that it .. simple!! you might require to add support library in your project.
you can use Word Mover's Distance algorithm. here is an easy description about WMD.
#load word2vec model, here GoogleNews is used
model = gensim.models.KeyedVectors.load_word2vec_format('../GoogleNews-vectors-negative300.bin', binary=True)
#two sample sentences
s1 = 'the first sentence'
s2 = 'the second text'
#calculate distance between two sentences using WMD algorithm
distance = model.wmdistance(s1, s2)
print ('distance = %.3f' % distance)
P.s.: if you face an error about import pyemd library, you can install it using following command:
pip install pyemd
There are apparently distributions or custom builds in which the ability to set Task Tags for non-Java files is not present. This post mentions that ColdFusion Builder (built on Eclipse) does not let you set non-Java Task Tags, but the beta version of CF Builder 2 does. (I know the OP wasn't using CF Builder, but I am, and I was wondering about this question myself ... because he didn't see the ability to set non-Java tags, I thought others might be in the same position.)
Please try the below XAML snippet:
<Button Width="300" Height="50">
<StackPanel Orientation="Horizontal">
<Image Source="Pictures/img.jpg" Width="20" Height="20"/>
<TextBlock Text="Blablabla" VerticalAlignment="Center" />
</StackPanel>
</Button>
In XAML elements are in a tree structure. So you have to add the child control to its parent control. The below code snippet also works fine. Give a name for your XAML root grid as 'MainGrid'.
Image img = new Image();
img.Source = new BitmapImage(new Uri(@"foo.png"));
StackPanel stackPnl = new StackPanel();
stackPnl.Orientation = Orientation.Horizontal;
stackPnl.Margin = new Thickness(10);
stackPnl.Children.Add(img);
Button btn = new Button();
btn.Content = stackPnl;
MainGrid.Children.Add(btn);
This is what I normally do with my projects:
npm version patch
git add *;
git commit -m "Commit message"
git push
npm publish
The first line, npm version patch
, will increase the patch version by 1 (x.x.1 to x.x.2) in package.json
. Then you add all files -- including package.json
which at that point has been modified.
Then, the usual git commit
and git push
, and finally npm publish
to publish the module.
I hope this makes sense...
Merc.
A combination of @Jack's answer and @ranierbit's answer should do the trick.
Set the ng build flag for --output-hashing so:
ng build --output-hashing=all
Then add this class either in a service or in your app.module
@Injectable()
export class NoCacheHeadersInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
const authReq = req.clone({
setHeaders: {
'Cache-Control': 'no-cache',
Pragma: 'no-cache'
}
});
return next.handle(authReq);
}
}
Then add this to your providers in your app.module
:
providers: [
... // other providers
{
provide: HTTP_INTERCEPTORS,
useClass: NoCacheHeadersInterceptor,
multi: true
},
... // other providers
]
This should prevent caching issues on live sites for client machines
More simple way...:
Dim dt As DataTable = DirectCast(GridView1.DataSource, DataTable)
Dim dv As New DataView(dt)
If GridView1.Attributes("dir") = SortDirection.Ascending Then
dv.Sort = e.SortExpression & " DESC"
GridView1.Attributes("dir") = SortDirection.Descending
Else
GridView1.Attributes("dir") = SortDirection.Ascending
dv.Sort = e.SortExpression & " ASC"
End If
GridView1.DataSource = dv
GridView1.DataBind()
You can opt to create your own custom events so you'll still have a clear separation of logic.
Bind to a custom event:
$('#laneconfigdisplay').bind('contentchanged', function() {
// do something after the div content has changed
alert('woo');
});
In your function that updates the div:
// all logic for grabbing xml and updating the div here ..
// and then send a message/event that we have updated the div
$('#laneconfigdisplay').trigger('contentchanged'); // this will call the function above
Here's a nice way of doing that.
static bool IsPrime(int n)
{
if (n > 1)
{
return Enumerable.Range(1, n).Where(x => n%x == 0)
.SequenceEqual(new[] {1, n});
}
return false;
}
And a quick way of writing your program will be:
for (;;)
{
Console.Write("Accept number: ");
int n = int.Parse(Console.ReadLine());
if (IsPrime(n))
{
Console.WriteLine("{0} is a prime number",n);
}
else
{
Console.WriteLine("{0} is not a prime number",n);
}
}
Warning, Chrome (and other browsers) will complain that multiple ACAO headers are set if you follow some of the other answers.
The error will be something like XMLHttpRequest cannot load ____. The 'Access-Control-Allow-Origin' header contains multiple values '____, ____, ____', but only one is allowed. Origin '____' is therefore not allowed access.
Try this:
$http_origin = $_SERVER['HTTP_ORIGIN'];
$allowed_domains = array(
'http://domain1.com',
'http://domain2.com',
);
if (in_array($http_origin, $allowed_domains))
{
header("Access-Control-Allow-Origin: $http_origin");
}
You could use THROW
(available in SQL Server 2012+):
THROW 50000, 'Your custom error message', 1
THROW <error_number>, <message>, <state>
When pthread_exit() is called, the calling threads stack is no longer addressable as "active" memory for any other thread. The .data, .text and .bss parts of "static" memory allocations are still available to all other threads. Thus, if you need to pass some memory value into pthread_exit() for some other pthread_join() caller to see, it needs to be "available" for the thread calling pthread_join() to use. It should be allocated with malloc()/new, allocated on the pthread_join threads stack, 1) a stack value which the pthread_join caller passed to pthread_create or otherwise made available to the thread calling pthread_exit(), or 2) a static .bss allocated value.
It's vital to understand how memory is managed between a threads stack, and values store in .data/.bss memory sections which are used to store process wide values.
Something like this should solve your problem:
$.getDocHeight = function(){
var D = document;
return Math.max(Math.max(D.body.scrollHeight, D.documentElement.scrollHeight), Math.max(D.body.offsetHeight, D.documentElement.offsetHeight), Math.max(D.body.clientHeight, D.documentElement.clientHeight));
};
alert( $.getDocHeight() );
Ps: Call that function every time you need it, the alert is for testing purposes..
Use Not IsEmpty()
.
For example:
Sub DoStuffIfNotEmpty()
If Not IsEmpty(ActiveCell.Value) Then
MsgBox "I'm not empty!"
End If
End Sub
I am just going to post the answer for python so people will have a reference.
from win32com.client import Dispatch
from win32com.client import constants
import win32com.client
xlApp = Dispatch("Excel.Application")
xlWb = xlApp.Workbooks.Open(filename_xls)
ws = xlWb.Worksheets(1)
xlApp.Visible=False
xlWbTemplate = xlApp.Workbooks.Open('otherfile.xls')
ws_sub = xlWbTemplate.Worksheets(1)
ws_sub.Activate()
xlWbTemplate.Worksheets(2).Copy(None,xlWb.Worksheets(1))
ws_sub = xlWbTemplate.Worksheets(2)
ws_sub.Activate()
xlWbTemplate.Close(SaveChanges=0)
xlWb.Worksheets(1).Activate()
xlWb.Close(SaveChanges=1)
xlApp.Quit()
I tried 2 solutions, both work.
Solution_1
.yml
available-users-list:
configurations:
-
username: eXvn817zDinHun2QLQ==
password: IP2qP+BQfWKJMVeY7Q==
-
username: uwJlOl/jP6/fZLMm0w==
password: IP2qP+BQKJLIMVeY7Q==
LoginInfos.java
@ConfigurationProperties(prefix = "available-users-list")
@Configuration
@Component
@Data
public class LoginInfos {
private List<LoginInfo> configurations;
@Data
public static class LoginInfo {
private String username;
private String password;
}
}
List<LoginInfos.LoginInfo> list = loginInfos.getConfigurations();
Solution_2
.yml
available-users-list: '[{"username":"eXvn817zHBVn2QLQ==","password":"IfWKJLIMVeY7Q=="}, {"username":"uwJlOl/g9jP6/0w==","password":"IP2qWKJLIMVeY7Q=="}]'
Java
@Value("${available-users-listt}")
String testList;
ObjectMapper mapper = new ObjectMapper();
LoginInfos.LoginInfo[] array = mapper.readValue(testList, LoginInfos.LoginInfo[].class);
Pseudo-elements are treated as descendants of their associated element. To position a pseudo-element below its parent, you have to create a new stacking context to change the default stacking order.
Positioning the pseudo-element (absolute) and assigning a z-index value other than “auto” creates the new stacking context.
#element { _x000D_
position: relative; /* optional */_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background-color: blue;_x000D_
}_x000D_
_x000D_
#element::after {_x000D_
content: "";_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
background-color: red;_x000D_
_x000D_
/* create a new stacking context */_x000D_
position: absolute;_x000D_
z-index: -1; /* to be below the parent element */_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>Position a pseudo-element below its parent</title>_x000D_
</head>_x000D_
<body>_x000D_
<div id="element">_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Wrap code in
window.onload = function(){
// your code
};
As an addition and observation to the other useful answers, it's worth noticing that actually doing [:10]
as slicing will return the first 10 elements of the list, not the last 10...
To get the last 10 you should do [-10:]
instead (see here). This will help you avoid using order_by('-id')
with the -
to reverse the elements.
Add an id "question" to your input element and then try this:
if( document.getElementById('question').value === '' ){
alert('empty');
}
The reason your current code doesn't work is because you don't have a FORM tag in there. Also, lookup using "name" is not recommended as its deprecated.
See @Paul Dixon's answer in this post : Is the 'name' attribute considered outdated for <a> anchor tags?
Solution that helped me is: do not map DispatcherServlet
to /*
, map it to /
. Final config is then:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
...
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Add XAttribute
in the constructor of the XElement
, like
new XElement("Conn", new XAttribute("Server", comboBox1.Text));
You can also add multiple attributes or elements via the constructor
new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));
or you can use the Add-Method of the XElement
to add attributes
XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);
library(tidyverse)
x <- data.frame(Category= c('First', 'First', 'First', 'Second', 'Third', 'Third', 'Second'),
Frequency = c(10, 15, 5, 2, 14, 20, 3))
count(x, Category, wt = Frequency)
you need to make county_ID
as index for the right frame:
frame_2.join ( frame_1.set_index( [ 'county_ID' ], verify_integrity=True ),
on=[ 'countyid' ], how='left' )
for your information, in pandas left join breaks when the right frame has non unique values on the joining column. see this bug.
so you need to verify integrity before joining by , verify_integrity=True
honoring font family, dynamic font I've concocted this abomination:
extension NSAttributedString
{
convenience fileprivate init?(html: String, font: UIFont? = Font.dynamic(style: .subheadline))
{
guard let data = html.data(using: String.Encoding.utf8, allowLossyConversion: true) else {
var totalString = html
/*
https://stackoverflow.com/questions/32660748/how-to-use-apples-new-san-francisco-font-on-a-webpage
.AppleSystemUIFont I get in font.familyName does not work
while -apple-system does:
*/
var ffamily = "-apple-system"
if let font = font {
let lLDBsucks = font.familyName
if !lLDBsucks.hasPrefix(".appleSystem") {
ffamily = font.familyName
}
totalString = "<style>\nhtml * {font-family: \(ffamily) !important;}\n </style>\n" + html
}
guard let data = totalString.data(using: String.Encoding.utf8, allowLossyConversion: true) else {
return nil
}
assert(Thread.isMainThread)
guard let attributedText = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil) else {
return nil
}
let mutable = NSMutableAttributedString(attributedString: attributedText)
if let font = font {
do {
var found = false
mutable.beginEditing()
mutable.enumerateAttribute(NSAttributedString.Key.font, in: NSMakeRange(0, attributedText.length), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (value, range, stop) in
if let oldFont = value as? UIFont {
let newsize = oldFont.pointSize * 15 * Font.scaleHeruistic / 12
let newFont = oldFont.withSize(newsize)
mutable.addAttribute(NSAttributedString.Key.font, value: newFont, range: range)
found = true
}
}
if !found {
// No font was found - do something else?
}
mutable.endEditing()
// mutable.addAttribute(.font, value: font, range: NSRange(location: 0, length: mutable.length))
}
self.init(attributedString: mutable)
}
}
alternatively you can use the versions this was derived from and set font on UILabel after setting attributedString
this will clobber the size and boldness encapsulated in the attributestring though
kudos for reading through all the answers up to here. You are a very patient man woman or child.
Here is a simple code that authenticate and make an LDAP search usin JNDI on a W2K3 :
class TestAD
{
static DirContext ldapContext;
public static void main (String[] args) throws NamingException
{
try
{
System.out.println("Début du test Active Directory");
Hashtable<String, String> ldapEnv = new Hashtable<String, String>(11);
ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
//ldapEnv.put(Context.PROVIDER_URL, "ldap://societe.fr:389");
ldapEnv.put(Context.PROVIDER_URL, "ldap://dom.fr:389");
ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
//ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=administrateur,cn=users,dc=societe,dc=fr");
ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=jean paul blanc,ou=MonOu,dc=dom,dc=fr");
ldapEnv.put(Context.SECURITY_CREDENTIALS, "pwd");
//ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl");
//ldapEnv.put(Context.SECURITY_PROTOCOL, "simple");
ldapContext = new InitialDirContext(ldapEnv);
// Create the search controls
SearchControls searchCtls = new SearchControls();
//Specify the attributes to return
String returnedAtts[]={"sn","givenName", "samAccountName"};
searchCtls.setReturningAttributes(returnedAtts);
//Specify the search scope
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//specify the LDAP search filter
String searchFilter = "(&(objectClass=user))";
//Specify the Base for the search
String searchBase = "dc=dom,dc=fr";
//initialize counter to total the results
int totalResults = 0;
// Search for objects using the filter
NamingEnumeration<SearchResult> answer = ldapContext.search(searchBase, searchFilter, searchCtls);
//Loop through the search results
while (answer.hasMoreElements())
{
SearchResult sr = (SearchResult)answer.next();
totalResults++;
System.out.println(">>>" + sr.getName());
Attributes attrs = sr.getAttributes();
System.out.println(">>>>>>" + attrs.get("samAccountName"));
}
System.out.println("Total results: " + totalResults);
ldapContext.close();
}
catch (Exception e)
{
System.out.println(" Search error: " + e);
e.printStackTrace();
System.exit(-1);
}
}
}
I have defined this:
if (PHP_SAPI === 'cli')
{
define( "LNBR", PHP_EOL);
}
else
{
define( "LNBR", "<BR/>");
}
After this use LNBR
wherever I want to use \n
.
The correct solution to the problem is to make sure SQL server authentication is turned on for your SQL Server.
If you are using JavaScript 1.6 or later (Firefox 1.5 or later) you can use Array.indexOf. Otherwise, I think you are going to end up with something similar to your original code.
To remove every :
from the beginning of a string, you can use ltrim:
$str = '::f:o:';
$str = ltrim($str, ':');
var_dump($str); //=> 'f:o:'
By passing a block to find_or_create
, you can pass additional parameters that will be added to the object if it is created new. This is useful if you are validating the presence of a field that you aren't searching by.
Assuming:
class GroupMember < ActiveRecord::Base
validates_presence_of :name
end
then
GroupMember.where(:member_id => 4, :group_id => 7).first_or_create { |gm| gm.name = "John Doe" }
will create a new GroupMember with the name "John Doe" if it doesn't find one with member_id 4
and group_id 7
The shortcut is: CTRL+shift+- ("shift+-" results in "_") After typing the shortcut, nano will let you to enter the line you wanna jump to, type in the line number, then press ENTR.
I couldn't get the SDK to install properly (some of the files seemed unsigned, something like that). I found another solution here and that seems to work okay for me. It doesn't require installation of new files at all. Basically, what you do is:
Edit the .csproj file in a text editor, and add:
<Reference Include="System.Management.Automation" />
to the relevant section.
Hope this helps.
The default is 20 minutes. http://msdn.microsoft.com/en-us/library/h6bb9cz9(v=vs.80).aspx
<sessionState
mode="[Off|InProc|StateServer|SQLServer|Custom]"
timeout="number of minutes"
cookieName="session identifier cookie name"
cookieless=
"[true|false|AutoDetect|UseCookies|UseUri|UseDeviceProfile]"
regenerateExpiredSessionId="[True|False]"
sqlConnectionString="sql connection string"
sqlCommandTimeout="number of seconds"
allowCustomSqlDatabase="[True|False]"
useHostingIdentity="[True|False]"
stateConnectionString="tcpip=server:port"
stateNetworkTimeout="number of seconds"
customProvider="custom provider name">
<providers>...</providers>
</sessionState>
Like @flodel wrote: This converts your dataframe into a list that has the same number of elements as number of rows in dataframe:
NewList <- split(df, f = seq(nrow(df)))
You can additionaly add a function to select only those columns that are not NA in each element of the list:
NewList2 <- lapply(NewList, function(x) x[,!is.na(x)])
Add the following line in MyApplicationDir\gradle.properties
org.gradle.jvmargs=-Xmx1024m
This is the most important thing to know about the Tuple type. Tuple is a class, not a struct. It thus will be allocated upon the managed heap. Each class instance that is allocated adds to the burden of garbage collection.
Note: The properties Item1, Item2, and further do not have setters. You cannot assign them. The Tuple is immutable once created in memory.
your list comphresnion will, work but will return list of None because append return None:
demo:
>>> a=[]
>>> [ a.append(x) for x in range(10) ]
[None, None, None, None, None, None, None, None, None, None]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
better way to use it like this:
>>> a= [ x for x in range(10) ]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
How to change the Push and Pop animations in a navigation based app...
Preamble:
Say you are new to iOS development. Confusingly, Apple provide two transitions which can be used easily. These are: "crossfade" and "flip".
But of course, "crossfade" and "flip" are useless. They are never used. Nobody knows why Apple provided those two useless transitions!
So:
Say you want to do an ordinary, common, transition such as "slide". In that case, you have to do a HUGE amount of work!.
That work, is explained in this post.
Just to repeat:
Surprisingly: with iOS, if you want the simplest, most common, everyday transitions (such as an ordinary slide), you do have to all the work of implementing a full custom transition.
Here's how to do it ...
UIViewControllerAnimatedTransitioning
You need a bool of your own like popStyle
. (Is it popping on, or popping off?)
You must include transitionDuration
(trivial) and the main call, animateTransition
In fact you must write two different routines for inside animateTransition
. One for the push, and one for the pop. Probably name them animatePush
and animatePop
. Inside animateTransition
, just branch on popStyle
to the two routines
The example below does a simple move-over/move-off
In your animatePush
and animatePop
routines. You must get the "from view" and the "to view". (How to do that, is shown in the code example.)
and you must addSubview
for the new "to" view.
and you must call completeTransition
at the end of your anime
So ..
class SimpleOver: NSObject, UIViewControllerAnimatedTransitioning {
var popStyle: Bool = false
func transitionDuration(
using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.20
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if popStyle {
animatePop(using: transitionContext)
return
}
let fz = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!
let tz = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
let f = transitionContext.finalFrame(for: tz)
let fOff = f.offsetBy(dx: f.width, dy: 55)
tz.view.frame = fOff
transitionContext.containerView.insertSubview(tz.view, aboveSubview: fz.view)
UIView.animate(
withDuration: transitionDuration(using: transitionContext),
animations: {
tz.view.frame = f
}, completion: {_ in
transitionContext.completeTransition(true)
})
}
func animatePop(using transitionContext: UIViewControllerContextTransitioning) {
let fz = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!
let tz = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
let f = transitionContext.initialFrame(for: fz)
let fOffPop = f.offsetBy(dx: f.width, dy: 55)
transitionContext.containerView.insertSubview(tz.view, belowSubview: fz.view)
UIView.animate(
withDuration: transitionDuration(using: transitionContext),
animations: {
fz.view.frame = fOffPop
}, completion: {_ in
transitionContext.completeTransition(true)
})
}
}
And then ...
Note: strangely, you only have to do this in the "first" view controller. (The one which is "underneath".)
With the one that you pop on top, do nothing. Easy.
So your class...
class SomeScreen: UIViewController {
}
becomes...
class FrontScreen: UIViewController,
UIViewControllerTransitioningDelegate, UINavigationControllerDelegate {
let simpleOver = SimpleOver()
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.delegate = self
}
func navigationController(
_ navigationController: UINavigationController,
animationControllerFor operation: UINavigationControllerOperation,
from fromVC: UIViewController,
to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
simpleOver.popStyle = (operation == .pop)
return simpleOver
}
}
That's it.
Push and pop exactly as normal, no change. To push ...
let n = UIStoryboard(name: "nextScreenStoryboardName", bundle: nil)
.instantiateViewController(withIdentifier: "nextScreenStoryboardID")
as! NextScreen
navigationController?.pushViewController(n, animated: true)
and to pop it, you can if you like just do that on the next screen:
class NextScreen: TotallyOrdinaryUIViewController {
@IBAction func userClickedBackOrDismissOrSomethingLikeThat() {
navigationController?.popViewController(animated: true)
}
}
Phew.
Scroll to @AlanZeino and @elias answer for more discussion on how to AnimatedTransitioning
in iOS apps these days!
The body is not fully stored as part of the response, the reason for this is because the body can contain a very large amount of data, if it was to be stored on the response object, the program's memory would be consumed quite fast.
Instead, Node.js uses a mechanism called Stream. This mechanism allows holding only a small part of the data and allows the programmer to decide if to fully consume it in memory or use each part of the data as its flowing.
There are multiple ways how to fully consume the data into memory, since HTTP Response
is a readable stream, all readable methods are available on the res
object
listening to the "data"
event and saving the chunks passed to the callback
const chunks = []
res.on("data", (chunk) => {
chunks.push(chunk)
});
res.on("end", () => {
const body = Buffer.concat(chunks);
});
When using this approach you do not interfere with the behavior of the stream and you are only gathering the data as it is available to the application.
using the "readble"
event and calling res.read()
const chunks = [];
res.on("readable", () => {
let chunk;
while(null !== (chunk = res.read())){
chunks.push(chunk)
}
});
res.on("end", () => {
const body = Buffer.concat(chunks);
});
When going with this approach you are fully in charge of the stream flow and until res.read
is called no more data will be passed into the stream.
using an async iterator
const chunks = [];
for await (const chunk of readable) {
chunks.push(chunk);
}
const body = Buffer.concat(chunks);
This approach is similar to the "data" event
approach. It will just simplify the scoping and allow the entire process to happen in the same scope.
While as described, it is possible to fully consume data from the response it is always important to keep in mind if it is actually necessary to do so. In many cases, it is possible to simply direct the data to its destination without fully saving it into memory.
Node.js read streams, including HTTP response, have a built-in method for doing this, this method is called pipe
. The usage is quite simple, readStream.pipe(writeStream);
.
for example:
If the final destination of your data is the file system, you can simply open a write stream to the file system and then pipe
the data to ts destination.
const { createWriteStream } = require("fs");
const writeStream = createWriteStream("someFile");
res.pipe(writeStream);
If your compiler supports (at least part of) C++11 you could do something like:
for (auto& t : myMap)
std::cout << t.first << " "
<< t.second.first << " "
<< t.second.second << "\n";
For C++03 I'd use std::copy
with an insertion operator instead:
typedef std::pair<string, std::pair<string, string> > T;
std::ostream &operator<<(std::ostream &os, T const &t) {
return os << t.first << " " << t.second.first << " " << t.second.second;
}
// ...
std:copy(myMap.begin(), myMap.end(), std::ostream_iterator<T>(std::cout, "\n"));
Felipsmartins is correct.
It is worth mentioning that it is because you cannot really use the -d/--data option if this is not a POST request. But this is still possible if you use the -G option.
Which means you can do this:
curl -X DELETE -G 'http://localhost:5000/locations' -d 'id=3'
Here it is a bit silly but when you are on the command line and you have a lot of parameters, it is a lot tidier.
I am saying this because cURL commands are usually quite long, so it is worth making it on more than one line escaping the line breaks.
curl -X DELETE -G \
'http://localhost:5000/locations' \
-d id=3 \
-d name=Mario \
-d surname=Bros
This is obviously a lot more comfortable if you use zsh. I mean when you need to re-edit the previous command because zsh lets you go line by line. (just saying)
Hope it helps.
With:
FILES = $(shell ls)
indented underneath all
like that, it's a build command. So this expands $(shell ls)
, then tries to run the command FILES ...
.
If FILES
is supposed to be a make
variable, these variables need to be assigned outside the recipe portion, e.g.:
FILES = $(shell ls)
all:
echo $(FILES)
Of course, that means that FILES
will be set to "output from ls
" before running any of the commands that create the .tgz files. (Though as Kaz notes the variable is re-expanded each time, so eventually it will include the .tgz files; some make variants have FILES := ...
to avoid this, for efficiency and/or correctness.1)
If FILES
is supposed to be a shell variable, you can set it but you need to do it in shell-ese, with no spaces, and quoted:
all:
FILES="$(shell ls)"
However, each line is run by a separate shell, so this variable will not survive to the next line, so you must then use it immediately:
FILES="$(shell ls)"; echo $$FILES
This is all a bit silly since the shell will expand *
(and other shell glob expressions) for you in the first place, so you can just:
echo *
as your shell command.
Finally, as a general rule (not really applicable to this example): as esperanto notes in comments, using the output from ls
is not completely reliable (some details depend on file names and sometimes even the version of ls
; some versions of ls
attempt to sanitize output in some cases). Thus, as l0b0 and idelic note, if you're using GNU make you can use $(wildcard)
and $(subst ...)
to accomplish everything inside make
itself (avoiding any "weird characters in file name" issues). (In sh
scripts, including the recipe portion of makefiles, another method is to use find ... -print0 | xargs -0
to avoid tripping over blanks, newlines, control characters, and so on.)
1The GNU Make documentation notes further that POSIX make added ::=
assignment in 2012. I have not found a quick reference link to a POSIX document for this, nor do I know off-hand which make
variants support ::=
assignment, although GNU make does today, with the same meaning as :=
, i.e., do the assignment right now with expansion.
Note that VAR := $(shell command args...)
can also be spelled VAR != command args...
in several make
variants, including all modern GNU and BSD variants as far as I know. These other variants do not have $(shell)
so using VAR != command args...
is superior in both being shorter and working in more variants.
Its painful to hear people are still suffering at the hands of *{COPY} whatever the version. I am a seasoned batch and Bash script writer and I recommend rsync , you can run this within cygwin (cygwin.org) or you can locate some binaries floating around . and you can redirect output to 2>&1 to some log file like out.log for later analysing. Good luck people its time to love life again . =M. Kaan=
If there are only two variables to check and you're using Guava, you can use MoreObjects.firstNonNull(T first, T second).
Whenever you want to get the changes from master into your work branch, do a git rebase <remote>/master
. If there are any conflicts. resolve them.
When your work branch is ready, rebase again and then do git push <remote> HEAD:master
. This will update the master branch on remote (central repo).
In addition for the accepted answer you'll need the following permissions into your AndroidManifest to get it working:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
Write a vba proc like:
Sub E_1()
Call sndPlaySound32(ThisWorkbook.Path & "\e1.wav", 0)
Range("AG" & (ActiveCell.Row)).Select 'go to column AG in the same row
End Sub
then go to developer tab, macros, select the macro, click options, then add a shortcut letter or button.
Simple code to redirect page
<!-- html button designing and calling the event in javascript -->
<input id="btntest" type="button" value="Check"
onclick="window.location.href = 'http://www.google.com'" />
Your EditText
should be wrapped in a TextInputLayout
<android.support.design.widget.TextInputLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/tilEmail">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="@+id/etEmail"
android:hint="Email"
android:layout_marginTop="10dp"
/>
</android.support.design.widget.TextInputLayout>
To get an error message like you wanted, set error to TextInputLayout
TextInputLayout tilEmail = (TextInputLayout) findViewById(R.id.tilEmail);
if (error){
tilEmail.setError("Invalid email id");
}
You should add design support library dependency. Add this line in your gradle dependencies
compile 'com.android.support:design:22.2.0'
I've SSL on Apache2.4.4 and executing this code at first, did the trick:
set OPENSSL_CONF=C:\wamp\bin\apache\Apache2.4.4\conf\openssl.cnf
then execute the rest codes..
Press F12 to Inspect Element and Ctrl+U to View Page Source
There's a -f option to umount that you can try:
umount -f /mnt/fileshare
Are you specifying the '-t cifs' option to mount? Also make sure you're not specifying the 'hard' option to mount.
You may also want to consider fusesmb, since the filesystem will be running in userspace you can kill it just like any other process.
See excerpt from official documentation for containment
option:
containment
Default:
false
Constrains dragging to within the bounds of the specified element or region.
Multiple types supported:
- Selector: The draggable element will be contained to the bounding box of the first element found by the selector. If no element is found, no containment will be set.
- Element: The draggable element will be contained to the bounding box of this element.
- String: Possible values:
"parent"
,"document"
,"window"
.- Array: An array defining a bounding box in the form
[ x1, y1, x2, y2 ]
.Code examples:
Initialize the draggable with thecontainment
option specified:$( ".selector" ).draggable({ containment: "parent" });
Get or set the
containment
option, after initialization:// Getter var containment = $( ".selector" ).draggable( "option", "containment" ); // Setter $( ".selector" ).draggable( "option", "containment", "parent" );
You are working way too hard. Your entire script should be:
if mkdir "$lockdir" 2> /dev/null; then
echo lock acquired
else
echo could not acquire lock >&2
fi
but even that is probably too verbose. I would code it:
mkdir "$lockdir" || exit 1
but the resulting error message is a bit obscure.
since version 3.11 of the google maps API, the Icon
object replaces MarkerImage
. Icon supports the same parameters as MarkerImage. I even found it to be a bit more straight forward.
An example could look like this:
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
for further information check this site
to perform a GET request using the fetch api I worked on this solution that doesn't require the installation of packages.
this is an example of a call to the google's map api
// encode to scape spaces
const esc = encodeURIComponent;
const url = 'https://maps.googleapis.com/maps/api/geocode/json?';
const params = {
key: "asdkfñlaskdGE",
address: "evergreen avenue",
city: "New York"
};
// this line takes the params object and builds the query string
const query = Object.keys(params).map(k => `${esc(k)}=${esc(params[k])}`).join('&')
const res = await fetch(url+query);
const googleResponse = await res.json()
feel free to copy this code and paste it on the console to see how it works!!
the generated url is something like:
https://maps.googleapis.com/maps/api/geocode/json?key=asdkf%C3%B1laskdGE&address=evergreen%20avenue&city=New%20York
this is what I was looking before I decided to write this, enjoy :D
You can set it at Property > Configuration Properties > Debugging > Environment
This Problem can be solved without using for loop.Single line code will be sufficient for this. Using Nested Map with lambda function will also works here.
l = [['40', '20', '10', '30'], ['20', '20', '20', '20', '20', '30', '20'], ['30', '20', '30', '50', '10', '30', '20', '20', '20'], ['100', '100'], ['100', '100', '100', '100', '100'], ['100', '100', '100', '100']]
map(lambda x:map(lambda y:float(y),x),l)
And Output List would be as follows:
[[40.0, 20.0, 10.0, 30.0], [20.0, 20.0, 20.0, 20.0, 20.0, 30.0, 20.0], [30.0, 20.0, 30.0, 50.0, 10.0, 30.0, 20.0, 20.0, 20.0], [100.0, 100.0], [100.0, 100.0, 100.0, 100.0, 100.0], [100.0, 100.0, 100.0, 100.0]]
The existing answers are correct, but sometimes you aren't actually returning something explicitly with a Write-Output
or a return
, yet there is some mystery value in the function results. This could be the output of a builtin function like New-Item
PS C:\temp> function ContrivedFolderMakerFunction {
>> $folderName = [DateTime]::Now.ToFileTime()
>> $folderPath = Join-Path -Path . -ChildPath $folderName
>> New-Item -Path $folderPath -ItemType Directory
>> return $true
>> }
PS C:\temp> $result = ContrivedFolderMakerFunction
PS C:\temp> $result
Directory: C:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2/9/2020 4:32 PM 132257575335253136
True
All that extra noise of the directory creation is being collected and emitted in the output. The easy way to mitigate this is to add | Out-Null
to the end of the New-Item
statement, or you can assign the result to a variable and just not use that variable. It would look like this...
PS C:\temp> function ContrivedFolderMakerFunction {
>> $folderName = [DateTime]::Now.ToFileTime()
>> $folderPath = Join-Path -Path . -ChildPath $folderName
>> New-Item -Path $folderPath -ItemType Directory | Out-Null
>> # -or-
>> $throwaway = New-Item -Path $folderPath -ItemType Directory
>> return $true
>> }
PS C:\temp> $result = ContrivedFolderMakerFunction
PS C:\temp> $result
True
New-Item
is probably the more famous of these, but others include all of the StringBuilder.Append*()
methods, as well as the SqlDataAdapter.Fill()
method.
This is documentation from Moq site:
// out arguments
var outString = "ack";
// TryParse will return true, and the out argument will return "ack", lazy evaluated
mock.Setup(foo => foo.TryParse("ping", out outString)).Returns(true);
// ref arguments
var instance = new Bar();
// Only matches if the ref argument to the invocation is the same instance
mock.Setup(foo => foo.Submit(ref instance)).Returns(true);
Just use the build-in feature of Angular CLI
ng update
to update to the latest version.
sudo
command not found
to check whether the sudo package is installed on your system, type sudo
, and press Enter . If you have sudo
installed the system will display a short help message, otherwise you will see something like sudo: command not found
To install sudo, run one of the following commands using root account:
apt-get install sudo
# If your system based on apt package manager
yum install sudo
# If your system based on yum package manager
For the above code to function; you need to make sure the following directories exist (mine didn't). Just add the following to a bat and run it:
mkdir C:\Windows\System32\GroupPolicy\Machine\Scripts\Startup
mkdir C:\Windows\System32\GroupPolicy\Machine\Scripts\Shutdown
mkdir C:\Windows\System32\GroupPolicy\User\Scripts\Startup
mkdir C:\Windows\System32\GroupPolicy\User\Scripts\Shutdown
It's just that GP needs those directories to exist for:
Group Policy\Local Computer Policy\Windows Settings\Scripts (Startup/Shutdown)
to function properly.
If every input asks the same question, you should use a for
loop and an array of inputs:
Scanner dd = new Scanner(System.in);
int[] vars = new int[3];
for(int i = 0; i < vars.length; i++) {
System.out.println("Enter next var: ");
vars[i] = dd.nextInt();
}
Or as Chip suggested, you can parse the input from one line:
Scanner in = new Scanner(System.in);
int[] vars = new int[3];
System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
vars[i] = in.nextInt();
You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.
Disabled is a Boolean Attribute of the select element as stated by WHATWG, that means the RIGHT WAY TO DISABLE with jQuery would be
jQuery("#selectId").attr('disabled',true);
This would make this HTML
<select id="selectId" name="gender" disabled="disabled">
<option value="-1">--Select a Gender--</option>
<option value="0">Male</option>
<option value="1">Female</option>
</select>
This works for both XHTML and HTML (W3School reference)
Yet it also can be done using it as property
jQuery("#selectId").prop('disabled', 'disabled');
getting
<select id="selectId" name="gender" disabled>
Which only works for HTML and not XTML
NOTE: A disabled element will not be submitted with the form as answered in this question: The disabled form element is not submitted
NOTE2: A disabled element may be greyed out.
NOTE3:
A form control that is disabled must prevent any click events that are queued on the user interaction task source from being dispatched on the element.
<script>
var update_pizza = function () {
if ($("#pizza").is(":checked")) {
$('#pizza_kind').attr('disabled', false);
} else {
$('#pizza_kind').attr('disabled', true);
}
};
$(update_pizza);
$("#pizza").change(update_pizza);
</script>
I liked this one, but it is sending JSON not string
as requested in the question, reposting the code here, in case the original github got removed or changed, and this one found to be useful by someone.
public static void postNewComment(Context context,final UserAccount userAccount,final String comment,final int blogId,final int postId){
mPostCommentResponse.requestStarted();
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST,"http://api.someservice.com/post/comment", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
mPostCommentResponse.requestCompleted();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mPostCommentResponse.requestEndedWithError(error);
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("user",userAccount.getUsername());
params.put("pass",userAccount.getPassword());
params.put("comment", Uri.encode(comment));
params.put("comment_post_ID",String.valueOf(postId));
params.put("blogId",String.valueOf(blogId));
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
queue.add(sr);
}
public interface PostCommentResponseListener {
public void requestStarted();
public void requestCompleted();
public void requestEndedWithError(VolleyError error);
}
I know this is an old question but I just found a solution which creates a user defined function using LTRIM and RTRIM. It does not handle double spaces in the middle of a string.
The solution is however straight forward:
For my point of view, First thing is to install soap into Centos
yum install php-soap
Second, see if the soap package exist or not
yum search php-soap
third, thus you must see some result of soap package you installed, now type a command in your terminal in the root folder for searching the location of soap for specific path
find -name soap.so
fourth, you will see the exact path where its installed/located, simply copy the path and find the php.ini to add the extension path,
usually the path of php.ini file in centos 6 is in
/etc/php.ini
fifth, add a line of code from below into php.ini file
extension='/usr/lib/php/modules/soap.so'
and then save the file and exit.
sixth run apache restart command in Centos. I think there is two command that can restart your apache ( whichever is easier for you )
service httpd restart
OR
apachectl restart
Lastly, check phpinfo() output in browser, you should see SOAP section where SOAP CLIENT, SOAP SERVER etc are listed and shown Enabled.
I use:
object-fit: cover;
-o-object-fit: cover;
to place images in a container with a fixed height and width, this also works great for my sliders. It will however cut of parts of the image depending on it's.
While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event
argument to the setMaster
function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):
function AdminController($scope) {
$scope.setMaster = function(obj, $event){
console.log($event.target);
}
}
this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.
The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event
argument) would be:
<div ng-controller="AdminController">
<ul class="list-holder">
<li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
<a ng-click="setMaster(section)">{{section.name}}</a>
</li>
</ul>
<hr>
{{selected | json}}
</div>
where methods in the controller would look like this:
$scope.setMaster = function(section) {
$scope.selected = section;
}
$scope.isSelected = function(section) {
return $scope.selected === section;
}
Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/
I encountered a rare edge case in cygwin, where I would get this error when doing exec('rsync');
somewhere before the query. Might be a general PHP problem, but I could only reproduce this in cygwin with rsync.
$pdo = new PDO('mysql:host=127.0.0.1;dbname=mysql', 'root');
var_dump($pdo->query('SELECT * FROM db'));
exec('rsync');
var_dump($pdo->query('SELECT * FROM db'));
produces
object(PDOStatement)#2 (1) {
["queryString"]=>
string(16) "SELECT * FROM db"
}
PHP Warning: Error while sending QUERY packet. PID=15036 in test.php on line 5
bool(false)
Bug reported in https://cygwin.com/ml/cygwin/2017-05/msg00272.html
Friend. Use this way, There will be no "Undefined variable message" and it will work fine.
<?php
if(isset($_POST['SubmitButton'])){
$price = $_POST["price"];
$qty = $_POST["qty"];
$message = $price*$qty;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="#" method="post">
<input type="number" name="price"> <br>
<input type="number" name="qty"><br>
<input type="submit" name="SubmitButton">
</form>
<?php echo "The Answer is" .$message; ?>
</body>
</html>
Several of the answers mention that you can use JNI or JNA to access cpython but I would not recommend starting from scratch because there are already open source libraries for accessing cpython from java. For example:
To quote the man:
The -e option is used to edit the current crontab using the editor specified by the VISUAL or EDITOR environment variables
Most often if you run crontab -e
from X, you have VISUAL
set; that's what is used. Try this:
VISUAL=vi crontab -e
It just worked for me :)
Using android studio to generate signed apk for react's android project is also a good and easy option , open react's android project in android studio and generate keystroke and signed apk.
Here is the representation of your pseudo-code in minimal Java code;
boolean isEven = a % 2 == 0;
I'll now break it down into its components. The modulus operator in Java is the percent character (%). Therefore taking an int % int returns another int. The double equals (==) operator is used to compare values, such as a pair of ints and returns a boolean. This is then assigned to the boolean variable 'isEven'. Based on operator precedence the modulus will be evaluated before the comparison.
Add this code structure to your page code
<?php
echo '<label>Admission Year:</label><br><select name="admission_year" data-component="date">';
for($year=1900; $year<=date('Y'); $year++){
echo '<option value="'.$year.'">'.$year.'</option>';
}
?>
It works perfectly and can be reverse engineered
<?php
echo '<label>Admission Year:</label><br><select name="admission_year" data-component="date">';
for($year=date('Y'); $year>=1900; $year++){
echo '<option value="'.$year.'">'.$year.'</option>';
}
?>
With this you are good to go.
bash --rcfile <(echo '. ~/.bashrc; some_command')
dispenses the creation of temporary files. Question on other sites:
Wow, can't believe that Joel would favor this:
var svc = new ShippingService(new ProductLocator(),
new PricingService(), new InventoryService(),
new TrackingRepository(new ConfigProvider()),
new Logger(new EmailLogger(new ConfigProvider())));
over this:
var svc = IoC.Resolve<IShippingService>();
Many folks don't realize that your dependencies chain can become nested, and it quickly becomes unwieldy to wire them up manually. Even with factories, the duplication of your code is just not worth it.
IoC containers can be complex, yes. But for this simple case I've shown it's incredibly easy.
Okay, let's justify this even more. Let's say you have some entities or model objects that you want to bind to a smart UI. This smart UI (we'll call it Shindows Morms) wants you to implement INotifyPropertyChanged so that it can do change tracking & update the UI accordingly.
"OK, that doesn't sound so hard" so you start writing.
You start with this:
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime CustomerSince { get; set; }
public string Status { get; set; }
}
..and end up with this:
public class UglyCustomer : INotifyPropertyChanged
{
private string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
string oldValue = _firstName;
_firstName = value;
if(oldValue != value)
OnPropertyChanged("FirstName");
}
}
private string _lastName;
public string LastName
{
get { return _lastName; }
set
{
string oldValue = _lastName;
_lastName = value;
if(oldValue != value)
OnPropertyChanged("LastName");
}
}
private DateTime _customerSince;
public DateTime CustomerSince
{
get { return _customerSince; }
set
{
DateTime oldValue = _customerSince;
_customerSince = value;
if(oldValue != value)
OnPropertyChanged("CustomerSince");
}
}
private string _status;
public string Status
{
get { return _status; }
set
{
string oldValue = _status;
_status = value;
if(oldValue != value)
OnPropertyChanged("Status");
}
}
protected virtual void OnPropertyChanged(string property)
{
var propertyChanged = PropertyChanged;
if(propertyChanged != null)
propertyChanged(this, new PropertyChangedEventArgs(property));
}
public event PropertyChangedEventHandler PropertyChanged;
}
That's disgusting plumbing code, and I maintain that if you're writing code like that by hand you're stealing from your client. There are better, smarter way of working.
Ever hear that term, work smarter, not harder?
Well imagine some smart guy on your team came up and said: "Here's an easier way"
If you make your properties virtual (calm down, it's not that big of a deal) then we can weave in that property behavior automatically. (This is called AOP, but don't worry about the name, focus on what it's going to do for you)
Depending on which IoC tool you're using, you could do something that looks like this:
var bindingFriendlyInstance = IoC.Resolve<Customer>(new NotifyPropertyChangedWrapper());
Poof! All of that manual INotifyPropertyChanged BS is now automatically generated for you, on every virtual property setter of the object in question.
Is this magic? YES! If you can trust the fact that this code does its job, then you can safely skip all of that property wrapping mumbo-jumbo. You've got business problems to solve.
Some other interesting uses of an IoC tool to do AOP:
I would like to answer your question, as there are various methods - here I’ll talk about the code that is widely used.
So, for hiding the sheet:
Sub try()
Worksheets("Sheet1").Visible = xlSheetHidden
End Sub
There are other methods also if you want to learn all Methods Click here
Have you tried using the wmic
commands?
Try
wmic os get version
This will give you the version number in a command line, then you just need to integrate into the batch file.
you could use the Thread.Sleep() function
Thread.sleep(4000);
myfunction();
Your function will execute after 4 seconds. However this might pause the entire program...
Correct, when you drag a view controller object onto your storyboard in order to create a new scene, it doesn't automatically make the new class for you, too.
Having added a new view controller scene to your storyboard, you then have to:
Create a UIViewController
subclass. For example, go to your target's folder in the project navigator panel on the left and then control-click and choose "New File...". Choose a "Cocoa Touch Class":
And then select a unique name for the new view controller subclass:
Specify this new subclass as the base class for the scene you just added to the storyboard.
Now hook up any IBOutlet
and IBAction
references for this new scene with the new view controller subclass.
Step 1.
vi ~/.bashrc
Step 2. Append this line on the last:
export CLASSPATH=$CLASSPATH:/home/abc/lib/*; (Assuming the jars are stored in /home/abc/lib)
Step 3.
source ~/.bashrc
After these steps direct complile and run your programs(e.g. javac xyz.java)
In Oracle, there is two views that describe columns:
DBA_TAB_COLUMNS describes the columns of all tables, views, and clusters in the database.
USER_TAB_COLUMNS describes the columns of the tables, views, and
clusters owned by the current user. This view does not display the
OWNER column.
A square is a rectangle where the width equals the height. If the square sets two different sizes for the width and height it violates the square invariant. This is worked around by introducing side effects. But if the rectangle had a setSize(height, width) with precondition 0 < height and 0 < width. The derived subtype method requires height == width; a stronger precondition (and that violates lsp). This shows that though square is a rectangle it is not a valid subtype because the precondition is strengthened. The work around (in general a bad thing) cause a side effect and this weakens the post condition (which violates lsp). setWidth on the base has post condition 0 < width. The derived weakens it with height == width.
Therefore a resizable square is not a resizable rectangle.
If you want to load the file, as part of your app functionality, then the best approach would be to include and reference to that file.
Another approach is to ask for the file, and load it during runtime. This can be done with the FileAPI. There is also another StackOverflow answer about using it: How to open a local disk file with Javascript?
I will include a slightly modified version for using it in React:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null
};
this.handleFileSelect = this.handleFileSelect.bind(this);
}
displayData(content) {
this.setState({data: content});
}
handleFileSelect(evt) {
let files = evt.target.files;
if (!files.length) {
alert('No file select');
return;
}
let file = files[0];
let that = this;
let reader = new FileReader();
reader.onload = function(e) {
that.displayData(e.target.result);
};
reader.readAsText(file);
}
render() {
const data = this.state.data;
return (
<div>
<input type="file" onChange={this.handleFileSelect}/>
{ data && <p> {data} </p> }
</div>
);
}
}
I overrode the Count method of the associated FragmentStatePagerAdapter and have it return the total count minus the number of pages to hide:
public class MyAdapter : Android.Support.V13.App.FragmentStatePagerAdapter
{
private List<Fragment> _fragments;
public int TrimmedPages { get; set; }
public MyAdapter(Android.App.FragmentManager fm) : base(fm) { }
public MyAdapter(Android.App.FragmentManager fm, List<Android.App.Fragment> fragments) : base(fm)
{
_fragments = fragments;
TrimmedPages = 0;
}
public override int Count
{
//get { return _fragments.Count; }
get { return _fragments.Count - TrimmedPages; }
}
}
So, if there are 3 fragments initially added to the ViewPager, and only the first 2 should be shown until some condition is met, override the page count by setting TrimmedPages to 1 and it should only show the first two pages.
This works good for pages on the end, but wont really help for ones on the beginning or middle (though there are plenty of ways of doing this).
When you create a StreamWriter
it always create a file from scratch, you will have to create a third file and copy from target and replace what you need, and then replace the old one.
But as I can see what you need is XML manipulation, you might want to use XmlDocument
and modify your file using Xpath.
How about $array_name = array();
?
Just change your controller to the following:
public function create()
{
$items = Subject::all(['id', 'name']);
return View::make('your view', compact('items',$items));
}
And your view to:
<div class="form-group">
{!! Form::Label('item', 'Item:') !!}
<select class="form-control" name="item_id">
@foreach($items as $item)
<option value="{{$item->item_id}}">{{$item->id}}</option>
@endforeach
</select>
</div>
Hope this will solve your problem
You could always use apache commons' DateUtils
class. It has the static method isSameDay()
which "Checks if two date objects are on the same day ignoring time."
static boolean isSameDay(Date date1, Date date2)
Note that this may also work:
SELECT * FROM table WHERE s=ANY(array)
Index access (mentioned here) is the practical difference. If you need to access the successor or predecessor, you need SortedList. SortedDictionary cannot do that so you are fairly limited with how you can use the sorting (first / foreach).
type ps -ef
check the process id.
Kill the process by typing kill -9 <pid>
You should never apply bindings more than once to a view. In 2.2, the behaviour was undefined, but still unsupported. In 2.3, it now correctly shows an error. When using knockout, the goal is to apply bindings once to your view(s) on the page, then use changes to observables on your viewmodel to change the appearance and behaviour of your view(s) on your page.
I had similar problem (in bash terminal command was working correctly but zsh showed command not found error)
just paste whatever you were earlier pasting in ~/.bashrc to:
~/.zshrc
I have used a temporary file to do this in the past, like this below.
DIR /B *.DAT | FIND.EXE /C /V "" > COUNT.TXT
FOR /F "tokens=1" %%f IN (COUNT.TXT) DO (
IF NOT %%f==6 SET _MSG=File count is %%f, and 6 were expected. & DEL COUNT.TXT & ECHO #### ERROR - FILE COUNT WAS %%f AND 6 WERE EXPECTED. #### >> %_LOGFILE% & GOTO SENDMAIL
)
Same comment as Philip Kirkbride. It wasn't a permission issue, but using the Arduino IDE downloaded from their website solved my problem. Thanks! Michael
This is what I am doing:
string tStamp = String.Format("{0:yyyyMMdd.HHmmss}", DateTime.Now); string ProcID = Process.GetCurrentProcess().Id.ToString(); string tmpFolder = System.IO.Path.GetTempPath(); string outFile = tmpFolder + ProcID + "_" + tStamp + ".txt";
I tried all above solution and fail, it just added a null file to the DB.
However, I was able to get it done by moving the image(fileName.jpg
) file first in to below folder(in my case) C:\ProgramData\MySQL\MySQL Server 5.7\Uploads
and then I executed below command and it works for me,
INSERT INTO xx_BLOB(ID,IMAGE) VALUES(1,LOAD_FILE('C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/fileName.jpg'));
Hope this helps.
use JSON.stringify(userData)
to coverty json object to string.
var dataStore = $.cookie("basket-data", JSON.stringify($("#ArticlesHolder").data()));
and for getting back from cookie use JSON.parse()
var data=JSON.parse($.cookie("basket-data"))
First, you'll need to add session_start()
at the top of any page that you wish to use SESSION
variables on.
Also, you should check to make sure the variable is set first before using it:
if(isset($_SESSION['SESS_fname'])){
echo $_SESSION['SESS_fname'];
}
Or, simply:
echo (isset($_SESSION['SESS_fname']) ? $_SESSION['SESS_fname'] : "Visitor");
It would be fine to use query parameters on a POST endpoint, provided they refer to already existing resources.
For example:
POST /user_settings?user_id=4
{
"use_safe_mode": 1
}
The POST above has a query parameter referring to an existing resource. The body parameter defines the new resource to be created.
(Granted, this may be more of a personal preference than a dogmatic principle.)
. "$PSScriptRoot\MyFunctions.ps1"
MyA1Func
Availalbe starting in v3, before that see How can I get the file system location of a PowerShell script?. It is VERY common.
P.S. I don't subscribe to the 'everything is a module' rule. My scripts are used by other developers out of GIT, so I don't like to put stuff in specific a place or modify system environment variables before my script will run. It's just a script (or two, or three).
Very often you have no option to setup the sending server so what I did I changed the XMLHttpRequest.open call in my javascript to a local get-file.php file where I have the following code in it:
<?php_x000D_
$file = file($_GET['url']);_x000D_
echo implode('', $file);_x000D_
?>
_x000D_
javascript is doing this:
var xhttp = new XMLHttpRequest();_x000D_
xhttp.onreadystatechange = function() {_x000D_
if (this.readyState == 4 && this.status == 200) {_x000D_
// File content is now in the this.responseText_x000D_
}_x000D_
};_x000D_
xhttp.open("GET", "get-file.php?url=http://site/file", true);_x000D_
xhttp.send();
_x000D_
In my case this solved the restriction/situation just perfectly. No need to hack Firefox or servers. Just load your javascript/html file with that small php file into the server and you're done.
check your cpanels space.remove unused file or error.log file & then try to login your application(This work for me);
Use
android:singleLine="true"
android:maxLines="1"
app:layout_constrainedWidth="true"
It's how my full TextView
looks:
<TextView
android:id="@+id/message_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:maxLines="1"
android:singleLine="true"
android:text="NAME PLACEHOLDER MORE Text"
android:textColor="@android:color/black"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constrainedWidth="true"
app:layout_constraintEnd_toStartOf="@id/message_check_sign"
app:layout_constraintHorizontal_bias="0"
app:layout_constraintStart_toEndOf="@id/img_chat_contact"
app:layout_constraintTop_toTopOf="@id/img_chat_contact" />
Form myForm;
myForm.WindowState = FormWindowState.Minimized;
Using Object.fromEntries:
const array = [_x000D_
{ key: "key1", value: "value1" },_x000D_
{ key: "key2", value: "value2" },_x000D_
];_x000D_
_x000D_
const obj = Object.fromEntries(array.map(item => [item.key, item.value]));_x000D_
_x000D_
console.log(obj);
_x000D_
Below solution worked for me:
On a RecyclerView item, user will click a button but another view like TextView will update without directly notifying adapter:
I found a good solution for this without using notifyDataSetChanged() method, this method reloads all data of recyclerView so if you have image or video inside item then they will reload and user experience will not good:
Here is an example of click on a ImageView like icon and only update a single TextView (Possible to update more view in same way of same item) to show like count update after adding +1:
// View holder class inside adapter class
public class MyViewHolder extends RecyclerView.ViewHolder{
ImageView imageViewLike;
public MyViewHolder(View itemView) {
super(itemView);
imageViewLike = itemView.findViewById(R.id.imageViewLike);
imageViewLike.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = getAdapterPosition(); // Get clicked item position
TextView tv = v.getRootView().findViewById(R.id.textViewLikeCount); // Find textView of recyclerView item
resultList.get(pos).setLike(resultList.get(pos).getLike() + 1); // Need to change data list to show updated data again after scrolling
tv.setText(String.valueOf(resultList.get(pos).getLike())); // Set data to TextView from updated list
}
});
}
I also got stuck with this issue. I got correct response from server, but couldn`t play video. After long time I found a solution here. Maybe, in future this link will be invalid. So, here is my correct code
Uri video = Uri.parse("Your link should be in this place ");
mVideoView.setVideoURI(video);
mVideoView.setZOrderOnTop(true); //Very important line, add it to Your code
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
// here write another part of code, which provides starting the video
}}
It's also much more better to not modify the app/config/database.php
file itself... otherwise modify .env
file and put your DB info there. (.env
file is available in Laravel 5, not sure if it was there in previous versions...)
NOTE: Of course you should have already set mysql
as your default database connection in the app/config/database.php
file.
The answers so far will work.. if you only want to use the height without padding, borders, etc.
If you would like to account for padding, borders, and margin, you should use .outerHeight
.
var bottom = $('#bottom').position().top + $('#bottom').outerHeight(true);
F5 reloads the page from server, but it uses the browser's cache for page elements like scripts, image, CSS stylesheets, etc, etc. But Ctrl + F5, reloads the page from the server and also reloads its contents from server and doesn't use local cache at all.
So by pressing F5 on, say, the Yahoo homepage, it just reloads the main HTML frame and then loads all other elements like images from its cache. If a new element was added or changed then it gets it from the server. But Ctrl + F5 reloads everything from the server.
An easy way is to use PowerShell ISE, open script, run and invoke your script, function...
The 2nd parameter in the get
call is a config object. You want something like this:
$http
.get('accept.php', {
params: {
source: link,
category_id: category
}
})
.success(function (data,status) {
$scope.info_show = data
});
See the Arguments section of http://docs.angularjs.org/api/ng.$http for more detail
It's not supported just yet... If you want to use it you will have to install Babel.
It's worth noting, since it's confusing for people new to XML, that the root (or document node) of an XML document is not the top-level element. It's the parent of the top-level element. This is confusing because it doesn't seem like the top-level element can have a parent. Isn't it the top level?
But look at this, a well-formed XML document:
<?xml-stylesheet href="my_transform.xsl" type="text/xsl"?>
<!-- Comments and processing instructions are XML nodes too, remember. -->
<TopLevelElement/>
The root of this document has three children: a processing instruction, a comment, and an element.
So, for example, if you wanted to write a transform that got rid of that comment, but left in any comments appearing anywhere else in the document, you'd add this to the identity transform:
<xsl:template match="/comment()"/>
Even simpler (and more commonly useful), here's an XPath pattern that matches the document's top-level element irrespective of its name: /*
.
Set Precompile Bridging Header to No fix the problem for me.
You can also specify the type of attachment you want in your e-mail, as an example I used pdf:
def send_email_pdf_figs(path_to_pdf, subject, message, destination, password_path=None):
## credits: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script
from socket import gethostname
#import email
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import json
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
with open(password_path) as f:
config = json.load(f)
server.login('[email protected]', config['password'])
# Craft message (obj)
msg = MIMEMultipart()
message = f'{message}\nSend from Hostname: {gethostname()}'
msg['Subject'] = subject
msg['From'] = '[email protected]'
msg['To'] = destination
# Insert the text to the msg going by e-mail
msg.attach(MIMEText(message, "plain"))
# Attach the pdf to the msg going by e-mail
with open(path_to_pdf, "rb") as f:
#attach = email.mime.application.MIMEApplication(f.read(),_subtype="pdf")
attach = MIMEApplication(f.read(),_subtype="pdf")
attach.add_header('Content-Disposition','attachment',filename=str(path_to_pdf))
msg.attach(attach)
# send msg
server.send_message(msg)
inspirations/credits to: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script
The problem of converting from any non-unicode source to a unicode SQL Server table can be solved by:
Using the =~
operator:
$ string="hello-world"
$ prefix="hell"
$ suffix="ld"
$ [[ "$string" =~ ^$prefix(.*)$suffix$ ]] && echo "${BASH_REMATCH[1]}"
o-wor
The key difference: NSMutableDictionary can be modified in place, NSDictionary cannot. This is true for all the other NSMutable* classes in Cocoa. NSMutableDictionary is a subclass of NSDictionary, so everything you can do with NSDictionary you can do with both. However, NSMutableDictionary also adds complementary methods to modify things in place, such as the method setObject:forKey:
.
You can convert between the two like this:
NSMutableDictionary *mutable = [[dict mutableCopy] autorelease];
NSDictionary *dict = [[mutable copy] autorelease];
Presumably you want to store data by writing it to a file. NSDictionary has a method to do this (which also works with NSMutableDictionary):
BOOL success = [dict writeToFile:@"/file/path" atomically:YES];
To read a dictionary from a file, there's a corresponding method:
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"/file/path"];
If you want to read the file as an NSMutableDictionary, simply use:
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/file/path"];
If you are using Statement
, go for the following
//MY_NUMBER is the column name in the database
String generatedColumns[] = {"MY_NUMBER"};
Statement stmt = conn.createStatement();
//String sql holds the insert query
stmt.executeUpdate(sql, generatedColumns);
ResultSet rs = stmt.getGeneratedKeys();
// The generated id
if(rs.next())
long key = rs.getLong(1);
If you are using PreparedStatement
, go for the following
String generatedColumns[] = {"MY_NUMBER"};
PreparedStatement pstmt = conn.prepareStatement(sql,generatedColumns);
pstmt.setString(1, "qwerty");
pstmt.execute();
ResultSet rs = pstmt.getGeneratedKeys();
if(rs.next())
long key = rs.getLong(1);
You could query the table_privileges
table in the information schema:
SELECT table_catalog, table_schema, table_name, privilege_type
FROM information_schema.table_privileges
WHERE grantee = 'MY_USER'
Try this
df.drop(df.iloc[:, 1:69], inplace=True, axis=1)
This works for me
Strace can be used as a debugging tool, or as a primitive profiler.
As a debugger, you can see how given system calls were called, executed and what they return. This is very important, as it allows you to see not only that a program failed, but WHY a program failed. Usually it's just a result of lousy coding not catching all the possible outcomes of a program. Other times it's just hardcoded paths to files. Without strace you get to guess what went wrong where and how. With strace you get a breakdown of a syscall, usually just looking at a return value tells you a lot.
Profiling is another use. You can use it to time execution of each syscalls individually, or as an aggregate. While this might not be enough to fix your problems, it will at least greatly narrow down the list of potential suspects. If you see a lot of fopen/close pairs on a single file, you probably unnecessairly open and close files every execution of a loop, instead of opening and closing it outside of a loop.
Ltrace is strace's close cousin, also very useful. You must learn to differenciate where your bottleneck is. If a total execution is 8 seconds, and you spend only 0.05secs on system calls, then stracing the program is not going to do you much good, the problem is in your code, which is usually a logic problem, or the program actually needs to take that long to run.
The biggest problem with strace/ltrace is reading their output. If you don't know how the calls are made, or at least the names of syscalls/functions, it's going to be difficult to decipher the meaning. Knowing what the functions return can also be very beneficial, especially for different error codes. While it's a pain to decipher, they sometimes really return a pearl of knowledge; once I saw a situation where I ran out of inodes, but not out of free space, thus all the usual utilities didn't give me any warning, I just couldn't make a new file. Reading the error code from strace's output pointed me in the right direction.
You can do a div over the padding as follows:
<div id= "paddingOne">
</div>
<div id= "paddingTwo">
</div>
#paddingOne {
width: 100;
length: 100;
background-color: #000000;
margin: 0;
z-index: 2;
}
#paddingTwo {
width: 200;
length: 200;
background-color: #ffffff;
margin: 0;
z-index: 3;
the width, length, background color, margins, and z-index can vary of course, but in order to cover the padding, the z-index must be higher than 0 so that it will lay over the padding. You can fiddle with positioning and such to change its orientation. Hope that helps!
P.S. the divs are html and the #paddingOne and #paddingTwo are css (in case anyone didn't get that:)
I get this every time I want to create an application in VC++.
Right-click the project, select Properties then under 'Configuration properties | C/C++ | Code Generation', select "Multi-threaded Debug (/MTd)" for Debug configuration.
Note that this does not change the setting for your Release configuration - you'll need to go to the same location and select "Multi-threaded (/MT)" for Release.
From my code, comparing to above solution, the simplest way is to define a layout which contains the fragment, then you could hide or unhide the fragment by controlling the layout attribute which is align with the general way of view. No additional code needed in this case and the additional deployment attributes of the fragment could be moved to the outer layout.
<LinearLayout style="@style/StHorizontalLinearView"
>
<fragment
android:layout_width="match_parent"
android:layout_height="390dp"
android:layout_alignParentTop="true"
/>
</LinearLayout>
THE 2019 ANSWER for macOS Sierra & High Sierra & Catalina:
PS: most of the other answers will have you to create a new ssh key ... but you don't need to do that :)
As described in detail on https://openradar.appspot.com/27348363, macOS/OS X till Yosemite used to remember SSH keys added by command ssh-add -K <key>
So here are the 4 steps i had to take in order for it to work:
1: ssh-add ~/.ssh/PATH_TO_YOUR_SSH_PRIVATE_KEY (e.g. ~/.ssh/id_rsa)
2: Add the following in ~/.ssh/config
Host *
AddKeysToAgent yes
UseKeychain yes
IdentityFile PATH_TO_YOUR_SSH_PRIVATE_KEY (e.g. ~/.ssh/id_rsa)
3: make sure to remove any gitconfig entry that use osxkeychain helper:
https://github.com/gregory/dotfiles/commit/e38000527fb1a82b577f2dcf685aeefd3b78a609#diff-6cb0f77b38346e0fed47293bdc6430c6L48
4: restart your terminal for it to take effect.