Since I reached here while searching to join on a specific property of a list of objects (and not the ToString() of it) here's an addition to the accepted answer:
var commaDelimited = string.Join(",", students.Where(i => i.Category == studentCategory)
.Select(i => i.FirstName));
If anyone is trying to build a hello world application using Jersey, I think one of the easiest ways is to follow Jersey documentation.
https://jersey.github.io/download.html
If you are already using maven, it'd take only a few minutes to see the result.
I used below.
mvn archetype:generate -DarchetypeGroupId=org.glassfish.jersey.archetypes -DarchetypeArtifactId=jersey-quickstart-webapp -DarchetypeVersion=2.26
What can you do if you need to make a change to a file, but don’t know the file’s encoding? If you know the encoding is ASCII-compatible and only want to examine or modify the ASCII parts, you can open the file with the surrogateescape error handler:
with open(fname, 'r', encoding="ascii", errors="surrogateescape") as f:
data = f.read()
Well I'am totally late to party :) I had the need for ansible play that creates multiple local users with randoms passwords. This what I came up with, used some of examples from top and put them together with some changes.
create-user-with-password.yml
---
# create_user playbook
- hosts: all
become: True
user: root
vars:
#Create following user
users:
- test24
- test25
#with group
group: wheel
roles:
- create-user-with-password
/roles/create-user-with-password/tasks/main.yml
- name: Generate password for new user
local_action: shell pwgen -s -N 1 20
register: user_password
with_items: "{{ users }}"
run_once: true
- name: Generate encrypted password
local_action: shell python -c 'import crypt; print(crypt.crypt( "{{ item.stdout }}", crypt.mksalt(crypt.METHOD_SHA512)))'
register: encrypted_user_password
with_items: "{{ user_password.results }}"
run_once: true
- name: Create new user with group
user:
name: "{{ item }}"
groups: "{{ group }}"
shell: /bin/bash
append: yes
createhome: yes
comment: 'Created with ansible'
with_items:
- "{{ users }}"
register: user_created
- name: Update user Passwords
user:
name: '{{ item.0 }}'
password: '{{ item.1.stdout }}'
with_together:
- "{{ users }}"
- "{{ encrypted_user_password.results }}"
when: user_created.changed
- name: Force user to change the password at first login
shell: chage -d 0 "{{ item }}"
with_items:
- "{{ users }}"
when: user_created.changed
- name: Save Passwords Locally
become: no
local_action: copy content={{ item.stdout }} dest=./{{ item.item }}.txt
with_items: "{{ user_password.results }}"
when: user_created.changed
There is a partial solution for Chrome:
select { width: 400px; text-align-last:center; }
It does center the selected option, but not the options inside the dropdown.
Another solution that doesn't require changing your existing code:
import Queue # Python 2.x
#from queue import Queue # Python 3.x
from threading import Thread
def foo(bar):
print 'hello {0}'.format(bar)
return 'foo'
que = Queue.Queue() # Python 2.x
#que = Queue() # Python 3.x
t = Thread(target=lambda q, arg1: q.put(foo(arg1)), args=(que, 'world!'))
t.start()
t.join()
result = que.get()
print result
It can be also easily adjusted to a multi-threaded environment:
import Queue # Python 2.x
#from queue import Queue # Python 3.x
from threading import Thread
def foo(bar):
print 'hello {0}'.format(bar)
return 'foo'
que = Queue.Queue() # Python 2.x
#que = Queue() # Python 3.x
threads_list = list()
t = Thread(target=lambda q, arg1: q.put(foo(arg1)), args=(que, 'world!'))
t.start()
threads_list.append(t)
# Add more threads here
...
threads_list.append(t2)
...
threads_list.append(t3)
...
# Join all the threads
for t in threads_list:
t.join()
# Check thread's return value
while not que.empty():
result = que.get()
print result
The HTML4 spec for the <input>
element specifies the following script events are available:
onfocus, onblur, onselect, onchange, onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup
here's an example that bind's to all these events and shows what's going on http://jsfiddle.net/pxfunc/zJ7Lf/
I think you can filter out which events are truly relevent to your situation and detect what the text value was before and after the event to determine a change
float
and double
don't store decimal places. They store binary places: float
is (assuming IEEE 754) 24 significant bits (7.22 decimal digits) and double is 53 significant bits (15.95 significant digits).
Converting from double
to float
will give you the closest possible float
, so rounding won't help you. Goining the other way may give you "noise" digits in the decimal representation.
#include <stdio.h>
int main(void) {
double orig = 12345.67;
float f = (float) orig;
printf("%.17g\n", f); // prints 12345.669921875
return 0;
}
To get a double
approximation to the nice decimal value you intended, you can write something like:
double round_to_decimal(float f) {
char buf[42];
sprintf(buf, "%.7g", f); // round to 7 decimal digits
return atof(buf);
}
This works, but all the children of the element with this class will also become transparent, without any way of preventing that.
.css-class-name {
opacity:0.8;
}
Try
var ts = TimeSpan.Parse(stringTime);
With a newer .NET you also have
TimeSpan ts;
if(!TimeSpan.TryParse(stringTime, out ts)){
// throw exception or whatnot
}
// ts now has a valid format
This is the general idiom for parsing strings in .NET with the first version handling erroneous string by throwing FormatException and the latter letting the Boolean TryParse give you the information directly.
Let me explain why sleep infinity
works though it is not documented. jp48's answer is also useful.
The most important thing: By specifying inf
or infinity
(both case-insensitive), you can sleep for the longest time your implementation permits (i.e. the smaller value of HUGE_VAL
and TYPE_MAXIMUM(time_t)
).
Now let's dig into the details. The source code of sleep
command can be read from coreutils/src/sleep.c. Essentially, the function does this:
double s; //seconds
xstrtod (argv[i], &p, &s, cl_strtod); //`p` is not essential (just used for error check).
xnanosleep (s);
xstrtod (argv[i], &p, &s, cl_strtod)
xstrtod()
According to gnulib/lib/xstrtod.c, the call of xstrtod()
converts string argv[i]
to a floating point value and stores it to *s
, using a converting function cl_strtod()
.
cl_strtod()
As can be seen from coreutils/lib/cl-strtod.c, cl_strtod()
converts a string to a floating point value, using strtod()
.
strtod()
According to man 3 strtod
, strtod()
converts a string to a value of type double
. The manpage says
The expected form of the (initial portion of the) string is ... or (iii) an infinity, or ...
and an infinity is defined as
An infinity is either "INF" or "INFINITY", disregarding case.
Although the document tells
If the correct value would cause overflow, plus or minus
HUGE_VAL
(HUGE_VALF
,HUGE_VALL
) is returned
, it is not clear how an infinity is treated. So let's see the source code gnulib/lib/strtod.c. What we want to read is
else if (c_tolower (*s) == 'i'
&& c_tolower (s[1]) == 'n'
&& c_tolower (s[2]) == 'f')
{
s += 3;
if (c_tolower (*s) == 'i'
&& c_tolower (s[1]) == 'n'
&& c_tolower (s[2]) == 'i'
&& c_tolower (s[3]) == 't'
&& c_tolower (s[4]) == 'y')
s += 5;
num = HUGE_VAL;
errno = saved_errno;
}
Thus, INF
and INFINITY
(both case-insensitive) are regarded as HUGE_VAL
.
HUGE_VAL
family
Let's use N1570 as the C standard. HUGE_VAL
, HUGE_VALF
and HUGE_VALL
macros are defined in §7.12-3
The macro
HUGE_VAL
expands to a positive double constant expression, not necessarily representable as a float. The macros
HUGE_VALF
HUGE_VALL
are respectively float and long double analogs ofHUGE_VAL
.
HUGE_VAL
,HUGE_VALF
, andHUGE_VALL
can be positive infinities in an implementation that supports infinities.
and in §7.12.1-5
If a floating result overflows and default rounding is in effect, then the function returns the value of the macro
HUGE_VAL
,HUGE_VALF
, orHUGE_VALL
according to the return type
xnanosleep (s)
Now we understand all essence of xstrtod()
. From the explanations above, it is crystal-clear that xnanosleep(s)
we've seen first actually means xnanosleep(HUGE_VALL)
.
xnanosleep()
According to the source code gnulib/lib/xnanosleep.c, xnanosleep(s)
essentially does this:
struct timespec ts_sleep = dtotimespec (s);
nanosleep (&ts_sleep, NULL);
dtotimespec()
This function converts an argument of type double
to an object of type struct timespec
. Since it is very simple, let me cite the source code gnulib/lib/dtotimespec.c. All of the comments are added by me.
struct timespec
dtotimespec (double sec)
{
if (! (TYPE_MINIMUM (time_t) < sec)) //underflow case
return make_timespec (TYPE_MINIMUM (time_t), 0);
else if (! (sec < 1.0 + TYPE_MAXIMUM (time_t))) //overflow case
return make_timespec (TYPE_MAXIMUM (time_t), TIMESPEC_HZ - 1);
else //normal case (looks complex but does nothing technical)
{
time_t s = sec;
double frac = TIMESPEC_HZ * (sec - s);
long ns = frac;
ns += ns < frac;
s += ns / TIMESPEC_HZ;
ns %= TIMESPEC_HZ;
if (ns < 0)
{
s--;
ns += TIMESPEC_HZ;
}
return make_timespec (s, ns);
}
}
Since time_t
is defined as an integral type (see §7.27.1-3), it is natural we assume the maximum value of type time_t
is smaller than HUGE_VAL
(of type double
), which means we enter the overflow case. (Actually this assumption is not needed since, in all cases, the procedure is essentially the same.)
make_timespec()
The last wall we have to climb up is make_timespec()
. Very fortunately, it is so simple that citing the source code gnulib/lib/timespec.h is enough.
_GL_TIMESPEC_INLINE struct timespec
make_timespec (time_t s, long int ns)
{
struct timespec r;
r.tv_sec = s;
r.tv_nsec = ns;
return r;
}
Often we have to modify a substring with a few keywords spread across lines preceding the substring. Consider an xml element:
<TASK>
<UID>21</UID>
<Name>Architectural design</Name>
<PercentComplete>81</PercentComplete>
</TASK>
Suppose we want to modify the 81, to some other value, say 40. First identify .UID.21..UID.
, then skip all characters including \n
till .PercentCompleted.
. The regular expression pattern and the replace specification are:
String hw = new String("<TASK>\n <UID>21</UID>\n <Name>Architectural design</Name>\n <PercentComplete>81</PercentComplete>\n</TASK>");
String pattern = new String ("(<UID>21</UID>)((.|\n)*?)(<PercentComplete>)(\\d+)(</PercentComplete>)");
String replaceSpec = new String ("$1$2$440$6");
//note that the group (<PercentComplete>) is $4 and the group ((.|\n)*?) is $2.
String iw = hw.replaceFirst(pattern, replaceSpec);
System.out.println(iw);
<TASK>
<UID>21</UID>
<Name>Architectural design</Name>
<PercentComplete>40</PercentComplete>
</TASK>
The subgroup (.|\n)
is probably the missing group $3
. If we make it non-capturing by (?:.|\n)
then the $3
is (<PercentComplete>)
. So the pattern and replaceSpec
can also be:
pattern = new String("(<UID>21</UID>)((?:.|\n)*?)(<PercentComplete>)(\\d+)(</PercentComplete>)");
replaceSpec = new String("$1$2$340$5")
and the replacement works correctly as before.
You will need to use openssl.
openssl pkcs12 -export -out domain.name.pfx -inkey domain.name.key -in domain.name.crt
The key file is just a text file with your private key in it.
If you have a root CA and intermediate certs, then include them as well using multiple -in
params
openssl pkcs12 -export -out domain.name.pfx -inkey domain.name.key -in domain.name.crt -in intermediate.crt -in rootca.crt
You can install openssl from here: openssl
$('input.abc').not(':checked').length > 0
select * from my_table where my_field Like '[a-z][a-z]%'
You probably mean Notification.Builder.setLargeIcon(Bitmap)
, right? :)
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.large_icon);
notBuilder.setLargeIcon(largeIcon);
This is a great method of converting resource images into Android Bitmap
s.
I think that the beginning of your query should look like that:
SELECT
tl.storenum [Store #],
co.ccnum [FuelFirst Card #],
co.dtentered [Date Entered],
CASE st.reasonid
WHEN 1 THEN 'Active'
WHEN 2 THEN 'Not Active'
WHEN 0 THEN st.ccstatustypename
ELSE 'Unknown'
END [Status],
CASE st.ccstatustypename
WHEN 'Active' THEN ' '
WHEN 'Not Active' THEN ' '
ELSE st.ccstatustypename
END [Reason],
UPPER(REPLACE(REPLACE(co.personentered,'RT\\\\',''),'RACETRAC\\\\','')) [Person Entered],
co.comments [Comments or Notes]
FROM comments co
INNER JOIN cards cc ON co.ccnum=cc.ccnum
INNER JOIN customerinfo ci ON cc.customerinfoid=ci.customerinfoid
INNER JOIN ccstatustype st ON st.ccstatustypeid=cc.ccstatustypeid
INNER JOIN customerstatus cs ON cs.customerstatuscd=ci.customerstatuscd
INNER JOIN transactionlog tl ON tl.transactionlogid=co.transactionlogid
LEFT JOIN stores s ON s.StoreNum = tl.StoreNum
WHERE
CASE
WHEN (LEN([TestPerson]) = 0 AND co.personentered = co.personentered) OR (LEN([TestPerson]) <> 0 AND co.personentered LIKE '%'+TestPerson) THEN 1
ELSE 0
END = 1
AND
BUT
what is in the tail is completely not understandable
import requests
site_request = requests.get("https://abhiunix.in")
site_response = str(site_request.content)
print(site_response)
He're the full migration for Laravel 5:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedInteger('user_id')->nullable()->change();
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedInteger('user_id')->nullable(false)->change();
});
}
The point is, you can remove nullable
by passing false
as an argument.
Your onClick
request:
<span class="A" onclick="var state = this.className.indexOf('A') > -1; $(this).toggleClass('A', !state).toggleClass('B', state);">Click Me</span>
Try it: https://jsfiddle.net/v15q6b5y/
Just the JS à la jQuery:
$('.selector').toggleClass('A', !state).toggleClass('B', state);
Bucket Brigade
They are used extensively in Apache. Basically they are a linked list that loops around on itself in a ring. I am not sure if they are used outside of Apache and Apache modules but they fit the bill as a cool yet lesser known data structure. A bucket is a container for some arbitrary data and a bucket brigade is a collection of buckets. The idea is that you want to be able to modify and insert data at any point in the structure.
Lets say that you have a bucket brigade that contains an html document with one character per bucket. You want to convert all the <
and >
symbols into <
and >
entities. The bucket brigade allows you to insert some extra buckets in the brigade when you come across a <
or >
symbol in order to fit the extra characters required for the entity. Because the bucket brigade is in a ring you can insert backwards or forwards. This is much easier to do (in C) than using a simple buffer.
Some reference on bucket brigades below:
Using a pseudo element, this method doesn't require knowledge of the original element and doesn't require any additional markup.
#someElement{
color: transparent; /* You may need to change this color */
position: relative;
}
#someElement:after { /* Or use :before if that tickles your fancy */
content: "New text";
color: initial;
position: absolute;
top: 0;
left: 0;
}
For me , df1.subtract(df2) was inconsistent. Worked correctly on one dataframe but not on the other . That was because of duplicates . df1.exceptAll(df2) returns a new dataframe with the records from df1 that do not exist in df2 , including any duplicates.
git reset HEAD~1
if you don't want your changes to be gone(unstaged changes). Change, commit and push again git push -f [origin] [branch]
Use \overleftarrow
to create a long arrow to the left.
\overleftarrow{blahblahblah}
The following script would obtain the ci.jenkins-ci.org public key certificate in base64-encoded DER format and convert it to an OpenSSH public key file. This code assumes that a 2048-bit RSA key is used and draws a lot from this Ian Boyd's answer. I've explained a bit more how it works in comments to this article in Jenkins wiki.
echo -n "ssh-rsa " > jenkins.pub
curl -sfI https://ci.jenkins-ci.org/ | grep -i X-Instance-Identity | tr -d \\r | cut -d\ -f2 | base64 -d | dd bs=1 skip=32 count=257 status=none | xxd -p -c257 | sed s/^/00000007\ 7373682d727361\ 00000003\ 010001\ 00000101\ / | xxd -p -r | base64 -w0 >> jenkins.pub
echo >> jenkins.pub
while (fscanf(input,"%s",arr) != EOF && count!=7) {
len=strlen(arr);
count++;
}
This code will work for you, because i had a simmilar problem and this worked for me. :)
1- Override Onstart() method in your fragment-dialog class.
@Override
public void onStart() {
super.onStart();
final AlertDialog D = (AlertDialog) getDialog();
if (D != null) {
Button positive = (Button) D.getButton(Dialog.BUTTON_POSITIVE);
positive.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (edittext.equals("")) {
Toast.makeText(getActivity(), "EditText empty",Toast.LENGTH_SHORT).show();
} else {
D.dismiss(); //dissmiss dialog
}
}
});
}
}
A cleaner way of iterating the lists is:
// initialise the collection
collection = new ArrayList<ArrayList<String>>();
// iterate
for (ArrayList<String> innerList : collection) {
for (String string : innerList) {
// do stuff with string
}
}
I found a workaround to this which worked for me.
With Chrome selected as your browser, click the Debug
menu and select Attach to Process...
.
In the subsequent dialog, select Chrome.exe
in the list and click the Select
button for Attach to:
. Tick the Native
box, then Attach
(or just double-click Chrome.exe
):
This starts the project running without launching the browser. Stop and restart in Chrome and the error is gone.
Of course, another potential solution is to use a different browser but I like debugging in Chrome. :-)
For Win7 Acrobat Pro X
Since I did all these without rechecking to see if the problem still existed afterwards, I am not sure which on of these actually fixed the problem, but one of them did. In fact, after doing the #3 and rebooting, it worked perfectly.
FYI: Below is the order in which I stepped through the repair.
Go to Control Panel
> folders options under each of the General
, View
and Search
Tabs
click the Restore Defaults
button and the Reset Folders
button
Go to Internet Explorer
, Tools
> Options
> Advanced
> Reset
( I did not need to delete personal settings)
Open Acrobat Pro X
, under Edit
> Preferences
> General
.
At the bottom of page select Default PDF Handler
. I chose Adobe Pro X
, and click Apply
.
You may be asked to reboot (I did).
Best Wishes
Updating:
Using adb shell input
:
Insert text:
adb shell input text "insert%syour%stext%shere"
(obs: %s means SPACE)
..
Event codes:
adb shell input keyevent 82
(82 ---> MENU_BUTTON)
"For more keyevents codes see list below"
..
Tap X,Y position:
adb shell input tap 500 1450
To find the exact X,Y position you want to Tap go to:
Settings > Developer Options > Check the option POINTER SLOCATION
..
Swipe X1 Y1 X2 Y2 [duration(ms)]:
adb shell input swipe 100 500 100 1450 100
in this example X1=100, Y1=500, X2=100, Y2=1450, Duration = 100ms
..
LongPress X Y:
adb shell input swipe 100 500 100 500 250
we utilise the same command for a swipe to emulate a long press
in this example X=100, Y=500, Duration = 250ms
..
Event Codes Updated List:
0 --> "KEYCODE_0"
1 --> "KEYCODE_SOFT_LEFT"
2 --> "KEYCODE_SOFT_RIGHT"
3 --> "KEYCODE_HOME"
4 --> "KEYCODE_BACK"
5 --> "KEYCODE_CALL"
6 --> "KEYCODE_ENDCALL"
7 --> "KEYCODE_0"
8 --> "KEYCODE_1"
9 --> "KEYCODE_2"
10 --> "KEYCODE_3"
11 --> "KEYCODE_4"
12 --> "KEYCODE_5"
13 --> "KEYCODE_6"
14 --> "KEYCODE_7"
15 --> "KEYCODE_8"
16 --> "KEYCODE_9"
17 --> "KEYCODE_STAR"
18 --> "KEYCODE_POUND"
19 --> "KEYCODE_DPAD_UP"
20 --> "KEYCODE_DPAD_DOWN"
21 --> "KEYCODE_DPAD_LEFT"
22 --> "KEYCODE_DPAD_RIGHT"
23 --> "KEYCODE_DPAD_CENTER"
24 --> "KEYCODE_VOLUME_UP"
25 --> "KEYCODE_VOLUME_DOWN"
26 --> "KEYCODE_POWER"
27 --> "KEYCODE_CAMERA"
28 --> "KEYCODE_CLEAR"
29 --> "KEYCODE_A"
30 --> "KEYCODE_B"
31 --> "KEYCODE_C"
32 --> "KEYCODE_D"
33 --> "KEYCODE_E"
34 --> "KEYCODE_F"
35 --> "KEYCODE_G"
36 --> "KEYCODE_H"
37 --> "KEYCODE_I"
38 --> "KEYCODE_J"
39 --> "KEYCODE_K"
40 --> "KEYCODE_L"
41 --> "KEYCODE_M"
42 --> "KEYCODE_N"
43 --> "KEYCODE_O"
44 --> "KEYCODE_P"
45 --> "KEYCODE_Q"
46 --> "KEYCODE_R"
47 --> "KEYCODE_S"
48 --> "KEYCODE_T"
49 --> "KEYCODE_U"
50 --> "KEYCODE_V"
51 --> "KEYCODE_W"
52 --> "KEYCODE_X"
53 --> "KEYCODE_Y"
54 --> "KEYCODE_Z"
55 --> "KEYCODE_COMMA"
56 --> "KEYCODE_PERIOD"
57 --> "KEYCODE_ALT_LEFT"
58 --> "KEYCODE_ALT_RIGHT"
59 --> "KEYCODE_SHIFT_LEFT"
60 --> "KEYCODE_SHIFT_RIGHT"
61 --> "KEYCODE_TAB"
62 --> "KEYCODE_SPACE"
63 --> "KEYCODE_SYM"
64 --> "KEYCODE_EXPLORER"
65 --> "KEYCODE_ENVELOPE"
66 --> "KEYCODE_ENTER"
67 --> "KEYCODE_DEL"
68 --> "KEYCODE_GRAVE"
69 --> "KEYCODE_MINUS"
70 --> "KEYCODE_EQUALS"
71 --> "KEYCODE_LEFT_BRACKET"
72 --> "KEYCODE_RIGHT_BRACKET"
73 --> "KEYCODE_BACKSLASH"
74 --> "KEYCODE_SEMICOLON"
75 --> "KEYCODE_APOSTROPHE"
76 --> "KEYCODE_SLASH"
77 --> "KEYCODE_AT"
78 --> "KEYCODE_NUM"
79 --> "KEYCODE_HEADSETHOOK"
80 --> "KEYCODE_FOCUS"
81 --> "KEYCODE_PLUS"
82 --> "KEYCODE_MENU"
83 --> "KEYCODE_NOTIFICATION"
84 --> "KEYCODE_SEARCH"
85 --> "KEYCODE_MEDIA_PLAY_PAUSE"
86 --> "KEYCODE_MEDIA_STOP"
87 --> "KEYCODE_MEDIA_NEXT"
88 --> "KEYCODE_MEDIA_PREVIOUS"
89 --> "KEYCODE_MEDIA_REWIND"
90 --> "KEYCODE_MEDIA_FAST_FORWARD"
91 --> "KEYCODE_MUTE"
92 --> "KEYCODE_PAGE_UP"
93 --> "KEYCODE_PAGE_DOWN"
94 --> "KEYCODE_PICTSYMBOLS"
...
122 --> "KEYCODE_MOVE_HOME"
123 --> "KEYCODE_MOVE_END"
The complete list of commands can be found on: http://developer.android.com/reference/android/view/KeyEvent.html
Arrange them in the order you wants to show. Suppose, you wanna show view 1 on top of view 2. Then write view 2 code then write view 1 code. If you cant does this ordering, then call bringToFront() to the root view of the layout you wants to bring in front.
INTERNAL : Table is created First and Data is loaded later
EXTERNAL : Data is present and Table is created on top of it.
There are times when it's useful to implement an interface that will be returned from within the class, but the implementation of that interface should be completely hidden from the outside world.
As an example - prior to the addition of yield to C#, one way to implement enumerators was to put the implementation of the enumerator as a private class within a collection. This would provide easy access to the members of the collection, but the outside world would not need/see the details of how this is implemented.
I think what you are looking for is this:
public class Ques2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine().toLowerCase();
StringBuilder result = new StringBuilder();
char currentCharacter;
int count;
for (int i = 0; i < input.length(); i++) {
currentCharacter = input.charAt(i);
count = 1;
while (i < input.length() - 1 && input.charAt(i + 1) == currentCharacter) {
count++;
i++;
}
result.append(currentCharacter);
result.append(count);
}
System.out.println("" + result);
}
}
To set image on your imageView use below line of code,
self.imgObj.image=[UIImage imageNamed:@"yourImage.png"];
function update() {
$("#notice_div").html('Loading..');
$.ajax({
type: 'GET',
url: 'jbede.php',
timeout: 2000,
success: function(data) {
$("#some_div").html(data);
$("#notice_div").html('');
window.setTimeout(update, 10000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#notice_div").html('Timeout contacting server..');
window.setTimeout(update, 60000);
}
});
}
$(document).ready(function() {
update();
});
This is Better Code
Because it's the same component. You can either listen to route change by injecting the ActivatedRoute
and reacting to changes of params and query params, or you can change the default RouteReuseStrategy
, so that a component will be destroyed and re-rendered when the URL changes instead of re-used.
Try the notepad++ plugin JSMinNpp(Changed name to JSTool since 1.15)
This worked just fine for me on Win 10:
[{ "keys": ["ctrl+7"], "command": "toggle_comment", "args": { "block": false } },
{ "keys": ["ctrl+shift+7"], "command": "toggle_comment", "args": { "block": true } }
]
note that "[ ]" are nesassary and it will give you an error if you miss them.
using System.Net;
WebClient webClient = new WebClient();
webClient.DownloadFile("http://mysite.com/myfile.txt", @"c:\myfile.txt");
They are almost as same... But the key difference is a thread is lightweight and a process is heavy-weight in terms of context switching, work load and so on.
Simple answer: (watch for blank & null)
isNaN(+'111') = false;
isNaN(+'111r') = true;
isNaN(+'r') = true;
isNaN(+'') = false;
isNaN(null) = false;
Generally speaking, it is set in the "Project Structure" dialog.
Go to File > Project Structure > SDK Location. The third field is "JDK Location" where you can set it. This will set it for the current project.
To set the default for new projects, go to File > Other Settings > Default Project Structure > SDK Location and set the "JDK Location".
Go to File > Project Structure > [Platform Settings] > SDKs. You'll need to either update you current SDK configuration to use the new directory, or define a new one and then change your project's settings to use the new one. This will set it for the current project.
To set the default for new projects, go to File > Other Settings > Structure for New Projects > [Platform Settings] > SDKs and set the SDK to use when creating a new project.
If you're in a heavily concurrent environment, then pure functional programming is useful. The lack of mutable state makes concurrency almost trivial. See Erlang.
In a multiparadigm language, you may want to model some things functionally if the existence of mutable state is must an implementation detail, and thus FP is a good model for the problem domain. For example, see list comprehensions in Python or std.range in the D programming language. These are inspired by functional programming.
This link "Finding All Installed Browsers in Windows XP and Vista – beware 64bit!" may be useful for Windows as suggested by "How to find all the browsers installed on a machine".
The installed web browsers are saved in this registry,
HKEY_LOCAL_MACHINE\SOFTWARE\Clients\StartMenuInternet
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Clients\StartMenuInternet.
Python does not have a defined entry point like Java, C, C++, etc. Rather it simply executes a source file line-by-line. The if
statement allows you to create a main
function which will be executed if your file is loaded as the "Main" module rather than as a library in another module.
To be clear, this means that the Python interpreter starts at the first line of a file and executes it. Executing lines like class Foobar:
and def foobar()
creates either a class or a function and stores them in memory for later use.
That's all unnecessary logic in partials, reduce it to something like this and process your data in controller/service where it should be
<div ng-repeat="details in myDataSet">
<p>{{ details.Name }}</p>
<p>{{ details.DOB }}</p>
<p>{{details.Payment[0].StatusName}}</p>
<p>{{ details.Gender}}</p>
</div>
JS:
angular.forEach(myDataSet.Payment, function (payment) {
if(payment.Status === 0){
payment.StatusName = 'No Payment';
} else if(payment.Status === 1 || payment.Status === 2){
payment.StatusName = 'Late';
} else if(payment.Status === 3 || payment.Status === 4 || payment.Status === 5){
payment.StatusName = 'Some payment made';
} else if(payment.Status === 6){
payment.StatusName = 'Late and further taken out';
}else{
payment.StatusName = 'Error';
}
})
I had similar issue running emulator from android studio everytime, or on a physical device. Instead, you can quickly run android emulator from command line,
android avd
Once the emulator is running, you can check with adb devices
if the emulator shows up.
Then you can simply use
react-native run-android
to run the app on the emulator.
Make sure you've platform tools installed to be able to use adb
. Or you can use
brew install android-platform-tools
You should remember that shell scripting is less of a language and more of a collection of commands. Instinctively you think that this "language" requires you to follow an if
with a [
or a [[
. Both of those are just commands that return an exit status indicating success or failure (just like every other command). For that reason I'd use grep
, and not the [
command.
Just do:
if grep -q foo <<<"$string"; then
echo "It's there"
fi
Now that you are thinking of if
as testing the exit status of the command that follows it (complete with semi-colon), why not reconsider the source of the string you are testing?
## Instead of this
filetype="$(file -b "$1")"
if grep -q "tar archive" <<<"$filetype"; then
#...
## Simply do this
if file -b "$1" | grep -q "tar archive"; then
#...
The -q
option makes grep not output anything, as we only want the return code. <<<
makes the shell expand the next word and use it as the input to the command, a one-line version of the <<
here document (I'm not sure whether this is standard or a Bashism).
well bubble sort is better than insertion sort only when someone is looking for top k elements from a large list of number i.e. in bubble sort after k iterations you'll get top k elements. However after k iterations in insertion sort, it only assures that those k elements are sorted.
If you have control over the structure of the list, the most pythonic thing to do would probably be to change it from:
l=[1,2,3,4]
to:
l=[(1,2),(3,4)]
Then, your loop would be:
for i,j in l:
print i, j
I wrote the #4 answer (at time of writing). But lately I have git installed on all my computers, so now I use @Sybren's solution. Here is a new answer that makes that solution handy from powershell (without putting all of git/usr/bin in the PATH, which is too much clutter for me).
Add this to your profile.ps1
:
$global:gitbin = 'C:\Program Files\Git\usr\bin'
Set-Alias file.exe $gitbin\file.exe
And used like: file.exe --mime-encoding *
. You must include .exe in the command for PS alias to work.
But if you don't customize your PowerShell profile.ps1 I suggest you start with mine: https://gist.github.com/yzorg/8215221/8e38fd722a3dfc526bbe4668d1f3b08eb7c08be0
and save it to ~\Documents\WindowsPowerShell
. It's safe to use on a computer without git, but will write warnings when git is not found.
The .exe in the command is also how I use C:\WINDOWS\system32\where.exe
from powershell; and many other OS CLI commands that are "hidden by default" by powershell, *shrug*.
The following gives you list of operating system users sorted by number of connections, which is useful when looking for excessive resource usage.
select osuser, count(*) as active_conn_count
from v$session
group by osuser
order by active_conn_count desc
you can write .WorkbookConnection.Delete after .Refresh BackgroundQuery:=False this will delete text file external connection.
You need to checkout the branch:
git checkout master
See the Git cheat sheets for more information.
Edit: Please note that git does not manage empty directories, so you'll have to manage them yourself. If your directory is empty, just remove it directly.
Inspired by samneric's answer using DataRowComparer.Default but needing something that would only compare a subset of columns within a DataTable, I made a DataTableComparer object where you can specify which columns to use in the comparison. Especially great if they have different columns/schemas.
DataRowComparer.Default works because it implements IEqualityComparer. Then I created an object where you can define which columns of the DataRow will be compared.
public class DataTableComparer : IEqualityComparer<DataRow>
{
private IEnumerable<String> g_TestColumns;
public void SetCompareColumns(IEnumerable<String> p_Columns)
{
g_TestColumns = p_Columns;
}
public bool Equals(DataRow x, DataRow y)
{
foreach (String sCol in g_TestColumns)
if (!x[sCol].Equals(y[sCol])) return false;
return true;
}
public int GetHashCode(DataRow obj)
{
StringBuilder hashBuff = new StringBuilder();
foreach (String sCol in g_TestColumns)
hashBuff.AppendLine(obj[sCol].ToString());
return hashBuff.ToString().GetHashCode();
}
}
You can use this by:
DataTableComparer comp = new DataTableComparer();
comp.SetCompareColumns(new String[] { "Name", "DoB" });
DataTable celebrities = SomeDataTableSource();
DataTable politicians = SomeDataTableSource2();
List<DataRow> celebrityPoliticians = celebrities.AsEnumerable().Intersect(politicians.AsEnumerable(), comp).ToList();
SET SQL_SAFE_UPDATES=0;
OR
Go to Edit --> Preferences
Click SQL Queries
tab and uncheck Safe Updates
check box
Query --> Reconnect to Server
Now execute your sql query
When we want to replace the new line character \n
with the space:
xargs < file
xargs
has own limits on the number of characters per line and the number of all characters combined, but we can increase them. Details can be found by running this command: xargs --show-limits
and of course in the manual: man xargs
When we want to replace one character with another exactly one character:
tr '\n' ' ' < file
When we want to replace one character with many characters:
tr '\n' '~' < file | sed s/~/many_characters/g
First, we replace the newline characters \n
for tildes ~
(or choose another unique character not present in the text), and then we replace the tilde characters with any other characters (many_characters
) and we do it for each tilde (flag g
).
void CMRSMATH1Dlg::Loadit(TCHAR *destination, CDC &memdc)
{
CImage img;
PBITMAPINFO bmi;
BITMAPINFOHEADER Info;
BITMAPFILEHEADER bFileHeader;
CBitmap bm;
CFile file2;
file2.Open(destination, CFile::modeRead | CFile::typeBinary);
file2.Read(&bFileHeader, sizeof(BITMAPFILEHEADER));
file2.Read(&Info, sizeof(BITMAPINFOHEADER));
BYTE ch;
int width = Info.biWidth;
int height = Info.biHeight;
if (height < 0)height = -height;
int size1 = width*height * 3;
int size2 = ((width * 24 + 31) / 32) * 4 * height;
int widthnew = (size2 - size1) / height;
BYTE * buffer = (BYTE *)GlobalAlloc(GPTR, size2);
//////////////////////////
HGDIOBJ old;
unsigned char alpha = 0;
int z = 0;
z = 0;
int gap = (size2 - size1) / height;
for (int y = 0;y < height;y++)
{
for (int x = 0;x < width*3;x++)
{
file2.Read(&ch, 1);
buffer[z] = ch;
z++;
}
for (int z1 = 0;z1 <gap;z1++)
{
file2.Read(&ch,1);
}
}
bm.CreateCompatibleBitmap(&memdc, width, height);
bm.SetBitmapBits(size1,buffer);
old = memdc.SelectObject(&bm);
///////////////////////////
//bm.SetBitmapBits(size1, buffer);
GetDC()->BitBlt(1, 95, width, height, &memdc, 0, 0, SRCCOPY);
memdc.SelectObject(&old);
bm.DeleteObject();
GlobalFree(buffer);
file2.Close();
}
void CMRSMATH1Dlg::saveit(CBitmap &bit1, CDC &memdc, TCHAR *destination)
{
BITMAP bm;
PBITMAPINFO bmi;
BITMAPINFOHEADER Info;
BITMAPFILEHEADER bFileHeader;
CFile file1;
CSize size = bit1.GetBitmap(&bm);
int z = 0;
BYTE ch = 0;
size.cx = bm.bmWidth;
size.cy = bm.bmHeight;
int width = size.cx;
int size1 = (size.cx)*(size.cy);
int size2 = size1 * 3;
size1 = ((size.cx * 24 + 31) / 32) *4* size.cy;
BYTE * buffer = (BYTE *)GlobalAlloc(GPTR, size2);
bFileHeader.bfType = 'B' + ('M' << 8);
bFileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
bFileHeader.bfSize = bFileHeader.bfOffBits + size1;
bFileHeader.bfReserved1 = 0;
bFileHeader.bfReserved2 = 0;
Info.biSize = sizeof(BITMAPINFOHEADER);
Info.biPlanes = 1;
Info.biBitCount = 24;//bm.bmBitsPixel;//bitsperpixel///////////////////32
Info.biCompression = BI_RGB;
Info.biWidth =bm.bmWidth;
Info.biHeight =-bm.bmHeight;///reverse pic if negative height
Info.biSizeImage =size1;
Info.biClrImportant = 0;
if (bm.bmBitsPixel <= 8)
{
Info.biClrUsed = 1 << bm.bmBitsPixel;
}else
Info.biClrUsed = 0;
Info.biXPelsPerMeter = 0;
Info.biYPelsPerMeter = 0;
bit1.GetBitmapBits(size2, buffer);
file1.Open(destination, CFile::modeCreate | CFile::modeWrite |CFile::typeBinary,0);
file1.Write(&bFileHeader, sizeof(BITMAPFILEHEADER));
file1.Write(&Info, sizeof(BITMAPINFOHEADER));
unsigned char alpha = 0;
for (int y = 0;y<size.cy;y++)
{
for (int x = 0;x<size.cx;x++)
{
//for reverse picture below
//z = (((size.cy - 1 - y)*size.cx) + (x)) * 3;
z = (((y)*size.cx) + (x)) * 3;
file1.Write(&buffer[z], 1);
file1.Write(&buffer[z + 1], 1);
file1.Write(&buffer[z + 2], 1);
}
for (int z = 0;z < (size1 - size2) / size.cy;z++)
{
file1.Write(&alpha, 1);
}
}
GlobalFree(buffer);
file1.Close();
file1.m_hFile = NULL;
}
In mongoDB shell this code might be helpful:
db.collection.update({}, {$unset: {fieldname: ""}} )
This code helps:
data final; set final;
first_date = INPUT(compress(char_date),date9.); format first_date date9.;
run;
I personally have tried it on SAS
If your SQL Server table has a column of type INT IDENTITY
(or BIGINT IDENTITY
), then you can get the latest inserted value using:
INSERT INTO dbo.YourTable(columns....)
VALUES(..........)
SELECT SCOPE_IDENTITY()
This works as long as you haven't inserted another row - it just returns the last IDENTITY
value handed out in this scope here.
There are at least two more options - @@IDENTITY
and IDENT_CURRENT
- read more about how they works and in what way they're different (and might give you unexpected results) in this excellent blog post by Pinal Dave here.
I did a work around. I had a hidden textbox to hold the value. Then, on form_onsubmit,
I copied the path value, less the file name to the hidden folder. Then, set the fileInput box to "". That way, no file is uploaded.
I don't recall the event of the fileUpload control. Maybe onchange. It's been a while. If there's a value, I parse off the file name and put the folder back to the box. Of, course you'd validate that the file as a valid file.
This would give you the clients workstation folder.
However, if you want to reflect server paths, that requires a whole different coding approach.
Ok, already having DOM, JaxB and XStream in the list of answers, there is still a complete different way to read and write XML: Data projection You can decouple the XML structure and the Java structure by using a library that provides read and writeable views to the XML Data as Java interfaces. From the tutorials:
Given some real world XML:
<weatherdata>
<weather
...
degreetype="F"
lat="50.5520210266113" lon="6.24060010910034"
searchlocation="Monschau, Stadt Aachen, NW, Germany"
... >
<current ... skytext="Clear" temperature="46"/>
</weather>
</weatherdata>
With data projection you can define a projection interface:
public interface WeatherData {
@XBRead("/weatherdata/weather/@searchlocation")
String getLocation();
@XBRead("/weatherdata/weather/current/@temperature")
int getTemperature();
@XBRead("/weatherdata/weather/@degreetype")
String getDegreeType();
@XBRead("/weatherdata/weather/current/@skytext")
String getSkytext();
/**
* This would be our "sub projection". A structure grouping two attribute
* values in one object.
*/
interface Coordinates {
@XBRead("@lon")
double getLongitude();
@XBRead("@lat")
double getLatitude();
}
@XBRead("/weatherdata/weather")
Coordinates getCoordinates();
}
And use instances of this interface just like POJOs:
private void printWeatherData(String location) throws IOException {
final String BaseURL = "http://weather.service.msn.com/find.aspx?outputview=search&weasearchstr=";
// We let the projector fetch the data for us
WeatherData weatherData = new XBProjector().io().url(BaseURL + location).read(WeatherData.class);
// Print some values
System.out.println("The weather in " + weatherData.getLocation() + ":");
System.out.println(weatherData.getSkytext());
System.out.println("Temperature: " + weatherData.getTemperature() + "°"
+ weatherData.getDegreeType());
// Access our sub projection
Coordinates coordinates = weatherData.getCoordinates();
System.out.println("The place is located at " + coordinates.getLatitude() + ","
+ coordinates.getLongitude());
}
This works even for creating XML, the XPath expressions can be writable.
A script that runs hourly to retrain my spam filters based two IMAP folder where span and ham are put.
#!/bin/sh
FNDIR="train-as-spam"
FPDIR="train-as-ham"
for dir in /home/*/.maildir
do
cd "${dir}"
USER=`stat -c %U .`
SRCDIR="${dir}/.${FNDIR}"
if [ ! -d ${SRCDIR} ]; then
echo no "${SRCDIR}" directory
else
cd "${SRCDIR}/cur"
ls -tr | while read file
do
if grep -q "^X-DSPAM" "${file}"; then
SOURCE="error"
else
SOURCE="corpus"
fi
dspam --user "${USER}" --class=spam --source="${SOURCE}" --deliver=innocent,spam --stdout < "${file}" > "../tmp/${file}"
mv "../tmp/${file}" "${dir}/new/${file%%:*}" && rm "${file}"
done
fi
SRCDIR="${dir}/.${FPDIR}"
if [ ! -d ${SRCDIR} ]; then
echo no "${SRCDIR}" directory
else
cd "${SRCDIR}/cur"
ls -tr | while read file
do
if grep -q "^X-DSPAM" "${file}"; then
SOURCE="error"
else
SOURCE="corpus"
fi
dspam --user "${USER}" --class=innocent --source="${SOURCE}" --deliver=innocent,spam --stdout < "${file}" > "../tmp/${file}"
mv "../tmp/${file}" "${dir}/new/${file%%:*}" && rm "${file}"
done
fi
done
Mecki's answer is absolutly perfect, but it's worth adding that FreeBSD also supports SO_REUSEPORT_LB
, which mimics Linux' SO_REUSEPORT
behaviour - it balances the load; see setsockopt(2)
you could read and write to a seperately like others. But if you want to write into the same one, you could try with this:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
double data[size of your data];
std::ifstream input("file.txt");
for (int i = 0; i < size of your data; i++) {
input >> data[i];
std::cout<< data[i]<<std::endl;
}
}
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
Typically if you have database connections or other objects declared that, whether used safely or created prior to your exception, will need to be cleaned up (disposed of), then returning your error handling code back to the ProcExit entry point will allow you to do your garbage collection in both cases.
If you drop out of your procedure by falling to Exit Sub, you may risk having a yucky build-up of instantiated objects that are just sitting around in your program's memory.
Use:
grep -- -X
Related: What does a bare double dash mean? (thanks to nutty about natty).
Try the display max_columns setting as follows:
import pandas as pd
from IPython.display import display
df = pd.read_csv("some_data.csv")
pd.options.display.max_columns = None
display(df)
Or
pd.set_option('display.max_columns', None)
Edit: Pandas 0.11.0 backwards
This is deprecated but in versions of Pandas older than 0.11.0 the max_columns
setting is specified as follows:
pd.set_printoptions(max_columns=500)
to overwiting the previous line in python all wath you need is to add end='\r' to the print function, test this example:
import time
for j in range(1,5):
print('waiting : '+j, end='\r')
time.sleep(1)
Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.
You can use User Accounts by pressing Window
+R
, typing netplwiz
and pressing OK as described here.
I would add, and also to answer the question find mean bin values using histogram2d python that the scipy also have a function specially designed to compute a bidimensional binned statistic for one or more sets of data
import numpy as np
from scipy.stats import binned_statistic_2d
x = np.random.rand(100)
y = np.random.rand(100)
values = np.random.rand(100)
bin_means = binned_statistic_2d(x, y, values, bins=10).statistic
the function scipy.stats.binned_statistic_dd is a generalization of this funcion for higher dimensions datasets
import json
myDict = {'dict': [{'a': 'none', 'b': 'none', 'c': 'none'}]}
test = json.dumps(myDict)
print(test)
{"dict": [{"a": "none", "b": "none", "c": "none"}]}
myDict['dict'].append(({'a': 'aaaa', 'b': 'aaaa', 'c': 'aaaa'}))
test = json.dumps(myDict)
print(test)
{"dict": [{"a": "none", "b": "none", "c": "none"}, {"a": "aaaa", "b": "aaaa", "c": "aaaa"}]}
Create the environment with virtualenv --system-site-packages
. Then, activate the virtualenv and when you want things installed in the virtualenv rather than the system python, use pip install --ignore-installed
or pip install -I
. That way pip will install what you've requested locally even though a system-wide version exists. Your python interpreter will look first in the virtualenv's package directory, so those packages should shadow the global ones.
CREATE FUNCTION dbo.UFN_GET_SQL_SEVER_VERSION
(
)
RETURNS sysname
AS
BEGIN
DECLARE @ServerVersion sysname, @ProductVersion sysname, @ProductLevel sysname, @Edition sysname;
SELECT @ProductVersion = CONVERT(sysname, SERVERPROPERTY('ProductVersion')),
@ProductLevel = CONVERT(sysname, SERVERPROPERTY('ProductLevel')),
@Edition = CONVERT(sysname, SERVERPROPERTY ('Edition'));
--see: http://support2.microsoft.com/kb/321185
SELECT @ServerVersion =
CASE
WHEN @ProductVersion LIKE '8.00.%' THEN 'Microsoft SQL Server 2000'
WHEN @ProductVersion LIKE '9.00.%' THEN 'Microsoft SQL Server 2005'
WHEN @ProductVersion LIKE '10.00.%' THEN 'Microsoft SQL Server 2008'
WHEN @ProductVersion LIKE '10.50.%' THEN 'Microsoft SQL Server 2008 R2'
WHEN @ProductVersion LIKE '11.0%' THEN 'Microsoft SQL Server 2012'
WHEN @ProductVersion LIKE '12.0%' THEN 'Microsoft SQL Server 2014'
END
RETURN @ServerVersion + N' ('+@ProductLevel + N'), ' + @Edition + ' - ' + @ProductVersion;
END
GO
If the previous answers do not solve your problem, check the source of the data that won't print/convert properly.
In my case, I was using json.load
on data incorrectly read from file by not using the encoding="utf-8"
. Trying to de-/encode the resulting string to latin-1
just does not help...
You can use unirest, It provides easy method to post request. `
import unirest
def callback(response):
print "code:"+ str(response.code)
print "******************"
print "headers:"+ str(response.headers)
print "******************"
print "body:"+ str(response.body)
print "******************"
print "raw_body:"+ str(response.raw_body)
# consume async post request
def consumePOSTRequestASync():
params = {'test1':'param1','test2':'param2'}
# we need to pass a dummy variable which is open method
# actually unirest does not provide variable to shift between
# application-x-www-form-urlencoded and
# multipart/form-data
params['dummy'] = open('dummy.txt', 'r')
url = 'http://httpbin.org/post'
headers = {"Accept": "application/json"}
# call get service with headers and params
unirest.post(url, headers = headers,params = params, callback = callback)
# post async request multipart/form-data
consumePOSTRequestASync()
You can do this, just wrap it in typeof()
foo.GetColumnValues(typeof(int))
public void GetColumnValues(Type type)
{
//logic
}
However, if you do end up using rm instead of git rm. You can skip the git add and directly commit the changes using:
git commit -a
git branch --merged master
lists branches merged into master
git branch --merged
lists branches merged into HEAD (i.e. tip of current branch)
git branch --no-merged
lists branches that have not been merged
By default this applies to only the local branches. The -a
flag will show both local and remote branches, and the -r
flag shows only the remote branches.
Sounds like you're looking to simulate the IE6 box model. You could use the CSS 3 property box-sizing: border-box to achieve this. This is supported by IE8, but for Firefox you would need to use -moz-box-sizing
and for Safari/Chrome, use -webkit-box-sizing
.
IE6 already computes the height wrong, so you're good in that browser, but I'm not sure about IE7, I think it will compute the height the same in quirks mode.
According to the official documentation on sitemaps.org it needs to be a full URL:
You can specify the location of the Sitemap using a robots.txt file. To do this, simply add the following line including the full URL to the sitemap:
Sitemap: http://www.example.com/sitemap.xml
Use of folloing command is depreciated
hadoop job -list
hadoop job -kill $jobId
consider using
mapred job -list
mapred job -kill $jobId
You can set background color of view to the UIColor with alpha, and not affect view.alpha
:
view.backgroundColor = UIColor(white: 1, alpha: 0.5)
or
view.backgroundColor = UIColor.red.withAlphaComponent(0.5)
There is a small error in the code of @DyingCactus. Here is the correct solution to add an UILabel to an UIButton to align the button text to better control the button 'title':
NSString *myLabelText = @"Hello World";
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
// position in the parent view and set the size of the button
myButton.frame = CGRectMake(myX, myY, myWidth, myHeight);
CGRect myButtonRect = myButton.bounds;
UILabel *myLabel = [[UILabel alloc] initWithFrame: myButtonRect];
myLabel.text = myLabelText;
myLabel.backgroundColor = [UIColor clearColor];
myLabel.textColor = [UIColor redColor];
myLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:14.0];
myLabel.textAlignment = UITextAlignmentLeft;
[myButton addSubview:myLabel];
[myLabel release];
Hope this helps....
Al
I think this is the culprit:
cmd = new SqlCommand(query, con);
DataTable dt = Select(query);
cmd.ExecuteNonQuery();
ddtype.DataSource = dt;
I don't know what that code is supposed to do, but it looks like you want to create an SqlDataReader
for that, as explained here and all over the web if you search for "SqlCommand DropDownList DataSource":
cmd = new SqlCommand(query, con);
ddtype.DataSource = cmd.ExecuteReader();
Or you can create a DataTable
as explained here:
cmd = new SqlCommand(query, con);
SqlDataAdapter listQueryAdapter = new SqlDataAdapter(cmd);
DataTable listTable = new DataTable();
listQueryAdapter.Fill(listTable);
ddtype.DataSource = listTable;
Try aligning top and bottom of text view to one of the icon, this will make text view sharing same height as them, then set gravity
to center_vertical
to make the text inside text view center vertically.
<TextView
android:id="@+id/func_text" android:layout_toRightOf="@id/icon"
android:layout_alignTop="@id/icon" android:layout_alignBottom="@id/icon"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:gravity="center_vertical" />
regular expression normally uses * and + in theory of language. I encounter the same bug while executing the line code
re.split("*",text)
to solve it, it needs to include \ before * and +
re.split("\*",text)
Spring documentation to disable csrf: https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#csrf-configure
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}
well when i had these problem i faced 2 code errors
{!! Form::model(['method' => 'POST','route' => ['message.store']]) !!}
i corrected it by doing this
{!! Form::open(['method' => 'POST','route' => 'message.store']) !!}
so just to expatiate i changed the form model
to open
and also the route where wrongly placed in square braces.
@chappers solution (in the comments) works as.integer(as.logical(data.frame$column.name))
The encoding declaration identifies which encoding is used to represent the characters in the document.
More on the XML Declaration here: http://msdn.microsoft.com/en-us/library/ms256048.aspx
You can use jQuery load method to get the contents and insert into an element.
Try this:
$(document).ready(function() {
$("#lesen").click(function() {
$(".text").load("helloworld.txt");
});
});
You, can also add a call back to execute something once the load process is complete
e.g:
$(document).ready(function() {
$("#lesen").click(function() {
$(".text").load("helloworld.txt", function(){
alert("Done Loading");
});
});
});
cq.select(cb.construct(entityClazz.class, root.get("ID"), root.get("VERSION"))); // HERE IS NO ERROR
Convert your image file to Base64 string with a tool like this and then replace the YourBase64StringHere
placeholder in the below snippet with your string and put the line in your HTML head section:
<link href="data:image/x-icon;base64,YourBase64StringHere" rel="icon" type="image/x-icon" />
This will work 100% in browsers.
I ran across a solution that doesn't use image maps at all but rather anchor tags that are absolutely positioned over the image. The only drawback would be that the hotspot would have to be rectangular, but the plus is that this solution doesn't rely on Javascript, just CSS. There is a website that you can use to generate the HTML code for the anchors: http://www.zaneray.com/responsive-image-map/
I put the image and the generated anchor tags in a relatively positioned div tag and everything worked perfectly on window resize and on my mobile phone.
Hibernate has a built-in "yes_no" type that would do what you want. It maps to a CHAR(1) column in the database.
Basic mapping: <property name="some_flag" type="yes_no"/>
Annotation mapping (Hibernate extensions):
@Type(type="yes_no")
public boolean getFlag();
The not straightforward way of doing it would be granting select on each table of the database:
postgres=# grant select on db_name.table_name to read_only_user;
You could automate that by generating your grant statements from the database metadata.
Tried pushy's answer above and it worked for the most part. However, in certain circumstances, I would see this exception:
java.lang.String cannot be cast to java.lang.ProcessEnvironment$Variable
This turns out to happen when the method was called more than once, owing to the implementation of certain inner classes of ProcessEnvironment.
If the setEnv(..)
method is called more than once, when the keys are retrieved from the theEnvironment
map, they are now strings (having been put in as strings by the first invocation of setEnv(...)
) and cannot be cast to the map's generic type, Variable,
which is a private inner class of ProcessEnvironment.
A fixed version (in Scala), is below. Hopefully it isn't too difficult to carry over into Java.
def setEnv(newenv: java.util.Map[String, String]): Unit = {
try {
val processEnvironmentClass = JavaClass.forName("java.lang.ProcessEnvironment")
val theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment")
theEnvironmentField.setAccessible(true)
val variableClass = JavaClass.forName("java.lang.ProcessEnvironment$Variable")
val convertToVariable = variableClass.getMethod("valueOf", classOf[java.lang.String])
convertToVariable.setAccessible(true)
val valueClass = JavaClass.forName("java.lang.ProcessEnvironment$Value")
val convertToValue = valueClass.getMethod("valueOf", classOf[java.lang.String])
convertToValue.setAccessible(true)
val sampleVariable = convertToVariable.invoke(null, "")
val sampleValue = convertToValue.invoke(null, "")
val env = theEnvironmentField.get(null).asInstanceOf[java.util.Map[sampleVariable.type, sampleValue.type]]
newenv.foreach { case (k, v) => {
val variable = convertToVariable.invoke(null, k).asInstanceOf[sampleVariable.type]
val value = convertToValue.invoke(null, v).asInstanceOf[sampleValue.type]
env.put(variable, value)
}
}
val theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment")
theCaseInsensitiveEnvironmentField.setAccessible(true)
val cienv = theCaseInsensitiveEnvironmentField.get(null).asInstanceOf[java.util.Map[String, String]]
cienv.putAll(newenv);
}
catch {
case e : NoSuchFieldException => {
try {
val classes = classOf[java.util.Collections].getDeclaredClasses
val env = System.getenv()
classes foreach (cl => {
if("java.util.Collections$UnmodifiableMap" == cl.getName) {
val field = cl.getDeclaredField("m")
field.setAccessible(true)
val map = field.get(env).asInstanceOf[java.util.Map[String, String]]
// map.clear() // Not sure why this was in the code. It means we need to set all required environment variables.
map.putAll(newenv)
}
})
} catch {
case e2: Exception => e2.printStackTrace()
}
}
case e1: Exception => e1.printStackTrace()
}
}
OP here, I have learned a lot more about node since I first asked this question. Though Dmitry's answer was very helpful, what ultimately did it for me is to install node with the correct permissions.
I highly recommend not installing node using any package managers, but rather to compile it yourself so that it resides in a local directory with normal permissions.
This article provides a very clear step-by-step instruction of how to do so:
var http = require("http");
var url = "http://api.example.com/api/v1/?param1=1¶m2=2";
var options = {
host: "http://api.example.com",
port: 80,
method: "GET",
path: url,//I don't know for some reason i have to use full url as a path
auth: username + ':' + password
};
http.get(options, function(rs) {
var result = "";
rs.on('data', function(data) {
result += data;
});
rs.on('end', function() {
console.log(result);
});
});
The following characters must be escaped in JSON data to avoid any problems:
"
(double quote)\
(backslash)\n
, \t
JSON Parser can help you to deal with JSON.
Just move the extra condition into the JOIN ON criteria, this way the existence of b is not required to return a result
SELECT a.* FROM a
LEFT JOIN b ON a.group_id=b.group_id AND b.user_id!=$_SESSION{['user_id']}
WHERE a.keyword LIKE '%".$keyword."%'
GROUP BY group_id
APIs are messy because they keep changing. This pure javascript way worked for me:
<div id="divScope" class="boom-lightbox" style="display: none;">
<iframe id="ytplayer" width="720" height="405" src="https://www.youtube.com/embed/M7lc1UVf-VE" frameborder="0" allowfullscreen> </iframe>
</div>
//if I want i can set scope to a specific region
var myScope = document.getElementById('divScope');
//otherwise set scope as the entire document
//var myScope = document;
//if there is an iframe inside maybe embedded multimedia video/audio, we should reload so it stops playing
var iframes = myScope.getElementsByTagName("iframe");
if (iframes != null) {
for (var i = 0; i < iframes.length; i++) {
iframes[i].src = iframes[i].src; //causes a reload so it stops playing, music, video, etc.
}
}
for line in f
reads all file to a memory, and that can be a problem.
My offer is to change the original source by replacing stripping and checking for empty line. Because if it is not last line - You will receive at least newline character in it ('\n'). And '.strip()' removes it. But in last line of a file You will receive truely empty line, without any characters. So the following loop will not give You false EOF, and You do not waste a memory:
with open("blablabla.txt", "r") as fl_in:
while True:
line = fl_in.readline()
if not line:
break
line = line.strip()
# do what You want
@hussachai and @Jeffrey Kemp answers are pretty good. But they have something in common is the url returned is of virtual-host-style, not in path style. For more info regarding to the s3 url style, can refer to AWS S3 URL Styles. In case of some people want to have path style s3 url generated. Here's the step. Basically everything will be the same as @hussachai and @Jeffrey Kemp answers, only with one line setting change as below:
AmazonS3Client s3Client = (AmazonS3Client) AmazonS3ClientBuilder.standard()
.withRegion("us-west-2")
.withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
.withPathStyleAccessEnabled(true)
.build();
// Upload a file as a new object with ContentType and title specified.
PutObjectRequest request = new PutObjectRequest(bucketName, stringObjKeyName, fileToUpload);
s3Client.putObject(request);
URL s3Url = s3Client.getUrl(bucketName, stringObjKeyName);
logger.info("S3 url is " + s3Url.toExternalForm());
This will generate url like: https://s3.us-west-2.amazonaws.com/mybucket/myfilename
You wont be able to access a local resource from your aspx page (web server). Have you tried a relative path from your aspx page to your css file like so...
<link rel="stylesheet" media="all" href="/CSS/Style.css" type="text/css" />
The above assumes that you have a folder called CSS
in the root of your website like this:
http://www.website.com/CSS/Style.css
The $?
syntax is pretty neat:
if [ $?BLAH == 1 ]; then
echo "Exists";
else
echo "Does not exist";
fi
What if you just wrap your code into function?
So this:
cd ~/documents
mkdir test
echo "useless script" > about.txt
Becomes this:
CommentedOutBlock() {
cd ~/documents
mkdir test
echo "useless script" > about.txt
}
While most of the above answers provide a way to do this, there is already a built-in way to accomplish this and it's 1 line of code (ThumbnailUtils.extractThumbnail()
)
int dimension = getSquareCropDimensionForBitmap(bitmap);
bitmap = ThumbnailUtils.extractThumbnail(bitmap, dimension, dimension);
...
//I added this method because people keep asking how
//to calculate the dimensions of the bitmap...see comments below
public int getSquareCropDimensionForBitmap(Bitmap bitmap)
{
//use the smallest dimension of the image to crop to
return Math.min(bitmap.getWidth(), bitmap.getHeight());
}
If you want the bitmap object to be recycled, you can pass options that make it so:
bitmap = ThumbnailUtils.extractThumbnail(bitmap, dimension, dimension, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
From: ThumbnailUtils Documentation
public static Bitmap extractThumbnail (Bitmap source, int width, int height)
Added in API level 8 Creates a centered bitmap of the desired size.
Parameters source original bitmap source width targeted width height targeted height
I was getting out of memory errors sometimes when using the accepted answer, and using ThumbnailUtils resolved those issues for me. Plus, this is much cleaner and more reusable.
Must it be mutable? Use a list. Must it not be mutable? Use a tuple.
Otherwise, it's a question of choice.
For collections of heterogeneous objects (like a address broken into name, street, city, state and zip) I prefer to use a tuple. They can always be easily promoted to named tuples.
Likewise, if the collection is going to be iterated over, I prefer a list. If it's just a container to hold multiple objects as one, I prefer a tuple.
Reading from specific line:
n = 4 # for reading from 5th line
with open("write.txt",'r') as t:
for i,line in enumerate(t):
if i >= n: # i == n-1 for nth line
print(line)
I've found this script example useful (from http://www.mrexcel.com/forum/excel-questions/898899-json-api-excel.html#post4332075 ):
Sub getData()
Dim Movie As Object
Dim scriptControl As Object
Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
scriptControl.Language = "JScript"
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json", False
.send
Set Movie = scriptControl.Eval("(" + .responsetext + ")")
.abort
With Sheets(2)
.Cells(1, 1).Value = Movie.Title
.Cells(1, 2).Value = Movie.Year
.Cells(1, 3).Value = Movie.Rated
.Cells(1, 4).Value = Movie.Released
.Cells(1, 5).Value = Movie.Runtime
.Cells(1, 6).Value = Movie.Director
.Cells(1, 7).Value = Movie.Writer
.Cells(1, 8).Value = Movie.Actors
.Cells(1, 9).Value = Movie.Plot
.Cells(1, 10).Value = Movie.Language
.Cells(1, 11).Value = Movie.Country
.Cells(1, 12).Value = Movie.imdbRating
End With
End With
End Sub
Here is the solution:
<input type="text" id="end_dt"/>
$(document).ready(function () {
$("#end_dt").datepicker({ dateFormat: "MM/dd/yyyy" });
});
hopefully this will resolve the issue :)
Like any project setting, the buildevents can be configured per Configuration. Just select the configuration you want to change in the dropdown of the Property Pages dialog and edit the post build step.
And if you mean select the ID of the last record inserted, its
SELECT @@IDENTITY FROM table
The zeroth parameter of a shell command is the command itself (or sometimes the shell itself). You should be using $1
.
(("$#" < 1)) && ( (("$1" != 1)) || (("$1" -ne 0q)) )
Your boolean logic is also a bit confused:
(( "$#" < 1 && # If the number of arguments is less than one…
"$1" != 1 || "$1" -ne 0)) # …how can the first argument possibly be 1 or 0?
This is probably what you want:
(( "$#" )) && (( $1 == 1 || $1 == 0 )) # If true, there is at least one argument and its value is 0 or 1
I think you are looking for below method:
var idList=new int[]{1, 2, 3, 4};
using (var db=new SomeDatabaseContext())
{
var friends= db.Friends.Where(f=>idList.Contains(f.ID));
friends.ForEachAsync(a=>a.msgSentBy='1234');
await db.SaveChangesAsync();
}
This should be the efficient way of handling this.
Best answer doesn't work for me. I needed ssh://
from the beggining.
# does not work
git remote set-url origin [email protected]:10000/aaa/bbbb/ccc.git
# work
git remote set-url origin ssh://[email protected]:10000/aaa/bbbb/ccc.git
Run the following immediately after the dialog is called in the Ajax:
$(".ui-dialog-titlebar").hide();
$(".ui-dialog").addClass("customclass");
This applies just to the dialog that is opened, so it can be changed for each one used.
(This quick answer is based on another response on Stack Overflow.)
According to ruby doc http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-key key(value) is the method to find the key on the base of value.
ROLE = {"customer" => 1, "designer" => 2, "admin" => 100}
ROLE.key(2)
it will return the "designer".
As everyone else says, LoadLibrary is the hard way to do it, and is hardly ever necessary.
The DLL should have come with a .lib file for linking, and one or more header files to #include into your sources. The header files will define the classes and function prototypes that you can use from the DLL. You will need this even if you use LoadLibrary.
To link with the library, you might have to add the .lib file to the project configuration under Linker/Input/Additional Dependencies.
The most compact (for dynamic data) put @mathias-dpunkt solution into MainApp (with Lombok @AllArgsConstructor
):
@SpringBootApplication
@AllArgsConstructor
public class RestaurantVotingApplication implements ApplicationRunner {
private final VoteRepository voteRepository;
private final UserRepository userRepository;
public static void main(String[] args) {
SpringApplication.run(RestaurantVotingApplication.class, args);
}
@Override
public void run(ApplicationArguments args) {
voteRepository.save(new Vote(userRepository.getOne(1), LocalDate.now(), LocalTime.now()));
}
}
TF2 runs Eager Execution by default, thus removing the need for Sessions. If you want to run static graphs, the more proper way is to use tf.function()
in TF2. While Session can still be accessed via tf.compat.v1.Session()
in TF2, I would discourage using it. It may be helpful to demonstrate this difference by comparing the difference in hello worlds:
TF1.x hello world:
import tensorflow as tf
msg = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(msg))
TF2.x hello world:
import tensorflow as tf
msg = tf.constant('Hello, TensorFlow!')
tf.print(msg)
For more info, see Effective TensorFlow 2
it's easy to export mylib.so
to env:
$ export LD_PRELOAD=/path/mylib.so
$ ./mybin
to disable :
$ export LD_PRELOAD=
You should not replace the text entirely. Add the text after the "# END WordPress".
Having looked at all the given solutions I thought that there has to be a pure SQL method that does not require a function or a CTE / XML query, and doesn't involve difficult to maintain nested REPLACE statements. Here is my solution:
SELECT
x
,CASE WHEN a NOT LIKE '%' + SUBSTRING(x, 1, 1) + '%' THEN '' ELSE SUBSTRING(x, 1, 1) END
+ CASE WHEN a NOT LIKE '%' + SUBSTRING(x, 2, 1) + '%' THEN '' ELSE SUBSTRING(x, 2, 1) END
+ CASE WHEN a NOT LIKE '%' + SUBSTRING(x, 3, 1) + '%' THEN '' ELSE SUBSTRING(x, 3, 1) END
+ CASE WHEN a NOT LIKE '%' + SUBSTRING(x, 4, 1) + '%' THEN '' ELSE SUBSTRING(x, 4, 1) END
+ CASE WHEN a NOT LIKE '%' + SUBSTRING(x, 5, 1) + '%' THEN '' ELSE SUBSTRING(x, 5, 1) END
+ CASE WHEN a NOT LIKE '%' + SUBSTRING(x, 6, 1) + '%' THEN '' ELSE SUBSTRING(x, 6, 1) END
-- Keep adding rows until you reach the column size
AS stripped_column
FROM (SELECT
column_to_strip AS x
,'ABCDEFGHIJKLMNOPQRSTUVWXYZ' AS a
FROM my_table) a
The advantage of doing it this way is that the valid characters are contained in the one string in the sub query making easy to reconfigure for a different set of characters.
The downside is that you have to add a row of SQL for each character up to the size of your column. To make that task easier I just used the Powershell script below, this example if for a VARCHAR(64):
1..64 | % {
" + CASE WHEN a NOT LIKE '%' + SUBSTRING(x, {0}, 1) + '%' THEN '' ELSE SUBSTRING(x, {0}, 1) END" -f $_
} | clip.exe
compareTo()
is from the Comparable
interface.
compare()
is from the Comparator
interface.
Both methods do the same thing, but each interface is used in a slightly different context.
The Comparable interface is used to impose a natural ordering on the objects of the implementing class. The compareTo()
method is called the natural comparison method. The Comparator interface is used to impose a total ordering on the objects of the implementing class. For more information, see the links for exactly when to use each interface.
The is not
operator is preferred over negating the result of is
for stylistic reasons. "if x is not None:
" reads just like English, but "if not x is None:
" requires understanding of the operator precedence and does not read like english.
If there is a performance difference my money is on is not
, but this almost certainly isn't the motivation for the decision to prefer that technique. It would obviously be implementation-dependent. Since is
isn't overridable, it should be easy to optimise out any distinction anyhow.
I find jackson fasterxml
is one good choice to serializing/deserializing
bean with XML.
Google's Android Documentation Says that :
An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
AsyncTask's generic types :
The three types used by an asynchronous task are the following:
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.
Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:
private class MyTask extends AsyncTask<Void, Void, Void> { ... }
You Can further refer : http://developer.android.com/reference/android/os/AsyncTask.html
Or You Can clear whats the role of AsyncTask by refering Sankar-Ganesh's Blog
private class MyTask extends AsyncTask<X, Y, Z>
protected void onPreExecute(){
}
This method is executed before starting the new Thread. There is no input/output values, so just initialize variables or whatever you think you need to do.
protected Z doInBackground(X...x){
}
The most important method in the AsyncTask class. You have to place here all the stuff you want to do in the background, in a different thread from the main one. Here we have as an input value an array of objects from the type “X” (Do you see in the header? We have “...extends AsyncTask” These are the TYPES of the input parameters) and returns an object from the type “Z”.
protected void onProgressUpdate(Y y){
}
This method is called using the method publishProgress(y) and it is usually used when you want to show any progress or information in the main screen, like a progress bar showing the progress of the operation you are doing in the background.
protected void onPostExecute(Z z){
}
This method is called after the operation in the background is done. As an input parameter you will receive the output parameter of the doInBackground method.
What about the X, Y and Z types?
As you can deduce from the above structure:
X – The type of the input variables value you want to set to the background process. This can be an array of objects.
Y – The type of the objects you are going to enter in the onProgressUpdate method.
Z – The type of the result from the operations you have done in the background process.
How do we call this task from an outside class? Just with the following two lines:
MyTask myTask = new MyTask();
myTask.execute(x);
Where x is the input parameter of the type X.
Once we have our task running, we can find out its status from “outside”. Using the “getStatus()” method.
myTask.getStatus();
and we can receive the following status:
RUNNING - Indicates that the task is running.
PENDING - Indicates that the task has not been executed yet.
FINISHED - Indicates that onPostExecute(Z) has finished.
Hints about using AsyncTask
Do not call the methods onPreExecute, doInBackground and onPostExecute manually. This is automatically done by the system.
You cannot call an AsyncTask inside another AsyncTask or Thread. The call of the method execute must be done in the UI Thread.
The method onPostExecute is executed in the UI Thread (here you can call another AsyncTask!).
The input parameters of the task can be an Object array, this way you can put whatever objects and types you want.
I had the exact same problem you describe above (Galaxy Nexus on t-mobile USA) it is because mobile data is turned off.
In Jelly Bean it is: Settings > Data Usage > mobile data
Note that I have to have mobile data turned on PRIOR to sending an MMS OR receiving one. If I receive an MMS with mobile data turned off, I will get the notification of a new message and I will receive the message with a download button. But if I do not have mobile data on prior, the incoming MMS attachment will not be received. Even if I turn it on after the message was received.
For some reason when your phone provider enables you with the ability to send and receive MMS you must have the Mobile Data enabled, even if you are using Wifi, if the Mobile Data is enabled you will be able to receive and send MMS, even if Wifi is showing as your internet on your device.
It is a real pain, as if you do not have it on, the message can hang a lot, even when turning on Mobile Data, and might require a reboot of the device.
hashlib.md5(pathlib.Path('path/to/file').read_bytes()).hexdigest()
Under ECMAScript 5, you can combine Object.keys()
and Array.prototype.forEach()
:
var obj = {_x000D_
first: "John",_x000D_
last: "Doe"_x000D_
};_x000D_
_x000D_
//_x000D_
// Visit non-inherited enumerable keys_x000D_
//_x000D_
Object.keys(obj).forEach(function(key) {_x000D_
_x000D_
console.log(key, obj[key]);_x000D_
_x000D_
});
_x000D_
If you want to add multiple items, you have to use the spread operator
a = [1,2]
b = [3,4,5,6]
a.push(...b)
The output will be
a = [1,2,3,4,5,6]
Yes, it's possible, from @Fábio Zangirolami answer
audio::-webkit-media-controls-panel, video::-webkit-media-controls-panel {
background-color: red;
}
You are correct, the default is my name asc. The only way I have found to change the sort order it to create a datatable from the FileInfo collection.
You can then used the DefaultView from the datatable and sort the directory with the .Sort method.
This is quite involve and fairly slow but I'm hoping someone will post a better solution.
One way to run a process from a different directory to the working directory of your Java program is to change directory and then run the process in the same command line. You can do this by getting cmd.exe
to run a command line such as cd some_directory && some_program
.
The following example changes to a different directory and runs dir
from there. Admittedly, I could just dir
that directory without needing to cd
to it, but this is only an example:
import java.io.*;
public class CmdTest {
public static void main(String[] args) throws Exception {
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "cd \"C:\\Program Files\\Microsoft SQL Server\" && dir");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) { break; }
System.out.println(line);
}
}
}
Note also that I'm using a ProcessBuilder
to run the command. Amongst other things, this allows me to redirect the process's standard error into its standard output, by calling redirectErrorStream(true)
. Doing so gives me only one stream to read from.
This gives me the following output on my machine:
C:\Users\Luke\StackOverflow>java CmdTest
Volume in drive C is Windows7
Volume Serial Number is D8F0-C934
Directory of C:\Program Files\Microsoft SQL Server
29/07/2011 11:03 <DIR> .
29/07/2011 11:03 <DIR> ..
21/01/2011 20:37 <DIR> 100
21/01/2011 20:35 <DIR> 80
21/01/2011 20:35 <DIR> 90
21/01/2011 20:39 <DIR> MSSQL10_50.SQLEXPRESS
0 File(s) 0 bytes
6 Dir(s) 209,496,424,448 bytes free
I was getting the same error and was able to solve it by updating my numpy installation to 1.8.0:
pip install -U numpy
You can solve the issue by adding below lines in web.config file.
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="8.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
As Jakob pointed out, android:popupBackground
is the key attribute for the dropdown (opened state of the Spinner), but instead of using just a colour, I got the best results with a 9-patch drawable like this:
menu_dropdown_panel.9.png
Note that it's very easy to generate this 9-patch image for the background colour of your choice, for example using this online tool as I explained in this answer!
So, my Spinner XML definition looks like:
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/navigationBlue"
android:spinnerMode="dropdown"
android:popupBackground="@drawable/menu_dropdown_panel"
/>
And the result:
(For custom fonts, as in the screenshot above, a custom SpinnerAdapter is needed too.)
Works at least on Android 4.0+ (API level 14+).
Use this for GET values:
Request.QueryString["key"]
And this for POST values
Request.Form["key"]
Also, this will work if you don't care whether it comes from GET or POST, or the HttpContext.Items collection:
Request["key"]
Another thing to note (if you need it) is you can check the type of request by using:
Request.RequestType
Which will be the verb used to access the page (usually GET or POST). Request.IsPostBack
will usually work to check this, but only if the POST request includes the hidden fields added to the page by the ASP.NET framework.
Version A (efficient push):
Version B (efficient pop):
This Can be Done by Style Property.
<!DOCTYPE html>
<html>
<head>
<style>
#main {
display: flex;
}
#main div {
flex-grow: 0;
flex-shrink: 0;
flex-basis: 40px;
}
</style>
</head>
<body>
<div id="main">
<div style="background-color:coral;">Red DIV</div>
<div style="background-color:lightblue;" id="myBlueDiv">Blue DIV</div>
</div>
</body>
</html>
Its Result will be :
Enjoy... Please Note: This works in Higher version of CSS (>3.0).
Try placing your text-decoration: none;
on your a:hover css.
You tagged the question with both sql-server and plsql so I will provide answers for both SQL Server and Oracle.
In SQL Server you can use FOR XML PATH
to concatenate multiple rows together:
select distinct t.[user],
STUFF((SELECT distinct ', ' + t1.department
from yourtable t1
where t.[user] = t1.[user]
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,2,'') department
from yourtable t;
See SQL Fiddle with Demo.
In Oracle 11g+ you can use LISTAGG
:
select "User",
listagg(department, ',') within group (order by "User") as departments
from yourtable
group by "User"
Prior to Oracle 11g, you could use the wm_concat
function:
select "User",
wm_concat(department) departments
from yourtable
group by "User"
The problem is that you are using a lower case v.
You need to set it to Value and it should fix your issue:
@Html.TextBoxFor(model => model.Destination, new { id = "txtPlace", Value= "3" })
Try the Following Code
SELECT Closing_Date = DATEADD(MONTH, DATEDIFF(MONTH, 0, Closing_Date), 0),
Category,
COUNT(Status) TotalCount
FROM MyTable
WHERE Closing_Date >= '2012-02-01'
AND Closing_Date <= '2012-12-31'
AND Defect_Status1 IS NOT NULL
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, Closing_Date), 0), Category;
You need to trick the browser to use hardware acceleration more effectively. You can do this with an empty 3d transform:
-webkit-transform: translate3d(0,0,0)
Particularly, you'll need this on child elements that have a position:relative;
declaration (or, just go all out and do it to all child elements).
Not a guaranteed fix, but fairly successful most of the time.
|
is the bitwise-or operator, and it is being applied like +=
.
For the sake of completion, what you describe as "position of points around a central point(assuming they're all equidistant from the center)" is nothing but "Polar Coordinates". And you are asking for way to Convert between polar and Cartesian coordinates which is given as x = r*cos(t)
, y = r*sin(t)
.
Clojure can be used, but it's slow.
See also: Clojure fork for Android, and a tutorial.
Note the extra comments.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
class JavaPaintUI extends JFrame {
private int tool = 1;
int currentX, currentY, oldX, oldY;
public JavaPaintUI() {
initComponents();
}
private void initComponents() {
// we want a custom Panel2, not a generic JPanel!
jPanel2 = new Panel2();
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
jPanel2.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
jPanel2.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
jPanel2MousePressed(evt);
}
public void mouseReleased(MouseEvent evt) {
jPanel2MouseReleased(evt);
}
});
jPanel2.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent evt) {
jPanel2MouseDragged(evt);
}
});
// add the component to the frame to see it!
this.setContentPane(jPanel2);
// be nice to testers..
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}// </editor-fold>
private void jPanel2MouseDragged(MouseEvent evt) {
if (tool == 1) {
currentX = evt.getX();
currentY = evt.getY();
oldX = currentX;
oldY = currentY;
System.out.println(currentX + " " + currentY);
System.out.println("PEN!!!!");
}
}
private void jPanel2MousePressed(MouseEvent evt) {
oldX = evt.getX();
oldY = evt.getY();
System.out.println(oldX + " " + oldY);
}
//mouse released//
private void jPanel2MouseReleased(MouseEvent evt) {
if (tool == 2) {
currentX = evt.getX();
currentY = evt.getY();
System.out.println("line!!!! from" + oldX + "to" + currentX);
}
}
//set ui visible//
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new JavaPaintUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private JPanel jPanel2;
// End of variables declaration
// This class name is very confusing, since it is also used as the
// name of an attribute!
//class jPanel2 extends JPanel {
class Panel2 extends JPanel {
Panel2() {
// set a preferred size for the custom panel.
setPreferredSize(new Dimension(420,420));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("BLAH", 20, 20);
g.drawRect(200, 200, 200, 200);
}
}
}
HFOE put a good link as the first comment on this thread. Camickr also has a description of active painting vs. drawing to a BufferedImage
in the Custom Painting Approaches article.
See also this approach using painting in a BufferedImage
.
This is very possible if you write your own helper. We are using a custom $
helper to accomplish this type of interaction (and more):
/*///////////////////////
Adds support for passing arguments to partials. Arguments are merged with
the context for rendering only (non destructive). Use `:token` syntax to
replace parts of the template path. Tokens are replace in order.
USAGE: {{$ 'path.to.partial' context=newContext foo='bar' }}
USAGE: {{$ 'path.:1.:2' replaceOne replaceTwo foo='bar' }}
///////////////////////////////*/
Handlebars.registerHelper('$', function(partial) {
var values, opts, done, value, context;
if (!partial) {
console.error('No partial name given.');
}
values = Array.prototype.slice.call(arguments, 1);
opts = values.pop();
while (!done) {
value = values.pop();
if (value) {
partial = partial.replace(/:[^\.]+/, value);
}
else {
done = true;
}
}
partial = Handlebars.partials[partial];
if (!partial) {
return '';
}
context = _.extend({}, opts.context||this, _.omit(opts, 'context', 'fn', 'inverse'));
return new Handlebars.SafeString( partial(context) );
});
Its not a good idea to pass Context
objects around. This often will lead to memory leaks. My suggestion is that you don't do it. I have made numerous Android apps without having to pass context to non-activity classes in the app. A better idea would be to get the resources you need access to while your in the Activity
or Fragment
, and hold onto it in another class. You can then use that class in any other classes in your app to access the resources, without having to pass around Context
objects.
You can use jsoup
to parse any kind of web page. Here you can find the jsoup library and full source code.
Here is an example: http://desicoding.blogspot.com/2011/03/how-to-parse-html-in-java-jsoup.html
To install in Eclipse:
You can parse according to tag/parent/child very comfortably
This problem appears when we are using any third party solution, without using the handlers for the cleanup activitiy. For me this was happening for EhCache. We were using EhCache in our project for caching. And often we used to see following error in the logs
SEVERE: The web application [/products] appears to have started a thread named [products_default_cache_configuration] but has failed to stop it. This is very likely to create a memory leak.
Aug 07, 2017 11:08:36 AM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/products] appears to have started a thread named [Statistics Thread-products_default_cache_configuration-1] but has failed to stop it. This is very likely to create a memory leak.
And we often noticed tomcat failing for OutOfMemory error during development where we used to do backend changes and deploy the application multiple times for reflecting our changes.
This is the fix we did
<listener>
<listener-class>
net.sf.ehcache.constructs.web.ShutdownListener
</listener-class>
</listener>
So point I am trying to make is check the documentation of the third party libraries which you are using. They should be providing some mechanisms to clean up the threads during shutdown. Which you need to use in your application. No need to re-invent the wheel unless its not provided by them. The worst case is to provide your own implementation.
Reference for EHCache Shutdown http://www.ehcache.org/documentation/2.8/operations/shutdown.html
This happened to me when an web request endpoint was switched to another server that accepted TLS1.2 requests only. Tried so many attempts mostly found on Stackoverflow like
The exception received did no make justice to the actual problem I was facing and found no help from the service operator.
To solve this I have to add a new Cipher Suite TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 I have used IIS Crypto 2.0 Tool from here as shown below.
using(var client = new System.Net.WebClient()) {
client.UploadData(address,"PUT",data);
}
Always try to do an associative fetch, that way you can easy get what you want in multiple case result
Here's an example
$result = $mysqli->query("SELECT COUNT(*) AS cityCount FROM myCity")
$row = $result->fetch_assoc();
echo $row['cityCount']." rows in table myCity.";
Bootstrap 3 with DataTables Example: Bootstrap Docs & DataTables Docs
$(document).ready(function() {
$('#example').DataTable();
});
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/css/dataTables.bootstrap.min.css rel=stylesheet><div class=container><h1>Bootstrap 3 DataTables</h1><table cellspacing=0 class="table table-bordered table-hover table-striped"id=example width=100%><thead><tr><th>Name<th>Position<th>Office<th>Salary<tbody><tr><td>Tiger Nixon<td>System Architect<td>Edinburgh<td>$320,800<tr><td>Garrett Winters<td>Accountant<td>Tokyo<td>$170,750<tr><td>Ashton Cox<td>Junior Technical Author<td>San Francisco<td>$86,000<tr><td>Cedric Kelly<td>Senior Javascript Developer<td>Edinburgh<td>$433,060<tr><td>Airi Satou<td>Accountant<td>Tokyo<td>$162,700<tr><td>Brielle Williamson<td>Integration Specialist<td>New York<td>$372,000<tr><td>Herrod Chandler<td>Sales Assistant<td>San Francisco<td>$137,500<tr><td>Rhona Davidson<td>Integration Specialist<td>Tokyo<td>$327,900<tr><td>Colleen Hurst<td>Javascript Developer<td>San Francisco<td>$205,500<tr><td>Sonya Frost<td>Software Engineer<td>Edinburgh<td>$103,600<tr><td>Jena Gaines<td>Office Manager<td>London<td>$90,560<tr><td>Quinn Flynn<td>Support Lead<td>Edinburgh<td>$342,000<tr><td>Charde Marshall<td>Regional Director<td>San Francisco<td>$470,600<tr><td>Haley Kennedy<td>Senior Marketing Designer<td>London<td>$313,500<tr><td>Tatyana Fitzpatrick<td>Regional Director<td>London<td>$385,750<tr><td>Michael Silva<td>Marketing Designer<td>London<td>$198,500<tr><td>Paul Byrd<td>Chief Financial Officer (CFO)<td>New York<td>$725,000<tr><td>Gloria Little<td>Systems Administrator<td>New York<td>$237,500<tr><td>Bradley Greer<td>Software Engineer<td>London<td>$132,000<tr><td>Dai Rios<td>Personnel Lead<td>Edinburgh<td>$217,500<tr><td>Jenette Caldwell<td>Development Lead<td>New York<td>$345,000<tr><td>Yuri Berry<td>Chief Marketing Officer (CMO)<td>New York<td>$675,000<tr><td>Caesar Vance<td>Pre-Sales Support<td>New York<td>$106,450<tr><td>Doris Wilder<td>Sales Assistant<td>Sidney<td>$85,600<tr><td>Angelica Ramos<td>Chief Executive Officer (CEO)<td>London<td>$1,200,000<tr><td>Gavin Joyce<td>Developer<td>Edinburgh<td>$92,575<tr><td>Jennifer Chang<td>Regional Director<td>Singapore<td>$357,650<tr><td>Brenden Wagner<td>Software Engineer<td>San Francisco<td>$206,850<tr><td>Fiona Green<td>Chief Operating Officer (COO)<td>San Francisco<td>$850,000<tr><td>Shou Itou<td>Regional Marketing<td>Tokyo<td>$163,000<tr><td>Michelle House<td>Integration Specialist<td>Sidney<td>$95,400<tr><td>Suki Burks<td>Developer<td>London<td>$114,500<tr><td>Prescott Bartlett<td>Technical Author<td>London<td>$145,000<tr><td>Gavin Cortez<td>Team Leader<td>San Francisco<td>$235,500<tr><td>Martena Mccray<td>Post-Sales support<td>Edinburgh<td>$324,050<tr><td>Unity Butler<td>Marketing Designer<td>San Francisco<td>$85,675<tr><td>Howard Hatfield<td>Office Manager<td>San Francisco<td>$164,500<tr><td>Hope Fuentes<td>Secretary<td>San Francisco<td>$109,850<tr><td>Vivian Harrell<td>Financial Controller<td>San Francisco<td>$452,500<tr><td>Timothy Mooney<td>Office Manager<td>London<td>$136,200<tr><td>Jackson Bradshaw<td>Director<td>New York<td>$645,750<tr><td>Olivia Liang<td>Support Engineer<td>Singapore<td>$234,500<tr><td>Bruno Nash<td>Software Engineer<td>London<td>$163,500<tr><td>Sakura Yamamoto<td>Support Engineer<td>Tokyo<td>$139,575<tr><td>Thor Walton<td>Developer<td>New York<td>$98,540<tr><td>Finn Camacho<td>Support Engineer<td>San Francisco<td>$87,500<tr><td>Serge Baldwin<td>Data Coordinator<td>Singapore<td>$138,575<tr><td>Zenaida Frank<td>Software Engineer<td>New York<td>$125,250<tr><td>Zorita Serrano<td>Software Engineer<td>San Francisco<td>$115,000<tr><td>Jennifer Acosta<td>Junior Javascript Developer<td>Edinburgh<td>$75,650<tr><td>Cara Stevens<td>Sales Assistant<td>New York<td>$145,600<tr><td>Hermione Butler<td>Regional Director<td>London<td>$356,250<tr><td>Lael Greer<td>Systems Administrator<td>London<td>$103,500<tr><td>Jonas Alexander<td>Developer<td>San Francisco<td>$86,500<tr><td>Shad Decker<td>Regional Director<td>Edinburgh<td>$183,000<tr><td>Michael Bruce<td>Javascript Developer<td>Singapore<td>$183,000<tr><td>Donna Snider<td>Customer Support<td>New York<td>$112,000</table></div><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/jquery.dataTables.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/dataTables.bootstrap.min.js></script>
_x000D_
Bootstrap 4 with DataTables Example: Bootstrap Docs & DataTables Docs
$(document).ready(function() {
$('#example').DataTable();
});
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/css/dataTables.bootstrap4.min.css rel=stylesheet><div class=container><h1>Bootstrap 4 DataTables</h1><table cellspacing=0 class="table table-bordered table-hover table-inverse table-striped"id=example width=100%><thead><tr><th>Name<th>Position<th>Office<th>Age<th>Start date<th>Salary<tfoot><tr><th>Name<th>Position<th>Office<th>Age<th>Start date<th>Salary<tbody><tr><td>Tiger Nixon<td>System Architect<td>Edinburgh<td>61<td>2011/04/25<td>$320,800<tr><td>Garrett Winters<td>Accountant<td>Tokyo<td>63<td>2011/07/25<td>$170,750<tr><td>Ashton Cox<td>Junior Technical Author<td>San Francisco<td>66<td>2009/01/12<td>$86,000<tr><td>Cedric Kelly<td>Senior Javascript Developer<td>Edinburgh<td>22<td>2012/03/29<td>$433,060<tr><td>Airi Satou<td>Accountant<td>Tokyo<td>33<td>2008/11/28<td>$162,700<tr><td>Brielle Williamson<td>Integration Specialist<td>New York<td>61<td>2012/12/02<td>$372,000<tr><td>Herrod Chandler<td>Sales Assistant<td>San Francisco<td>59<td>2012/08/06<td>$137,500<tr><td>Rhona Davidson<td>Integration Specialist<td>Tokyo<td>55<td>2010/10/14<td>$327,900<tr><td>Colleen Hurst<td>Javascript Developer<td>San Francisco<td>39<td>2009/09/15<td>$205,500<tr><td>Sonya Frost<td>Software Engineer<td>Edinburgh<td>23<td>2008/12/13<td>$103,600<tr><td>Jena Gaines<td>Office Manager<td>London<td>30<td>2008/12/19<td>$90,560<tr><td>Quinn Flynn<td>Support Lead<td>Edinburgh<td>22<td>2013/03/03<td>$342,000<tr><td>Charde Marshall<td>Regional Director<td>San Francisco<td>36<td>2008/10/16<td>$470,600<tr><td>Haley Kennedy<td>Senior Marketing Designer<td>London<td>43<td>2012/12/18<td>$313,500<tr><td>Tatyana Fitzpatrick<td>Regional Director<td>London<td>19<td>2010/03/17<td>$385,750<tr><td>Michael Silva<td>Marketing Designer<td>London<td>66<td>2012/11/27<td>$198,500<tr><td>Paul Byrd<td>Chief Financial Officer (CFO)<td>New York<td>64<td>2010/06/09<td>$725,000<tr><td>Gloria Little<td>Systems Administrator<td>New York<td>59<td>2009/04/10<td>$237,500<tr><td>Bradley Greer<td>Software Engineer<td>London<td>41<td>2012/10/13<td>$132,000<tr><td>Dai Rios<td>Personnel Lead<td>Edinburgh<td>35<td>2012/09/26<td>$217,500<tr><td>Jenette Caldwell<td>Development Lead<td>New York<td>30<td>2011/09/03<td>$345,000<tr><td>Yuri Berry<td>Chief Marketing Officer (CMO)<td>New York<td>40<td>2009/06/25<td>$675,000<tr><td>Caesar Vance<td>Pre-Sales Support<td>New York<td>21<td>2011/12/12<td>$106,450<tr><td>Doris Wilder<td>Sales Assistant<td>Sidney<td>23<td>2010/09/20<td>$85,600<tr><td>Angelica Ramos<td>Chief Executive Officer (CEO)<td>London<td>47<td>2009/10/09<td>$1,200,000<tr><td>Gavin Joyce<td>Developer<td>Edinburgh<td>42<td>2010/12/22<td>$92,575<tr><td>Jennifer Chang<td>Regional Director<td>Singapore<td>28<td>2010/11/14<td>$357,650<tr><td>Brenden Wagner<td>Software Engineer<td>San Francisco<td>28<td>2011/06/07<td>$206,850<tr><td>Fiona Green<td>Chief Operating Officer (COO)<td>San Francisco<td>48<td>2010/03/11<td>$850,000<tr><td>Shou Itou<td>Regional Marketing<td>Tokyo<td>20<td>2011/08/14<td>$163,000<tr><td>Michelle House<td>Integration Specialist<td>Sidney<td>37<td>2011/06/02<td>$95,400<tr><td>Suki Burks<td>Developer<td>London<td>53<td>2009/10/22<td>$114,500<tr><td>Prescott Bartlett<td>Technical Author<td>London<td>27<td>2011/05/07<td>$145,000<tr><td>Gavin Cortez<td>Team Leader<td>San Francisco<td>22<td>2008/10/26<td>$235,500<tr><td>Martena Mccray<td>Post-Sales support<td>Edinburgh<td>46<td>2011/03/09<td>$324,050<tr><td>Unity Butler<td>Marketing Designer<td>San Francisco<td>47<td>2009/12/09<td>$85,675<tr><td>Howard Hatfield<td>Office Manager<td>San Francisco<td>51<td>2008/12/16<td>$164,500<tr><td>Hope Fuentes<td>Secretary<td>San Francisco<td>41<td>2010/02/12<td>$109,850<tr><td>Vivian Harrell<td>Financial Controller<td>San Francisco<td>62<td>2009/02/14<td>$452,500<tr><td>Timothy Mooney<td>Office Manager<td>London<td>37<td>2008/12/11<td>$136,200<tr><td>Jackson Bradshaw<td>Director<td>New York<td>65<td>2008/09/26<td>$645,750<tr><td>Olivia Liang<td>Support Engineer<td>Singapore<td>64<td>2011/02/03<td>$234,500<tr><td>Bruno Nash<td>Software Engineer<td>London<td>38<td>2011/05/03<td>$163,500<tr><td>Sakura Yamamoto<td>Support Engineer<td>Tokyo<td>37<td>2009/08/19<td>$139,575<tr><td>Thor Walton<td>Developer<td>New York<td>61<td>2013/08/11<td>$98,540<tr><td>Finn Camacho<td>Support Engineer<td>San Francisco<td>47<td>2009/07/07<td>$87,500<tr><td>Serge Baldwin<td>Data Coordinator<td>Singapore<td>64<td>2012/04/09<td>$138,575<tr><td>Zenaida Frank<td>Software Engineer<td>New York<td>63<td>2010/01/04<td>$125,250<tr><td>Zorita Serrano<td>Software Engineer<td>San Francisco<td>56<td>2012/06/01<td>$115,000<tr><td>Jennifer Acosta<td>Junior Javascript Developer<td>Edinburgh<td>43<td>2013/02/01<td>$75,650<tr><td>Cara Stevens<td>Sales Assistant<td>New York<td>46<td>2011/12/06<td>$145,600<tr><td>Hermione Butler<td>Regional Director<td>London<td>47<td>2011/03/21<td>$356,250<tr><td>Lael Greer<td>Systems Administrator<td>London<td>21<td>2009/02/27<td>$103,500<tr><td>Jonas Alexander<td>Developer<td>San Francisco<td>30<td>2010/07/14<td>$86,500<tr><td>Shad Decker<td>Regional Director<td>Edinburgh<td>51<td>2008/11/13<td>$183,000<tr><td>Michael Bruce<td>Javascript Developer<td>Singapore<td>29<td>2011/06/27<td>$183,000<tr><td>Donna Snider<td>Customer Support<td>New York<td>27<td>2011/01/25<td>$112,000</table></div><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/jquery.dataTables.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/dataTables.bootstrap4.min.js></script>
_x000D_
Bootstrap 3 with Bootstrap Table Example: Bootstrap Docs & Bootstrap Table Docs
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.16.0/bootstrap-table.min.css rel=stylesheet><table data-sort-name=stargazers_count data-sort-order=desc data-toggle=table data-url="https://api.github.com/users/wenzhixin/repos?type=owner&sort=full_name&direction=asc&per_page=100&page=1"><thead><tr><th data-field=name data-sortable=true>Name<th data-field=stargazers_count data-sortable=true>Stars<th data-field=forks_count data-sortable=true>Forks<th data-field=description data-sortable=true>Description</thead></table><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.16.0/bootstrap-table.min.js></script>
_x000D_
Bootstrap 3 with Bootstrap Sortable Example: Bootstrap Docs & Bootstrap Sortable Docs
function randomDate(t,e){return new Date(t.getTime()+Math.random()*(e.getTime()-t.getTime()))}function randomName(){return["Jack","Peter","Frank","Steven"][Math.floor(4*Math.random())]+" "+["White","Jackson","Sinatra","Spielberg"][Math.floor(4*Math.random())]}function newTableRow(){var t=moment(randomDate(new Date(2e3,0,1),new Date)).format("D.M.YYYY"),e=Math.round(Math.random()*Math.random()*100*100)/100,a=Math.round(Math.random()*Math.random()*100*100)/100,r=Math.round(Math.random()*Math.random()*100*100)/100;return"<tr><td>"+randomName()+"</td><td>"+e+"</td><td>"+a+"</td><td>"+r+"</td><td>"+Math.round(100*(e+a+r))/100+"</td><td data-dateformat='D-M-YYYY'>"+t+"</td></tr>"}function customSort(){alert("Custom sort.")}!function(t,e){"use strict";"function"==typeof define&&define.amd?define("tinysort",function(){return e}):t.tinysort=e}(this,function(){"use strict";function t(t,e){for(var a,r=t.length,o=r;o--;)e(t[a=r-o-1],a)}function e(t,e,a){for(var o in e)(a||t[o]===r)&&(t[o]=e[o]);return t}function a(t,e,a){u.push({prepare:t,sort:e,sortBy:a})}var r,o=!1,n=null,s=window,d=s.document,i=parseFloat,l=/(-?\d+\.?\d*)\s*$/g,c=/(\d+\.?\d*)\s*$/g,u=[],f=0,h=0,p=String.fromCharCode(4095),m={selector:n,order:"asc",attr:n,data:n,useVal:o,place:"org",returns:o,cases:o,natural:o,forceStrings:o,ignoreDashes:o,sortFunction:n,useFlex:o,emptyEnd:o};return s.Element&&function(t){t.matchesSelector=t.matchesSelector||t.mozMatchesSelector||t.msMatchesSelector||t.oMatchesSelector||t.webkitMatchesSelector||function(t){for(var e=this,a=(e.parentNode||e.document).querySelectorAll(t),r=-1;a[++r]&&a[r]!=e;);return!!a[r]}}(Element.prototype),e(a,{loop:t}),e(function(a,s){function v(t){var a=!!t.selector,r=a&&":"===t.selector[0],o=e(t||{},m);E.push(e({hasSelector:a,hasAttr:!(o.attr===n||""===o.attr),hasData:o.data!==n,hasFilter:r,sortReturnNumber:"asc"===o.order?1:-1},o))}function b(t,e,a){for(var r=a(t.toString()),o=a(e.toString()),n=0;r[n]&&o[n];n++)if(r[n]!==o[n]){var s=Number(r[n]),d=Number(o[n]);return s==r[n]&&d==o[n]?s-d:r[n]>o[n]?1:-1}return r.length-o.length}function g(t){for(var e,a,r=[],o=0,n=-1,s=0;e=(a=t.charAt(o++)).charCodeAt(0);){var d=46==e||e>=48&&57>=e;d!==s&&(r[++n]="",s=d),r[n]+=a}return r}function w(){return Y.forEach(function(t){F.appendChild(t.elm)}),F}function S(t){var e=t.elm,a=d.createElement("div");return t.ghost=a,e.parentNode.insertBefore(a,e),t}function y(t,e){var a=t.ghost,r=a.parentNode;r.insertBefore(e,a),r.removeChild(a),delete t.ghost}function C(t,e){var a,r=t.elm;return e.selector&&(e.hasFilter?r.matchesSelector(e.selector)||(r=n):r=r.querySelector(e.selector)),e.hasAttr?a=r.getAttribute(e.attr):e.useVal?a=r.value||r.getAttribute("value"):e.hasData?a=r.getAttribute("data-"+e.data):r&&(a=r.textContent),M(a)&&(e.cases||(a=a.toLowerCase()),a=a.replace(/\s+/g," ")),null===a&&(a=p),a}function M(t){return"string"==typeof t}M(a)&&(a=d.querySelectorAll(a)),0===a.length&&console.warn("No elements to sort");var x,N,F=d.createDocumentFragment(),D=[],Y=[],$=[],E=[],k=!0,A=a.length&&a[0].parentNode,T=A.rootNode!==document,R=a.length&&(s===r||!1!==s.useFlex)&&!T&&-1!==getComputedStyle(A,null).display.indexOf("flex");return function(){0===arguments.length?v({}):t(arguments,function(t){v(M(t)?{selector:t}:t)}),f=E.length}.apply(n,Array.prototype.slice.call(arguments,1)),t(a,function(t,e){N?N!==t.parentNode&&(k=!1):N=t.parentNode;var a=E[0],r=a.hasFilter,o=a.selector,n=!o||r&&t.matchesSelector(o)||o&&t.querySelector(o)?Y:$,s={elm:t,pos:e,posn:n.length};D.push(s),n.push(s)}),x=Y.slice(0),Y.sort(function(e,a){var n=0;for(0!==h&&(h=0);0===n&&f>h;){var s=E[h],d=s.ignoreDashes?c:l;if(t(u,function(t){var e=t.prepare;e&&e(s)}),s.sortFunction)n=s.sortFunction(e,a);else if("rand"==s.order)n=Math.random()<.5?1:-1;else{var p=o,m=C(e,s),v=C(a,s),w=""===m||m===r,S=""===v||v===r;if(m===v)n=0;else if(s.emptyEnd&&(w||S))n=w&&S?0:w?1:-1;else{if(!s.forceStrings){var y=M(m)?m&&m.match(d):o,x=M(v)?v&&v.match(d):o;y&&x&&m.substr(0,m.length-y[0].length)==v.substr(0,v.length-x[0].length)&&(p=!o,m=i(y[0]),v=i(x[0]))}n=m===r||v===r?0:s.natural&&(isNaN(m)||isNaN(v))?b(m,v,g):v>m?-1:m>v?1:0}}t(u,function(t){var e=t.sort;e&&(n=e(s,p,m,v,n))}),0==(n*=s.sortReturnNumber)&&h++}return 0===n&&(n=e.pos>a.pos?1:-1),n}),function(){var t=Y.length===D.length;if(k&&t)R?Y.forEach(function(t,e){t.elm.style.order=e}):N?N.appendChild(w()):console.warn("parentNode has been removed");else{var e=E[0].place,a="start"===e,r="end"===e,o="first"===e,n="last"===e;if("org"===e)Y.forEach(S),Y.forEach(function(t,e){y(x[e],t.elm)});else if(a||r){var s=x[a?0:x.length-1],d=s&&s.elm.parentNode,i=d&&(a&&d.firstChild||d.lastChild);i&&(i!==s.elm&&(s={elm:i}),S(s),r&&d.appendChild(s.ghost),y(s,w()))}else(o||n)&&y(S(x[o?0:x.length-1]),w())}}(),Y.map(function(t){return t.elm})},{plugin:a,defaults:m})}()),function(t,e){"function"==typeof define&&define.amd?define(["jquery","tinysort","moment"],e):e(t.jQuery,t.tinysort,t.moment||void 0)}(this,function(t,e,a){var r,o,n,s=t(document);function d(e){var s=void 0!==a;r=e.sign?e.sign:"arrow","default"==e.customSort&&(e.customSort=c),o=e.customSort||o||c,n=e.emptyEnd,t("table.sortable").each(function(){var r=t(this),o=!0===e.applyLast;r.find("span.sign").remove(),r.find("> thead [colspan]").each(function(){for(var e=parseFloat(t(this).attr("colspan")),a=1;a<e;a++)t(this).after('<th class="colspan-compensate">')}),r.find("> thead [rowspan]").each(function(){for(var e=t(this),a=parseFloat(e.attr("rowspan")),r=1;r<a;r++){var o=e.parent("tr"),n=o.next("tr"),s=o.children().index(e);n.children().eq(s).before('<th class="rowspan-compensate">')}}),r.find("> thead tr").each(function(e){t(this).find("th").each(function(a){var r=t(this);r.addClass("nosort").removeClass("up down"),r.attr("data-sortcolumn",a),r.attr("data-sortkey",a+"-"+e)})}),r.find("> thead .rowspan-compensate, .colspan-compensate").remove(),r.find("th").each(function(){var e=t(this);if(void 0!==e.attr("data-dateformat")&&s){var o=parseFloat(e.attr("data-sortcolumn"));r.find("td:nth-child("+(o+1)+")").each(function(){var r=t(this);r.attr("data-value",a(r.text(),e.attr("data-dateformat")).format("YYYY/MM/DD/HH/mm/ss"))})}else if(void 0!==e.attr("data-valueprovider")){o=parseFloat(e.attr("data-sortcolumn"));r.find("td:nth-child("+(o+1)+")").each(function(){var a=t(this);a.attr("data-value",new RegExp(e.attr("data-valueprovider")).exec(a.text())[0])})}}),r.find("td").each(function(){var e=t(this);void 0!==e.attr("data-dateformat")&&s?e.attr("data-value",a(e.text(),e.attr("data-dateformat")).format("YYYY/MM/DD/HH/mm/ss")):void 0!==e.attr("data-valueprovider")?e.attr("data-value",new RegExp(e.attr("data-valueprovider")).exec(e.text())[0]):void 0===e.attr("data-value")&&e.attr("data-value",e.text())});var n=l(r),d=n.bsSort;r.find('> thead th[data-defaultsort!="disabled"]').each(function(e){var a=t(this),r=a.closest("table.sortable");a.data("sortTable",r);var s=a.attr("data-sortkey"),i=o?n.lastSort:-1;d[s]=o?d[s]:a.attr("data-defaultsort"),void 0!==d[s]&&o===(s===i)&&(d[s]="asc"===d[s]?"desc":"asc",u(a,r))})})}function i(e){var a=t(e),r=a.data("sortTable")||a.closest("table.sortable");u(a,r)}function l(e){var a=e.data("bootstrap-sortable-context");return void 0===a&&(a={bsSort:[],lastSort:void 0},e.find('> thead th[data-defaultsort!="disabled"]').each(function(e){var r=t(this),o=r.attr("data-sortkey");a.bsSort[o]=r.attr("data-defaultsort"),void 0!==a.bsSort[o]&&(a.lastSort=o)}),e.data("bootstrap-sortable-context",a)),a}function c(t,a){e(t,a)}function u(e,a){a.trigger("before-sort");var s=parseFloat(e.attr("data-sortcolumn")),d=l(a),i=d.bsSort;if(e.attr("colspan")){var c=parseFloat(e.data("mainsort"))||0,f=parseFloat(e.data("sortkey").split("-").pop());if(a.find("> thead tr").length-1>f)return void u(a.find('[data-sortkey="'+(s+c)+"-"+(f+1)+'"]'),a);s+=c}var h=e.attr("data-defaultsign")||r;if(a.find("> thead th").each(function(){t(this).removeClass("up").removeClass("down").addClass("nosort")}),t.browser.mozilla){var p=a.find("> thead div.mozilla");void 0!==p&&(p.find(".sign").remove(),p.parent().html(p.html())),e.wrapInner('<div class="mozilla"></div>'),e.children().eq(0).append('<span class="sign '+h+'"></span>')}else a.find("> thead span.sign").remove(),e.append('<span class="sign '+h+'"></span>');var m=e.attr("data-sortkey"),v="desc"!==e.attr("data-firstsort")?"desc":"asc",b=i[m]||v;d.lastSort!==m&&void 0!==i[m]||(b="asc"===b?"desc":"asc"),i[m]=b,d.lastSort=m,"desc"===i[m]?(e.find("span.sign").addClass("up"),e.addClass("up").removeClass("down nosort")):e.addClass("down").removeClass("up nosort");var g=a.children("tbody").children("tr"),w=[];t(g.filter('[data-disablesort="true"]').get().reverse()).each(function(e,a){var r=t(a);w.push({index:g.index(r),row:r}),r.remove()});var S=g.not('[data-disablesort="true"]');if(0!=S.length){var y="asc"===i[m]&&n;o(S,{emptyEnd:y,selector:"td:nth-child("+(s+1)+")",order:i[m],data:"value"})}t(w.reverse()).each(function(t,e){0===e.index?a.children("tbody").prepend(e.row):a.children("tbody").children("tr").eq(e.index-1).after(e.row)}),a.find("> tbody > tr > td.sorted,> thead th.sorted").removeClass("sorted"),S.find("td:eq("+s+")").addClass("sorted"),e.addClass("sorted"),a.trigger("sorted")}if(t.bootstrapSortable=function(t){null==t?d({}):t.constructor===Boolean?d({applyLast:t}):void 0!==t.sortingHeader?i(t.sortingHeader):d(t)},s.on("click",'table.sortable>thead th[data-defaultsort!="disabled"]',function(t){i(this)}),!t.browser){t.browser={chrome:!1,mozilla:!1,opera:!1,msie:!1,safari:!1};var f=navigator.userAgent;t.each(t.browser,function(e){t.browser[e]=!!new RegExp(e,"i").test(f),t.browser.mozilla&&"mozilla"===e&&(t.browser.mozilla=!!new RegExp("firefox","i").test(f)),t.browser.chrome&&"safari"===e&&(t.browser.safari=!1)})}t(t.bootstrapSortable)}),function(){var t=$("table");t.append(newTableRow()),t.append(newTableRow()),$("button.add-row").on("click",function(){var e=$(this);t.append(newTableRow()),e.data("sort")?$.bootstrapSortable(!0):$.bootstrapSortable(!1)}),$("button.change-sort").on("click",function(){$(this).data("custom")?$.bootstrapSortable(!0,void 0,customSort):$.bootstrapSortable(!0,void 0,"default")}),t.on("sorted",function(){alert("Table was sorted.")}),$("#event").on("change",function(){$(this).is(":checked")?t.on("sorted",function(){alert("Table was sorted.")}):t.off("sorted")}),$("input[name=sign]:radio").change(function(){$.bootstrapSortable(!0,$(this).val())})}();
_x000D_
table.sortable span.sign { display: block; position: absolute; top: 50%; right: 5px; font-size: 12px; margin-top: -10px; color: #bfbfc1; } table.sortable th:after { display: block; position: absolute; top: 50%; right: 5px; font-size: 12px; margin-top: -10px; color: #bfbfc1; } table.sortable th.arrow:after { content: ''; } table.sortable span.arrow, span.reversed, th.arrow.down:after, th.reversedarrow.down:after, th.arrow.up:after, th.reversedarrow.up:after { border-style: solid; border-width: 5px; font-size: 0; border-color: #ccc transparent transparent transparent; line-height: 0; height: 0; width: 0; margin-top: -2px; } table.sortable span.arrow.up, th.arrow.up:after { border-color: transparent transparent #ccc transparent; margin-top: -7px; } table.sortable span.reversed, th.reversedarrow.down:after { border-color: transparent transparent #ccc transparent; margin-top: -7px; } table.sortable span.reversed.up, th.reversedarrow.up:after { border-color: #ccc transparent transparent transparent; margin-top: -2px; } table.sortable span.az:before, th.az.down:after { content: "a .. z"; } table.sortable span.az.up:before, th.az.up:after { content: "z .. a"; } table.sortable th.az.nosort:after, th.AZ.nosort:after, th._19.nosort:after, th.month.nosort:after { content: ".."; } table.sortable span.AZ:before, th.AZ.down:after { content: "A .. Z"; } table.sortable span.AZ.up:before, th.AZ.up:after { content: "Z .. A"; } table.sortable span._19:before, th._19.down:after { content: "1 .. 9"; } table.sortable span._19.up:before, th._19.up:after { content: "9 .. 1"; } table.sortable span.month:before, th.month.down:after { content: "jan .. dec"; } table.sortable span.month.up:before, th.month.up:after { content: "dec .. jan"; } table.sortable thead th:not([data-defaultsort=disabled]) { cursor: pointer; position: relative; top: 0; left: 0; } table.sortable thead th:hover:not([data-defaultsort=disabled]) { background: #efefef; } table.sortable thead th div.mozilla { position: relative; }
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css rel=stylesheet><link href=https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><div class=container><div class=hero-unit><h1>Bootstrap Sortable</h1></div><table class="sortable table table-bordered table-striped"><thead><tr><th style=width:20%;vertical-align:middle data-defaultsign=nospan class=az data-defaultsort=asc rowspan=2><i class="fa fa-fw fa-map-marker"></i>Name<th style=text-align:center colspan=4 data-mainsort=3>Results<th data-defaultsort=disabled><tr><th style=width:20% colspan=2 data-mainsort=1 data-firstsort=desc>Round 1<th style=width:20%>Round 2<th style=width:20%>Total<t
Further to Ryan's answer you will also need to set the DataColumn
's Ordinal
property if you are dealing with a table-valued parameter
with multiple columns whose ordinals are not in alphabetical order.
As an example, if you have the following table value that is used as a parameter in SQL:
CREATE TYPE NodeFilter AS TABLE (
ID int not null
Code nvarchar(10) not null,
);
You would need to order your columns as such in C#:
table.Columns["ID"].SetOrdinal(0);
// this also bumps Code to ordinal of 1
// if you have more than 2 cols then you would need to set more ordinals
If you fail to do this you will get a parse error, failed to convert nvarchar to int.
A couple things
(a) you cant have both background-color and background, background will always win. in the example below, i combined them through shorthand, but this will produce the color only as a fallback method when the image does not show.
(b) no-scroll does not work, i don't believe it is a valid property of a background-image. try something like fixed:
.button:after {
content: "";
width: 30px;
height: 30px;
background:red url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") no-repeat -30px -50px fixed;
top: 10px;
right: 5px;
position: absolute;
display: inline-block;
}
I updated your jsFiddle to this and it showed the image.
With \
you escape special characters
Escapes special characters to literal and literal characters to special.
E.g:
/\(s\)/
matches '(s)' while/(\s)/
matches any whitespace and captures the match.
Source: http://www.javascriptkit.com/javatutors/redev2.shtml
public string CreateFile(string id, string name, string description, SupportedPermissions supportedPermissions)
{
file = new File
{
Name = name,
Id = id,
Description = description,
SupportedPermissions = supportedPermissions
};
return file.Id;
}
I believe using --no-index
is what you're looking for:
git diff [<options>] --no-index [--] <path> <path>
as mentioned in the git manual:
This form is to compare the given two paths on the filesystem. You can omit the
--no-index
option when running the command in a working tree controlled by Git and at least one of the paths points outside the working tree, or when running the command outside a working tree controlled by Git.
This should do your work :
df_agg <- aggregate(num~name+type,df,FUN=NROW)
names(df_agg)[3] <- "count"
df <- merge(df,df_agg,by=c('name','type'),all.x=TRUE)
+----------------------- | RESOURCE EXISTS ? (if private it is often checked AFTER auth check) +----------------------- | | NO | v YES v +----------------------- 404 | IS LOGGED-IN ? (authenticated, aka has session or JWT cookie) or +----------------------- 401 | | 403 NO | | YES 3xx v v 401 +----------------------- (404 no reveal) | CAN ACCESS RESOURCE ? (permission, authorized, ...) or +----------------------- redirect | | to login NO | | YES | | v v 403 OK 200, redirect, ... (or 404: no reveal) (or 404: resource does not exist if private) (or 3xx: redirection)
Checks are usually done in this order:
UNAUTHORIZED: Status code (401) indicating that the request requires authentication, usually this means user needs to be logged-in (session). User/agent unknown by the server. Can repeat with other credentials. NOTE: This is confusing as this should have been named 'unauthenticated' instead of 'unauthorized'. This can also happen after login if session expired. Special case: Can be used instead of 404 to avoid revealing presence or non-presence of resource (credits @gingerCodeNinja)
FORBIDDEN: Status code (403) indicating the server understood the request but refused to fulfill it. User/agent known by the server but has insufficient credentials. Repeating request will not work, unless credentials changed, which is very unlikely in a short time span. Special case: Can be used instead of 404 to avoid revealing presence or non-presence of resource (credits @gingerCodeNinja)
NOT FOUND: Status code (404) indicating that the requested resource is not available. User/agent known but server will not reveal anything about the resource, does as if it does not exist. Repeating will not work. This is a special use of 404 (github does it for example).
As mentioned by @ChrisH there are a few options for redirection 3xx (301, 302, 303, 307 or not redirecting at all and using a 401):
If each user has its own SQL Server login you could try this
select
so.name, su.name, so.crdate
from
sysobjects so
join
sysusers su on so.uid = su.uid
order by
so.crdate
This is not answering the problem but if anyone comes to this question when they stumble upon this exception of no suitable message converter found, here is my problem and solution.
In Spring 4.0.9, we were able to send this
JSONObject jsonCredential = new JSONObject();
jsonCredential.put(APPLICATION_CREDENTIALS, data);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
ResponseEntity<String> res = restTemplate.exchange(myRestUrl), HttpMethod.POST,request, String.class);
In Spring 4.3.5 release, we starting seeing errors with the message that converter was not found.
The way Convertors work is that if you have it in your classpath, they get registered.
Jackson-asl was still in classpath but was not being recognized by spring. We replaced Jackson-asl with faster-xml jackson core.
Once we added I could see the converter being registered.
This is a solution that came up with for a similar issue
exit_status () {
if [ $? = 0 ]
then
true
else
false
fi
}
usage:
do-command exit_status && echo "worked" || echo "didnt work"
You enter the
if (!(cin >> input_var))
statement if an error occurs when taking the input from cin. If an error occurs then an error flag is set and future attempts to get input will fail. That's why you need
cin.clear();
to get rid of the error flag. Also, the input which failed will be sitting in what I assume is some sort of buffer. When you try to get input again, it will read the same input in the buffer and it will fail again. That's why you need
cin.ignore(10000,'\n');
It takes out 10000 characters from the buffer but stops if it encounters a newline (\n). The 10000 is just a generic large value.
Probably something like this if it's the text part you want...
from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')
print " ".join(t.nodeValue for t in name[0].childNodes if t.nodeType == t.TEXT_NODE)
The text part of a node is considered a node in itself placed as a child-node of the one you asked for. Thus you will want to go through all its children and find all child nodes that are text nodes. A node can have several text nodes; eg.
<name>
blabla
<somestuff>asdf</somestuff>
znylpx
</name>
You want both 'blabla' and 'znylpx'; hence the " ".join(). You might want to replace the space with a newline or so, or perhaps by nothing.
# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.
keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]
Trust this certificate: [Yes]
changeit is the default truststore password
While calling the .asmx / wcf web service please take care of below points:
e.g. For the WebService declared as below
[WebService(Namespace = "http://MyDomain.com/TestService")]
public class FooClass : System.Web.Services.WebService
{
[WebMethod]
public bool Foo( string name)
{
......
}
}
The SOAP request must maintain the same case for namespace while calling.Sometime we overlook the case sensitivity.
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<Foo xmlns="http://MyDomain.com/TestService">
<name>string</name>
</Foo>
</soap:Body>
</soap:Envelope>
e.g. Above service may be hosted at http://84.23.9.65/MyTestService , but still while invoking the Web Service from client the namespace should be the same which the serice class is having i.e.http://MyDomain.com/TestService
(tensorflow)$ pip install --upgrade pip # for Python 2.7
(tensorflow)$ pip3 install --upgrade pip # for Python 3.n
(tensorflow)$ pip install --upgrade tensorflow # for Python 2.7
(tensorflow)$ pip3 install --upgrade tensorflow # for Python 3.n
(tensorflow)$ pip install --upgrade tensorflow-gpu # for Python 2.7 and GPU
(tensorflow)$ pip3 install --upgrade tensorflow-gpu # for Python 3.n and GPU
(tensorflow)$ pip install --upgrade tensorflow-gpu==1.4.1 # for a specific version
Details on install tensorflow.
The most important difference will be the clarity of your code. Yes, yes, what's been said above is true, but [[ ]] brings your code in line with what you would expect in high level languages, especially in regards to AND (&&), OR (||), and NOT (!) operators. Thus, when you move between systems and languages you will be able to interpret script faster which makes your life easier. Get the nitty gritty from a good UNIX/Linux reference. You may find some of the nitty gritty to be useful in certain circumstances, but you will always appreciate clear code! Which script fragment would you rather read? Even out of context, the first choice is easier to read and understand.
if [[ -d $newDir && -n $(echo $newDir | grep "^${webRootParent}") && -n $(echo $newDir | grep '/$') ]]; then ...
or
if [ -d "$newDir" -a -n "$(echo "$newDir" | grep "^${webRootParent}")" -a -n "$(echo "$newDir" | grep '/$')" ]; then ...
Be careful how you define the table for you will get different results on insert. Consider the following
CREATE TABLE IF NOT EXISTS t1 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT);
INSERT INTO t1 (a, b) VALUES
('Alice', 'Some title'),
('Bob', 'Palindromic guy'),
('Charles', 'chucky cheese'),
('Alice', 'Some other title')
ON CONFLICT(a) DO UPDATE SET b=excluded.b;
CREATE TABLE IF NOT EXISTS t2 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT, UNIQUE(a) ON CONFLICT REPLACE);
INSERT INTO t2 (a, b) VALUES
('Alice', 'Some title'),
('Bob', 'Palindromic guy'),
('Charles', 'chucky cheese'),
('Alice', 'Some other title');
$ sqlite3 test.sqlite
SQLite version 3.28.0 2019-04-16 19:49:53
Enter ".help" for usage hints.
sqlite> CREATE TABLE IF NOT EXISTS t1 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT);
sqlite> INSERT INTO t1 (a, b) VALUES
...> ('Alice', 'Some title'),
...> ('Bob', 'Palindromic guy'),
...> ('Charles', 'chucky cheese'),
...> ('Alice', 'Some other title')
...> ON CONFLICT(a) DO UPDATE SET b=excluded.b;
sqlite> CREATE TABLE IF NOT EXISTS t2 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT, UNIQUE(a) ON CONFLICT REPLACE);
sqlite> INSERT INTO t2 (a, b) VALUES
...> ('Alice', 'Some title'),
...> ('Bob', 'Palindromic guy'),
...> ('Charles', 'chucky cheese'),
...> ('Alice', 'Some other title');
sqlite> .mode col
sqlite> .headers on
sqlite> select * from t1;
id a b
---------- ---------- ----------------
1 Alice Some other title
2 Bob Palindromic guy
3 Charles chucky cheese
sqlite> select * from t2;
id a b
---------- ---------- ---------------
2 Bob Palindromic guy
3 Charles chucky cheese
4 Alice Some other titl
sqlite>
While the insert/update effect is the same, the id
changes based on the table definition type (see the second table where 'Alice' now has id = 4
; the first table is doing more of what I expect it to do, keep the PRIMARY KEY the same). Be aware of this effect.
I was looking for the TOTAL size of the column and hit this article, my solution is based off of MarcE's.
SELECT sum(DATALENGTH(your_field)) AS FIELDSIZE FROM your_table
Check whether you have put name="your_radio" where you have inserted radio tag
if you have done this then check your php code. Use isset()
e.g.
if(isset($_POST['submit']))
{
/*other variables*/
$radio_value = $_POST["your_radio"];
}
If you have done this as well then we need to look through your codes
"2011-05-19 10:30:14".to_time
As an alternate you can use reactive forms. Here is an example: https://stackblitz.com/edit/angular-pqb2xx
Template
<form [formGroup]="mainForm" ng-submit="submitForm()">
Global Price: <input type="number" formControlName="globalPrice">
<button type="button" [disabled]="mainForm.get('globalPrice').value === null" (click)="applyPriceToAll()">Apply to all</button>
<table border formArrayName="orderLines">
<ng-container *ngFor="let orderLine of orderLines let i=index" [formGroupName]="i">
<tr>
<td>{{orderLine.time | date}}</td>
<td>{{orderLine.quantity}}</td>
<td><input formControlName="price" type="number"></td>
</tr>
</ng-container>
</table>
</form>
Component
import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 6';
mainForm: FormGroup;
orderLines = [
{price: 10, time: new Date(), quantity: 2},
{price: 20, time: new Date(), quantity: 3},
{price: 30, time: new Date(), quantity: 3},
{price: 40, time: new Date(), quantity: 5}
]
constructor() {
this.mainForm = this.getForm();
}
getForm(): FormGroup {
return new FormGroup({
globalPrice: new FormControl(),
orderLines: new FormArray(this.orderLines.map(this.getFormGroupForLine))
})
}
getFormGroupForLine(orderLine: any): FormGroup {
return new FormGroup({
price: new FormControl(orderLine.price)
})
}
applyPriceToAll() {
const formLines = this.mainForm.get('orderLines') as FormArray;
const globalPrice = this.mainForm.get('globalPrice').value;
formLines.controls.forEach(control => control.get('price').setValue(globalPrice));
// optionally recheck value and validity without emit event.
}
submitForm() {
}
}
Short and easy version:
1. First create this abstract class
public abstract class HorizontalSwipeListener implements View.OnTouchListener {
private float firstX;
private int minDistance;
HorizontalSwipeListener(int minDistance) {
this.minDistance = minDistance;
}
abstract void onSwipeRight();
abstract void onSwipeLeft();
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
firstX = event.getX();
return true;
case MotionEvent.ACTION_UP:
float secondX = event.getX();
if (Math.abs(secondX - firstX) > minDistance) {
if (secondX > firstX) {
onSwipeLeft();
} else {
onSwipeRight();
}
}
return true;
}
return view.performClick();
}
}
2.Then create a concrete class implementing what you need:
public class SwipeListener extends HorizontalSwipeListener {
public SwipeListener() {
super(200);
}
@Override
void onSwipeRight() {
System.out.println("right");
}
@Override
void onSwipeLeft() {
System.out.println("left");
}
}
You have a couple of basic misconceptions about Java:
I want it to return the array without having to explicitly tell the console to print.
1) Java does not work that way. Nothing ever gets printed implicitly. (Java does not support an interactive interpreter with a "repl" loop ... like Python, Ruby, etc.)
2) The "main" doesn't "return" anything. The method signature is:
public static void main(String[] args)
and the void
means "no value is returned". (And, sorry, no you can't replace the void
with something else. If you do then the java
command won't recognize the "main" method.)
3) If (hypothetically) you did want your "main" method to return something, and you altered the declaration to allow that, then you still would need to use a return
statement to tell it what value to return. Unlike some language, Java does not treat the value of the last statement of a method as the return value for the method. You have to use a return
statement ...
Options -Indexes perfectly works for me ,
here is .htaccess
file :
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes <---- This Works for Me :)
</IfModule>
....etc stuff
</IfModule>
After :
This does it:
Do
c = c + 1
Loop While Cells(c, "A").Value <> ""
'prints the last empty row
Debug.Print c
If the list you use for the spinner is an object then you can find its position like this
private int selectSpinnerValue( List<Object> ListSpinner,String myString)
{
int index = 0;
for(int i = 0; i < ListSpinner.size(); i++){
if(ListSpinner.get(i).getValueEquals().equals(myString)){
index=i;
break;
}
}
return index;
}
using:
int index=selectSpinnerValue(ListOfSpinner,StringEquals);
spinner.setSelection(index,true);
Beginning with Java 7, you can use the following idiom:
String someString = "...";
InputStream is = new ByteArrayInputStream( someString.getBytes(StandardCharsets.UTF_8) );
The answers above did not work for me because in my project, the ngIf is on an input element. I needed access to the nativeElement attribute in order to focus on the input when ngIf is true. There seems to be no nativeElement attribute on ViewContainerRef. Here is what I did (following @ViewChild documentation):
<button (click)='showAsset()'>Add Asset</button>
<div *ngIf='showAssetInput'>
<input #assetInput />
</div>
...
private assetInputElRef:ElementRef;
@ViewChild('assetInput') set assetInput(elRef: ElementRef) {
this.assetInputElRef = elRef;
}
...
showAsset() {
this.showAssetInput = true;
setTimeout(() => { this.assetInputElRef.nativeElement.focus(); });
}
I used setTimeout before focusing because the ViewChild takes a sec to be assigned. Otherwise it would be undefined.
Assuming you mean you want to do this automatically from a "local" machine, without manually logging into the "remote" machine, you should look into a TCL extension known as Expect, it is designed precisely for this sort of situation. I've also provided a link to a script for logging-in/interacting via SSH.