You can do it via ssh.
ssh [email protected] "python ./hello.py"
You can also edit the script in ssh using a textual editor or X11 forwarding.
add .change()
after setting the value.
example:('id').val.('value').change();
also don't forget to add onchange
or ng-change
tag in html
That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).
i received this message for an application on iis 7.5 with a classic app pool assigned to .net 2.0. i needed to go to Handler Mappings and add two script maps, both were the same with except for the name. one name was svc-ISAPI-2.0-64, the other was svc-ISAPI-2.0. The request path was .svc. And the Executable was %SystemRoot%\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll. i restarted iis and all was happy
Interesting if maddening puzzle...but here's the best I could get:
The data seems to repeat every 8 bytes or so.
import struct
import base64
target = \
r'''Q5YACgAAAABDlgAbAAAAAEOWAC0AAAAAQ5YAPwAAAABDlgdNAAAAAEOWB18AAAAAQ5YH
[snip.]
ZAAAAABExxniAAAAAETH/rQAAAAARMf/MwAAAABEx/+yAAAAAETIADEAAAAA'''
data = base64.b64decode(target)
cleaned_data = []
struct_format = ">ff"
for i in range(len(data) // 8):
cleaned_data.append(struct.unpack_from(struct_format, data, 8*i))
That gives output like the following (a sampling of lines from the first 100 or so):
(300.00030517578125, 0.0)
(300.05975341796875, 241.93943786621094)
(301.05612182617187, 0.0)
(301.05667114257812, 8.7439727783203125)
(326.9617919921875, 0.0)
(326.96826171875, 0.0)
(328.34432983398438, 280.55218505859375)
That first number does seem to monotonically increase through the entire set. If you plot it:
import matplotlib.pyplot as plt
f, ax = plt.subplots()
ax.plot(*zip(*cleaned_data))
format = 'hhhh'
(possibly with various paddings/directions (e.g. '<hhhh'
, '<xhhhh'
) also might be worth a look (again, random lines):
(-27069, 2560, 0, 0)
(-27069, 8968, 0, 0)
(-27069, 13576, 3139, -18487)
(-27069, 18184, 31043, -5184)
(-27069, -25721, -25533, -8601)
(-27069, -7289, 0, 0)
(-25533, 31066, 0, 0)
(-25533, -29350, 0, 0)
(-25533, 25179, 0, 0)
(-24509, -1888, 0, 0)
(-24509, -4447, 0, 0)
(-23741, -14725, 32067, 27475)
(-23741, -3973, 0, 0)
(-23485, 4908, -29629, -20922)
I also got stuck with this issue. I got correct response from server, but couldn`t play video. After long time I found a solution here. Maybe, in future this link will be invalid. So, here is my correct code
Uri video = Uri.parse("Your link should be in this place ");
mVideoView.setVideoURI(video);
mVideoView.setZOrderOnTop(true); //Very important line, add it to Your code
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
// here write another part of code, which provides starting the video
}}
No call mp.start with an OnPreparedListener to avoid the zero state i the log..
This is the perfect answer for difference between Cloud Computing and Grid Computing ? Check this:
Go to projects menu, click on clean menu item.
After that close the eclipse and reopen and try compiling..
It is software glitch you find some times.
((\n.*){0,3})(.*)\W*\.txt
This will select all the content before the particular word ".txt" including any context in different lines up to 3 lines
This will also work for tags (remove the 'uniq' below and other parts if you need to see all changes):
git diff v1.58 HEAD
The below is the same, and that could be useful for continuous integration (CI) for microservices in a monolithic repository:
git diff v1.58 HEAD --name-only | sort -u | awk 'BEGIN {FS="/"} {print $1}' | uniq
<Folder Name>
(Credit - https://dzone.com/articles/build-test-and-deploy-apps-independently-from-a-mo)
Well to be honest, first and foremost you shouldn't generate UML model from code, but code from UML model ;).
Even if you are in a rare situation, when you need to do this reverse engineering, it is generally suggested that you do it by hand or at least tidy-up the diagrams, as auto-generated UML has really poor visual (=information) value most of the time.
If you just need to generate the diagrams, it's probably a good thing to ask yourself why exactly? Who is the intended audience and what is the goal? What does the auto-generated diagram have to offer, what code doesn't?
Basicly I accept only one answer to that question. It just got too big and incomprehensible.
Which again is a reason to start with UML in the first place, as opposed to start coding ;) It's called analysis and it's on decline, because every second guy in business thinks it's a bit too expensive and not really necessary.
Here is what I did.
Dim strPath As String
strPath = "\\server\Instructions\"
Shell "cmd.exe /c start """" """ & strPath & """", vbNormalFocus
Pros:
Cons:
This consistently opens a window to the folder if there is none open and switches to the open window if there is one open to that folder.
Thanks to PhilHibbs and AnorZaken for the basis for this. PhilHibbs comment didn't quite work for me, I needed to the command string to have a pair of double quotes before the folder name. And I preferred having a command prompt window appear for a bit rather than be forced to have the Explorer window maximized or minimized.
Below code will help you:
public class DeckListAdapter extends BaseAdapter{
private LayoutInflater mInflater;
ArrayList<String> teams=new ArrayList<String>();
ArrayList<Integer> teamcolor=new ArrayList<Integer>();
public DeckListAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
teams.add("Upload");
teams.add("Download");
teams.add("Device Browser");
teams.add("FTP Browser");
teams.add("Options");
teamcolor.add(Color.WHITE);
teamcolor.add(Color.LTGRAY);
teamcolor.add(Color.WHITE);
teamcolor.add(Color.LTGRAY);
teamcolor.add(Color.WHITE);
}
public int getCount() {
return teams.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.decklist, null);
holder = new ViewHolder();
holder.icon = (ImageView) convertView.findViewById(R.id.deckarrow);
holder.text = (TextView) convertView.findViewById(R.id.textname);
.......here you can use holder.text.setonclicklistner(new View.onclick.
for each textview
System.out.println(holder.text.getText().toString());
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(teams.get(position));
if(position<teamcolor.size())
holder.text.setBackgroundColor(teamcolor.get(position));
holder.icon.setImageResource(R.drawable.arraocha);
return convertView;
}
class ViewHolder {
ImageView icon;
TextView text;
}
}
Hope this helps.
pom
is basically a container of submodules, each submodule is represented by a subdirectory in the same directory as pom.xml
with pom
packaging.
Somewhere, nested within the project structure you will find artifacts (modules) with war
packaging. Maven generally builds everything into /target
subdirectories of each module. So after mvn install
look into target
subdirectory in a module with war
packaging.
Of course:
$ find . -iname "*.war"
works equally well ;-).
EDIT : this answer used to claim that it isn't possible to center an absolutely positioned element with margin: auto;
, but this simply isn't true. Because this is the most up-voted and accepted answer, I guessed I'd just change it to be correct.
When you apply the following CSS to an element
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
And then give the element a fixed width and height, such as 200px or 40%, the element will center itself.
Here's a Fiddle that demonstrates the effect.
You can change the default location of .m2 directory in m2.conf file. It resides in your maven installation directory.
add modify this line in
m2.conf
set maven.home C:\Users\me\.m2
If you're on Windows, you can use kbhit()
which is part of the Microsoft run-time library. If you're on Linux, you can implement kbhit
thus (source):
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
int kbhit(void)
{
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if(ch != EOF)
{
ungetc(ch, stdin);
return 1;
}
return 0;
}
Update: The above function works on OS X (at least, on OS X 10.5.8 - Leopard, so I would expect it to work on more recent versions of OS X). This gist can be saved as kbhit.c
and compiled on both Linux and OS X with
gcc -o kbhit kbhit.c
When run with
./kbhit
It prompts you for a keypress, and exits when you hit a key (not limited to Enter or printable keys).
@Johnsyweb - please elaborate what you mean by "detailed canonical answer" and "all the concerns". Also, re "cross-platform": With this implementation of kbhit()
you can have the same functionality in a C++ program on Linux/Unix/OS X/Windows - which other platforms might you be referring to?
Further update for @Johnsyweb: C++ applications do not live in a hermetically sealed C++ environment. A big reason for C++'s success is interoperability with C. All mainstream platforms are implemented with C interfaces (even if internal implementation is using C++) so your talk of "legacy" seems out of place. Plus, as we are talking about a single function, why do you need C++ for this ("C with classes")? As I pointed out, you can write in C++ and access this functionality easily, and your application's users are unlikely to care how you implemented it.
I had to solve a similar problem. I inherited a large source table from MS Access with nearly 15000 records that did not have a primary key, which I had to normalize and make CakePHP compatible. One convention of CakePHP is that every table has a the primary key, that it is first column and that it is called 'id'. The following simple statement did the trick for me under MySQL 5.5:
ALTER TABLE `database_name`.`table_name`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (`id`);
This added a new column 'id' of type integer in front of the existing data ("FIRST" keyword). The AUTO_INCREMENT keyword increments the ids starting with 1. Now every dataset has a unique numerical id. (Without the AUTO_INCREMENT statement all rows are populated with id = 0).
Try this jquery plugin. Although, this is not a pure HTML and CSS solution, but it is a lazy way to achieve what you want. You can customize your greyscale to best suit your usage. Use it as follow:
$("#myImageID").tancolor();
There's an interactive demo. You can play around with it.
Check out the documentation on the usage, it is pretty simple. docs
In case of adding new rows for array in loop, Assign the array directly for firsttime in loop instead of initialising an empty array.
for i in range(0,len(0,100)):
SOMECALCULATEDARRAY = .......
if(i==0):
finalArrayCollection = SOMECALCULATEDARRAY
else:
finalArrayCollection = np.vstack(finalArrayCollection,SOMECALCULATEDARRAY)
This is mainly useful when the shape of the array is unknown
You can use finish()
method or you can use:
android:noHistory="true"
And then there is no need to call finish()
anymore.
<activity android:name=".ClassName" android:noHistory="true" ... />
I'm sorry I don't have enough reputation to comment the "answer" of "Andres Jaan Tack".
I think my messege will be deleted (( But I just want to warn "lurscher" and others who got the same error: be carefull doing
$ mkdir include
$ mv common include
$ git rm -r common
$ git add include/common
It may cause you will not see the git history of your project in new folder.
I tryed
$ git mv oldFolderName newFolderName
got
fatal: bad source, source=oldFolderName/somepath/__init__.py, dest
ination=ESWProj_Base/ESWProj_DebugControlsMenu/somepath/__init__.py
I did
git rm -r oldFolderName
and
git add newFolderName
and I don't see old git history in my project. At least my project is not lost. Now I have my project in newFolderName, but without the history (
Just want to warn, be carefull using advice of "Andres Jaan Tack", if you dont want to lose your git hsitory.
"each" uses callback function. Callback function execute irrespective of the calling function,so it is not possible to return to calling function from callback function.
use for loop if you have to stop the loop execution based on some condition and remain in to the same function.
Hmmm... Keep in mind that Class may or may not implement equals() -- that is not required by the spec. For instance, HP Fortify will flag myClass.equals(myOtherClass).
For files in a directory, you can use things like:
if exist *.csv echo "csv file found"
or
if not exist *.csv goto nofile
Using table-layout: fixed
as a property for table
and width: calc(100%/3);
for td
(assuming there are 3 td
's). With these two properties set, the table cells will be equal in size.
Refer to the demo.
So after a long time of playing around with AccessibilityServices, window insets, screen height detection, etc, I think I found a way to do this.
Disclaimer: it uses a hidden method in Android, meaning it might not be consistent. However, in my testing, it seems to work.
The method is InputMethodManager#getInputMethodWindowVisibleHeight(), and it's existed since Lollipop (5.0).
Calling that returns the height, in pixels, of the current keyboard. In theory, a keyboard shouldn't be 0 pixels tall, so I did a simple height check (in Kotlin):
val imm by lazy { context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager }
if (imm.inputMethodWindowVisibleHeight > 0) {
//keyboard is shown
else {
//keyboard is hidden
}
I use Android Hidden API to avoid reflection when I call hidden methods (I do that a lot for the apps I develop, which are mostly hacky/tuner apps), but this should be possible with reflection as well:
val imm by lazy { context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager }
val windowHeightMethod = InputMethodManager::class.java.getMethod("getInputMethodWindowVisibleHeight")
val height = windowHeightMethod.invoke(imm) as Int
//use the height val in your logic
basically object and instance are the two words used interchangeably. A class is template for an object and an object is an instance of a class.
try this
$('#div_id').animate({scrollTop:0}, '500', 'swing');
Try this too,
private void getContactList() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if ((cur != null ? cur.getCount() : 0) > 0) {
while (cur != null && cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
if (cur.getInt(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i(TAG, "Name: " + name);
Log.i(TAG, "Phone Number: " + phoneNo);
}
pCur.close();
}
}
}
if(cur!=null){
cur.close();
}
}
If you need more reference means refer this link Read ContactList
yo can extend your JS with a select method like this
Array.prototype.select = function(closure){
for(var n = 0; n < this.length; n++) {
if(closure(this[n])){
return this[n];
}
}
return null;
};
now you can use this:
var x = [1,2,3,4];
var a = x.select(function(v) {
return v == 2;
});
console.log(a);
or for objects in a array
var x = [{id: 1, a: true},
{id: 2, a: true},
{id: 3, a: true},
{id: 4, a: true}];
var a = x.select(function(obj) {
return obj.id = 2;
});
console.log(a);
I took your question as a challenge to write this in "portable" shell code, i.e.
It runs on any POSIX conformant shell (zsh, bash, ksh, ash, busybox, ...). It even contains a testsuite to verify its operation. Canonicalization of pathnames is left as an exercise. :-)
#!/bin/sh
# Find common parent directory path for a pair of paths.
# Call with two pathnames as args, e.g.
# commondirpart foo/bar foo/baz/bat -> result="foo/"
# The result is either empty or ends with "/".
commondirpart () {
result=""
while test ${#1} -gt 0 -a ${#2} -gt 0; do
if test "${1%${1#?}}" != "${2%${2#?}}"; then # First characters the same?
break # No, we're done comparing.
fi
result="$result${1%${1#?}}" # Yes, append to result.
set -- "${1#?}" "${2#?}" # Chop first char off both strings.
done
case "$result" in
(""|*/) ;;
(*) result="${result%/*}/";;
esac
}
# Turn foo/bar/baz into ../../..
#
dir2dotdot () {
OLDIFS="$IFS" IFS="/" result=""
for dir in $1; do
result="$result../"
done
result="${result%/}"
IFS="$OLDIFS"
}
# Call with FROM TO args.
relativepath () {
case "$1" in
(*//*|*/./*|*/../*|*?/|*/.|*/..)
printf '%s\n' "'$1' not canonical"; exit 1;;
(/*)
from="${1#?}";;
(*)
printf '%s\n' "'$1' not absolute"; exit 1;;
esac
case "$2" in
(*//*|*/./*|*/../*|*?/|*/.|*/..)
printf '%s\n' "'$2' not canonical"; exit 1;;
(/*)
to="${2#?}";;
(*)
printf '%s\n' "'$2' not absolute"; exit 1;;
esac
case "$to" in
("$from") # Identical directories.
result=".";;
("$from"/*) # From /x to /x/foo/bar -> foo/bar
result="${to##$from/}";;
("") # From /foo/bar to / -> ../..
dir2dotdot "$from";;
(*)
case "$from" in
("$to"/*) # From /x/foo/bar to /x -> ../..
dir2dotdot "${from##$to/}";;
(*) # Everything else.
commondirpart "$from" "$to"
common="$result"
dir2dotdot "${from#$common}"
result="$result/${to#$common}"
esac
;;
esac
}
set -f # noglob
set -x
cat <<EOF |
/ / .
/- /- .
/? /? .
/?? /?? .
/??? /??? .
/?* /?* .
/* /* .
/* /** ../**
/* /*** ../***
/*.* /*.** ../*.**
/*.??? /*.?? ../*.??
/[] /[] .
/[a-z]* /[0-9]* ../[0-9]*
/foo /foo .
/foo / ..
/foo/bar / ../..
/foo/bar /foo ..
/foo/bar /foo/baz ../baz
/foo/bar /bar/foo ../../bar/foo
/foo/bar/baz /gnarf/blurfl/blubb ../../../gnarf/blurfl/blubb
/foo/bar/baz /gnarf ../../../gnarf
/foo/bar/baz /foo/baz ../../baz
/foo. /bar. ../bar.
EOF
while read FROM TO VIA; do
relativepath "$FROM" "$TO"
printf '%s\n' "FROM: $FROM" "TO: $TO" "VIA: $result"
if test "$result" != "$VIA"; then
printf '%s\n' "OOOPS! Expected '$VIA' but got '$result'"
fi
done
# vi: set tabstop=3 shiftwidth=3 expandtab fileformat=unix :
BeautifulSoup(text, features="html.parser").text
For the people who were seeking deep info in my answer, sorry.
I'll explain it.
Beautifulsoup is a widely use python package that helps the user (developer) to interact with HTML within python.
The above like just take all the HTML text (text
) and cast it to Beautifulsoup object - that means behind the sense its parses everything up (Every HTML tag within the given text)
Once done so, we just request all the text from within the HTML object.
var str = "hello,how,are,you,today?";
var pieces = str.split(/[\s,]+/);
At this point, pieces
is an array and pieces.length
contains the size of the array so to get the last element of the array, you check pieces[pieces.length-1]
. If there are no commas or spaces it will simply output the string as it was given.
alert(pieces[pieces.length-1]); // alerts "today?"
You can KILL the processid.
mysql> show full processlist;
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| Id | User | Host | db | Command | Time | State | Info |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| 1193777 | TestUser12 | 192.168.1.11:3775 | www | Sleep | 25946 | | NULL |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
mysql> kill 1193777;
But:
Or you configure your mysql-server by setting a shorter timeout on wait_timeout
and interactive_timeout
mysql> show variables like "%timeout%";
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| connect_timeout | 5 |
| delayed_insert_timeout | 300 |
| innodb_lock_wait_timeout | 50 |
| interactive_timeout | 28800 |
| net_read_timeout | 30 |
| net_write_timeout | 60 |
| slave_net_timeout | 3600 |
| table_lock_wait_timeout | 50 |
| wait_timeout | 28800 |
+--------------------------+-------+
9 rows in set (0.00 sec)
Set with:
set global wait_timeout=3;
set global interactive_timeout=3;
(and also set in your configuration file, for when your server restarts)
But you're treating the symptoms instead of the underlying cause - why are the connections open? If the PHP script finished, shouldn't they close? Make sure your webserver is not using connection pooling...
In addition to substring answer, you can do it as mystring.SubString(0,3) and check in case statement if its "abc".
But before the switch statement you need to ensure that your mystring is atleast 3 in length.
Try this:
x = "{{ Hello }} {0}"
user2540984, as well as many others have pointed out that you can try increasing your timeout settings. I myself faced a similar issue to this one and tried to change my timeout settings in the /etc/nginx/nginx.conf file, as almost everyone in these threads suggest. This, however, did not help me a single bit; there was no apparent change in NGINX' timeout settings. After many hours of searching, I finally managed to solve my issue.
The solution lies in this forum thread, and what it says is that you should put your timeout settings in /etc/nginx/conf.d/timeout.conf (and if this file doesn't exist, you should create it). I used the same settings as suggested in the thread:
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
This might not be the solution to your particular problem, but if anyone else notices that the timeout changes in /etc/nginx/nginx.conf don't do anything, I hope this answer helps!
Append the following line to the end of your .vimrc
to prevent highlighting altogether:
set nohlsearch
it's a bit old, but nevertheless... I found the answer of Peter Wilkinson nice except for the fact that it does not work for primitive types like int/Integer.
The problem is the .getClass()
for the parameters[i]
, which returns for instance java.lang.Integer
, which on the other hand will not be correctly interpreted by getMethod(methodName,parameters[])
(Java's fault) ...
I combined it with the suggestion of Daniel Spiewak (in his answer to this); steps to success included: catching NoSuchMethodException
-> getMethods()
-> looking for the matching one by method.getName()
-> and then explicitly looping through the list of parameters and applying Daniels solution, such identifying the type matches and the signature matches.
functionName() : ReturnType { ... }
I know I'm a bit late for that one, but I'll share what I did too, in case it helps someone else :
HashMap<String, HashMap> selects = new HashMap<String, HashMap>();
for(Map.Entry<String, HashMap> entry : selects.entrySet()) {
String key = entry.getKey();
HashMap value = entry.getValue();
// do what you have to do here
// In your case, another loop.
}
I can not see where do you declare context
. For the purpose of the intent creation you can use MainActivity.this
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent = new Intent(MainActivity.this, SendMessage.class);
String message = "abc";
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
});
To retrieve the object upon you have clicked you can use the AdapterView
:
ListEntry entry = (ListEntry) parent.getItemAtPosition(position);
You may do as follows. one line of code will be enough
let array = $('ul>li').toArray().map(item => $(item).html());
Get the interested element
get children
get the array from toArray() method
filter out the results you want
let array = $('ul>li').toArray().map(item => $(item).html());_x000D_
console.log(array);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<ul>_x000D_
<li>text1</li>_x000D_
<li>text2</li>_x000D_
<li>text3</li>_x000D_
</ul>
_x000D_
I just wanted to add these from TLDP:
~:$ echo $SHELL
/bin/bash
~:$ echo ${#SHELL}
9
~:$ ARRAY=(one two three)
~:$ echo ${#ARRAY}
3
~:$ echo ${TEST:-test}
test
~:$ echo $TEST
~:$ export TEST=a_string
~:$ echo ${TEST:-test}
a_string
~:$ echo ${TEST2:-$TEST}
a_string
~:$ echo $TEST2
~:$ echo ${TEST2:=$TEST}
a_string
~:$ echo $TEST2
a_string
~:$ export STRING="thisisaverylongname"
~:$ echo ${STRING:4}
isaverylongname
~:$ echo ${STRING:6:5}
avery
~:$ echo ${ARRAY[*]}
one two one three one four
~:$ echo ${ARRAY[*]#one}
two three four
~:$ echo ${ARRAY[*]#t}
one wo one hree one four
~:$ echo ${ARRAY[*]#t*}
one wo one hree one four
~:$ echo ${ARRAY[*]##t*}
one one one four
~:$ echo $STRING
thisisaverylongname
~:$ echo ${STRING%name}
thisisaverylong
~:$ echo ${STRING/name/string}
thisisaverylongstring
Here's a Swift version of that function (for getting a UIColor representation of a UInt
value):
func UIColorFromRGB(rgbValue: UInt) -> UIColor {
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
view.backgroundColor = UIColorFromRGB(0x209624)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "USER_ID")
Long userId;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
List<Notification> sender;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
List<Notification> receiver;
}
public class Notification implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "NOTIFICATION_ID")
Long notificationId;
@Column(name = "TEXT")
String text;
@Column(name = "ALERT_STATUS")
@Enumerated(EnumType.STRING)
AlertStatus alertStatus = AlertStatus.NEW;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "SENDER_ID")
@JsonIgnore
User sender;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "RECEIVER_ID")
@JsonIgnore
User receiver;
}
What I understood from the answer. mappedy="sender" value should be the same in the notification model. I will give you an example..
User model:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "**sender**", cascade = CascadeType.ALL)
List<Notification> sender;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "**receiver**", cascade = CascadeType.ALL)
List<Notification> receiver;
Notification model:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
List<Notification> **sender**;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
List<Notification> **receiver**;
I gave bold font to user model and notification field. User model mappedBy="sender " should be equal to notification List sender; and mappedBy="receiver" should be equal to notification List receiver; If not, you will get error.
You have to use the didSelectRow
delegate method, because a UIPickerView
can have an arbitrary number of components. There is no "objectValue" or anything like that, because that's entirely up to you.
You can try using Runtime.getRuntime().gc()
or use utility method System.gc()
Note: These methods do not ensure GC. And their scope should be limited to JVM rather than programmatically handling it in your application.
I agree with the other answerers that in most cases (almost always) it is necessary to sanitize Your input.
But consider such code (it is for a REST controller):
$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
case 'GET':
return $this->doGet($request, $object);
case 'POST':
return $this->doPost($request, $object);
case 'PUT':
return $this->doPut($request, $object);
case 'DELETE':
return $this->doDelete($request, $object);
default:
return $this->onBadRequest();
}
It would not be very useful to apply sanitizing here (although it would not break anything, either).
So, follow recommendations, but not blindly - rather understand why they are for :)
You can't wrap that text as it's unbroken without any spaces. You need a JavaScript or server side solution which splits the string after a few characters.
EDIT
You need to add this property in CSS.
word-wrap: break-word;
you could submit all parameters with such naming:
params[0][topdiameter]
params[0][bottomdiameter]
params[1][topdiameter]
params[1][bottomdiameter]
then later you do something like this:
foreach ($_REQUEST['params'] as $item) {
echo $item['topdiameter'];
echo $item['bottomdiameter'];
}
Quoting from the Wikipedia article on Web Storage:
Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity (10 MB per origin in Google Chrome(https://plus.google.com/u/0/+FrancoisBeaufort/posts/S5Q9HqDB8bh), Mozilla Firefox, and Opera; 10 MB per storage area in Internet Explorer) and better programmatic interfaces.
And also quoting from a John Resig article [posted January 2007]:
Storage Space
It is implied that, with DOM Storage, you have considerably more storage space than the typical user agent limitations imposed upon Cookies. However, the amount that is provided is not defined in the specification, nor is it meaningfully broadcast by the user agent.
If you look at the Mozilla source code we can see that 5120KB is the default storage size for an entire domain. This gives you considerably more space to work with than a typical 2KB cookie.
However, the size of this storage area can be customized by the user (so a 5MB storage area is not guaranteed, nor is it implied) and the user agent (Opera, for example, may only provide 3MB - but only time will tell.)
Swift 5 another way. Resistant to interaction with UI
I would like to show a solution that is resistant to user interaction with other UI elements during countdown. In the comments I explained what each line of code means.
var timeToSet = 0
var timer: Timer?
...
@IBAction func btnWasPressed(_ sender: UIButton) {
//Setting the countdown time
timeLeft = timeToSet
//Disabling any previous timers.
timer?.invalidate()
//Initialization of the Timer with interval every 1 second with the function call.
timer = Timer(timeInterval: 1.0, target: self, selector: #selector(countDown), userInfo: nil, repeats: true)
//Adding Timer to the current loop
RunLoop.current.add(timer!, forMode: .common)
}
...
@objc func countDown() {
if timeLeft > 0 {
print(timeLeft)
timeLeft -= 1
} else {
// Timer stopping
timer?.invalidate()
}
}
Everyone's mentioned the ready
function (and its shortcuts), but even earlier than that, you can just put code in a script
tag just before the closing body
tag (this is what the YUI and Google Closure folks recommend), like this:
<script type='text/javascript'>
pageLoad();
</script>
</body>
At this point, everything above that script tag is available in the DOM.
So your options in order of occurrence:
Earliest: Function call in script
tag just before closing the body
tag. The DOM is ready at this point (according to the Google Closure folks, and they should know; I've also tested it on a bunch of browsers).
Earlyish: the jQuery.ready
callback (and its shortcut forms).
Late, after all page elements including images are fully loaded: window
onload
event.
Here's a live example: http://jsbin.com/icazi4, relevant extract:
</body>
<script type='text/javascript'>
runPage();
jQuery(function() {
display("From <tt>jQuery.ready</tt> callback.");
});
$(window).load(function() {
display("From <tt>window.onload</tt> callback.");
});
function runPage() {
display("From function call at end of <tt>body</tt> tag.");
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
</script>
(Yes, I could have used jQuery for the display
function, but I was starting with a non-jQuery template.)
The easiest option for me was to rename the title of the terminal instead. Please see: https://superuser.com/questions/362227/how-to-change-the-title-of-the-mintty-window
In this answer, they mention to modify the PS1 variable. Note: my situation was particular to cygwin.
TL;DR Put this in your .bashrc file:
function settitle() {
export PS1="\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[0m\]\n$ "
echo -ne "\e]0;$1\a"
}
Put this in your .tmux.conf file, or similar formatting:
set -g pane-border-status bottom
set -g pane-border-format "#P #T #{pane_current_command}"
Then you can change the title of the pane by typing this in the console:
settitle titlename
You can do it with Linq, as mamoo showed, but the oldies are good too:
var filteredDataTable = dt.Select(@"EmpId > 2
AND (EmpName <> 'abc' OR EmpName <> 'xyz')
AND EmpName like '%il%'" );
Could be an issue with MySQL and the number of open connections, hence why it sorts itself out when you restart every few days. Are they auto closing on script shutdown?
in your location block you can do:
location / {
try_files $uri $uri/index.html;
}
which will tell ngingx to look for a file with the exact name given first, and if none such file is found it will try uri/index.html. So if a request for https://www.example.com/ comes it it would look for an exact file match first, and not finding that would then check for index.html
The latest way to do this with ES2016 JavaScript
let makeGamePlayer = (name, totalScore, gamesPlayed) => ({
name,
totalScore,
gamesPlayed
})
Two options:
<button>multiline<br/>button<br/>text</button>
or
<input type="button" value="Carriage return separators" style="text-align:center;">
I'm on XP. I've installed MySQL-5.6.10 manually from .zip
, no Windows auto-installer provided by MySQL site. The /bin
directory of my MySQL is in my PATH. So I start the server with mysqld --console
command, like this:
C:\Documents and Settings\User>mysqld --console
2013-04-12 14:39:19 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_times
tamp server option (see documentation for more details).
From now on it is running. And that cmd window is occupied. I open and use another one.
I've tried to use the answers from above but none of them can stop the server. Only errors are throw. So I stop the server with mysqladmin -u root shutdown
on the other cmd window or with Ctrl + C
on the cmd window it is running in. The latter works not so good as the former, sometimes I have to click Ctrl + C
twice or more.
The log of the shutdown process is like this:
2013-04-12 17:55:29 3968 [Note] Giving 0 client threads a chance to die gracefully
2013-04-12 17:55:29 3968 [Note] Event Scheduler: Purging the queue. 0 events
2013-04-12 17:55:29 3968 [Note] Shutting down slave threads
2013-04-12 17:55:29 3968 [Note] Forcefully disconnecting 0 remaining clients
2013-04-12 17:55:29 3968 [Note] Binlog end
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'partition'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'PERFORMANCE_SCHEMA'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_DATAFILES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_TABLESPACES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN_COLS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_FIELDS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_COLUMNS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_INDEXES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_TABLESTATS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_TABLES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_INDEX_TABLE'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_INDEX_CACHE'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_CONFIG'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_BEING_DELETED'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_DELETED'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_INSERTED'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_DEFAULT_STOPWORD'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_METRICS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_BUFFER_POOL_STATS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE_LRU'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX_RESET'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMPMEM_RESET'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMPMEM'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP_RESET'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_LOCK_WAITS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_LOCKS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_TRX'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'InnoDB'
2013-04-12 17:55:29 3968 [Note] InnoDB: FTS optimize thread exiting.
2013-04-12 17:55:29 3968 [Note] InnoDB: Starting shutdown...
2013-04-12 17:55:30 3968 [Note] InnoDB: Shutdown completed; log sequence number 1719777
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'BLACKHOLE'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'ARCHIVE'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'MRG_MYISAM'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'MyISAM'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'MEMORY'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'CSV'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'sha256_password'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'mysql_old_password'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'mysql_native_password'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'binlog'
2013-04-12 17:55:30 3968 [Note] mysqld: Shutdown complete
And I still don't know if it is 100% right way to shutdown the server, but it works :)
It is because you forgot to pass in event
into the click
function:
$('.menuOption').on('click', function (e) { // <-- the "e" for event
e.preventDefault(); // now it'll work
var categories = $(this).attr('rel');
$('.pages').hide();
$(categories).fadeIn();
});
On a side note, e
is more commonly used as opposed to the word event
since Event
is a global variable in most browsers.
jsdom is too strict to do any real screen scraping sort of things, but beautifulsoup doesn't choke on bad markup.
node-soupselect is a port of python's beautifulsoup into nodejs, and it works beautifully
SELECT
student.firstname,
student.lastname,
exam.name,
exam.date,
grade.grade
FROM grade
INNER JOIN student
ON student.studentId = grade.fk_studentId
INNER JOIN exam
ON exam.examId = grade.fk_examId
GROUP BY grade.gradeId
ORDER BY exam.date
Try this:
var text = $('#YourDropdownId').find('option:selected').text();
In stead of "live" you need to use "on" event, but assign it to the document object:
Use:
$(document).on('hidden.bs.modal', '#Control_id', function (event) {
// code to run on closing
});
I use openssl, but if you prefer not to, or are on a system (particularly Windows) that doesn't have it, since java 7 in 2011 keytool
can do the whole job:
keytool -printcert -sslserver host[:port] -rfc >tempfile
keytool -import [-noprompt] -alias nm -keystore file [-storepass pw] [-storetype ty] <tempfile
# or with noprompt and storepass (so nothing on stdin besides the cert) piping works:
keytool -printcert -sslserver host[:port] -rfc | keytool -import -noprompt -alias nm -keystore file -storepass pw [-storetype ty]
Conversely, for java 9 up always, and for earlier versions in many cases, Java can use a PKCS12 file for a keystore instead of the traditional JKS file, and OpenSSL can create a PKCS12 without any assistance from keytool:
openssl s_client -connect host:port </dev/null | openssl pkcs12 -export -nokeys [-name nm] [-passout option] -out p12file
# <NUL on Windows
# default is to prompt for password, but -passout supports several options
# including actual value, envvar, or file; see the openssl(1ssl) man page
The answer for Swift 2.0 Alamofire 3.0 should actually look more like this:
Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON).responseJSON
{ response in switch response.result {
case .Success(let JSON):
print("Success with JSON: \(JSON)")
let response = JSON as! NSDictionary
//example if there is an id
let userId = response.objectForKey("id")!
case .Failure(let error):
print("Request failed with error: \(error)")
}
}
UPDATE for Alamofire 4.0 and Swift 3.0 :
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { response in
print(response)
//to get status code
if let status = response.response?.statusCode {
switch(status){
case 201:
print("example success")
default:
print("error with response status: \(status)")
}
}
//to get JSON return value
if let result = response.result.value {
let JSON = result as! NSDictionary
print(JSON)
}
}
LENGTH()
returns the length of the string measured in bytes.
CHAR_LENGTH()
returns the length of the string measured in characters.
This is especially relevant for Unicode, in which most characters are encoded in two bytes. Or UTF-8, where the number of bytes varies. For example:
select length(_utf8 '€'), char_length(_utf8 '€')
--> 3, 1
As you can see the Euro sign occupies 3 bytes (it's encoded as 0xE282AC
in UTF-8) even though it's only one character.
rm -r ./folder -Force
...worked for me
Using pathlib you can get the folder in which the current file is located. __file__
is the pathname of the file from which the module was loaded.
Ref: docs
import pathlib
current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)
Doc ref: link
You don't need to send messages.
Add an event to the one form and an event handler to the other. Then you can use a third project which references the other two to attach the event handler to the event. The two DLLs don't need to reference each other for this to work.
It depends on where you want to use those.
TextBoxBase
-derived controls already implement those shortcuts. If you want to use custom keyboard shortcuts you should take a look on Commands and Input gestures. Here is a small tutorial from Switch on the Code: WPF Tutorial - Command Bindings and Custom Commands
On some kind of linux like ubuntu, first, do apt-get update and then try installing the python-pip package. without apt-get update, you might get error such as
E: Unable to locate package python-pip
1.Update :
sudo apt-get update
2.Install the pip package
For python2
sudo apt-get install python-pip
or
For python3
sudo apt-get install python3-pip
And done!
I picked node-sass implementer for libsass because it is based on node.js.
$ npm install -g node-sass
installs node-sass globally -g
.This will hopefully install all you need, if not read libsass at the bottom.
General format:
$ node-sass [options] <input.scss> [output.css]
$ cat <input.scss> | node-sass > output.css
Examples:
$ node-sass my-styles.scss my-styles.css
compiles a single file manually.$ node-sass my-sass-folder/ -o my-css-folder/
compiles all the files in a folder manually.$ node-sass -w sass/ -o css/
compiles all the files in a folder automatically whenever the source file(s) are modified. -w
adds a watch for changes to the file(s).More usefull options like 'compression' @ here. Command line is good for a quick solution, however, you can use task runners like Grunt.js or Gulp.js to automate the build process.
You can also add the above examples to npm scripts. To properly use npm scripts as an alternative to gulp read this comprehensive article @ css-tricks.com especially read about grouping tasks.
package.json
file in your project directory running $ npm init
will create one. Use it with -y
to skip the questions. "sass": "node-sass -w sass/ -o css/"
to scripts
in package.json
file. It should look something like this:"scripts": {
"test" : "bla bla bla",
"sass": "node-sass -w sass/ -o css/"
}
$ npm run sass
will compile your files.$ npm install -g gulp
installs Gulp globally.package.json
file in your project directory running $ npm init
will create one. Use it with -y
to skip the questions.$ npm install --save-dev gulp
installs Gulp locally. --save-dev
adds gulp
to devDependencies
in package.json
.$ npm install gulp-sass --save-dev
installs gulp-sass locally.gulpfile.js
file in your project root folder with this content:'use strict';
var gulp = require('gulp');
A basic example to transpile
Add this code to your gulpfile.js:
var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('sass', function () {
gulp.src('./sass/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'));
});
$ gulp sass
runs the above task which compiles .scss file(s) in the sass
folder and generates .css file(s) in the css
folder.
To make life easier, let's add a watch so we don't have to compile it manually. Add this code to your gulpfile.js
:
gulp.task('sass:watch', function () {
gulp.watch('./sass/**/*.scss', ['sass']);
});
All is set now! Just run the watch task:
$ gulp sass:watch
As the name of node-sass implies, you can write your own node.js scripts for transpiling. If you are curious, check out node-sass project page.
Libsass is a library that needs to be built by an implementer such as sassC or in our case node-sass. Node-sass contains a built version of libsass which it uses by default. If the build file doesn't work on your machine, it tries to build libsass for your machine. This process requires Python 2.7.x (3.x doesn't work as of today). In addition:
LibSass requires GCC 4.6+ or Clang/LLVM. If your OS is older, this version may not compile. On Windows, you need MinGW with GCC 4.6+ or VS 2013 Update 4+. It is also possible to build LibSass with Clang/LLVM on Windows.
Using dis
to look at the bytecode generated for the two versions:
not ==
4 0 LOAD_FAST 0 (foo)
3 LOAD_FAST 1 (bar)
6 COMPARE_OP 2 (==)
9 UNARY_NOT
10 RETURN_VALUE
!=
4 0 LOAD_FAST 0 (foo)
3 LOAD_FAST 1 (bar)
6 COMPARE_OP 3 (!=)
9 RETURN_VALUE
The latter has fewer operations, and is therefore likely to be slightly more efficient.
It was pointed out in the commments (thanks, @Quincunx) that where you have if foo != bar
vs. if not foo == bar
the number of operations is exactly the same, it's just that the COMPARE_OP
changes and POP_JUMP_IF_TRUE
switches to POP_JUMP_IF_FALSE
:
not ==
:
2 0 LOAD_FAST 0 (foo)
3 LOAD_FAST 1 (bar)
6 COMPARE_OP 2 (==)
9 POP_JUMP_IF_TRUE 16
!=
2 0 LOAD_FAST 0 (foo)
3 LOAD_FAST 1 (bar)
6 COMPARE_OP 3 (!=)
9 POP_JUMP_IF_FALSE 16
In this case, unless there was a difference in the amount of work required for each comparison, it's unlikely you'd see any performance difference at all.
However, note that the two versions won't always be logically identical, as it will depend on the implementations of __eq__
and __ne__
for the objects in question. Per the data model documentation:
There are no implied relationships among the comparison operators. The truth of
x==y
does not imply thatx!=y
is false.
For example:
>>> class Dummy(object):
def __eq__(self, other):
return True
def __ne__(self, other):
return True
>>> not Dummy() == Dummy()
False
>>> Dummy() != Dummy()
True
Finally, and perhaps most importantly: in general, where the two are logically identical, x != y
is much more readable than not x == y
.
For me this setting was working.
In my windows 8.1 the path for php7 is
C:\user\test\tools\php7\php.exe
settings.json
{
"php.executablePath":"/user/test/tools/php7/php.exe",
"php.validate.executablePath": "/user/test/tools/php7/php.exe"
}
class Program
{
double[] a = new double[] { 1, 3, 4, 8, 21, 38 };
double[] b = new double[] { 1, 7, 19, 3, 2, 24 };
double[] result;
public double[] CheckSorting()
{
for(int i = 1; i < a.Length; i++)
{
if (a[i] < a[i - 1])
result = b;
else
result = a;
}
return result;
}
static void Main(string[] args)
{
Program checkSorting = new Program();
checkSorting.CheckSorting();
Console.ReadLine();
}
}
This should work, otherwise i got the error that not all codepaths return a value. Therefor i set the result as the returned value, which is set as either B or A depending on which is true
Note that starting git1.8.4 (July 2013), you wouldn't have to go back to the root directory anymore.
cd ~/.janus/snipmate-snippets
git submodule add <git@github ...> snippets
(Bouke Versteegh comments that you don't have to use /.
, as in snippets/.
: snippets
is enough)
See commit 091a6eb0feed820a43663ca63dc2bc0bb247bbae:
submodule: drop the top-level requirement
Use the new
rev-parse --prefix
option to process all paths given to the submodule command, dropping the requirement that it be run from the top-level of the repository.Since the interpretation of a relative submodule URL depends on whether or not "
remote.origin.url
" is configured, explicitly block relative URLs in "git submodule add
" when not at the top level of the working tree.Signed-off-by: John Keeping
Depends on commit 12b9d32790b40bf3ea49134095619700191abf1f
This makes '
git rev-parse
' behave as if it were invoked from the specified subdirectory of a repository, with the difference that any file paths which it prints are prefixed with the full path from the top of the working tree.This is useful for shell scripts where we may want to
cd
to the top of the working tree but need to handle relative paths given by the user on the command line.
A blog post that I found useful: Understanding JavaScript Prototypes
You can mess with the __proto__ property of the Object.
var fooJSON = jQuery.parseJSON({"a":4, "b": 3});
fooJSON.__proto__ = Foo.prototype;
This allows fooJSON to inherit the Foo prototype.
I don't think this works in IE, though... at least from what I've read.
From developer.android.com:
public void finishAffinity ()
Added in API level 16
Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and in to its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch.
Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.
String.prototype.padZero= function(len, c){
var s= this, c= c || '0';
while(s.length< len) s= c+ s;
return s;
}
dispite the name, you can left-pad with any character, including a space. I never had a use for right side padding, but that would be easy enough.
The first thing I would recommend is to take measurements. Where are you losing your time? Is it in the read, or the write?
Over 100,000 accesses (sum the times): How much time is spent allocating the buffer array? How much time is spent opening the file for read (is it the same file every time?) How much time is spent in read and write operations?
If you aren't doing any type of transformation on the file, do you need a BinaryWriter, or can you use a filestream for writes? (try it, do you get identical output? does it save time?)
Do this:
list.ForEach(i => Console.Write("{0}\t", i));
EDIT: To others that have responded - he wants them all on the same line, with tabs between them. :)
You can combine this all into one formula, but you need to use a regular IF
first to find out if the VLOOKUP
came back with something, then use your COUNTIF
if it did.
=IF(ISERROR(VLOOKUP(B1,Sheet2!A1:A9,1,FALSE)),"Not there",COUNTIF(Sheet2!A1:A9,B1))
In this case, Sheet2-A1:A9 is the range I was searching, and Sheet1-B1 had the value I was looking for ("To retire" in your case).
The URI to open a specific channel in Slack app is:
slack://channel?id=<CHANNEL-ID>&team=<TEAM-ID>
You will probably need these resources of the Slack API to get IDs of your team and channel:
Here's the full documentation from Slack
Here is a snippet I wrote; to ask for users' password and set it in /etc/passwd. You can manipulate it a little probably to get what you need:
echo -n " Please enter the password for the given user: "
read userPass
useradd $userAcct && echo -e "$userPass\n$userPass\n" | passwd $userAcct > /dev/null 2>&1 && echo " User account has been created." || echo " ERR -- User account creation failed!"
It requires a bit of rearranging, but when
does a good job to replace conditionals above. Here's the example from above written using the declarative syntax. Note that test3
stage is now two different stages. One that runs on the master branch and one that runs on anything else.
stage ('Test 3: Master') {
when { branch 'master' }
steps {
echo 'I only execute on the master branch.'
}
}
stage ('Test 3: Dev') {
when { not { branch 'master' } }
steps {
echo 'I execute on non-master branches.'
}
}
Alternatively, you could invert the image using the bitwise_not
function of OpenCV:
imagem = cv2.bitwise_not(imagem)
I liked this example.
This seems considerably easier than what anyone else has suggested
select sysdate-to_date('30-jul-1977') from dual;
For most it is a breeze, however like you I had a difficult time installing jq
The best resources I found are: https://stedolan.github.io/jq/download/ and http://macappstore.org/jq/
However neither worked for me. I run python 2 & 3, and use brew in addition to pip, as well as Jupyter. I was only successful after brew uninstall jq then updating brew and rebooting my system
What worked for me was removing all previous installs then pip install jq
Try this:
onclick="myfunction(
'/myController/myAction',
function(){myfuncionOnOK('/myController2/myAction2','myParameter2');},
function(){myfuncionOnCancel('/myController3/myAction3','myParameter3');}
);"
Then you just need to call these two functions passed to myfunction
:
function myfunction(url, f1, f2) {
// …
f1();
f2();
}
Fast image resize/resample algorithm using Hermite filter with JavaScript. Support transparency, gives good quality. Preview:
Update: version 2.0 added on GitHub (faster, web workers + transferable objects). Finally i got it working!
Git: https://github.com/viliusle/Hermite-resize
Demo: http://viliusle.github.io/miniPaint/
/**
* Hermite resize - fast image resize/resample using Hermite filter. 1 cpu version!
*
* @param {HtmlElement} canvas
* @param {int} width
* @param {int} height
* @param {boolean} resize_canvas if true, canvas will be resized. Optional.
*/
function resample_single(canvas, width, height, resize_canvas) {
var width_source = canvas.width;
var height_source = canvas.height;
width = Math.round(width);
height = Math.round(height);
var ratio_w = width_source / width;
var ratio_h = height_source / height;
var ratio_w_half = Math.ceil(ratio_w / 2);
var ratio_h_half = Math.ceil(ratio_h / 2);
var ctx = canvas.getContext("2d");
var img = ctx.getImageData(0, 0, width_source, height_source);
var img2 = ctx.createImageData(width, height);
var data = img.data;
var data2 = img2.data;
for (var j = 0; j < height; j++) {
for (var i = 0; i < width; i++) {
var x2 = (i + j * width) * 4;
var weight = 0;
var weights = 0;
var weights_alpha = 0;
var gx_r = 0;
var gx_g = 0;
var gx_b = 0;
var gx_a = 0;
var center_y = (j + 0.5) * ratio_h;
var yy_start = Math.floor(j * ratio_h);
var yy_stop = Math.ceil((j + 1) * ratio_h);
for (var yy = yy_start; yy < yy_stop; yy++) {
var dy = Math.abs(center_y - (yy + 0.5)) / ratio_h_half;
var center_x = (i + 0.5) * ratio_w;
var w0 = dy * dy; //pre-calc part of w
var xx_start = Math.floor(i * ratio_w);
var xx_stop = Math.ceil((i + 1) * ratio_w);
for (var xx = xx_start; xx < xx_stop; xx++) {
var dx = Math.abs(center_x - (xx + 0.5)) / ratio_w_half;
var w = Math.sqrt(w0 + dx * dx);
if (w >= 1) {
//pixel too far
continue;
}
//hermite filter
weight = 2 * w * w * w - 3 * w * w + 1;
var pos_x = 4 * (xx + yy * width_source);
//alpha
gx_a += weight * data[pos_x + 3];
weights_alpha += weight;
//colors
if (data[pos_x + 3] < 255)
weight = weight * data[pos_x + 3] / 250;
gx_r += weight * data[pos_x];
gx_g += weight * data[pos_x + 1];
gx_b += weight * data[pos_x + 2];
weights += weight;
}
}
data2[x2] = gx_r / weights;
data2[x2 + 1] = gx_g / weights;
data2[x2 + 2] = gx_b / weights;
data2[x2 + 3] = gx_a / weights_alpha;
}
}
//clear and resize canvas
if (resize_canvas === true) {
canvas.width = width;
canvas.height = height;
} else {
ctx.clearRect(0, 0, width_source, height_source);
}
//draw
ctx.putImageData(img2, 0, 0);
}
Have you tried Chromebug? It's the Firebug for extensions.
as suggested here solving the famous LazyInitializationException is one of the following methods:
(1) Use Hibernate.initialize
Hibernate.initialize(topics.getComments());
(2) Use JOIN FETCH
You can use the JOIN FETCH syntax in your JPQL to explicitly fetch the child collection out. This is somehow like EAGER fetching.
(3) Use OpenSessionInViewFilter
LazyInitializationException often occurs in the view layer. If you use Spring framework, you can use OpenSessionInViewFilter. However, I do not suggest you to do so. It may leads to a performance issue if not used correctly.
The answer that helped me: The directive [(ngModel)]= not working anymore in rc5
To sum it up: input fields now require property name
in the form.
l = [1, 2, 3, 4, 5]
del l[0:3] # Here 3 specifies the number of items to be deleted.
This is the code if you want to delete a number of items from the list. You might as well skip the zero before the colon. It does not have that importance. This might do as well.
l = [1, 2, 3, 4, 5]
del l[:3] # Here 3 specifies the number of items to be deleted.
Here's your code fixed up. Next forget bindingsource
var select = "SELECT * FROM tblEmployee";
var c = new SqlConnection(yourConnectionString); // Your Connection String here
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
var ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
SOURCE: https://git-scm.com/book/en/v2/Distributed-Git-Maintaining-a-Project#Integrating-Contributed-Work
The other way to move introduced work from one branch to another is to cherry-pick it. A cherry-pick in Git is like a rebase for a single commit. It takes the patch that was introduced in a commit and tries to reapply it on the branch you’re currently on. This is useful if you have a number of commits on a topic branch and you want to integrate only one of them, or if you only have one commit on a topic branch and you’d prefer to cherry-pick it rather than run rebase. For example, suppose you have a project that looks like this:
If you want to pull commit e43a6 into your master branch, you can run
$ git cherry-pick e43a6
Finished one cherry-pick.
[master]: created a0a41a9: "More friendly message when locking the index fails."
3 files changed, 17 insertions(+), 3 deletions(-)
This pulls the same change introduced in e43a6, but you get a new commit SHA-1 value, because the date applied is different. Now your history looks like this:
Now you can remove your topic branch and drop the commits you didn’t want to pull in.
Use FormData
and fetch
to grab and send data
fetch(form.action, {method:'post', body: new FormData(form)});
function send(e,form) {
fetch(form.action, {method:'post', body: new FormData(form)});
console.log('We send post asynchronously (AJAX)');
e.preventDefault();
}
_x000D_
<form method="POST" action="myapi/send" onsubmit="send(event,this)">
<input hidden name="crsfToken" value="a1e24s1">
<input name="email" value="[email protected]">
<input name="phone" value="123-456-789">
<input type="submit">
</form>
Look on chrome console>network before/after 'submit'
_x000D_
tr.rowhighlight td, tr.rowhighlight th{
background-color:#f0f8ff;
}
This will match yyyy-mm-dd
and also yyyy-m-d
:
^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])$
If you're looking for an exact match for yyyy-mm-dd
then try this
^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$
or use this one if you need to find a date inside a string like The date is 2017-11-30
\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])*
Can “git pull --all” update all my local branches?
No it cannot. For fast-forwarding, I just wrote a small tool to do so. https://github.com/changyuheng/git-fast-forward-all
Advantages of this tool:
hub sync
doesn't support multiple remotes at the moment.)This one will allow also for signed and float numbers or empty string:
var reg = /^-?\d*\.?\d*$/
If you don't want allow to empty string use this one:
var reg = /^-?\d+\.?\d*$/
PowerShell code to find all document library files modified from last 2 days.
$web = Get-SPWeb -Identity http://siteName:9090/
$list = $web.GetList("http://siteName:9090/Style Library/")
$folderquery = New-Object Microsoft.SharePoint.SPQuery
$foldercamlQuery =
'<Where> <Eq>
<FieldRef Name="ContentType" /> <Value Type="text">Folder</Value>
</Eq> </Where>'
$folderquery.Query = $foldercamlQuery
$folders = $list.GetItems($folderquery)
foreach($folderItem in $folders)
{
$folder = $folderItem.Folder
if($folder.ItemCount -gt 0){
Write-Host " find Item count " $folder.ItemCount
$oldest = $null
$files = $folder.Files
$date = (Get-Date).AddDays(-2).ToString(“MM/dd/yyyy”)
foreach ($file in $files){
if($file.Item["Modified"]-Ge $date)
{
Write-Host "Last 2 days modified folder name:" $folder " File Name: " $file.Item["Name"] " Date of midified: " $file.Item["Modified"]
}
}
}
else
{
Write-Warning "$folder['Name'] is empty"
}
}
Also struggled with this issue, trying to upload .csv data into AWS RDS instance from my local machine using MySQL Workbench on Windows.
The addition I needed was adding OPT_LOCAL_INFILE=1
in: Connection > Advanced > Others. Note CAPS was required.
I found this answer by PeterMag in AWS Developer Forums.
For further info:
SHOW VARIABLES LIKE 'local_infile';
already returned ON
and the query was:
LOAD DATA LOCAL INFILE 'filepath/file.csv'
INTO TABLE `table_name`
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;
Copying from the answer source referenced above:
Apparently this is a bug in MYSQL Workbench V8.X. In addition to the configurations shown earlier in this thread, you also need to change the MYSQL Connection in Workbench as follows:
- Go to the Welcome page of MYSQL which displays all your connections
- Select Manage Server Connections (the little spanner icon)
- Select your connection
- Select Advanced tab
- In the Others box, add OPT_LOCAL_INFILE=1
Now I can use the LOAD DATA LOCAL INFILE query on MYSQL RDS. It seems that the File_priv permission is not required.*
For example,
package main
import "fmt"
func main() {
type Map1 map[string]interface{}
type Map2 map[string]int
m := Map1{"foo": Map2{"first": 1}, "boo": Map2{"second": 2}}
//m = map[foo:map[first: 1] boo: map[second: 2]]
fmt.Println("m:", m)
for k, v := range m {
fmt.Println("k:", k, "v:", v)
}
}
Output:
m: map[boo:map[second:2] foo:map[first:1]]
k: boo v: map[second:2]
k: foo v: map[first:1]
While this question is really old. I believe there is a much simpler approach in numpy (a one liner).
import numpy as np
list = [1,3,9,5,2,5,6,9,7]
np.diff(np.sign(np.diff(list))) #the one liner
#output
array([ 0, -2, 0, 2, 0, 0, -2])
To find a local max or min we essentially want to find when the difference between the values in the list (3-1, 9-3...) changes from positive to negative (max) or negative to positive (min). Therefore, first we find the difference. Then we find the sign, and then we find the changes in sign by taking the difference again. (Sort of like a first and second derivative in calculus, only we have discrete data and don't have a continuous function.)
The output in my example does not contain the extrema (the first and last values in the list). Also, just like calculus, if the second derivative is negative, you have max, and if it is positive you have a min.
Thus we have the following matchup:
[1, 3, 9, 5, 2, 5, 6, 9, 7]
[0, -2, 0, 2, 0, 0, -2]
Max Min Max
A better cleaner thing to do: Just install the available, free, Microsoft Japanese language pack. (Other oriental language packs will also work, but I have tested the Japanese one.)
This gives you the fonts with the larger sets of glyphs, makes them the default behavior, changes the various Windows tools like cmd, WordPad, etc.
Add the following CSS:
For the parent div:
style="display: flex;"
For child div:
style="align-items: stretch;"
string actionName = this.ControllerContext.RouteData.Values["action"].ToString();
string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
Ok what you probably want will be provide to you by result of:
in CSS:
div { column-count: 2; }
in html:
<div> some text, bla bla bla </div>
In CSS you make div to split your paragraph on to column, you can make them 3, 4...
If you want to have many differend paragraf like that, then put id or class in your div:
--save-dev: Package will appear in your devDependencies.
According to the npm install docs.
If someone is planning on downloading and using your module in their program, then they probably don't want or need to download and build the external test or documentation framework that you use.
In other words, when you run npm install
, your project's devDependencies will be installed, but the devDependencies for any packages that your app depends on will not be installed; further, other apps having your app as a dependency need not install your devDependencies. Such modules should only be needed when developing the app (eg grunt, mocha etc).
According to the package.json docs
npm install
does:You can simply implement the same using the application iResign.
Give path of 1).ipa
2) New provision profile
3) Entitlement file (Optional, add only if you have entitlement)
4) Bundle id
5) Distribution Certificate
You can see output .ipa file saved after re-sign
Simple and powerful tool
(I don't have enough rep points to add a comment, but I want to add some clarity on the answers here)
Application.AskToUpdateLinks = False is probably not what you want.
If set to False, then MS Excel will attempt to update the links automatically it just won't prompt the user beforehand, sorta counter-intuitive.
The correct solution, if you're looking to open a file without updating links should be:
Workbook.Open(UpdateLinks:=0)
Related link: Difference in AskToUpdateLinks=False and UpdateLinks:=0
Heavy-weight:
Lightweight:
Drawing frameworks without GUI widgets:
IN WORDPRESS:
global $wpdb; $table_name=$wpdb->prefix.'posts';
foreach ( $wpdb->get_col( "DESC " . $table_name, 0 ) as $column_name ) {
var_dump( $column_name );
}
Solution is change the version of Spring in file pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
It happen that after some time we need to run
'php artisan passport:install --force
again to generate a key this solved my problem ,
I had the same problem and copying C:\Program Files\Java\jdk1.6.0_26\lib\tools.jar
to C:\Program Files\Java\jre6\lib\ext
worked for me
Question: Check whether a $_POST value is empty.
Translation: Check to see if an array key/index has a value associated with it.
Answer: Depends on your emphasis on security. Depends on what is allowed as valid input.
1. Some people say use empty().
From the PHP Manual:
"[Empty] determines whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE."
The following are thus considered empty.
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
If none of these values are valid for your input control, then empty()
would work. The problem here is that empty()
might be too broad to be used consistently (the same way, for the same reason, on different input control submissions to $_POST
or $_GET
). A good use of empty()
is to check if an entire array is empty (has no elements).
2. Some people say use isset().
isset()
(a language construct) cannot operate on entire arrays, as in isset($myArray)
. It can only operate on variables and array elements (via the index/key): isset($var)
and isset($_POST['username'])
. The isset()
language construct does two things. First it checks to see if a variable or array index/key has a value associated with it. Second, it checks to make sure that value is not equal to the PHP NULL value.
In short, the most accurate check can be accomplished best with isset()
, as some input controls do not even register with $_POST when they are not selected or checked. I have never known a form that submitted the PHP NULL value. None of mine do, so I use isset()
to check if a $_POST
key has no value associated with it (and that is not NULL). isset()
is a much stricter test of emptiness (in the sense of your question) than empty()
.
3. Some people say just do if($var), if($myArray), or if($myArray['userName']) to determine emptiness.
You can test anything that evaluates to true or false in an if statement. Empty arrays evaluate to false and so do variables that are not set. Variables that contain the PHP NULL value also evaluate to false. Unfortunately in this case, like with
empty()
, many more things also evaluate to false: 1. the empty string '', zero (0), zero.zero (0.0), the string zero '0', boolean false, and certain empty XML objects.--Doyle, Beginning PHP 5.3
In conclusion, use isset()
and consider combining it with other tests. Example:
May not work due to superglobal screwiness, but would work for other arrays without question.
if (is_array($_POST) && !empty($_POST)) {
// Now test for your successful controls in $_POST with isset()
}
Hence, why look for a value associated with a key before you even know for sure that $_POST
represents an array and has any values stored in it at all (something many people fail to consider)? Remember, people can send data to your form without using a web browser. You may one day get to the point of testing that $_POST
only has the allowed keys, but that conversation is for another day.
Useful reference:
The answer that worked for me was indeed what OP mentions in his 2015 update: uncheck these two boxes in your Python run config:
I already had the run config set to use the proper venv, so PyCharm doing additional work to add things to the path was not necessary. Instead it was causing errors.
There are two types in this parsing.
From a file, you can use the following
import json
json = json.loads(open('/path/to/file.json').read())
value = json['key']
print json['value']
This arcticle explains the full parsing and getting values using two scenarios.Parsing JSON using Python
It's even easier to do without a library
window.onload = function() {
// code
};
I see this is an old thread, but for what it's worth, here's a free (MIT License) 1-D power-of-2-length-only C# FFT implementation I wrote in 2010.
I haven't compared its performance to other C# FFT implementations. I wrote it mainly to compare the performance of Flash/ActionScript and Silverlight/C#. The latter is much faster, at least for number crunching.
/**
* Performs an in-place complex FFT.
*
* Released under the MIT License
*
* Copyright (c) 2010 Gerald T. Beauregard
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
public class FFT2
{
// Element for linked list in which we store the
// input/output data. We use a linked list because
// for sequential access it's faster than array index.
class FFTElement
{
public double re = 0.0; // Real component
public double im = 0.0; // Imaginary component
public FFTElement next; // Next element in linked list
public uint revTgt; // Target position post bit-reversal
}
private uint m_logN = 0; // log2 of FFT size
private uint m_N = 0; // FFT size
private FFTElement[] m_X; // Vector of linked list elements
/**
*
*/
public FFT2()
{
}
/**
* Initialize class to perform FFT of specified size.
*
* @param logN Log2 of FFT length. e.g. for 512 pt FFT, logN = 9.
*/
public void init(
uint logN )
{
m_logN = logN;
m_N = (uint)(1 << (int)m_logN);
// Allocate elements for linked list of complex numbers.
m_X = new FFTElement[m_N];
for (uint k = 0; k < m_N; k++)
m_X[k] = new FFTElement();
// Set up "next" pointers.
for (uint k = 0; k < m_N-1; k++)
m_X[k].next = m_X[k+1];
// Specify target for bit reversal re-ordering.
for (uint k = 0; k < m_N; k++ )
m_X[k].revTgt = BitReverse(k,logN);
}
/**
* Performs in-place complex FFT.
*
* @param xRe Real part of input/output
* @param xIm Imaginary part of input/output
* @param inverse If true, do an inverse FFT
*/
public void run(
double[] xRe,
double[] xIm,
bool inverse = false )
{
uint numFlies = m_N >> 1; // Number of butterflies per sub-FFT
uint span = m_N >> 1; // Width of the butterfly
uint spacing = m_N; // Distance between start of sub-FFTs
uint wIndexStep = 1; // Increment for twiddle table index
// Copy data into linked complex number objects
// If it's an IFFT, we divide by N while we're at it
FFTElement x = m_X[0];
uint k = 0;
double scale = inverse ? 1.0/m_N : 1.0;
while (x != null)
{
x.re = scale*xRe[k];
x.im = scale*xIm[k];
x = x.next;
k++;
}
// For each stage of the FFT
for (uint stage = 0; stage < m_logN; stage++)
{
// Compute a multiplier factor for the "twiddle factors".
// The twiddle factors are complex unit vectors spaced at
// regular angular intervals. The angle by which the twiddle
// factor advances depends on the FFT stage. In many FFT
// implementations the twiddle factors are cached, but because
// array lookup is relatively slow in C#, it's just
// as fast to compute them on the fly.
double wAngleInc = wIndexStep * 2.0*Math.PI/m_N;
if (inverse == false)
wAngleInc *= -1;
double wMulRe = Math.Cos(wAngleInc);
double wMulIm = Math.Sin(wAngleInc);
for (uint start = 0; start < m_N; start += spacing)
{
FFTElement xTop = m_X[start];
FFTElement xBot = m_X[start+span];
double wRe = 1.0;
double wIm = 0.0;
// For each butterfly in this stage
for (uint flyCount = 0; flyCount < numFlies; ++flyCount)
{
// Get the top & bottom values
double xTopRe = xTop.re;
double xTopIm = xTop.im;
double xBotRe = xBot.re;
double xBotIm = xBot.im;
// Top branch of butterfly has addition
xTop.re = xTopRe + xBotRe;
xTop.im = xTopIm + xBotIm;
// Bottom branch of butterly has subtraction,
// followed by multiplication by twiddle factor
xBotRe = xTopRe - xBotRe;
xBotIm = xTopIm - xBotIm;
xBot.re = xBotRe*wRe - xBotIm*wIm;
xBot.im = xBotRe*wIm + xBotIm*wRe;
// Advance butterfly to next top & bottom positions
xTop = xTop.next;
xBot = xBot.next;
// Update the twiddle factor, via complex multiply
// by unit vector with the appropriate angle
// (wRe + j wIm) = (wRe + j wIm) x (wMulRe + j wMulIm)
double tRe = wRe;
wRe = wRe*wMulRe - wIm*wMulIm;
wIm = tRe*wMulIm + wIm*wMulRe;
}
}
numFlies >>= 1; // Divide by 2 by right shift
span >>= 1;
spacing >>= 1;
wIndexStep <<= 1; // Multiply by 2 by left shift
}
// The algorithm leaves the result in a scrambled order.
// Unscramble while copying values from the complex
// linked list elements back to the input/output vectors.
x = m_X[0];
while (x != null)
{
uint target = x.revTgt;
xRe[target] = x.re;
xIm[target] = x.im;
x = x.next;
}
}
/**
* Do bit reversal of specified number of places of an int
* For example, 1101 bit-reversed is 1011
*
* @param x Number to be bit-reverse.
* @param numBits Number of bits in the number.
*/
private uint BitReverse(
uint x,
uint numBits)
{
uint y = 0;
for (uint i = 0; i < numBits; i++)
{
y <<= 1;
y |= x & 0x0001;
x >>= 1;
}
return y;
}
}
You can use java.util.Arrays.binarySearch to find an element in an array or to check for its existence:
import java.util.Arrays;
...
char[] array = new char[] {'a', 'x', 'm'};
Arrays.sort(array);
if (Arrays.binarySearch(array, 'm') >= 0) {
System.out.println("Yes, m is there");
}
Be aware that for binarySearch to work correctly, the array needs to be sorted. Hence the call to Arrays.sort() in the example. If your data is already sorted, you don't need to do that. Thus, this isn't strictly a one-liner if you need to sort your array first. Unfortunately, Arrays.sort() does not return a reference to the array - thus it is not possible to combine sort and binarySearch (i.e. Arrays.binarySearch(Arrays.sort(myArray), key)) does not work).
If you can afford the extra allocation, using Arrays.asList() seems cleaner.
If you are looking inside dockerfile while creating image, add this line:
RUN apk add --update yourPackageName
I have a library that is doing exactly you need.
Some time ago I had wrote simple and fast enough library for work with CSV files. You can find it by the following link: https://github.com/ukushu/DataExporter
It works with CSV like with 2 dimensions array. Exactly like you need.
As example, in case of you need all of values of 3rd row only you need is to write:
Csv csv = new Csv();
csv.FileOpen("c:\\file1.csv");
var allValuesOf3rdRow = csv.Rows[2];
or to read 2nd cell of
var value = csv.Rows[2][1];
Found here:
/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>
/*
Include directly the different
headers from cppconn/ and mysql_driver.h + mysql_util.h
(and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
using namespace std;
int main(void)
{
cout << endl;
cout << "Running 'SELECT 'Hello World!' »
AS _message'..." << endl;
try {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
/* Create a connection */
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
/* Connect to the MySQL test database */
con->setSchema("test");
stmt = con->createStatement();
res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // replace with your statement
while (res->next()) {
cout << "\t... MySQL replies: ";
/* Access column data by alias or column name */
cout << res->getString("_message") << endl;
cout << "\t... MySQL says it again: ";
/* Access column fata by numeric offset, 1 is the first column */
cout << res->getString(1) << endl;
}
delete res;
delete stmt;
delete con;
} catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line " »
<< __LINE__ << endl;
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}
cout << endl;
return EXIT_SUCCESS;
}
If you use Maven, you can use xvfb-maven-plugin to start xvfb before tests, run them using related DISPLAY
environment variable, and stop xvfb after all.
-p|--parent
will be used if you are trying to create a directory with top-down
approach. That will create the parent directory then child and so on iff none exists.
-p, --parents no error if existing, make parent directories as needed
About rlidwka
it means giving full or administrative access. Found it here https://itservices.stanford.edu/service/afs/intro/permissions/unix.
Here is a simple way (to use before or after pseudo elements / classes):
input[type=checkbox] {
position: relative;
}
input[type=checkbox]:after {
position: absolute;
top: 0;
left: 0;
/* Above three lines allow the checkbox:after position at checkbox's position */
content: '';
width: 32px;
height: 32px;
z-index: 1; /* This allows the after overlap the checkbox */
/* Anything you want */
}
i did it like this android:background="@color/colorAccent" i just go to folder res then click on folder values and then on colors.xml in colors.xml I just change the color of colorAccent and call it in android:background and its done
I found this https://typescriptbcl.codeplex.com/SourceControl/latest
here is the Guid version they have in case the link does not work later.
module System {
export class Guid {
constructor (public guid: string) {
this._guid = guid;
}
private _guid: string;
public ToString(): string {
return this.guid;
}
// Static member
static MakeNew(): Guid {
var result: string;
var i: string;
var j: number;
result = "";
for (j = 0; j < 32; j++) {
if (j == 8 || j == 12 || j == 16 || j == 20)
result = result + '-';
i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
result = result + i;
}
return new Guid(result);
}
}
}
From the first link on google;
function call_func(_0x41dcx2) {
var _0x41dcx3 = eval('(' + _0x41dcx2 + ')');
var _0x41dcx4 = document['createElement']('div');
var _0x41dcx5 = _0x41dcx3['id'];
var _0x41dcx6 = _0x41dcx3['Student_name'];
var _0x41dcx7 = _0x41dcx3['student_dob'];
var _0x41dcx8 = '<b>ID:</b>';
_0x41dcx8 += '<a href="/learningyii/index.php?r=student/view& id=' + _0x41dcx5 + '">' + _0x41dcx5 + '</a>';
_0x41dcx8 += '<br/>';
_0x41dcx8 += '<b>Student Name:</b>';
_0x41dcx8 += _0x41dcx6;
_0x41dcx8 += '<br/>';
_0x41dcx8 += '<b>Student DOB:</b>';
_0x41dcx8 += _0x41dcx7;
_0x41dcx8 += '<br/>';
_0x41dcx4['innerHTML'] = _0x41dcx8;
_0x41dcx4['setAttribute']('class', 'view');
$('#StudentGridViewId')['find']('.items')['prepend'](_0x41dcx4);
};
It won't get you all the way back to source, and that's not really possible, but it'll get you out of a hole.
var getDaysLeft = function (date1, date2) {
var daysDiffInMilliSec = Math.abs(new Date(date1) - new Date(date2));
var daysLeft = daysDiffInMilliSec / (1000 * 60 * 60 * 24);
return daysLeft;
};
var date1='2018-05-18';
var date2='2018-05-25';
var dateDiff = getDaysLeft(date1, date2);
console.log(dateDiff);
There are times that I want to include my web service source codes along with its client-side project. Both of them have a separate git repositories. I am actually used to add all files using the command:
git add -A
But for some reason, it only adds the folder. Later on I found out that the server files also have its .git
folder in it so the command doesn't work.
tl;dr: Make sure there are no .git
folder inside the folder you want to stage.
In the controller action append to the header the following lines
public ActionResult Create(string PositionID)
{
Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
Response.AppendHeader("Expires", "0"); // Proxies.
Use:
git checkout -- <file>
To discard the changes in the working directory.
Swift version - create base64 for image
In my opinion Implicitly Unwrapped Optional in case of UIImagePNGRepresenatation()
is not safe, so I recommend to use extension like below:
extension UIImage {
func toBase64() -> String? {
let imageData = UIImagePNGRepresentation(self)
return imageData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
}
}
You can script it with a tool like expect (there are handy bindings too, like Pexpect for Python).
(a–b)/c*(d + e – f / g)
step 1: (a-b)/c*(d+e- /fg))
step 2: (a-b)/c*(+de - /fg)
step 3: (a-b)/c * -+de/fg
Step 4: -ab/c * -+de/fg
step 5: /-abc * -+de/fg
step 6: */-abc-+de/fg
This is prefix notation.
The solution from Shinebayar G worked, but this other one is a little bit more elegant:
Copied from Python unresolved import issue #3840:
Given the following example project structure:
What I did to resolve this issue:
Can you be a little more specific? If you're trying to get the HTML inside of a tag you can do something like this:
HTML snippet:
<p><b>This is some text</b></p>
jQuery:
var txt = $('p').html(); // Value of text is <b>This is some text</b>
For completely silencing the output, here what works for me
```{r error=FALSE, warning=FALSE, message=FALSE}
invisible({capture.output({
# Your code here
2 * 2
# etc etc
})})
```
The 5 measures used above are
error = FALSE
warning = FALSE
message = FALSE
invisible()
capture.output()
I think what you want might be to run the following from the command line:
ipython notebook --matplotlib=inline
If you don't like typing it at the cmd line every time then you could create an alias to do it for you.
I tried to make a class that would solve your problem using asynchronous stream read, by taking in account Mark Byers, Rob, stevejay answers. Doing so I realised that there is a bug related to asynchronous process output stream read.
I reported that bug at Microsoft: https://connect.microsoft.com/VisualStudio/feedback/details/3119134
Summary:
You can't do that:
process.BeginOutputReadLine(); process.Start();
You will receive System.InvalidOperationException : StandardOut has not been redirected or the process hasn't started yet.
============================================================================================================================
Then you have to start asynchronous output read after the process is started:
process.Start(); process.BeginOutputReadLine();
Doing so, make a race condition because the output stream can receive data before you set it to asynchronous:
process.Start();
// Here the operating system could give the cpu to another thread.
// For example, the newly created thread (Process) and it could start writing to the output
// immediately before next line would execute.
// That create a race condition.
process.BeginOutputReadLine();
============================================================================================================================
Then some people could say that you just have to read the stream before you set it to asynchronous. But the same problem occurs. There will be a race condition between the synchronous read and set the stream into asynchronous mode.
============================================================================================================================
There is no way to acheive safe asynchronous read of an output stream of a process in the actual way "Process" and "ProcessStartInfo" has been designed.
You are probably better using asynchronous read like suggested by other users for your case. But you should be aware that you could miss some information due to race condition.
Select many is like cross join operation in SQL where it takes the cross product.
For example if we have
Set A={a,b,c}
Set B={x,y}
Select many can be used to get the following set
{ (x,a) , (x,b) , (x,c) , (y,a) , (y,b) , (y,c) }
Note that here we take the all the possible combinations that can be made from the elements of set A and set B.
Here is a LINQ example you can try
List<string> animals = new List<string>() { "cat", "dog", "donkey" };
List<int> number = new List<int>() { 10, 20 };
var mix = number.SelectMany(num => animals, (n, a) => new { n, a });
the mix will have following elements in flat structure like
{(10,cat), (10,dog), (10,donkey), (20,cat), (20,dog), (20,donkey)}
_.each(['Hello', 'World!'], function(word){_x000D_
console.log(word);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
Here's simple example that could use _.each
:
function basket() {_x000D_
this.items = [];_x000D_
this.addItem = function(item) {_x000D_
this.items.push(item);_x000D_
};_x000D_
this.show = function() {_x000D_
console.log('items: ', this.items);_x000D_
}_x000D_
}_x000D_
_x000D_
var x = new basket();_x000D_
x.addItem('banana');_x000D_
x.addItem('apple');_x000D_
x.addItem('kiwi');_x000D_
x.show();
_x000D_
Output:
items: [ 'banana', 'apple', 'kiwi' ]
Instead of calling addItem
multiple times you could use underscore this way:
_.each(['banana', 'apple', 'kiwi'], function(item) { x.addItem(item); });
which is identical to calling addItem
three times sequentially with these items. Basically it iterates your array and for each item calls your anonymous callback function that calls x.addItem(item)
. The anonymous callback function is similar to addItem
member function (e.g. it takes an item) and is kind of pointless. So, instead of going through anonymous function it's better that _.each
avoids this indirection and calls addItem
directly:
_.each(['banana', 'apple', 'kiwi'], x.addItem);
but this won't work, as inside basket's addItem
member function this
won't refer to your x
basket that you created. That's why you have an option to pass your basket x
to be used as [context]
:
_.each(['banana', 'apple', 'kiwi'], x.addItem, x);
function basket() {_x000D_
this.items = [];_x000D_
this.addItem = function(item) {_x000D_
this.items.push(item);_x000D_
};_x000D_
this.show = function() {_x000D_
console.log('items: ', this.items);_x000D_
}_x000D_
}_x000D_
var x = new basket();_x000D_
_.each(['banana', 'apple', 'kiwi'], x.addItem, x);_x000D_
x.show();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
In short, if callback function that you pass to _.each
in any way uses this
then you need to specify what this
should be referring to inside your callback function. It may seem like x
is redundant in my example, but x.addItem
is just a function and could be totally unrelated to x
or basket
or any other object, for example:
function basket() {_x000D_
this.items = [];_x000D_
this.show = function() {_x000D_
console.log('items: ', this.items);_x000D_
}_x000D_
}_x000D_
function addItem(item) {_x000D_
this.items.push(item);_x000D_
};_x000D_
_x000D_
var x = new basket();_x000D_
_.each(['banana', 'apple', 'kiwi'], addItem, x);_x000D_
x.show();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
In other words, you bind some value to this
inside your callback, or you may as well use bind directly like this:
_.each(['banana', 'apple', 'kiwi'], addItem.bind(x));
how this feature can be useful with some different underscore methods?
In general, if some underscorejs
method takes a callback function and if you want that callback be called on some member function of some object (e.g. a function that uses this
) then you may bind that function to some object or pass that object as the [context]
parameter and that's the primary intention. And at the top of underscorejs documentation, that's exactly what they state: The iteratee is bound to the context object, if one is passed
int
converts by truncation, as has been mentioned by others. This can result in the answer being one different than expected. One way around this is to check if the result is 'close enough' to an integer and adjust accordingly, otherwise the usual conversion. This is assuming you don't get too much roundoff and calculation error, which is a separate issue. For example:
def toint(f):
trunc = int(f)
diff = f - trunc
# trunc is one too low
if abs(f - trunc - 1) < 0.00001:
return trunc + 1
# trunc is one too high
if abs(f - trunc + 1) < 0.00001:
return trunc - 1
# trunc is the right value
return trunc
This function will adjust for off-by-one errors for near integers. The mpmath
library does something similar for floating point numbers that are close to integers.
I wanna clear something that no one mention before I think.
svg
image or icon<svg width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M4 10.127L12 18.127L20 10.127H4Z" fill="#8E8E93"/> </svg>
try to find it.data:image/svg+xml;utf8,
fill="#8E8E93"
to this fill="%238E8E93"
If you want to add hexadecmal color you should change #
to %23
Here is the html code:
<fieldset>
<label for="editName">Country</label>
<select class="ra-select">
<option value="bangladesh" selected>Bangladesh</option>
<option value="saudi arabia">Saudi Arabia</option>
<option value="us">Uinited State Of America</option>
<option value="india">India</option>
</select>
</fieldset>
Here is the css code:
.ra-select {
width: 30%;
padding: 10px;
/* Replace Default styling (arrow) */
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
background-image: url('data:image/svg+xml;utf8,<svg width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 10.127L12 18.127L20 10.127H4Z" fill="%238E8E93"/></svg>');
background-repeat: no-repeat;
background-position-y: 50%;
background-position-x: 98%;
}
.ra-select:focus,
.ra-select:hover {
outline: none;
border: 1px solid #bbb;
}
.ra-select option {
background-color: #fff;
}
This solution doesn't need web.config file changes or catch-all routes.
First, create a controller like this;
public class ErrorController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Regular Error";
return View();
}
public ActionResult NotFound404()
{
ViewBag.Title = "Error 404 - File not Found";
return View("Index");
}
}
Then create the view under "Views/Error/Index.cshtml" as;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<p>We're sorry, page you're looking for is, sadly, not here.</p>
Then add the following in the Global asax file as below:
protected void Application_Error(object sender, EventArgs e)
{
// Do whatever you want to do with the error
//Show the custom error page...
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "Error";
if ((Context.Server.GetLastError() is HttpException) && ((Context.Server.GetLastError() as HttpException).GetHttpCode() != 404))
{
routeData.Values["action"] = "Index";
}
else
{
// Handle 404 error and response code
Response.StatusCode = 404;
routeData.Values["action"] = "NotFound404";
}
Response.TrySkipIisCustomErrors = true; // If you are using IIS7, have this line
IController errorsController = new ErrorController();
HttpContextWrapper wrapper = new HttpContextWrapper(Context);
var rc = new System.Web.Routing.RequestContext(wrapper, routeData);
errorsController.Execute(rc);
Response.End();
}
If you still get the custom IIS error page after doing this, make sure the following sections are commented out(or empty) in the web config file:
<system.web>
<customErrors mode="Off" />
</system.web>
<system.webServer>
<httpErrors>
</httpErrors>
</system.webServer>
Codo was exactly right on Oct. 5 that ¤t[i] is the intended text (with the currency symbol inadvertently introduced when the source was put into HTML (see original): http://downloads.securityfocus.com/vulnerabilities/exploits/59846-1.c
Codo's change makes this exploit code compile without error. I did that and was able to use the exploit on Ubuntu 12.04 to escalate to root privilege.
This is not an answer to your original question: "Appending output of a Batch file To log file?"
For reference, it's an answer to your followup question: "What lines should i add to my batch file which will make it execute after every 30mins?"
(But I would take Jon Skeet's advice: "You probably shouldn't do that in your batch file - instead, use Task Scheduler.")
Timeout:
Example (1 second):
TIMEOUT /T 1000 /NOBREAK
Sleep:
Example (1 second):
sleep -m 1000
Alternative methods:
Here's an answer to your 2nd followup question: "Along with the Timestamp?"
Create a date and time stamp in your batch files
Example:
echo *** Date: %DATE:/=-% and Time:%TIME::=-% *** >> output.log
I had this issue and it looked like a bug in xcode's 10.x New build system.
Go to File > Project Settings
Change the Build system to use Legacy build system
.
Deep clean the project by holding Option(?)+Shift(?)+Command(?)+K or holding Option(?) and selecting Product > Clean Build Folder
Run on a device
All POSIX operating systems have 3 streams: stdin, stdout, and stderr. stdin is the input, which can accept the stdout or stderr. stdout is the primary output, which is redirected with >
, >>
, or |
. stderr is the error output, which is handled separately so that any exceptions do not get passed to a command or written to a file that it might break; normally, this is sent to a log of some kind, or dumped directly, even when the stdout is redirected. To redirect both to the same place, use:
command &> /some/file
EDIT: thanks to Zack for pointing out that the above solution is not portable--use instead:
*command* > file 2>&1
If you want to silence the error, do:
*command* 2> /dev/null
Here's a three-step, somewhat minimalist version of ThorSummoner's answer for the sake of clarity. It doesn't quite do what I want (I'll explain at the bottom), but it works okay.
setup.py
filepath_to/project_name/
setup.py
In setup.py
, write:
import setuptools
setuptools.setup(name='project_name')
Run this code in console:
python -m pip install --editable filepath_to/project_name
Instead of python
, you may need to use python3
or something, depending on how your python is installed. Also, you can use -e
instead of --editable
.
Now, your directory will look more or less like this. I don't know what the egg stuff is.
filepath_to/project_name/
setup.py
test_3.egg-info/
dependency_links.txt
PKG-INFO
SOURCES.txt
top_level.txt
This folder is considered a python package and you can import from files in this parent directory even if you're writing a script anywhere else on your computer.
Let's say you make two files, one in your project's main directory and another in a sub directory. It'll look like this:
filepath_to/project_name/
top_level_file.py
subdirectory/
subfile.py
setup.py |
test_3.egg-info/ |----- Ignore these guys
... |
Now, if top_level_file.py
looks like this:
x = 1
Then I can import it from subfile.py
, or really any other file anywhere else on your computer.
# subfile.py OR some_other_python_file_somewhere_else.py
import random # This is a standard package that can be imported anywhere.
import top_level_file # Now, top_level_file.py works similarly.
print(top_level_file.x)
This is different than what I was looking for: I hoped python had a one-line way to import from a file above. Instead, I have to treat the script like a module, do a bunch of boilerplate, and install it globally for the entire python installation to have access to it. It's overkill. If anyone has a simpler method than doesn't involve the above process or importlib
shenanigans, please let me know.
I know this is a pretty old question but this was my solution that helped with visualizing the table so you can create a class structure. This is also using the HTML Agility Pack
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(@"<html><body><p><table id=""foo""><tr><th>hello</th></tr><tr><td>world</td></tr></table></body></html>");
var table = doc.DocumentNode.SelectSingleNode("//table");
var tableRows = table.SelectNodes("tr");
var columns = tableRows[0].SelectNodes("th/text()");
for (int i = 1; i < tableRows.Count; i++)
{
for (int e = 0; e < columns.Count; e++)
{
var value = tableRows[i].SelectSingleNode($"td[{e + 1}]");
Console.Write(columns[e].InnerText + ":" + value.InnerText);
}
Console.WriteLine();
}
How about
<a href="url"><input type="button" value="Cancel"></a>
Android supports string formatting using HTML tags in the strings xml. So the following would work:
<string name="label_testinghtmltags"><u>This text has an underscore</u></string>
Then you just use it as you normally would. You can see more in the documentation here
Update:
To further expand on the answer, the documentation says:
... the
format(String, Object...)
andgetString(int, Object...)
methods strip all the style information from the string. . The work-around to this is to write the HTML tags with escaped entities, which are then recovered with fromHtml(String), after the formatting takes place
For example, the resulting string from the following code snippet will not show up as containing underscored elements:
<string name="html_bold_test">This <u>%1$s</u> has an underscore</string>
String result = getString(R.string.html_bold_test, "text")
However the result from the following snippet would contain underscores:
<string name="html_bold_test">This <u> %1$s </u> has an underscore</string>
String result = Html.fromHtml(getString(R.string.html_bold_test, "text"))
string.Join
is better, but if you really want a LINQ ForEach
:
var strgroupids = string.Empty;
groupIds.ForEach(g =>
{
if(strgroupids != string.Empty){
strgroupids += ",";
}
strgroupids += g;
});
Some notes:
string.Join
and foreach
are both better than this, vastly slower, approach,
since it's never appended+=
) is handy for appending to strings.ToString()
is unnecessary as it is called automatically when concatenating non-stringsStringBuilder
should be considered instead of concatenating stringsFor devices with API 26 and higher, you can get it like this:
ZonedDateTime.now().getZone().toString();
SELECT RIGHT('0' + CAST(sortexport_csv AS VARCHAR), 2)
FROM your_table
I implemented this extension method to get the description from enum values. It works for all kind of enums.
public static class EnumExtension
{
public static string ToDescription(this System.Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : value.ToString();
}
}
For a bandpass filter, ws is a tuple containing the lower and upper corner frequencies. These represent the digital frequency where the filter response is 3 dB less than the passband.
wp is a tuple containing the stop band digital frequencies. They represent the location where the maximum attenuation begins.
gpass is the maximum attenutation in the passband in dB while gstop is the attentuation in the stopbands.
Say, for example, you wanted to design a filter for a sampling rate of 8000 samples/sec having corner frequencies of 300 and 3100 Hz. The Nyquist frequency is the sample rate divided by two, or in this example, 4000 Hz. The equivalent digital frequency is 1.0. The two corner frequencies are then 300/4000 and 3100/4000.
Now lets say you wanted the stopbands to be down 30 dB +/- 100 Hz from the corner frequencies. Thus, your stopbands would start at 200 and 3200 Hz resulting in the digital frequencies of 200/4000 and 3200/4000.
To create your filter, you'd call buttord as
fs = 8000.0
fso2 = fs/2
N,wn = scipy.signal.buttord(ws=[300/fso2,3100/fso2], wp=[200/fs02,3200/fs02],
gpass=0.0, gstop=30.0)
The length of the resulting filter will be dependent upon the depth of the stop bands and the steepness of the response curve which is determined by the difference between the corner frequency and stopband frequency.
To force LF line endings for all text files, you can create .gitattributes
file in top-level of your repository with the following lines (change as desired):
# Ensure all C and PHP files use LF.
*.c eol=lf
*.php eol=lf
which ensures that all files that Git considers to be text files have normalized (LF
) line endings in the repository (normally core.eol
configuration controls which one do you have by default).
Based on the new attribute settings, any text files containing CRLFs should be normalized by Git. If this won't happen automatically, you can refresh a repository manually after changing line endings, so you can re-scan and commit the working directory by the following steps (given clean working directory):
$ echo "* text=auto" >> .gitattributes
$ rm .git/index # Remove the index to force Git to
$ git reset # re-scan the working directory
$ git status # Show files that will be normalized
$ git add -u
$ git add .gitattributes
$ git commit -m "Introduce end-of-line normalization"
or as per GitHub docs:
git add . -u
git commit -m "Saving files before refreshing line endings"
git rm --cached -r . # Remove every file from Git's index.
git reset --hard # Rewrite the Git index to pick up all the new line endings.
git add . # Add all your changed files back, and prepare them for a commit.
git commit -m "Normalize all the line endings" # Commit the changes to your repository.
See also: @Charles Bailey post.
In addition, if you would like to exclude any files to not being treated as a text, unset their text attribute, e.g.
manual.pdf -text
Or mark it explicitly as binary:
# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary
To see some more advanced git normalization file, check .gitattributes
at Drupal core:
# Drupal git normalization
# @see https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html
# @see https://www.drupal.org/node/1542048
# Normally these settings would be done with macro attributes for improved
# readability and easier maintenance. However macros can only be defined at the
# repository root directory. Drupal avoids making any assumptions about where it
# is installed.
# Define text file attributes.
# - Treat them as text.
# - Ensure no CRLF line-endings, neither on checkout nor on checkin.
# - Detect whitespace errors.
# - Exposed by default in `git diff --color` on the CLI.
# - Validate with `git diff --check`.
# - Deny applying with `git apply --whitespace=error-all`.
# - Fix automatically with `git apply --whitespace=fix`.
*.config text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.css text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.dist text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.engine text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.html text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=html
*.inc text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.install text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.js text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.json text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.lock text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.map text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.md text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.module text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.php text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.po text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.profile text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.script text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.sh text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.sql text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.svg text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.theme text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.twig text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.txt text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.xml text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.yml text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
# Define binary file attributes.
# - Do not treat them as text.
# - Include binary diff in patches instead of "binary files differ."
*.eot -text diff
*.exe -text diff
*.gif -text diff
*.gz -text diff
*.ico -text diff
*.jpeg -text diff
*.jpg -text diff
*.otf -text diff
*.phar -text diff
*.png -text diff
*.svgz -text diff
*.ttf -text diff
*.woff -text diff
*.woff2 -text diff
See also:
Void is the equivalent of Visual Basic's Sub.
According to cURL docs you can also pass the certificate to the curl
command:
Get a CA certificate that can verify the remote server and use the proper option to point out this CA cert for verification when connecting. For
libcurl
hackers:curl_easy_setopt(curl, CURLOPT_CAPATH, capath);
With the curl command line tool:
--cacert [file]
For example:
curl --cacert mycertificate.cer -v https://www.stackoverflow.com
With Swift 3 and Swift 4, String
has a method called data(using:allowLossyConversion:)
. data(using:allowLossyConversion:)
has the following declaration:
func data(using encoding: String.Encoding, allowLossyConversion: Bool = default) -> Data?
Returns a Data containing a representation of the String encoded using a given encoding.
With Swift 4, String
's data(using:allowLossyConversion:)
can be used in conjunction with JSONDecoder
's decode(_:from:)
in order to deserialize a JSON string into a dictionary.
Furthermore, with Swift 3 and Swift 4, String
's data(using:allowLossyConversion:)
can also be used in conjunction with JSONSerialization
's json?Object(with:?options:?)
in order to deserialize a JSON string into a dictionary.
With Swift 4, JSONDecoder
has a method called decode(_:from:)
. decode(_:from:)
has the following declaration:
func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable
Decodes a top-level value of the given type from the given JSON representation.
The Playground code below shows how to use data(using:allowLossyConversion:)
and decode(_:from:)
in order to get a Dictionary
from a JSON formatted String
:
let jsonString = """
{"password" : "1234", "user" : "andreas"}
"""
if let data = jsonString.data(using: String.Encoding.utf8) {
do {
let decoder = JSONDecoder()
let jsonDictionary = try decoder.decode(Dictionary<String, String>.self, from: data)
print(jsonDictionary) // prints: ["user": "andreas", "password": "1234"]
} catch {
// Handle error
print(error)
}
}
With Swift 3 and Swift 4, JSONSerialization
has a method called json?Object(with:?options:?)
. json?Object(with:?options:?)
has the following declaration:
class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
Returns a Foundation object from given JSON data.
The Playground code below shows how to use data(using:allowLossyConversion:)
and json?Object(with:?options:?)
in order to get a Dictionary
from a JSON formatted String
:
import Foundation
let jsonString = "{\"password\" : \"1234\", \"user\" : \"andreas\"}"
if let data = jsonString.data(using: String.Encoding.utf8) {
do {
let jsonDictionary = try JSONSerialization.jsonObject(with: data, options: []) as? [String : String]
print(String(describing: jsonDictionary)) // prints: Optional(["user": "andreas", "password": "1234"])
} catch {
// Handle error
print(error)
}
}
uint16_t
is guaranteed to be a unsigned integer that is 16 bits large
unsigned short int
is guaranteed to be a unsigned short integer
, where short integer
is defined by the compiler (and potentially compiler flags) you are currently using. For most compilers for x86 hardware a short integer
is 16 bits large.
Also note that per the ANSI C standard only the minimum size of 16 bits is defined, the maximum size is up to the developer of the compiler
Minimum Type Limits
Any compiler conforming to the Standard must also respect the following limits with respect to the range of values any particular type may accept. Note that these are lower limits: an implementation is free to exceed any or all of these. Note also that the minimum range for a char is dependent on whether or not a char is considered to be signed or unsigned.
Type Minimum Range
signed char -127 to +127 unsigned char 0 to 255 short int -32767 to +32767 unsigned short int 0 to 65535
There is also a function in pandas
called factorize
which you can use to automatically do this type of work. It converts labels to numbers: ['male', 'female', 'male'] -> [0, 1, 0]
. See this answer for more information.
By default, IE displays webpages in the Intranet zone in compatibility view. To change this:
At this point, IE should rely on the webpage itself (or any relevant group policies) to determine the compatibility settings for your Intranet webpages.
Note that certain sites may no longer function correctly after making this change. You can use the same dialog box to add specific sites to enable compatibility view when needed.
The table names are case-sensitive so you should use lower-case nat instead of upper-case NAT. For example;
iptables -t nat -A POSTROUTING -s 192.168.1.1/24 -o eth0 -j MASQUERADE
Uses reqclient, it's a small client module on top of request
that allows you to log all the activity with cURL style (optional, for development environments). Also has nice features like URL and parameters parsing, authentication integrations, cache support, etc.
For example, if you create a client object an do a request:
var RequestClient = require("reqclient").RequestClient;
var client = new RequestClient({
baseUrl:"http://baseurl.com/api/v1.1",
debugRequest:true, debugResponse:true
});
var resp = client.post("client/orders", {"client":1234,"ref_id":"A987"}, {headers: {"x-token":"AFF01XX"}})
It will log within the console something like this:
[Requesting client/orders]-> -X POST http://baseurl.com/api/v1.1/client/orders -d '{"client": 1234, "ref_id": "A987"}' -H '{"x-token": "AFF01XX"}' -H Content-Type:application/json
[Response client/orders]<- Status 200 - {"orderId": 1320934}
The request will return a Promise object, so you have to handle with then
and catch
what to do with the result.
reqclient
is available with npm, you can install the module with: npm install reqclient
.
You can create a function:
function changeInputType(oldObj, oTyp, nValue) {
var newObject = document.createElement('input');
newObject.type = oTyp;
if(oldObj.size) newObject.size = oldObj.size;
if(oldObj.value) newObject.value = nValue;
if(oldObj.name) newObject.name = oldObj.name;
if(oldObj.id) newObject.id = oldObj.id;
if(oldObj.className) newObject.className = oldObj.className;
oldObj.parentNode.replaceChild(newObject,oldObj);
return newObject;
}
And you do a call like:
changeInputType(document.getElementById('DATE_RANGE_VALUE'), 'checkbox', 7);
Why not Try EFS PhP-ZiP MultiVolume Script ... I zipped and transferred hundreds of gigs and millions of files ... ssh is needed to effectively create archives.
But i belive that resulting files can be used with exec directly from php:
exec('zip -r backup-2013-03-30_0 . -i@backup-2013-03-30_0.txt');
I do not know if it works. I have not tried ...
"the secret" is that the execution time for archiving should not exceed the time allowed for execution of PHP code.
On StackOverflow, pressing the up-vote button is AJAX whereas typing in your question or answer and seeing it appear in the real-time preview window below it is JavaScript (JQuery).
This means that the difference between AJAX and Javascript is that AJAX allows you to communicate with the server without doing a page refresh (i.e. going to a new page) whereas JavaScript (JQuery) allows you to embed logic and behaviour on your page. Of course, with this logic you create AJAX as well.
Something like:
class TestClass {
private $var1;
private $var2;
private function TestClass($var1, $var2){
$this->var1 = $var1;
$this->var2 = $var2;
}
public static function create($var1, $var2){
if (is_numeric($var1)){
return new TestClass($var1, $var2);
}
else return NULL;
}
}
$myArray = array();
$myArray[] = TestClass::create(15, "asdf");
$myArray[] = TestClass::create(20, "asdfa");
$myArray[] = TestClass::create("a", "abcd");
print_r($myArray);
$myArray = array_filter($myArray, function($e){ return !is_null($e);});
print_r($myArray);
I think that there are situations where this constructions are preferable to arrays. You can move all the checking logic to the class.
Here, before the call to array_filter $myArray has 3 elements. Two correct objects and a NULL. After the call, only the 2 correct elements persist.
import org.apache.commons.lang3.StringUtils;
// path = "http://cdn.gs.com/new/downloads/Q22010MVR_PressRelease.pdf.null"
StringUtils.removeEnd(path, ".null");
// path = "http://cdn.gs.com/new/downloads/Q22010MVR_PressRelease.pdf"
Try using itertools.count([n])
Or, if you are looking for simple collection of errors for your apps.. here is my implementation of this:
public override void OnActionExecuting(HttpActionContext actionContext)
{
var modelState = actionContext.ModelState;
if (!modelState.IsValid)
{
var errors = new List<string>();
foreach (var state in modelState)
{
foreach (var error in state.Value.Errors)
{
errors.Add(error.ErrorMessage);
}
}
var response = new { errors = errors };
actionContext.Response = actionContext.Request
.CreateResponse(HttpStatusCode.BadRequest, response, JsonMediaTypeFormatter.DefaultMediaType);
}
}
Error Message Response will look like:
{ "errors": [ "Please enter a valid phone number (7+ more digits)", "Please enter a valid e-mail address" ] }
** Update ** A scalars converter has been added to retrofit that allows for a String
response with less ceremony than my original answer below.
Example interface --
public interface GitHubService {
@GET("/users/{user}")
Call<String> listRepos(@Path("user") String user);
}
Add the ScalarsConverterFactory
to your retrofit builder. Note: If using ScalarsConverterFactory
and another factory, add the scalars factory first.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
// add other factories here, if needed.
.build();
You will also need to include the scalars converter in your gradle file --
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
--- Original Answer (still works, just more code) ---
I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject
land. I suspect your specific problem might be better solved using a custom gson TypeAdapter
or a retrofit Converter
if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -
First, if you are using Retrofit 2, you should start using the Call
API. Instead of sending an object to convert as the type parameter, use ResponseBody
from okhttp --
public interface GitHubService {
@GET("/users/{user}")
Call<ResponseBody> listRepos(@Path("user") String user);
}
then you can create and execute your call --
GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});
Note The code above calls string()
on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream()
instead. See the ResponseBody
docs.
You will have to read in all the data from the Stream object into a byte[]
buffer and then pass that into the MemoryStream
via its constructor. It may be better to be more specific about the type of stream object you are using. Stream
is very generic and may not implement the Length
attribute, which is rather useful when reading in data.
Here's some code for you:
public MyClass(Stream inputStream) {
byte[] inputBuffer = new byte[inputStream.Length];
inputStream.Read(inputBuffer, 0, inputBuffer.Length);
_ms = new MemoryStream(inputBuffer);
}
If the Stream
object doesn't implement the Length
attribute, you will have to implement something like this:
public MyClass(Stream inputStream) {
MemoryStream outputStream = new MemoryStream();
byte[] inputBuffer = new byte[65535];
int readAmount;
while((readAmount = inputStream.Read(inputBuffer, 0, inputBuffer.Length)) > 0)
outputStream.Write(inputBuffer, 0, readAmount);
_ms = outputStream;
}
Try this tag. This will refresh the index.html
page every 30 seconds.
<meta http-equiv="refresh" content="30;url=index.html">
Improved version of what Ustaman Sangat did
static inline uint64_t
log2(uint64_t n)
{
uint64_t val;
for (val = 0; n > 1; val++, n >>= 1);
return val;
}
Forcing the TCP/IP connection (by providing 127.0.0.1
instead of localhost
or .
) can reveal the real reason for the error. In my case, the database name specified in connection string was incorrect.
So, here is the checklist so far:
As mentioned in .NET Framework documentation
We don't recommend that you use the
ArrayList
class for new development. Instead, we recommend that you use the genericList<T>
class. TheArrayList
class is designed to hold heterogeneous collections of objects. However, it does not always offer the best performance. Instead, we recommend the following:
- For a heterogeneous collection of objects, use the
List<Object>
(in C#) orList(Of Object)
(in Visual Basic) type.- For a homogeneous collection of objects, use the
List<T>
class.
Convert Date To String
Use name Space
using System.Globalization;
Code
string date = DateTime.ParseExact(datetext.Text, "dd-MM-yyyy", CultureInfo.InstalledUICulture).ToString("yyyy-MM-dd");
For pandas people :
ax = s.plot(kind='barh') # s is a Series (float) in [0,1]
[ax.text(v, i, '{:.2f}%'.format(100*v)) for i, v in enumerate(s)];
That's it.
Alternatively, for those who prefer apply
over looping with enumerate:
it = iter(range(len(s)))
s.apply(lambda x: ax.text(x, next(it),'{:.2f}%'.format(100*x)));
Also, ax.patches
will give you the bars that you would get with ax.bar(...)
. In case you want to apply the functions of @SaturnFromTitan or techniques of others.
Example: Read json from file
/* test.json */
{
"appDesc": {
"description": "SomeDescription",
"message": "SomeMessage"
},
"appName": {
"description": "Home",
"message": "Welcome",
"imp":["awesome","best","good"]
}
}
void readJson()
{
QString val;
QFile file;
file.setFileName("test.json");
file.open(QIODevice::ReadOnly | QIODevice::Text);
val = file.readAll();
file.close();
qWarning() << val;
QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
QJsonObject sett2 = d.object();
QJsonValue value = sett2.value(QString("appName"));
qWarning() << value;
QJsonObject item = value.toObject();
qWarning() << tr("QJsonObject of description: ") << item;
/* in case of string value get value and convert into string*/
qWarning() << tr("QJsonObject[appName] of description: ") << item["description"];
QJsonValue subobj = item["description"];
qWarning() << subobj.toString();
/* in case of array get array and convert into string*/
qWarning() << tr("QJsonObject[appName] of value: ") << item["imp"];
QJsonArray test = item["imp"].toArray();
qWarning() << test[1].toString();
}
OUTPUT
QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) )
"QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"})
"QJsonObject[appName] of description: " QJsonValue(string, "Home")
"Home"
"QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) )
"best"
Example: Read json from string
Assign json to string as below and use the readJson()
function shown before:
val =
' {
"appDesc": {
"description": "SomeDescription",
"message": "SomeMessage"
},
"appName": {
"description": "Home",
"message": "Welcome",
"imp":["awesome","best","good"]
}
}';
OUTPUT
QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) )
"QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"})
"QJsonObject[appName] of description: " QJsonValue(string, "Home")
"Home"
"QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) )
"best"
i tend to use this calculation a lot in things i make, so i like to add it to the Math object:
Math.dist=function(x1,y1,x2,y2){
if(!x2) x2=0;
if(!y2) y2=0;
return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}
Math.dist(0,0, 3,4); //the output will be 5
Math.dist(1,1, 4,5); //the output will be 5
Math.dist(3,4); //the output will be 5
Update:
this approach is especially happy making when you end up in situations something akin to this (i often do):
varName.dist=Math.sqrt( ( (varName.paramX-varX)/2-cx )*( (varName.paramX-varX)/2-cx ) + ( (varName.paramY-varY)/2-cy )*( (varName.paramY-varY)/2-cy ) );
that horrid thing becomes the much more manageable:
varName.dist=Math.dist((varName.paramX-varX)/2, (varName.paramY-varY)/2, cx, cy);
Wait and notify method always called on object so whether it may be Thread object or simple object (which does not extends Thread class) Given Example will clear your all the doubts.
I have called wait and notify on class ObjB and that is the Thread class so we can say that wait and notify are called on any object.
public class ThreadA {
public static void main(String[] args){
ObjB b = new ObjB();
Threadc c = new Threadc(b);
ThreadD d = new ThreadD(b);
d.setPriority(5);
c.setPriority(1);
d.start();
c.start();
}
}
class ObjB {
int total;
int count(){
for(int i=0; i<100 ; i++){
total += i;
}
return total;
}}
class Threadc extends Thread{
ObjB b;
Threadc(ObjB objB){
b= objB;
}
int total;
@Override
public void run(){
System.out.print("Thread C run method");
synchronized(b){
total = b.count();
System.out.print("Thread C notified called ");
b.notify();
}
}
}
class ThreadD extends Thread{
ObjB b;
ThreadD(ObjB objB){
b= objB;
}
int total;
@Override
public void run(){
System.out.print("Thread D run method");
synchronized(b){
System.out.println("Waiting for b to complete...");
try {
b.wait();
System.out.print("Thread C B value is" + b.total);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
I have a similar issue running Linux systems. After the system was booted, a container with a restart policy of "unless-stopped" would not restart automatically unless I typed a command that used docker in some way such as "docker ps". I was surprised as I expected that command to just report some status information. Next I tried the command "systemctl status docker". On a system where no docker commands had been run, this command reported the following:
? docker.service - Docker Application Container Engine
Loaded: loaded (/lib/systemd/system/docker.service; disabled; vendor preset: enabled)
Active: inactive (dead) TriggeredBy: ? docker.socket
Docs: https://docs.docker.com
On a system where "docker ps" had been run with no other Docker commands, I got the following:
? docker.service - Docker Application Container Engine
Loaded: loaded (/lib/systemd/system/docker.service; disabled; vendor preset: enabled)
Active: active (running) since Sun 2020-11-22 08:33:23 PST; 1h 25min ago
TriggeredBy: ? docker.socket
Docs: https://docs.docker.com
Main PID: 3135 (dockerd)
Tasks: 13
Memory: 116.9M
CGroup: /system.slice/docker.service
+-3135 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
... [various messages not shown ]
The most likely explanation is that Docker waits for some docker command before fully initializing and starting containers. You could presumably run "docker ps" in a systemd unit file at a point after all the services your containers need have been initialized. I've tested this by putting a file named docker-onboot.service in the directory /lib/systemd/system with the following contents:
[Unit]
# This service is provided to force Docker containers
# that should automatically restart to restart when the system
# is booted. While the Docker daemon will start automatically,
# it will not be fully initialized until some Docker command
# is actually run. This unit merely runs "docker ps": any
# Docker command will result in the Docker daemon completing
# its initialization, at which point all containers that can be
# automatically restarted after booting will be restarted.
#
Description=Docker-Container Startup on Boot
Requires=docker.socket
After=docker.socket network-online.target containerd.service
[Service]
Type=oneshot
ExecStart=/usr/bin/docker ps
[Install]
WantedBy=multi-user.target
So far (one test, with this service enabled), the container started when the computer was booted. I did not try a dependency on docker.service because docker.service won't start until a docker command is run. The next test will be with the docker-onboot disabled (to see if the WantedBy dependency will automatically start it).
You can use this attributes:
background-size: contain;
background-repeat: no-repeat;
and you code is then like this:
<div style="text-align:center;background-image: url(/media/img_1_bg.jpg); background-size: contain;
background-repeat: no-repeat;" id="mainpage">
Here is another way with leading '0' for all of them.
$secCount = 10000;
$hours = str_pad(floor($secCount / (60*60)), 2, '0', STR_PAD_LEFT);
$minutes = str_pad(floor(($secCount - $hours*60*60)/60), 2, '0', STR_PAD_LEFT);
$seconds = str_pad(floor($secCount - ($hours*60*60 + $minutes*60)), 2, '0', STR_PAD_LEFT);
It is an adaptation from the answer of Flaxious.
I used the RowHeight
property of a range (which means cells as well). If it's zero then it's hidden.
So just loop through all rows as you would normally but in the if
condition check for that property as in If myRange.RowHeight > 0 then DoStuff
where DoStuff
is something you want to do with the visible cells.
You can try searching for local .m2 repository by using the command in the project directory.
mvn help:evaluate -Dexpression=settings.localRepository
your output will be similar to below and you can see local .m2 directory path as shown below: /Users/arai/.m2/repository
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/commons/commons-lang3/3.7/commons-lang3-3.7.jar
Downloaded from central: https://repo.maven.apache.org/maven2/net/sf/jtidy/jtidy/r938/jtidy-r938.jar (250 kB at 438 kB/s)
Downloaded from central: https://repo.maven.apache.org/maven2/commons-codec/commons-codec/1.11/commons-codec-1.11.jar (335 kB at 530 kB/s)
Downloaded from central: https://repo.maven.apache.org/maven2/org/jdom/jdom2/2.0.6/jdom2-2.0.6.jar (305 kB at 430 kB/s)
Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/commons/commons-lang3/3.7/commons-lang3-3.7.jar (500 kB at 595 kB/s)
Downloaded from central: https://repo.maven.apache.org/maven2/com/thoughtworks/xstream/xstream/1.4.11.1/xstream-1.4.11.1.jar (621 kB at 671 kB/s)
[INFO] No artifact parameter specified, using 'org.apache.maven:standalone-pom:pom:1' as project.
[INFO]
/Users/arai/.m2/repository
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.540 s
[INFO] Finished at: 2019-01-23T13:57:54-05:00
[INFO] ------------------------------------------------------------------------
It is a little difficult to answer your specific question without a full, reproducible example. However something like this should work:
#Turn your 'treatment' column into a character vector
data$Treatment <- as.character(data$Treatment)
#Then turn it back into a factor with the levels in the correct order
data$Treatment <- factor(data$Treatment, levels=unique(data$Treatment))
In this example, the order of the factor will be the same as in the data.csv
file.
If you prefer a different order, you can order them by hand:
data$Treatment <- factor(data$Treatment, levels=c("Y", "X", "Z"))
However this is dangerous if you have a lot of levels: if you get any of them wrong, that will cause problems.
I think people saying stderr
should be used only for error messages is misleading.
It should also be used for informative messages that are meant for the user running the command and not for any potential downstream consumers of the data (i.e. if you run a shell pipe chaining several commands you do not want informative messages like "getting item 30 of 42424" to appear on stdout
as they will confuse the consumer, but you might still want the user to see them.
See this for historical rationale:
"All programs placed diagnostics on the standard output. This had always caused trouble when the output was redirected into a ?le, but became intolerable when the output was sent to an unsuspecting process. Nevertheless, unwilling to violate the simplicity of the standard-input-standard-output model, people tolerated this state of affairs through v6. Shortly thereafter Dennis Ritchie cut the Gordian knot by introducing the standard error ?le. That was not quite enough. With pipelines diagnostics could come from any of several programs running simultaneously. Diagnostics needed to identify themselves."
(I was going to leave this as a comment on @jldupont's answer, but I don't have enough reputation.)
I've seen answers like @jldupont's answer in other places as well. FWIW, I think it's important to note that this:
except Exception as e:
print(e)
will print the error output to sys.stdout
by default. A more appropriate approach to error handling in general would be:
except Exception as e:
print(e, file=sys.stderr)
(Note that you have to import sys
for this to work.) This way, the error is printed to STDERR
instead of STDOUT
, which allows for the proper output parsing/redirection/etc. I understand that the question was strictly about 'printing an error', but it seems important to point out the best practice here rather than leave out this detail that could lead to non-standard code for anyone who doesn't eventually learn better.
I haven't used the traceback
module as in Cat Plus Plus's answer, and maybe that's the best way, but I thought I'd throw this out there.
ObservableCollection is a collection that allows code outside the collection be aware of when changes to the collection (add, move, remove) occur. It is used heavily in WPF and Silverlight but its use is not limited to there. Code can add event handlers to see when the collection has changed and then react through the event handler to do some additional processing. This may be changing a UI or performing some other operation.
The code below doesn't really do anything but demonstrates how you'd attach a handler in a class and then use the event args to react in some way to the changes. WPF already has many operations like refreshing the UI built in so you get them for free when using ObservableCollections
class Handler
{
private ObservableCollection<string> collection;
public Handler()
{
collection = new ObservableCollection<string>();
collection.CollectionChanged += HandleChange;
}
private void HandleChange(object sender, NotifyCollectionChangedEventArgs e)
{
foreach (var x in e.NewItems)
{
// do something
}
foreach (var y in e.OldItems)
{
//do something
}
if (e.Action == NotifyCollectionChangedAction.Move)
{
//do something
}
}
}
Keep it simple.
func NowAsUnixMilli() int64 {
return time.Now().UnixNano() / 1e6
}