Once java-8 is out (March 2014) you'll be able to use streams:
int sum = IntStream.of(a).sum();
or even
int sum = IntStream.of(a).parallel().sum();
You could upload via $resource
by assigning data to params attribute of resource actions
like so:
$scope.uploadFile = function(files) {
var fdata = new FormData();
fdata.append("file", files[0]);
$resource('api/post/:id', { id: "@id" }, {
postWithFile: {
method: "POST",
data: fdata,
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}
}).postWithFile(fdata).$promise.then(function(response){
//successful
},function(error){
//error
});
};
var datetime = new Date();_x000D_
console.log(datetime.toISOString().slice(0,10));
_x000D_
This answer is not the direct answer for the question. But it should help you figure out which solution fits best for your problem.
When analysing the problem you should activate the debug option -vv
Then rsync will output which files are included or excluded by which pattern:
building file list ...
[sender] hiding file FILE1 because of pattern FILE1*
[sender] showing file FILE2 because of pattern *
Here is a solution using Application
class.
public class AppSingleton extends Application implements Application.ActivityLifecycleCallbacks {
private WeakReference<Context> foregroundActivity;
@Override
public void onActivityResumed(Activity activity) {
foregroundActivity=new WeakReference<Context>(activity);
}
@Override
public void onActivityPaused(Activity activity) {
String class_name_activity=activity.getClass().getCanonicalName();
if (foregroundActivity != null &&
foregroundActivity.get().getClass().getCanonicalName().equals(class_name_activity)) {
foregroundActivity = null;
}
}
//............................
public boolean isOnForeground(@NonNull Context activity_cntxt) {
return isOnForeground(activity_cntxt.getClass().getCanonicalName());
}
public boolean isOnForeground(@NonNull String activity_canonical_name) {
if (foregroundActivity != null && foregroundActivity.get() != null) {
return foregroundActivity.get().getClass().getCanonicalName().equals(activity_canonical_name);
}
return false;
}
}
You can simply use it like follows,
((AppSingleton)context.getApplicationContext()).isOnForeground(context_activity);
If you have a reference to the required Activity or using the canonical name of the Activity, you can find out whether it's in the foreground or not. This solution may not be foolproof. Therefore your comments are really welcome.
To improve the solution of Slinky Sloth I had to add this beforere get from clipboard :
Set objPDF = New MSForms.DataObject
Sadly it didn't worked for a pdf of 10 pages.
Implementation in Java : Using codaddict's algorithm (Maybe slightly different)
import java.util.HashMap;
public class ArrayPairSum {
public static void main(String[] args) {
int []a = {2,45,7,3,5,1,8,9};
printSumPairs(a,10);
}
public static void printSumPairs(int []input, int k){
Map<Integer, Integer> pairs = new HashMap<Integer, Integer>();
for(int i=0;i<input.length;i++){
if(pairs.containsKey(input[i]))
System.out.println(input[i] +", "+ pairs.get(input[i]));
else
pairs.put(k-input[i], input[i]);
}
}
}
For input = {2,45,7,3,5,1,8,9}
and if Sum is 10
Output pairs:
3,7
8,2
9,1
Some notes about the solution :
I had the same problem, and want to let you know that none of the above worked for me. What worked for me was:
Intent dialogIntent = new Intent(this, myActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(dialogIntent);
and in one my subclasses, stored in a separate file I had to:
public static Service myService;
myService = this;
new SubService(myService);
Intent dialogIntent = new Intent(myService, myActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
myService.startActivity(dialogIntent);
All the other answers gave me a nullpointerexception
.
I had a similar issue when adding a class to the main method. Turns out it wasn't an issue, it was me not checking my spelling. So, as a noob, I learned that mis-spelling can and will mess things up. These posts helped me "see" my mistake and all is good now.
You can use the keyCode of the arrow keys (37, 38, 39 and 40 for left, up, right and down):
$('.selector').keydown(function (e) {
var arrow = { left: 37, up: 38, right: 39, down: 40 };
switch (e.which) {
case arrow.left:
//..
break;
case arrow.up:
//..
break;
case arrow.right:
//..
break;
case arrow.down:
//..
break;
}
});
Check the above example here.
Use OUTER APPLY instead of LEFT JOIN:
SELECT u.id, mbg.marker_value
FROM dps_user u
OUTER APPLY
(SELECT TOP 1 m.marker_value, um.profile_id
FROM dps_usr_markers um (NOLOCK)
INNER JOIN dps_markers m (NOLOCK)
ON m.marker_id= um.marker_id AND
m.marker_key = 'moneyBackGuaranteeLength'
WHERE um.profile_id=u.id
ORDER BY m.creation_date
) AS MBG
WHERE u.id = 'u162231993';
Unlike JOIN, APPLY allows you to reference the u.id inside the inner query.
Here is a rough explanation of the concepts.
[ACK]
is the acknowledgement that the previously sent data packet was received.
[FIN]
is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN
).
So, suppose
[FIN,ACK]
indicating that it received the sent packet and wants to close the session.[FIN,ACK]
indicating that it received the termination request (the ACK
part) and that it too will close the connection (the FIN
part).However, if host A wants to close the session after sending the packet, it would only send a [FIN]
packet (nothing to acknowledge) but host B would respond with [FIN,ACK]
(acknowledges the request and responds with FIN
).
Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST]
instead of the usual [FIN,ACK]
. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.
You can find a more detailed and comprehensive explanation here.
If you are specifically looking for getting the difference between two files, then this might help:
with open('first_file', 'r') as file1:
with open('second_file', 'r') as file2:
difference = set(file1).difference(file2)
difference.discard('\n')
with open('diff.txt', 'w') as file_out:
for line in difference:
file_out.write(line)
I know this is an old question, but thought that I should anyway present the simple solution using the paste() function as suggested to by the questioner:
data_1<-data.frame(a=data$a,"x"=paste(data$b,data$c,data$d,sep="-"))
data_1
a x
1 1 a-d-g
2 2 b-e-h
3 3 c-f-i
user1247808 has a good link with: wget -c
http://www.androidtech.com/downloads/wordnet20-from-prolog-all-3.zip
If that isn't enough words for you:
http://dumps.wikimedia.org/enwiktionary/latest/enwiktionary-latest-all-titles-in-ns0.gz (updated url from Michael Kropat's suggestion)
Although that file name changes, you'll want to find the latest ... that turns out just to be a big (very big) text file.
You can either use:
<button onclick="window.history.back()">Back</button>
or..
<button onclick="window.history.go(-1)">Back</button>
The difference, of course, is back()
only goes back 1 page but go()
goes back/forward the number of pages you pass as a parameter, relative to your current page.
For width it's easy, simply remove the width: 100%
rule. By default, the div
will stretch to fit the parent container.
Height is not quite so simple. You could do something like the equal height column trick.
html, body {width:100%;height:100%;margin:0;padding:0;}
.border {border:1px solid black;}
.margin { margin:5px;}
#one {width:500px;height:300px; overflow: hidden;}
#two {height:50px;}
#three {width:100px; padding-bottom: 30000px; margin-bottom: -30000px;}
Simplest way is to use dimensions in % or em. Just change the base font size everything will change.
Less
@media (max-width: @screen-xs) {
body{font-size: 10px;}
}
@media (max-width: @screen-sm) {
body{font-size: 14px;}
}
h5{
font-size: 1.4rem;
}
Look at all the ways at https://stackoverflow.com/a/21981859/406659
You could use viewport units (vh,vw...) but they dont work on Android < 4.4
On windows:
std::string replace(std::string str, std::string substr1, std::string substr2)
{
for (size_t index = str.find(substr1, 0); index != std::string::npos && substr1.length(); index = str.find(substr1, index + substr2.length() ) )
str.replace(index, substr1.length(), substr2);
return str;
}
Short solution where you don't need any extra Libraries.
This answer tells how to make a custom system keyboard that can be used in any app that a user has installed on their phone. If you want to make a keyboard that will only be used within your own app, then see my other answer.
The example below will look like this. You can modify it for any keyboard layout.
The following steps show how to create a working custom system keyboard. As much as possible I tried to remove any unnecessary code. If there are other features that you need, I provided links to more help at the end.
I named my project "Custom Keyboard". Call it whatever you want. There is nothing else special here. I will just leave the MainActivity
and "Hello World!" layout as it is.
Add the following two files to your app's res/layout
folder:
keyboard_view.xml
This view is like a container that will hold our keyboard. In this example there is only one keyboard, but you could add other keyboards and swap them in and out of this KeyboardView
.
<?xml version="1.0" encoding="utf-8"?>
<android.inputmethodservice.KeyboardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/keyboard_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:keyPreviewLayout="@layout/key_preview"
android:layout_alignParentBottom="true">
</android.inputmethodservice.KeyboardView>
key_preview.xml
The key preview is a layout that pops up when you press a keyboard key. It just shows what key you are pressing (in case your big, fat fingers are covering it). This isn't a multiple choice popup. For that you should check out the Candidates view.
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="@android:color/white"
android:textColor="@android:color/black"
android:textSize="30sp">
</TextView>
Create an xml
folder in your res
folder. (Right click res
and choose New > Directory.)
Then add the following two xml files to it. (Right click the xml
folder and choose New > XML resource file.)
number_pad.xml
This is where it starts to get more interesting. This Keyboard
defines the layout of the keys.
<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
android:keyWidth="20%p"
android:horizontalGap="5dp"
android:verticalGap="5dp"
android:keyHeight="60dp">
<Row>
<Key android:codes="49" android:keyLabel="1" android:keyEdgeFlags="left"/>
<Key android:codes="50" android:keyLabel="2"/>
<Key android:codes="51" android:keyLabel="3"/>
<Key android:codes="52" android:keyLabel="4"/>
<Key android:codes="53" android:keyLabel="5" android:keyEdgeFlags="right"/>
</Row>
<Row>
<Key android:codes="54" android:keyLabel="6" android:keyEdgeFlags="left"/>
<Key android:codes="55" android:keyLabel="7"/>
<Key android:codes="56" android:keyLabel="8"/>
<Key android:codes="57" android:keyLabel="9"/>
<Key android:codes="48" android:keyLabel="0" android:keyEdgeFlags="right"/>
</Row>
<Row>
<Key android:codes="-5"
android:keyLabel="DELETE"
android:keyWidth="40%p"
android:keyEdgeFlags="left"
android:isRepeatable="true"/>
<Key android:codes="10"
android:keyLabel="ENTER"
android:keyWidth="60%p"
android:keyEdgeFlags="right"/>
</Row>
</Keyboard>
Here are some things to note:
keyWidth
: This is the default width of each key. The 20%p
means that each key should take up 20% of the width of the parent. It can be overridden by individual keys, though, as you can see happened with the Delete and Enter keys in the third row.keyHeight
: It is hard coded here, but you could use something like @dimen/key_height
to set it dynamically for different screen sizes.Gap
: The horizontal and vertical gap tells how much space to leave between keys. Even if you set it to 0px
there is still a small gap.codes
: This can be a Unicode or custom code value that determines what happens or what is input when the key is pressed. See keyOutputText
if you want to input a longer Unicode string. keyLabel
: This is the text that is displayed on the key.keyEdgeFlags
: This indicates which edge the key should be aligned to.isRepeatable
: If you hold down the key it will keep repeating the input.method.xml
This file tells the system the input method subtypes that are available. I am just including a minimal version here.
<?xml version="1.0" encoding="utf-8"?>
<input-method
xmlns:android="http://schemas.android.com/apk/res/android">
<subtype
android:imeSubtypeMode="keyboard"/>
</input-method>
Create a new Java file. Let's call it MyInputMethodService
. This file ties everything together. It handles input received from the keyboard and sends it on to whatever view is receiving it (an EditText
, for example).
public class MyInputMethodService extends InputMethodService implements KeyboardView.OnKeyboardActionListener {
@Override
public View onCreateInputView() {
// get the KeyboardView and add our Keyboard layout to it
KeyboardView keyboardView = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard_view, null);
Keyboard keyboard = new Keyboard(this, R.xml.number_pad);
keyboardView.setKeyboard(keyboard);
keyboardView.setOnKeyboardActionListener(this);
return keyboardView;
}
@Override
public void onKey(int primaryCode, int[] keyCodes) {
InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
switch (primaryCode) {
case Keyboard.KEYCODE_DELETE:
CharSequence selectedText = ic.getSelectedText(0);
if (TextUtils.isEmpty(selectedText)) {
// no selection, so delete previous character
ic.deleteSurroundingText(1, 0);
} else {
// delete the selection
ic.commitText("", 1);
}
break;
default:
char code = (char) primaryCode;
ic.commitText(String.valueOf(code), 1);
}
}
@Override
public void onPress(int primaryCode) { }
@Override
public void onRelease(int primaryCode) { }
@Override
public void onText(CharSequence text) { }
@Override
public void swipeLeft() { }
@Override
public void swipeRight() { }
@Override
public void swipeDown() { }
@Override
public void swipeUp() { }
}
Notes:
OnKeyboardActionListener
listens for keyboard input. It is also requires all those empty methods in this example.InputConnection
is what is used to send input to another view like an EditText
.I put this last rather than first because it refers to the files we already added above. To register your custom keyboard as a system keyboard, you need to add a service
section to your AndroidManifest.xml file. Put it in the application
section after activity
.
<manifest ...>
<application ... >
<activity ... >
...
</activity>
<service
android:name=".MyInputMethodService"
android:label="Keyboard Display Name"
android:permission="android.permission.BIND_INPUT_METHOD">
<intent-filter>
<action android:name="android.view.InputMethod"/>
</intent-filter>
<meta-data
android:name="android.view.im"
android:resource="@xml/method"/>
</service>
</application>
</manifest>
That's it! You should be able to run your app now. However, you won't see much until you enable your keyboard in the settings.
Every user who wants to use your keyboard will have to enable it in the Android settings. For detailed instructions on how to do that, see the following link:
Here is a summary:
Now you should be able to use your keyboard anywhere that you can type in Android.
The keyboard above is usable, but to create a keyboard that other people will want to use you will probably have to add more functionality. Study the links below to learn how.
Don't like how the standard KeyboardView
looks and behaves? I certainly don't. It looks like it hasn't been updated since Android 2.0. How about all those custom keyboards in the Play Store? They don't look anything like the ugly keyboard above.
The good news is that you can completely customize your own keyboard's look and behavior. You will need to do the following things:
ViewGroup
. You could fill it with Button
s or even make your own custom key views that subclass View
. If you use popup views, then note this.onKeyClicked(String text)
or onBackspace()
.keyboard_view.xml
, key_preview.xml
, or number_pad.xml
described in the directions above since these are all for the standard KeyboardView
. You will handle all these UI aspects in your custom view.MyInputMethodService
class, implement the custom keyboard listener that you defined in your keyboard class. This is in place of KeyboardView.OnKeyboardActionListener
, which is no longer needed.MyInputMethodService
class's onCreateInputView()
method, create and return an instance of your custom keyboard. Don't forget to set the keyboard's custom listener to this
. If your app uses CoreData, a nifty trick is to search for the name of the sqlite file using terminal.
find ~ -name my_app_db_name.sqlite
The results will list the full file paths to any simulators that have run your app.
I really wish Apple would just add a button to the iOS Simulator file menu like "Reveal Documents folder in Finder".
From Perlfaq8:
You're confusing the purpose of system() and backticks (``). system() runs a command and returns exit status information (as a 16 bit value: the low 7 bits are the signal the process died from, if any, and the high 8 bits are the actual exit value). Backticks (``) run a command and return what it sent to STDOUT.
$exit_status = system("mail-users");
$output_string = `ls`;
There are many ways to execute external commands from Perl. The most commons with their meanings are:
[Long thread, not sure if its already listed as an option...].
A simple alternative for contsants only, would be defining the const outside of class.
This will be accessible only from the module itself, unless accompanied with a getter.
This way prototype
isn't littered and you get the const
.
// will be accessible only from the module itself
const MY_CONST = 'string';
class MyClass {
// optional, if external access is desired
static get MY_CONST(){return MY_CONST;}
// access example
static someMethod(){
console.log(MY_CONST);
}
}
I had this issue and tried both, but had to settle for removing crap like "pageEditState", but not removing user info lest I have to look it up again.
public static void RemoveEverythingButUserInfo()
{
foreach (String o in HttpContext.Current.Session.Keys)
{
if (o != "UserInfoIDontWantToAskForAgain")
keys.Add(o);
}
}
i also have a solution with standard inputs and outputs
#include<stdio.h>
#include<malloc.h>
int main()
{
char *str,ch;
int size=10,len=0;
str=realloc(NULL,sizeof(char)*size);
if(!str)return str;
while(EOF!=scanf("%c",&ch) && ch!="\n")
{
str[len++]=ch;
if(len==size)
{
str = realloc(str,sizeof(char)*(size+=10));
if(!str)return str;
}
}
str[len++]='\0';
printf("%s\n",str);
free(str);
}
I am wondering what's your purpose of doing the iframe print.
I met a similar problem a moment ago: use chrome's print preview to generate a PDF file of a iframe.
Finally I solved my problem with a trick:
$('#print').click(function() {_x000D_
$('#noniframe').hide(); // hide other elements_x000D_
window.print(); // now, only the iframe left_x000D_
$('#noniframe').show(); // show other elements again._x000D_
});
_x000D_
I'm pretty sure the syntax for this in python is:
user_input1 = raw_input("Enter Name: ")
user_input2 = raw_input("Enter Value: ")
info = (user_input1, user_input2)
once set, tuples cannot be changed.
using(var myDb = new MyDbEntities())
{
user user = new user();
user.username = "me";
user.email = "[email protected]";
myDb.Users.Add(user);
myDb.users.Attach(user);
myDb.Entry(user).State = EntityState.Modified;//this is for modiying/update existing entry
myDb.SaveChanges();
}
The clear()
method removes all the elements of a single ArrayList
. It's a fast operation, as it just sets the array elements to null
.
The removeAll(Collection)
method, which is inherited from AbstractCollection
, removes all the elements that are in the argument collection from the collection you call the method on. It's a relatively slow operation, as it has to search through one of the collections involved.
we can use this two line of code to generate unique string have tested around 10000000 times of iteration
$sffledStr= str_shuffle('abscdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_-+');
$uniqueString = md5(time().$sffledStr);
steps :
replace
DocumentRoot "C:/xampp/htdocs"
<Directory "C:/xampp/htdocs">
Those 2 lines
| C:/xampp/htdocs == current location for root |
|change C:/xampp/htdocs with any location you want|
DONE: start apache and go to the localhost see in action [ watch video click here ]
MacVim is just Vim. Anything you are used to do in Vim will work exactly the same way in MacVim.
MacVim is more integrated in the whole OS than Vim in the Terminal or even GVim in Linux, it follows a lot of Mac OS X's conventions.
If you work mainly with GUI apps (YummyFTP + GitX + Charles, for example) you may prefer MacVim.
If you work mainly with CLI apps (ssh + svn + tcpdump, for example) you may prefer vim in the terminal.
Entering and leaving one realm (CLI) for the other (GUI) and vice-versa can be "expensive".
I use both MacVim and Vim depending on the task and the context: if I'm in CLI-land I'll just type vim filename
and if I'm in GUI-land I'll just invoke Quicksilver and launch MacVim.
When I switched from TextMate I kind of liked the fact that MacVim supported almost all of the regular shortcuts Mac users are accustomed to. I added some of my own, mimiking TextMate but, since I was working in multiple environments I forced my self to learn the vim way. Now I use both MacVim and Vim almost exactly the same way. Using one or the other is just a question of context for me.
Also, like El Isra said, the default vim (CLI) in OS X is slightly outdated. You may install an up-to-date version via MacPorts or you can install MacVim and add an alias to your .profile
:
alias vim='/path/to/MacVim.app/Contents/MacOS/Vim'
to have the same vim in MacVim and Terminal.app.
Another difference is that many great colorschemes out there work out of the box in MacVim but look terrible in the Terminal.app which only supports 8 colors (+ highlights) but you can use iTerm — which can be set up to support 256 colors — instead of Terminal.
So… basically my advice is to just use both.
EDIT: I didn't try it but the latest version of Terminal.app (in 10.7) is supposed to support 256 colors. I'm still on 10.6.x at work so I'll still use iTerm2 for a while.
EDIT: An even better way to use MacVim's CLI executable in your shell is to move the mvim
script bundled with MacVim somewhere in your $PATH
and use this command:
$ mvim -v
EDIT: Yes, Terminal.app now supports 256 colors. So if you don't need iTerm2's advanced features you can safely use the default terminal emulator.
This works in Firefox and Chrome.
I had a need to open a special html file locally (by pressing Enter
when the file is selected in the file explorer in Windows), either just for viewing the file or for editing it in a special online editor.
So I wanted to distinguish between these two options by holding down the Ctrl
-key or not, while pressing Enter
.
As you all have understood from all the answers here, this seems to be not really possible, but here is a way that mimics this behaviour in a way that was acceptable for me.
The way this works is like this:
If you hold down the Ctrl
-key when opening the file then a keydown event will never fire in the javascript code. But a keyup event will fire (when you finally release the Ctrl
-key). The code captures that.
The code also turns off keyevents (both keyup and keydown) as soon as one of them occurs. So if you press the Ctrl
-key after the file has opened, nothing will happen.
window.onkeyup = up;
window.onkeydown = down;
function up(e) {
if (e.key === 'F5') return; // if you want this to work also on reload with F5.
window.onkeyup = null;
window.onkeyup = null;
if (e.key === 'Control') {
alert('Control key was released. You must have held it down while opening the file, so we will now load the file into the editor.');
}
}
function down() {
window.onkeyup = null;
window.onkeyup = null;
}
I had the same problem for days until I noticed (how could I look at it and not read the code :-(..) that config.inc.php
is calling config-db.php
** MySql Server version: 5.7.5-m15
** Apache/2.4.10 (Ubuntu)
** phpMyAdmin 4.2.9.1deb0.1
/etc/phpmyadmin/config-db.php:
$dbuser='yourDBUserName';
$dbpass='';
$basepath='';
$dbname='phpMyAdminDBName';
$dbserver='';
$dbport='';
$dbtype='mysql';
Here you need to define your username, password, dbname and others that are showing empty' use default unless you changed their configuration.
That solved the issue for me.
U hope it helps you.
latest.phpmyadmin.docs
You can call:
arr.slice(Math.max(arr.length - 5, 1))
If you don't want to exclude the first element, use
arr.slice(Math.max(arr.length - 5, 0))
For me, It's working like this one.
C:\Program Files\PostgreSQL\12\bin> psql -U postgres -p 5432 -d dummy -f C:\Users\Downloads\d2cm_test.sql
for(var key in object) {
console.log(object[key]);
}
first ensure that your table storage engine type should be innoDB (you can set it using Table operations Tab)
if you are using new phpmyadmin then use new "Relation view" tab to make foreign key relation
if you are using old version of phpmyadmin then the "relation view" button will show on the bottom of the table columns
Pipe them through sort
and uniq
. This removes all duplicates.
uniq -d
gives only the duplicates, uniq -u
gives only the unique ones (strips duplicates).
Just another approach:
string mystr = "hello";
MessageBox.show(mystr.Substring(0, 1));
Article on Programming.Guide: Switch on enum
enum MyEnum { CONST_ONE, CONST_TWO }
class Test {
public static void main(String[] args) {
MyEnum e = MyEnum.CONST_ONE;
switch (e) {
case CONST_ONE: System.out.println(1); break;
case CONST_TWO: System.out.println(2); break;
}
}
}
Switches for strings are implemented in Java 7.
Non of these worked for me... when I converted the timestamp back it's 4 years off.
This worked perfectly: =(A2-DATE(1970,1,1))*86400
Credit goes to: Filip Czaja http://fczaja.blogspot.ca
Original Post: http://fczaja.blogspot.ca/2011/06/convert-excel-date-into-timestamp.html
You can un-check the build automatically in Project menu and then build by hand by type Ctrl + B, or clicking an icon the appears to the right of the printer icon.
subprocess.call
will avoid problems with having to deal with quoting conventions of various shells. It accepts a list, rather than a string, so arguments are more easily delimited. i.e.
import subprocess
subprocess.call(['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt'])
On mac I used
sed -i '' -e 's/text-on-line-to-be-changed.*/text-to-replace-the=whole-line/' file-name
It only opens the first (bookmarked) page full screen. Any next page will be opened WITH the address bar visible again. Whatever meta tag you put into your page header...
You need to use smtp as backend in settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
If you use backend as console, you will receive output in console
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
And also below settings in addition
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'password'
If you are using gmail for this, setup 2-step verification and Application specific password and copy and paste that password in above EMAIL_HOST_PASSWORD value.
You might find this article of interest which is available at codeplex.com.
The article presents a new way of expressing queries that span multiple tables in the form of declarative graph shapes.
Moreover, the article contains a thorough performance comparison of this new approach with EF queries. This analysis shows that GBQ quickly outperforms EF queries.
For me. I changed the color of .xml image (vector image) like this.
ic_action_add.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="#FFFFFF"
android:alpha="0.8">
<path
android:fillColor="@android:color/white"
android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
</vector>
to:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="#FFFFFF"
android:alpha="0.8">
<path
android:fillColor="#FF000000"
android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
</vector>
i just changed android:fillColor="@android:color/white"
to android:fillColor="#FF000000"
and it's worked for me :)
As per my personal experience Adobe edge is the best tool for HTML5. It's still in preview mode but you will download it free from Adobe site.
JPA is the interface, Hibernate is one implementation of that interface.
We had this same issue. We solved it adding 'length' to entity attribute definition:
@Column(columnDefinition="text", length=10485760)
private String configFileXml = "";
data = [4, 5, 6] # Your global variable
def print_data(data): # <-- Pass in a parameter called "data"
print data # <-- Note: You can access global variable inside your function, BUT for now, which is which? the parameter or the global variable? Confused, huh?
print_data(data)
When you use @SpringBootApplication annotation in for example package
com.company.config
it will automatically make component scan like this:
@ComponentScan("com.company.config")
So it will NOT scan packages like com.company.controller etc.. Thats why you have to declare your @SpringBootApplication in package one level prior to your normal packages like this: com.company OR use scanBasePackages property, like this:
@SpringBootApplication(scanBasePackages = { "com.company" })
OR componentScan:
@SpringBootApplication
@ComponentScan("com.company")
I found it best to only update the calculation when a specific cell is changed. Here is an example VBA code to place in the "Worksheet" "Change" event:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("F3")) Is Nothing Then
Application.CalculateFull
End If
End Sub
disable the button on click, enable it after the operation completes
$(document).ready(function () {
$("#btn").on("click", function() {
$(this).attr("disabled", "disabled");
doWork(); //this method contains your logic
});
});
function doWork() {
alert("doing work");
//actually this function will do something and when processing is done the button is enabled by removing the 'disabled' attribute
//I use setTimeout so you can see the button can only be clicked once, and can't be clicked again while work is being done
setTimeout('$("#btn").removeAttr("disabled")', 1500);
}
Intent takePhoto = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(takePhoto, CAMERA_PIC_REQUEST)
and set
CAMERA_PIC_REQUEST= 1 or 0
Solution
You can now use base64 files to produce sounds when imported as data URI. The solution is almost the same as the previous ones, except you do not need to import an external audio file.
function beep() {
var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxEjzFUgfHoSQ9Qq7KNwqHwuB13MA4a1q/DmBrHgPcmjiGoh//EwC5nGPEmS4RcfkVKOhJf+WOgoxJclFz3kgn//dBA+ya1GhurNn8zb//9NNutNuhz31f////9vt///z+IdAEAAAK4LQIAKobHItEIYCGAExBwe8jcToF9zIKrEdDYIuP2MgOWFSE34wYiR5iqQPj0JIeoVdlG4VD4XA67mAcNa1fhzA1jwHuTRxDUQ//iYBczjHiTJcIuPyKlHQkv/LHQUYkuSi57yQT//uggfZNajQ3Vmz+Zt//+mm3Wm3Q576v////+32///5/EOgAAADVghQAAAAA//uQZAUAB1WI0PZugAAAAAoQwAAAEk3nRd2qAAAAACiDgAAAAAAABCqEEQRLCgwpBGMlJkIz8jKhGvj4k6jzRnqasNKIeoh5gI7BJaC1A1AoNBjJgbyApVS4IDlZgDU5WUAxEKDNmmALHzZp0Fkz1FMTmGFl1FMEyodIavcCAUHDWrKAIA4aa2oCgILEBupZgHvAhEBcZ6joQBxS76AgccrFlczBvKLC0QI2cBoCFvfTDAo7eoOQInqDPBtvrDEZBNYN5xwNwxQRfw8ZQ5wQVLvO8OYU+mHvFLlDh05Mdg7BT6YrRPpCBznMB2r//xKJjyyOh+cImr2/4doscwD6neZjuZR4AgAABYAAAABy1xcdQtxYBYYZdifkUDgzzXaXn98Z0oi9ILU5mBjFANmRwlVJ3/6jYDAmxaiDG3/6xjQQCCKkRb/6kg/wW+kSJ5//rLobkLSiKmqP/0ikJuDaSaSf/6JiLYLEYnW/+kXg1WRVJL/9EmQ1YZIsv/6Qzwy5qk7/+tEU0nkls3/zIUMPKNX/6yZLf+kFgAfgGyLFAUwY//uQZAUABcd5UiNPVXAAAApAAAAAE0VZQKw9ISAAACgAAAAAVQIygIElVrFkBS+Jhi+EAuu+lKAkYUEIsmEAEoMeDmCETMvfSHTGkF5RWH7kz/ESHWPAq/kcCRhqBtMdokPdM7vil7RG98A2sc7zO6ZvTdM7pmOUAZTnJW+NXxqmd41dqJ6mLTXxrPpnV8avaIf5SvL7pndPvPpndJR9Kuu8fePvuiuhorgWjp7Mf/PRjxcFCPDkW31srioCExivv9lcwKEaHsf/7ow2Fl1T/9RkXgEhYElAoCLFtMArxwivDJJ+bR1HTKJdlEoTELCIqgEwVGSQ+hIm0NbK8WXcTEI0UPoa2NbG4y2K00JEWbZavJXkYaqo9CRHS55FcZTjKEk3NKoCYUnSQ0rWxrZbFKbKIhOKPZe1cJKzZSaQrIyULHDZmV5K4xySsDRKWOruanGtjLJXFEmwaIbDLX0hIPBUQPVFVkQkDoUNfSoDgQGKPekoxeGzA4DUvnn4bxzcZrtJyipKfPNy5w+9lnXwgqsiyHNeSVpemw4bWb9psYeq//uQZBoABQt4yMVxYAIAAAkQoAAAHvYpL5m6AAgAACXDAAAAD59jblTirQe9upFsmZbpMudy7Lz1X1DYsxOOSWpfPqNX2WqktK0DMvuGwlbNj44TleLPQ+Gsfb+GOWOKJoIrWb3cIMeeON6lz2umTqMXV8Mj30yWPpjoSa9ujK8SyeJP5y5mOW1D6hvLepeveEAEDo0mgCRClOEgANv3B9a6fikgUSu/DmAMATrGx7nng5p5iimPNZsfQLYB2sDLIkzRKZOHGAaUyDcpFBSLG9MCQALgAIgQs2YunOszLSAyQYPVC2YdGGeHD2dTdJk1pAHGAWDjnkcLKFymS3RQZTInzySoBwMG0QueC3gMsCEYxUqlrcxK6k1LQQcsmyYeQPdC2YfuGPASCBkcVMQQqpVJshui1tkXQJQV0OXGAZMXSOEEBRirXbVRQW7ugq7IM7rPWSZyDlM3IuNEkxzCOJ0ny2ThNkyRai1b6ev//3dzNGzNb//4uAvHT5sURcZCFcuKLhOFs8mLAAEAt4UWAAIABAAAAAB4qbHo0tIjVkUU//uQZAwABfSFz3ZqQAAAAAngwAAAE1HjMp2qAAAAACZDgAAAD5UkTE1UgZEUExqYynN1qZvqIOREEFmBcJQkwdxiFtw0qEOkGYfRDifBui9MQg4QAHAqWtAWHoCxu1Yf4VfWLPIM2mHDFsbQEVGwyqQoQcwnfHeIkNt9YnkiaS1oizycqJrx4KOQjahZxWbcZgztj2c49nKmkId44S71j0c8eV9yDK6uPRzx5X18eDvjvQ6yKo9ZSS6l//8elePK/Lf//IInrOF/FvDoADYAGBMGb7FtErm5MXMlmPAJQVgWta7Zx2go+8xJ0UiCb8LHHdftWyLJE0QIAIsI+UbXu67dZMjmgDGCGl1H+vpF4NSDckSIkk7Vd+sxEhBQMRU8j/12UIRhzSaUdQ+rQU5kGeFxm+hb1oh6pWWmv3uvmReDl0UnvtapVaIzo1jZbf/pD6ElLqSX+rUmOQNpJFa/r+sa4e/pBlAABoAAAAA3CUgShLdGIxsY7AUABPRrgCABdDuQ5GC7DqPQCgbbJUAoRSUj+NIEig0YfyWUho1VBBBA//uQZB4ABZx5zfMakeAAAAmwAAAAF5F3P0w9GtAAACfAAAAAwLhMDmAYWMgVEG1U0FIGCBgXBXAtfMH10000EEEEEECUBYln03TTTdNBDZopopYvrTTdNa325mImNg3TTPV9q3pmY0xoO6bv3r00y+IDGid/9aaaZTGMuj9mpu9Mpio1dXrr5HERTZSmqU36A3CumzN/9Robv/Xx4v9ijkSRSNLQhAWumap82WRSBUqXStV/YcS+XVLnSS+WLDroqArFkMEsAS+eWmrUzrO0oEmE40RlMZ5+ODIkAyKAGUwZ3mVKmcamcJnMW26MRPgUw6j+LkhyHGVGYjSUUKNpuJUQoOIAyDvEyG8S5yfK6dhZc0Tx1KI/gviKL6qvvFs1+bWtaz58uUNnryq6kt5RzOCkPWlVqVX2a/EEBUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU=");
snd.play();
}
beep();
Compatibility
Data URI is supported on almost every browser now. More information on http://caniuse.com/datauri
Demo
Conversion Tool
And here is where you can convert mp3 or wav files into Data URI format:
It seems there are pros and cons to using either ??
or ?:
. The pro to using ?:
is that it evaluates false and null and "" the same. The con is that it reports an E_NOTICE if the preceding argument is null. With ??
the pro is that there is no E_NOTICE, but the con is that it does not evaluate false and null the same. In my experience, I have seen people begin using null and false interchangeably but then they eventually resort to modifying their code to be consistent with using either null or false, but not both. An alternative is to create a more elaborate ternary condition: (isset($something) or !$something) ? $something : $something_else
.
The following is an example of the difference of using the ??
operator using both null and false:
$false = null;
$var = $false ?? "true";
echo $var . "---<br>";//returns: true---
$false = false;
$var = $false ?? "true";
echo $var . "---<br>"; //returns: ---
By elaborating on the ternary operator however, we can make a false or empty string "" behave as if it were a null without throwing an e_notice:
$false = null;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---
$false = false;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---
$false = "";
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---
$false = true;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: 1---
Personally, I think it would be really nice if a future rev of PHP included another new operator: :?
that replaced the above syntax. ie:
// $var = $false :? "true";
That syntax would evaluate null, false, and "" equally and not throw an E_NOTICE...
The reason that visible="false" does not work is because HTML is defined as a standard by a consortium group. The standard for the Table element does not have a visibility property defined.
You can see all the valid properties for a table by going to the standards web page for tables.
That page can be a bit hard to read, so here is a link to another page that makes it easier to read.
No need to extract the month and year.Just need to use the unix_timestamp(date String,format String) function.
For Example:
select yourdate_column
from your_table
where unix_timestamp(yourdate_column, 'yyyy-MM-dd') >= unix_timestamp('2014-06-02', 'yyyy-MM-dd')
and unix_timestamp(yourdate_column, 'yyyy-MM-dd') <= unix_timestamp('2014-07-02','yyyy-MM-dd')
order by yourdate_column limit 10;
Simple Example
var request = require('request');
//Custom Header pass
var headersOpt = {
"content-type": "application/json",
};
request(
{
method:'post',
url:'https://www.googleapis.com/urlshortener/v1/url',
form: {name:'hello',age:25},
headers: headersOpt,
json: true,
}, function (error, response, body) {
//Print the Response
console.log(body);
});
Yes, you can.
However, it requires SQL CLR with EXTERNAL_ACCESS or UNSAFE permission and specifying a connection string. This is obviously not recommended.
For example, using Eval SQL.NET (a SQL CLR which allow to add C# syntax in SQL)
CREATE FUNCTION [dbo].[fn_modify_table_state]
(
@conn VARCHAR(8000) ,
@sql VARCHAR(8000)
)
RETURNS INT
AS
BEGIN
RETURN SQLNET::New('
using(var connection = new SqlConnection(conn))
{
connection.Open();
using(var command = new SqlCommand(sql, connection))
{
return command.ExecuteNonQuery();
}
}
').ValueString('conn', @conn).ValueString('sql', @sql).EvalReadAccessInt()
END
GO
DECLARE @conn VARCHAR(8000) = 'Data Source=XPS8700;Initial Catalog=SqlServerEval_Debug;Integrated Security=True'
DECLARE @sql VARCHAR(8000) = 'UPDATE [Table_1] SET Value = -1 WHERE Name = ''zzz'''
DECLARE @rowAffecteds INT = dbo.fn_modify_table_state(@conn, @sql)
Documentation: Modify table state within a SQL Function
Disclaimer: I'm the owner of the project Eval SQL.NET
I don't think there's a built-in way to do it without catching exceptions. You could instead use something like this:
public static MyEnum asMyEnum(String str) {
for (MyEnum me : MyEnum.values()) {
if (me.name().equalsIgnoreCase(str))
return me;
}
return null;
}
Edit: As Jon Skeet notes, values()
works by cloning a private backing array every time it is called. If performance is critical, you may want to call values()
only once, cache the array, and iterate through that.
Also, if your enum has a huge number of values, Jon Skeet's map alternative is likely to perform better than any array iteration.
Well... I flipped the internet upside down three times but did not find anything that might help me because it was a Drupal project rather than other scenarios people described.
My problem was that someone in the project added a js which his address was: <script src="http://base_url/?p4sxbt"></script>
and it was attached in this way:
drupal_add_js('',
array('scope' => 'footer', 'weight' => 5)
);
Hope this will help someone in the future.
I have run into this problem too. My case is as following:
In text:
HKEY_CURRENT_USER\Environment
Path REG_SZ %JAVA_HOME%\bin;C:\ProgramFiles\nodejs
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
JAVA_HOME REG_SZ C:\ProgramFiles\Java\jdk
Path REG_EXPAND_SZ C:\bin;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\
WindowsPowerShell\v1.0\;C:\Program Files\Intel\DMIX;c:\Program Files (x86)\Microsoft SQL Server\90\Tools\binn\;C:\Progra
m Files (x86)\Perforce;C:\ProgramFiles\010 Editor;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\ProgramFiles\
Git\cmd;C:\Program Files (x86)\Skype\Phone\
C:\Users\ssfang> echo %^JAVA_HOME% = "%^JAVA_HOME%" = %%JAVA_HOME%% %JAVA_HOME%
%JAVA_HOME% = "%^JAVA_HOME%" = %C:\ProgramFiles\Java\jdk% C:\ProgramFiles\Java\jdk
I found their types of the registry value Path
are different, so I checked whether the path is valid or not by the following command:
C:\Users\ssfang> where node java
C:\ProgramFiles\nodejs\node.exe
INFO: Could not find "java".
As a result, I reset the local (current user) environment by the following commands (Setx):
C:\Users\ssfang> setx PATH %^JAVA_HOME%\bin;"C:\ProgramFiles\nodejs"
SUCCESS: Specified value was saved.
C:\Users\ssfang> reg query HKEY_CURRENT_USER\Environment /v Path
HKEY_CURRENT_USER\Environment
Path REG_EXPAND_SZ %JAVA_HOME%\bin;C:\ProgramFiles\nodejs
C:\Users\ssfang> where node java
C:\ProgramFiles\nodejs\node.exe
INFO: Could not find "java".
C:\Users\ssfang>echo %PATH%
C:\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Fi
les\Intel\DMIX;c:\Program Files (x86)\Microsoft SQL Server\90\Tools\binn\;C:\Program Files (x86)\Perforce;C:\ProgramFile
s\010 Editor;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\ProgramFiles\Git\cmd;C:\Program Files (x86)\Skype\
Phone\;%JAVA_HOME%\bin;C:\ProgramFiles\nodejs
But, in the current process, it cannot propagate those changes to other running processes.
However, if you directly modify user environment variables in the Registry Editor,
those modifications to the environment variables do not result in immediate change. For example, if you start another Command Prompt after making the changes, the environment variables will reflect the previous (not the current) values. The changes do not take effect until you log off and then log back on.
To effect these changes without having to log off, broadcast a WM_SETTINGCHANGE message to all windows in the system, so that any interested applications (such as Windows Explorer, Program Manager, Task Manager, Control Panel, and so forth) can perform an update.
See details at How to propagate environment variables to the system
Here, I give a powershell script to do it:
# powershell -ExecutionPolicy ByPass -File
# Standard, inline approach: (i.e. behaviour you'd get when using & in Linux)
# START /B CMD /C CALL "foo.bat" [args [...]]
# powershell -ExecutionPolicy ByPass -WindowStyle Hidden -File myScript.ps1
<#
Add-Type @'
public class CSharp
{
public static void Method(object[] first, object[] second)
{
System.Console.WriteLine("Hello world");
}
}
'@
$a = 1..4;
[string[]]$b = "a","b","c","d";
[CSharp]::Method($a, $b);
#>
<#
#http://stackoverflow.com/questions/16552801/how-do-i-conditionally-add-a-class-with-add-type-typedefinition-if-it-isnt-add
#Problem Add-Type : Cannot add type. The type name 'PInvoke.User32' already exists.
if (-not ("MyClass" -as [type])) {
add-type @"
public class MyClass { }
"@
}
p.s. there's no Remove-Type; see this answer for more on how to best work around this limitation:
http://stackoverflow.com/questions/3369662/can-you-remove-an-add-ed-type-in-powershell-again
I think it will be wanted when debugging.
It is much simpler to close a tab in Console and open new one in PowerShell_ISE.exe or close PowerShell.exe.
Or
Start-Job -ScriptBlock {
param([uri]$url,$OutputDir)
# download and save pages
Invoke-RestMethod $url | Out-File "$OutputDir\$($url.Segments[-1])" -Force
} -ArgumentList $link,$OutputDir
#>
if (-not ([System.Management.Automation.PSTypeName]'PInvoke.Program').Type)
{
$sig=@"
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Generic;
// The global namespace is the "root" namespace: global::system will always refer to the .NET Framework namespace System.
///P/Invoke (Platform Invoke)
namespace PInvoke
{
public static class User32
{
/// http://www.pinvoke.net/default.aspx/Constants/HWND.html
// public const IntPtr HWND_BROADCAST = new IntPtr(0xffff);
/// https://msdn.microsoft.com/en-us/library/windows/desktop/ms725497(v=vs.85).aspx
/// http://www.pinvoke.net/default.aspx/Constants/WM.html
public const UInt32 WM_SETTINGCHANGE = 0x001A;
// SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM) "Environment", SMTO_ABORTIFHUNG, 5000, &dwReturnValue);
/// https://msdn.microsoft.com/en-us/library/windows/desktop/ms644952(v=vs.85).aspx
/// If the function succeeds, the return value is nonzero.
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SendMessageTimeout", SetLastError = true)]
public static extern uint SendMessageTimeout(IntPtr hWnd, uint Msg, int wParam, string lParam, SendMessageTimeoutFlags fuFlags, uint uTimeout, out int lpdwResult);
}
[Flags]
public enum SendMessageTimeoutFlags : uint
{
SMTO_NORMAL = 0x0,
SMTO_BLOCK = 0x1,
SMTO_ABORTIFHUNG = 0x2,
SMTO_NOTIMEOUTIFNOTHUNG = 0x8,
SMTO_ERRORONEXIT = 0x20
}
public class Program
{
public static void Main(string[] args)
{
//int innerPinvokeResult;
//uint pinvokeResult = User32.SendMessageTimeout(User32.HWND_BROADCAST, User32.WM_SETTINGCHANGE, 0, "Environment", SendMessageTimeoutFlags.SMTO_NORMAL, 1000, out innerPinvokeResult);
Console.WriteLine("Over!!!!!!!!!!!!!!!!!!!!!!!!!");
}
}
}
"@
Add-Type -TypeDefinition $sig
}
## [PInvoke.Program]::Main([IntPtr]::Zero);
$innerPinvokeResult=[int]0
[PInvoke.User32]::SendMessageTimeout([IntPtr]0xffff, [PInvoke.User32]::WM_SETTINGCHANGE, 0, "Environment", [PInvoke.SendMessageTimeoutFlags]::SMTO_NORMAL, 1000, [ref]$innerPinvokeResult);
Setx setx [/s [/u [] [/p []]]] [/m]
/m Specifies to set the variable in the system environment. The default setting is the local environment
I solved it on Centos 7 by using:
sudo yum install libcurl-devel
use the --expression option
grep searchterm myfile.csv | sed --expression='s/replaceme/withthis/g'
Answer for 2015
Sandbox mode is gone.
Proceed to My Apps -> Your App -> Status & Review
and change the slider to yes for:
Do you want to make this app and all its live features available to the general public?
You try to instantiate an object of the Friends
class like this:
Friends f = new Friends(friendsName, friendsAge);
The class does not have a constructor that takes parameters. You should either add the constructor, or create the object using the constructor that does exist and then use the set-methods. For example, instead of the above:
Friends f = new Friends();
f.setName(friendsName);
f.setAge(friendsAge);
Note: This answer is less current than it was when posted in 2009. Using the subprocess
module shown in other answers is now recommended in the docs
(Note that the subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions.)
If you want your process to start in the background you can either use system()
and call it in the same way your shell script did, or you can spawn
it:
import os
os.spawnl(os.P_DETACH, 'some_long_running_command')
(or, alternatively, you may try the less portable os.P_NOWAIT
flag).
See the documentation here.
updated() should be what you're looking for:
Called after a data change causes the virtual DOM to be re-rendered and patched.
The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here.
I have ran into that same problem. I actually developed my using server side programming, but I did a quick search to try and help you out and found this.
Seems alright, didn't look at the source too much, but seems to be purely JavaScript.
Take look:
http://www.rainforestnet.com/datetimepicker/datetimepicker.htm
Here is the demo page link:
http://www.rainforestnet.com/datetimepicker/datetimepicker-demo.htm
good luck
You don't really need to do it all in jQuery to do that smoothly. Do it like this:
$(".nextbutton").click(function() {
document.forms["form1"].submit();
});
Along with JFileChooser is possible use this:
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
for have a Look and Feel like Windows.
for others settings, view here: https://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html#available
place jakarta and delete javax
if you download servlet.api.jar :
NOTICE : this answer every time is not correct ( can be javax in JEE )
Correct
jakarta.servlet.*;
Incorrect
javax.servlet.*;
else :
place jar files into JAVA_HOME/jre/lib/ext
You have to add the row explicitly to the table
table.Rows.Add(row);
I suggest you to look at this highly rated blog post which manages to give a solution to the problem you're facing :
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emulator.html
His code is based on the current Android APIs and should work in your case given that you are using a recent Android API.
Here's extension method to convert DataTable to object list:
public static class Extensions
{
public static List<T> ToList<T>(this DataTable table) where T : new()
{
IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
List<T> result = new List<T>();
foreach (var row in table.Rows)
{
var item = CreateItemFromRow<T>((DataRow)row, properties);
result.Add(item);
}
return result;
}
private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
{
T item = new T();
foreach (var property in properties)
{
if (property.PropertyType == typeof(System.DayOfWeek))
{
DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), row[property.Name].ToString());
property.SetValue(item,day,null);
}
else
{
if(row[property.Name] == DBNull.Value)
property.SetValue(item, null, null);
else
property.SetValue(item, row[property.Name], null);
}
}
return item;
}
}
usage:
List<Employee> lst = ds.Tables[0].ToList<Employee>();
@itay.b
CODE EXPLAINED:
We first read all the property names from the class T using reflection
then we iterate through all the rows in datatable and create new object of T,
then we set the properties of the newly created object using reflection.
The property values are picked from the row's matching column cell.
PS: class property name and table column names must be same
Try this, it's simple and clear. I have found it from here : https://css-tricks.com/tinted-images-multiple-backgrounds/
.tinted-image {
width: 300px;
height: 200px;
background:
/* top, transparent red */
linear-gradient(
rgba(255, 0, 0, 0.45),
rgba(255, 0, 0, 0.45)
),
/* bottom, image */
url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/owl1.jpg);
}
How to specify the JDK version?
Use any of three ways: (1) Spring Boot feature, or use Maven compiler plugin with either (2) source
& target
or (3) with release
.
<java.version>
is not referenced in the Maven documentation.
It is a Spring Boot specificity.
It allows to set the source and the target java version with the same version such as this one to specify java 1.8 for both :
Feel free to use it if you use Spring Boot.
maven-compiler-plugin
with source
& target
maven-compiler-plugin
or maven.compiler.source
/maven.compiler.target
properties are equivalent.That is indeed :
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
is equivalent to :
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
according to the Maven documentation of the compiler plugin
since the <source>
and the <target>
elements in the compiler configuration use the properties maven.compiler.source
and maven.compiler.target
if they are defined.
The
-source
argument for the Java compiler.
Default value is:1.6
.
User property is:maven.compiler.source
.
The
-target
argument for the Java compiler.
Default value is:1.6
.
User property is:maven.compiler.target
.
About the default values for source
and target
, note that
since the 3.8.0
of the maven compiler, the default values have changed from 1.5
to 1.6
.
maven-compiler-plugin
with release
instead of source
& target
The maven-compiler-plugin 3.6
and later versions provide a new way :
You could also declare just :
<properties>
<maven.compiler.release>9</maven.compiler.release>
</properties>
But at this time it will not work as the maven-compiler-plugin
default version you use doesn't rely on a recent enough version.
The Maven release
argument conveys release
: a new JVM standard option that we could pass from Java 9 :
Compiles against the public, supported and documented API for a specific VM version.
This way provides a standard way to specify the same version for the source
, the target
and the bootstrap
JVM options.
Note that specifying the bootstrap
is a good practice for cross compilations and it will not hurt if you don't make cross compilations either.
Which is the best way to specify the JDK version?
The first way (<java.version>
) is allowed only if you use Spring Boot.
For Java 8 and below :
About the two other ways : valuing the maven.compiler.source
/maven.compiler.target
properties or using the maven-compiler-plugin
, you can use one or the other. It changes nothing in the facts since finally the two solutions rely on the same properties and the same mechanism : the maven core compiler plugin.
Well, if you don't need to specify other properties or behavior than Java versions in the compiler plugin, using this way makes more sense as this is more concise:
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
From Java 9 :
The release
argument (third point) is a way to strongly consider if you want to use the same version for the source and the target.
What happens if the version differs between the JDK in JAVA_HOME and which one specified in the pom.xml?
It is not a problem if the JDK referenced by the JAVA_HOME
is compatible with the version specified in the pom but to ensure a better cross-compilation compatibility think about adding the bootstrap
JVM option with as value the path of the rt.jar
of the target
version.
An important thing to consider is that the source
and the target
version in the Maven configuration should not be superior to the JDK version referenced by the JAVA_HOME
.
A older version of the JDK cannot compile with a more recent version since it doesn't know its specification.
To get information about the source, target and release supported versions according to the used JDK, please refer to java compilation : source, target and release supported versions.
How handle the case of JDK referenced by the JAVA_HOME is not compatible with the java target and/or source versions specified in the pom?
For example, if your JAVA_HOME
refers to a JDK 1.7 and you specify a JDK 1.8 as source and target in the compiler configuration of your pom.xml, it will be a problem because as explained, the JDK 1.7 doesn't know how to compile with.
From its point of view, it is an unknown JDK version since it was released after it.
In this case, you should configure the Maven compiler plugin to specify the JDK in this way :
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerVersion>1.8</compilerVersion>
<fork>true</fork>
<executable>D:\jdk1.8\bin\javac</executable>
</configuration>
</plugin>
You could have more details in examples with maven compiler plugin.
It is not asked but cases where that may be more complicated is when you specify source but not target. It may use a different version in target according to the source version. Rules are particular : you can read about them in the Cross-Compilation Options part.
Why the compiler plugin is traced in the output at the execution of the Maven package
goal even if you don't specify it in the pom.xml?
To compile your code and more generally to perform all tasks required for a maven goal, Maven needs tools. So, it uses core Maven plugins (you recognize a core Maven plugin by its groupId
: org.apache.maven.plugins
) to do the required tasks : compiler plugin for compiling classes, test plugin for executing tests, and so for... So, even if you don't declare these plugins, they are bound to the execution of the Maven lifecycle.
At the root dir of your Maven project, you can run the command : mvn help:effective-pom
to get the final pom effectively used. You could see among other information, attached plugins by Maven (specified or not in your pom.xml), with the used version, their configuration and the executed goals for each phase of the lifecycle.
In the output of the mvn help:effective-pom
command, you could see the declaration of these core plugins in the <build><plugins>
element, for example :
...
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>2.5</version>
<executions>
<execution>
<id>default-clean</id>
<phase>clean</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>default-testResources</id>
<phase>process-test-resources</phase>
<goals>
<goal>testResources</goal>
</goals>
</execution>
<execution>
<id>default-resources</id>
<phase>process-resources</phase>
<goals>
<goal>resources</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<executions>
<execution>
<id>default-compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>default-testCompile</id>
<phase>test-compile</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
...
You can have more information about it in the introduction of the Maven lifeycle in the Maven documentation.
Nevertheless, you can declare these plugins when you want to configure them with other values as default values (for example, you did it when you declared the maven-compiler plugin in your pom.xml to adjust the JDK version to use) or when you want to add some plugin executions not used by default in the Maven lifecycle.
It is Possible to add Multiple Get and Post methods in the same Web API Controller. Here default Route is Causing the Issue. Web API checks for Matching Route from Top to Bottom and Hence Your Default Route Matches for all Requests. As per default route only one Get and Post Method is possible in one controller. Either place the following code on top or Comment Out/Delete Default Route
config.Routes.MapHttpRoute("API Default",
"api/{controller}/{action}/{id}",
new { id = RouteParameter.Optional });
In Wordpress jQuery.noConflict()
is called on the jQuery file it includes (scroll to the bottom of the file it's including for jQuery to see this), which means $
doesn't work, but jQuery
does, so your code should look like this:
<script type="text/javascript">
jQuery(function($) {
for(var i=0; i <= 20; i++)
$("ol li:nth-child(" + i + ")").addClass('olli' + i);
});
</script>
As of today I still find the Ahead-of-Time Compilation cookbook as the best recipe for production bundling. You can find it here: https://angular.io/docs/ts/latest/cookbook/aot-compiler.html
My experience with Angular 2 so far is that AoT creates the smallest builds with almost no loading time. And most important as the question here is about - you only need to ship a few files to production.
This seems to be because the Angular compiler will not be shipped with the production builds as the templates are compiled "Ahead of Time". It's also very cool to see your HTML template markup transformed to javascript instructions that would be very hard to reverse engineer into the original HTML.
I've made a simple video where I demonstrate download size, number of files etc. for an Angular 2 app in dev vs AoT build - which you can see here:
You'll find the source code used in the video here:
from selenium import webdriver
from selenium.webdriver.common.proxy import *
myProxy = "86.111.144.194:3128"
proxy = Proxy({
'proxyType': ProxyType.MANUAL,
'httpProxy': myProxy,
'ftpProxy': myProxy,
'sslProxy': myProxy,
'noProxy':''})
driver = webdriver.Firefox(proxy=proxy)
driver.set_page_load_timeout(30)
driver.get('http://whatismyip.com')
As it is written in the documentation you have to change the cell type to a markdown.
Git 1.8.2 features a new option ,--remote
, that will enable exactly this behavior. Running
git submodule update --rebase --remote
will fetch the latest changes from upstream in each submodule, rebase them, and check out the latest revision of the submodule. As the documentation puts it:
--remote
This option is only valid for the update command. Instead of using the superproject’s recorded SHA-1 to update the submodule, use the status of the submodule’s remote-tracking branch.
This is equivalent to running git pull
in each submodule, which is generally exactly what you want.
(This was copied from this answer.)
Also had this issue, This array was out of range:
order: [1, 'asc'],
You should not use space character while naming database objects. Even though it's possible by using double quotes(quoted identifiers), CREATE TABLE "chartered flight" ...
, it's not recommended. Take a closer look here
Try this:
<?php
/*
Template Name: [contact us]
*/
get_header();
echo do_shortcode('[CONTACT-US-FORM]');
?>
The Nan example above misses one piece, which makes it less generic. To do this more "generically" use df['column_name'].value_counts()
This will give you the counts of each value in that column.
d=['A','A','A','B','C','C'," " ," "," "," "," ","-1"] # for simplicity
df=pd.DataFrame(d)
df.columns=["col1"]
df["col1"].value_counts()
5
A 3
C 2
-1 1
B 1
dtype: int64
"""len(df) give you 12, so we know the rest must be Nan's of some form, while also having a peek into other invalid entries, especially when you might want to ignore them like -1, 0 , "", also"""
getimagesize('image.jpg')
function works only if allow_url_fopen
is set to 1 or On inside php.ini file on the server,
if it is not enabled, one should use
ini_set('allow_url_fopen',1);
on top of the file where getimagesize() function is used.
The settings file is never created automatically, you must create it yourself, whether you use embedded or "real" maven.
Create it at the following location <your home folder>/.m2/settings.xml
e.g. C:\Users\YourUserName\.m2\settings.xml
on Windows or /home/YourUserName/.m2/settings.xml
on Linux
Here's an empty skeleton you can use:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository/>
<interactiveMode/>
<usePluginRegistry/>
<offline/>
<pluginGroups/>
<servers/>
<mirrors/>
<proxies/>
<profiles/>
<activeProfiles/>
</settings>
If you use Eclipse to edit it, it will give you auto-completion when editing it.
And here's the Maven settings.xml Reference page
If you are using spring-boot, this is the best answer.
I feel that @PostConstruct
and other various life cycle interjections are round-about ways. These can lead directly to runtime issues or cause less than obvious defects due to unexpected bean/context lifecycle events. Why not just directly invoke your bean using plain Java? You still invoke the bean the 'spring way' (eg: through the spring AoP proxy). And best of all, it's plain java, can't get any simpler than that. No need for context listeners or odd schedulers.
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext app = SpringApplication.run(DemoApplication.class, args);
MyBean myBean = (MyBean)app.getBean("myBean");
myBean.invokeMyEntryPoint();
}
}
Try add min-width: 100%
to style of your textarea:
<textarea class="form-control" style="min-width: 100%"></textarea>
If you're not using a remote repository (like artifactory), use plain old:
mvn clean install
Pretty old topic but AFAIK, if you run your own repository (eg: with artifactory) to share jar among your team(s), you might want to use
mvn clean deploy
instead.
This way, your continuous integration server can be sure that all dependencies are correctly pushed into your remote repository. If you missed one, mvn will not be able to find it into your CI local m2 repository.
A method based on np.split
:
df = pd.DataFrame({ 'A':[2,4,6,8,10,2,4,6,8,10],
'B':[10,-10,0,20,-10,10,-10,0,20,-10],
'C':[4,12,8,0,0,4,12,8,0,0],
'D':[9,10,0,1,3,np.nan,np.nan,np.nan,np.nan,np.nan]})
listOfDfs = [df.loc[idx] for idx in np.split(df.index,5)]
A small function that uses a modulo could take care of cases where the split is not even (e.g. np.split(df.index,4)
will throw an error).
(Yes, I am aware that the original question was somewhat more specific than this. However, this is supposed to answer the question in the title.)
If i have understood correct then it is one line of code .It worked for me .
Collections.reverse(yourList);
It is better to avoid writing out temporary spool files. Use a PL/SQL block. You can run this from SQL*Plus or put this thing into a package or procedure. The join to USER_TABLES is there to avoid view constraints.
It's unlikely that you really want to disable all constraints (including NOT NULL, primary keys, etc). You should think about putting constraint_type in the WHERE clause.
BEGIN
FOR c IN
(SELECT c.owner, c.table_name, c.constraint_name
FROM user_constraints c, user_tables t
WHERE c.table_name = t.table_name
AND c.status = 'ENABLED'
AND NOT (t.iot_type IS NOT NULL AND c.constraint_type = 'P')
ORDER BY c.constraint_type DESC)
LOOP
dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" disable constraint ' || c.constraint_name);
END LOOP;
END;
/
Enabling the constraints again is a bit tricker - you need to enable primary key constraints before you can reference them in a foreign key constraint. This can be done using an ORDER BY on constraint_type. 'P' = primary key, 'R' = foreign key.
BEGIN
FOR c IN
(SELECT c.owner, c.table_name, c.constraint_name
FROM user_constraints c, user_tables t
WHERE c.table_name = t.table_name
AND c.status = 'DISABLED'
ORDER BY c.constraint_type)
LOOP
dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" enable constraint ' || c.constraint_name);
END LOOP;
END;
/
sudo nginx -t
should test all files and return errors and warnings locations
Use a JSON parser, like JSON.NET
string json = "{ \"Atlantic/Canary\": \"GMT Standard Time\", \"Europe/Lisbon\": \"GMT Standard Time\", \"Antarctica/Mawson\": \"West Asia Standard Time\", \"Etc/GMT+3\": \"SA Eastern Standard Time\", \"Etc/GMT+2\": \"UTC-02\", \"Etc/GMT+1\": \"Cape Verde Standard Time\", \"Etc/GMT+7\": \"US Mountain Standard Time\", \"Etc/GMT+6\": \"Central America Standard Time\", \"Etc/GMT+5\": \"SA Pacific Standard Time\", \"Etc/GMT+4\": \"SA Western Standard Time\", \"Pacific/Wallis\": \"UTC+12\", \"Europe/Skopje\": \"Central European Standard Time\", \"America/Coral_Harbour\": \"SA Pacific Standard Time\", \"Asia/Dhaka\": \"Bangladesh Standard Time\", \"America/St_Lucia\": \"SA Western Standard Time\", \"Asia/Kashgar\": \"China Standard Time\", \"America/Phoenix\": \"US Mountain Standard Time\", \"Asia/Kuwait\": \"Arab Standard Time\" }";
var data = (JObject)JsonConvert.DeserializeObject(json);
string timeZone = data["Atlantic/Canary"].Value<string>();
The image needs to be in the same folder that your html page is in, then create a href to that folder with the picture name at the end. Example:
<img src="C:\users\home\pictures\picture.png"/>
Perhaps this example could explain.
CREATE TABLE `test`(`fla` FLOAT,`flb` FLOAT,`dba` DOUBLE(10,2),`dbb` DOUBLE(10,2));
We have a table like this:
+-------+-------------+
| Field | Type |
+-------+-------------+
| fla | float |
| flb | float |
| dba | double(10,2)|
| dbb | double(10,2)|
+-------+-------------+
For first difference, we try to insert a record with '1.2' to each field:
INSERT INTO `test` values (1.2,1.2,1.2,1.2);
The table showing like this:
SELECT * FROM `test`;
+------+------+------+------+
| fla | flb | dba | dbb |
+------+------+------+------+
| 1.2 | 1.2 | 1.20 | 1.20 |
+------+------+------+------+
See the difference?
We try to next example:
SELECT fla+flb, dba+dbb FROM `test`;
Hola! We can find the difference like this:
+--------------------+---------+
| fla+flb | dba+dbb |
+--------------------+---------+
| 2.4000000953674316 | 2.40 |
+--------------------+---------+
Fixed positioning will do what you need:
#main
{
position:fixed;
top:0px;
bottom:0px;
left:0px;
right:0px;
}
Modulus, in modular arithmetic as you're referring, is the value left over or remaining value after arithmetic division. This is commonly known as remainder. % is formally the remainder operator in C / C++. Example:
7 % 3 = 1 // dividend % divisor = remainder
What's left for discussion is how to treat negative inputs to this % operation. Modern C and C++ produce a signed remainder value for this operation where the sign of the result always matches the dividend input without regard to the sign of the divisor input.
ytd2
is a fully functional YouTube video downloader. Check out its source code if you want to see how it's done.
Alternatively, you can also call an external process like youtube-dl
to do the job. This is probably the easiest solution but it isn't in "pure" Java.
As far as I'm aware this isn't possible with HTML and CSS.
Quicksort is in place. You need very little extra memory. Which is extremely important.
Good choice of median makes it even more efficient but even a bad choice of median quarantees Theta(nlogn).
stdout is the standard output file stream. Obviously, it's first and default pointer to output is the screen, however you can point it to a file as desired!
Please read:
http://www.cplusplus.com/reference/cstdio/stdout/
C++ is very similar to C however, object oriented.
var inputs = events.Select(async ev => await ProcessEventAsync(ev))
.Select(t => t.Result)
.Where(i => i != null)
.ToList();
But this seems very weird to me, first of all the use of async and await in the select. According to this answer by Stephen Cleary I should be able to drop those.
The call to Select
is valid. These two lines are essentially identical:
events.Select(async ev => await ProcessEventAsync(ev))
events.Select(ev => ProcessEventAsync(ev))
(There's a minor difference regarding how a synchronous exception would be thrown from ProcessEventAsync
, but in the context of this code it doesn't matter at all.)
Then the second Select which selects the result. Doesn't this mean the task isn't async at all and is performed synchronously (so much effort for nothing), or will the task be performed asynchronously and when it's done the rest of the query is executed?
It means that the query is blocking. So it is not really asynchronous.
Breaking it down:
var inputs = events.Select(async ev => await ProcessEventAsync(ev))
will first start an asynchronous operation for each event. Then this line:
.Select(t => t.Result)
will wait for those operations to complete one at a time (first it waits for the first event's operation, then the next, then the next, etc).
This is the part I don't care for, because it blocks and also would wrap any exceptions in AggregateException
.
and is it completely the same like this?
var tasks = await Task.WhenAll(events.Select(ev => ProcessEventAsync(ev)));
var inputs = tasks.Where(result => result != null).ToList();
var inputs = (await Task.WhenAll(events.Select(ev => ProcessEventAsync(ev))))
.Where(result => result != null).ToList();
Yes, those two examples are equivalent. They both start all asynchronous operations (events.Select(...)
), then asynchronously wait for all the operations to complete in any order (await Task.WhenAll(...)
), then proceed with the rest of the work (Where...
).
Both of these examples are different from the original code. The original code is blocking and will wrap exceptions in AggregateException
.
If you frequently use a large number of exceptions, you can pre-define a tuple, so you don't have to re-type them many times.
#This example code is a technique I use in a library that connects with websites to gather data
ConnectErrs = (URLError, SSLError, SocketTimeoutError, BadStatusLine, ConnectionResetError)
def connect(url, data):
#do connection and return some data
return(received_data)
def some_function(var_a, var_b, ...):
try: o = connect(url, data)
except ConnectErrs as e:
#do the recovery stuff
blah #do normal stuff you would do if no exception occurred
NOTES:
If you, also, need to catch other exceptions than those in the pre-defined tuple, you will need to define another except block.
If you just cannot tolerate a global variable, define it in main() and pass it around where needed...
Not gonna happen with CSS only
Inline javascript
<a href='index.html'
onmouseover='this.style.textDecoration="none"'
onmouseout='this.style.textDecoration="underline"'>
Click Me
</a>
In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:
<a href="http://www.w3.org/Style/CSS"
style="{color: blue; background: white} /* a+=0 b+=0 c+=0 */
:visited {color: green} /* a+=0 b+=1 c+=0 */
:hover {background: yellow} /* a+=0 b+=1 c+=0 */
:visited:hover {color: purple} /* a+=0 b+=2 c+=0 */
">
</a>
but it was never implemented in the release of the spec as far as I know.
http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules
If you have already installed app on your device, try to change bundle identifer on the web .plist (not app plist) with something else like "com.vistair.docunet-test2", after that refresh webpage and try to reinstall... It works for me
From the official site: phantomjs site
sudo apt-get install build-essential chrpath git-core libssl-dev libfontconfig1-dev
git clone git://github.com/ariya/phantomjs.git
cd phantomjs
git checkout 1.8
./build.sh
Make sure you start your application in Debug mode (F5), not without debugging (Ctrl+F5) and then select "Show output from: Debug" in the Output panel in Visual Studio.
Use import scala.collection.mutable.MutableList or similar if you really need mutation.
import scala.collection.mutable.MutableList
val x = MutableList(1, 2, 3, 4, 5)
x += 6 // MutableList(1, 2, 3, 4, 5, 6)
x ++= MutableList(7, 8, 9) // MutableList(1, 2, 3, 4, 5, 6, 7, 8, 9)
Actually, I did not want to be dependent of anything else but Python (Cairo, Ink.., etc.)
My requirements were to be as simple as possible, at most, a simple pip install "savior"
would suffice, that's why any of those above didn't suit for me.
I came through this (going further than Stackoverflow on the research). https://www.tutorialexample.com/best-practice-to-python-convert-svg-to-png-with-svglib-python-tutorial/
Looks good, so far. So I share it in case anyone in the same situation.
Create a block using
#define MACRO(...) do { ... } while(false)
Do not add a ; after the while(false)
You can remove the entire line below:
.map((res: Response) => res.json());
No need to use the map method at all.
System properties are set on the Java command line using the -Dpropertyname=value
syntax. They can also be added at runtime
using System.setProperty(String key, String value)
or via the various
System.getProperties().load()
methods.
To get a specific system property you can use System.getProperty(String key)
or System.getProperty(String key, String def)
.
Environment variables are set in the OS, e.g. in Linux export HOME=/Users/myusername
or on Windows SET WINDIR=C:\Windows
etc,
and, unlike properties, may not be set at runtime.
To get a specific environment variable you can use System.getenv(String name)
.
I implemented something like this, using pickle for persistance and using sha1 for short almost-certainly-unique IDs. Basically the cache hashed the code of the function and the hist of arguments to get a sha1 then looked for a file with that sha1 in the name. If it existed, it opened it and returned the result; if not, it calls the function and saves the result (optionally only saving if it took a certain amount of time to process).
That said, I'd swear I found an existing module that did this and find myself here trying to find that module... The closest I can find is this, which looks about right: http://chase-seibert.github.io/blog/2011/11/23/pythondjango-disk-based-caching-decorator.html
The only problem I see with that is it wouldn't work well for large inputs since it hashes str(arg), which isn't unique for giant arrays.
It would be nice if there were a unique_hash() protocol that had a class return a secure hash of its contents. I basically manually implemented that for the types I cared about.
You can also run arbitrary commands using the Groovy Post Build - and that will give you a lot of control over when they run and so forth. We use that to run a 'finger of blame' shell script in the case of failed or unstable builds.
if (manager.build.result.isWorseThan(hudson.model.Result.SUCCESS)) {
item = hudson.model.Hudson.instance.getItem("PROJECTNAMEHERE")
lastStableBuild = item.getLastStableBuild()
lastStableDate = lastStableBuild.getTime()
formattedLastStableDate = lastStableDate.format("MM/dd/yyyy h:mm:ss a")
now = new Date()
formattedNow = now.format("MM/dd/yyyy h:mm:ss a")
command = ['/appframe/jenkins/appframework/fob.ksh', "${formattedLastStableDate}", "${formattedNow}"]
manager.listener.logger.println "FOB Command: ${command}"
manager.listener.logger.println command.execute().text
}
(Our command takes the last stable build date and the current time as parameters so it can go investigate who might have broken the build, but you could run whatever commands you like in a similar fashion)
Looks like people are saying to use str.isalpha
.
This is the one line function to check if all characters are letters.
def only_letters(string):
return all(letter.isalpha() for letter in string)
all
accepts an iterable of booleans, and returns True
iff all of the booleans are True
.
More generally, all
returns True
if the objects in your iterable would be considered True
. These would be considered False
None
len(list) == 0
)False
. (duh)It seems your makefile didn't include the appropriate .so
file. You can correct this problem with the steps below:
sqlite-devel
(or libsqlite3-dev
on some Debian-based systems)./configure --enable-loadable-sqlite-extensions && make && sudo make install
Note
The sudo make install
part will set that python version to be the system-wide standard, which can have unforseen consequences. If you run this command on your workstation, you'll probably want to have it installed alongside the existing python, which can be done with sudo make altinstall
.
In my case, i was calling twice the import...
@click="$router.push({ path: 'searcherresult' })"
import SearcherResult from "../views/SearcherResult"; --- ERROR
Cause i call in other component...
I konw it's an old thread but I have found something interesting from the official site of python. Just for sharing another idea for removing of all contents in a directory. Because I have some problems of authorization when using shutil.rmtree() and I don't want to remove the directory and recreate it. The address original is http://docs.python.org/2/library/os.html#os.walk. Hope that could help someone.
def emptydir(top):
if(top == '/' or top == "\\"): return
else:
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
process.env.ENV_VARIABLE
Where ENV_VARIABLE
is the name of the variable you wish to access.
||
and &&
bind with the precedence that you expect from boolean operators in programming languages (&&
is very strong, ||
is slightly less strong).
and
and or
have lower precedence.
For example, unlike ||
, or
has lower precedence than =
:
> a = false || true
=> true
> a
=> true
> a = false or true
=> true
> a
=> false
Likewise, unlike &&
, and
also has lower precedence than =
:
> a = true && false
=> false
> a
=> false
> a = true and false
=> false
> a
=> true
What's more, unlike &&
and ||
, and
and or
bind with equal precedence:
> !puts(1) || !puts(2) && !puts(3)
1
=> true
> !puts(1) or !puts(2) and !puts(3)
1
3
=> true
> !puts(1) or (!puts(2) and !puts(3))
1
=> true
The weakly-binding and
and or
may be useful for control-flow purposes: see http://devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby/ .
Try this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<title>Untitled Document</title>_x000D_
<style type="text/css">_x000D_
.OutlineText {_x000D_
font: Tahoma, Geneva, sans-serif;_x000D_
font-size: 64px;_x000D_
color: white;_x000D_
text-shadow:_x000D_
/* Outline */_x000D_
-1px -1px 0 #000000,_x000D_
1px -1px 0 #000000,_x000D_
-1px 1px 0 #000000,_x000D_
1px 1px 0 #000000, _x000D_
-2px 0 0 #000000,_x000D_
2px 0 0 #000000,_x000D_
0 2px 0 #000000,_x000D_
0 -2px 0 #000000; /* Terminate with a semi-colon */_x000D_
}_x000D_
</style></head>_x000D_
_x000D_
<body>_x000D_
<div class="OutlineText">Hello world!</div>_x000D_
</body>_x000D_
</html>
_x000D_
...and you might also want to do this too:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<title>Untitled Document</title>_x000D_
<style type="text/css">_x000D_
.OutlineText {_x000D_
font: Tahoma, Geneva, sans-serif;_x000D_
font-size: 64px;_x000D_
color: white;_x000D_
text-shadow:_x000D_
/* Outline 1 */_x000D_
-1px -1px 0 #000000,_x000D_
1px -1px 0 #000000,_x000D_
-1px 1px 0 #000000,_x000D_
1px 1px 0 #000000, _x000D_
-2px 0 0 #000000,_x000D_
2px 0 0 #000000,_x000D_
0 2px 0 #000000,_x000D_
0 -2px 0 #000000, _x000D_
/* Outline 2 */_x000D_
-2px -2px 0 #ff0000,_x000D_
2px -2px 0 #ff0000,_x000D_
-2px 2px 0 #ff0000,_x000D_
2px 2px 0 #ff0000, _x000D_
-3px 0 0 #ff0000,_x000D_
3px 0 0 #ff0000,_x000D_
0 3px 0 #ff0000,_x000D_
0 -3px 0 #ff0000; /* Terminate with a semi-colon */_x000D_
}_x000D_
</style></head>_x000D_
_x000D_
<body>_x000D_
<div class="OutlineText">Hello world!</div>_x000D_
</body>_x000D_
</html>
_x000D_
You can do as many Outlines as you like, and there's enough scope for coming up with lots of creative ideas.
Have fun!
For visualization our group had some success with prefuse. We extended it to handle architectural floorplates and bubble diagraming, and it didn't complain too much. They have a new Flex toolkit out too called Flare that uses a very similar API.
UPDATE: I'd have to agree with the comment, we ended up writing a lot of custom functionality/working around prefuse limitations. I can't say that starting from scratch would have been better though as we were able to demonstrate progress from day 1 by using prefuse. On the other hand if we were doing a second implementation of the same stuff, I might skip prefuse since we'd understand the requirements a lot better.
In many situations, a custom attribute attached to a pd.DataFrame
object is not necessary. In addition, note that pandas
-object attributes may not serialize. So pickling will lose this data.
Instead, consider creating a dictionary with appropriately named keys and access the dataframe via dfs['some_label']
.
df = pd.DataFrame()
dfs = {'some_label': df}
No one has mentioned the obvious:
var myCallback = function() { console.log("name or age changed"); };
$scope.$watch("name", myCallback);
$scope.$watch("age", myCallback);
This might mean a little less polling. If you watch both name + age
(for this) and name
(elsewhere) then I assume Angular will effectively look at name
twice to see if it's dirty.
It's arguably more readable to use the callback by name instead of inlining it. Especially if you can give it a better name than in my example.
And you can watch the values in different ways if you need to:
$scope.$watch("buyers", myCallback, true);
$scope.$watchCollection("sellers", myCallback);
$watchGroup
is nice if you can use it, but as far as I can tell, it doesn't let you watch the group members as a collection or with object equality.
If you need the old and new values of both expressions inside one and the same callback function call, then perhaps some of the other proposed solutions are more convenient.
For Windows you could use msvcrt
like this:
import msvcrt
while True:
if msvcrt.kbhit():
key = msvcrt.getch()
print(key) # just to show the result
From a theoretical point of view, the most elegant way of doing it, in my humble opinion, is to get a single random number between 0 and n!-1 and to compute a one to one mapping from {0, 1, …, n!-1}
to all permutations of (0, 1, 2, …, n-1)
. As long as you can use a (pseudo-)random generator reliable enough for getting such a number without any significant bias, you have enough information in it for achieving what you want without needing several other random numbers.
When computing with IEEE754 double precision floating numbers, you can expect your random generator to provide about 15 decimals. Since you have 15!=1,307,674,368,000 (with 13 digits), you can use the following functions with arrays containing up to 15 elements and assume there will be no significant bias with arrays containing up to 14 elements. If you work on a fixed-size problem requiring to compute many times this shuffle operation, you may want to try the following code which may be faster than other codes since it uses Math.random
only once (it involves several copy operations however).
The following function will not be used, but I give it anyway; it returns the index of a given permutation of (0, 1, 2, …, n-1)
according to the one to one mapping used in this message (the most natural one when enumerating permuations); it is intended to work with up to 16 elements:
function permIndex(p) {
var fact = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000];
var tail = [];
var i;
if (p.length == 0) return 0;
for(i=1;i<(p.length);i++) {
if (p[i] > p[0]) tail.push(p[i]-1);
else tail.push(p[i]);
}
return p[0] * fact[p.length-1] + permIndex(tail);
}
The reciprocal of the previous function (required for your own question) is below; it is intended to work with up to 16 elements; it returns the permutation of order n of (0, 1, 2, …, s-1)
:
function permNth(n, s) {
var fact = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000];
var i, j;
var p = [];
var q = [];
for(i=0;i<s;i++) p.push(i);
for(i=s-1; i>=0; i--) {
j = Math.floor(n / fact[i]);
n -= j*fact[i];
q.push(p[j]);
for(;j<i;j++) p[j]=p[j+1];
}
return q;
}
Now, what you want merely is:
function shuffle(p) {
var fact = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000, 20922789888000];
return permNth(Math.floor(Math.random()*fact[p.length]), p.length).map(
function(i) { return p[i]; });
}
It should work for up to 16 elements with a little theoretical bias (though unnoticeable from a practical point of view); it can be seen as fully usable for 15 elements; with arrays containing less than 14 elements, you can safely consider there will be absolutely no bias.
Abstraction
Abstraction is an act of representing essentail details without including the background details. A abstract class have only method signatures and implementing class can have its own implementation, in this way the complex details will be hidden from the user. Abstraction focuses on the outside view. In otherwords, Abstraction is sepration of interfaces from the actual implementation.
Encapsulation
Encapsulation explains binding the data members and methods into a single unit. Information hiding is the main purpose of encapsulation. Encapsulation is acheived by using access specifiers like private, public, protected. Class member variables are made private so that they cann't be accessible directly to outside world. Encapsulation focuses on the inner view. In otherwords, Encapsulation is a technique used to protect the information in an object from the other object.
You could use the following. It supports Bootstrap 3.x above.
<img src="..." alt="..." class="img-responsive center-block" />
Install file loader first:
$ npm install file-loader --save-dev
And add this rule in webpack.config.js
{
test: /\.(png|jpg|gif)$/,
use: [{
loader: 'file-loader',
options: {}
}]
}
You can't see this method in javadoc because it's added by the compiler.
Documented in three places :
The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type.
Enum.valueOf
classvalues
method is mentioned in description of valueOf
method)All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type.
The values
function simply list all values of the enumeration.
For me none of the above solutions worked. Instead i do following steps that solved the issue :
Note : This is checked on Redmi MIUI Global 8.5 version.
This solution will specifically solve the issue if you have recently logged out of Mi account & again logged in.
Hope it may help someone.
Here's something that will do what you'd want when using a string array for the ChildPath.
$path = "C:"
@( "Program Files", "Microsoft Office" ) | %{ $path = Join-Path $path $_ }
Write-Host $path
Which outputs
C:\Program Files\Microsoft Office
The only caveat I found is that the initial value for $path must have a value (cannot be null or empty).
The standalone
declaration is a way of telling the parser to ignore any markup declarations in the DTD. The DTD is thereafter used for validation only.
As an example, consider the humble <img>
tag. If you look at the XHTML 1.0 DTD, you see a markup declaration telling the parser that <img>
tags must be EMPTY and possess src
and alt
attributes. When a browser is going through an XHTML 1.0 document and finds an <img>
tag, it should notice that the DTD requires src
and alt
attributes and add them if they are not present. It will also self-close the <img>
tag since it is supposed to be EMPTY. This is what the XML specification means by "markup declarations can affect the content of the document." You can then use the standalone
declaration to tell the parser to ignore these rules.
Whether or not your parser actually does this is another question, but a standards-compliant validating parser (like a browser) should.
Note that if you do not specify a DTD, then the standalone declaration "has no meaning," so there's no reason to use it unless you also specify a DTD.
Use shuf
with the -n
option as shown below, to get N
random lines:
shuf -n N input > output
This could be related to one of the bugs in JDK 6 Update 14, as indicated in the release notes for JDK 6 update 15.
If this indeed turns out to be the issue, you should move to a higher version of the JDK (that's no guarantee though, since fixes have been released against 6u16, 6u18 and 7b1). The best bet is to use -XX:+UseParallelGC flag. Increasing the size of the minimum and maximum heap size, to delay the first GC, bring temporary relief.
By the way, use this bug report in Eclipse to track how others have been faring.
You can make it even simplier, if you want to avoid extra structures.
service:
mappings:
key1: value1
key2: value2
@Configuration
@EnableConfigurationProperties
public class ServiceConfigurationProperties {
@Bean
@ConfigurationProperties(prefix = "service.mappings")
public Map<String, String> serviceMappings() {
return new HashMap<>();
}
}
And then use it as usual, for example with a constructor:
public class Foo {
private final Map<String, String> serviceMappings;
public Foo(Map<String, String> serviceMappings) {
this.serviceMappings = serviceMappings;
}
}
It could be something like:
var qry = from t in db.Lasttraces
group t by t.AccountId into g
orderby t.Date
select new { g.AccountId, Date = g.Max(e => e.Date) };
Its a bit late to anwser, but I hope my answer been useful for someone, who needs to select Composite foreign keys.
SELECT
"C"."CONSTRAINT_NAME",
"C"."OWNER" AS "SCHEMA_NAME",
"C"."TABLE_NAME",
"COL"."COLUMN_NAME",
"REF_COL"."OWNER" AS "REF_SCHEMA_NAME",
"REF_COL"."TABLE_NAME" AS "REF_TABLE_NAME",
"REF_COL"."COLUMN_NAME" AS "REF_COLUMN_NAME"
FROM
"USER_CONSTRAINTS" "C"
INNER JOIN "USER_CONS_COLUMNS" "COL" ON "COL"."OWNER" = "C"."OWNER"
AND "COL"."CONSTRAINT_NAME" = "C"."CONSTRAINT_NAME"
INNER JOIN "USER_CONS_COLUMNS" "REF_COL" ON "REF_COL"."OWNER" = "C"."R_OWNER"
AND "REF_COL"."CONSTRAINT_NAME" = "C"."R_CONSTRAINT_NAME"
AND "REF_COL"."POSITION" = "COL"."POSITION"
WHERE "C"."TABLE_NAME" = 'TableName' AND "C"."CONSTRAINT_TYPE" = 'R'
Here's an example (source):
SET @randomId = Cast(((@maxValue + 1) - @minValue) * Rand() + @minValue AS tinyint);
there's an open-source library for CSV which you can get using nuget: http://joshclose.github.io/CsvHelper/
You can parse the XML using this library System.Xml.Linq
. Below is the sample code I used to parse a XML file
public CatSubCatList GenerateCategoryListFromProductFeedXML()
{
string path = System.Web.HttpContext.Current.Server.MapPath(_xmlFilePath);
XDocument xDoc = XDocument.Load(path);
XElement xElement = XElement.Parse(xDoc.ToString());
List<Category> lstCategory = xElement.Elements("Product").Select(d => new Category
{
Code = Convert.ToString(d.Element("CategoryCode").Value),
CategoryPath = d.Element("CategoryPath").Value,
Name = GetCateOrSubCategory(d.Element("CategoryPath").Value, 0), // Category
SubCategoryName = GetCateOrSubCategory(d.Element("CategoryPath").Value, 1) // Sub Category
}).GroupBy(x => new { x.Code, x.SubCategoryName }).Select(x => x.First()).ToList();
CatSubCatList catSubCatList = GetFinalCategoryListFromXML(lstCategory);
return catSubCatList;
}
You could use the String Convert.ToBase64String(byte[]) to encode the byte array into a base64 string, then Byte[] Convert.FromBase64String(string) to convert the resulting string back into a byte array.
Here is my PHP 5 class.
<?php
class Bijective
{
public $dictionary = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
public function __construct()
{
$this->dictionary = str_split($this->dictionary);
}
public function encode($i)
{
if ($i == 0)
return $this->dictionary[0];
$result = '';
$base = count($this->dictionary);
while ($i > 0)
{
$result[] = $this->dictionary[($i % $base)];
$i = floor($i / $base);
}
$result = array_reverse($result);
return join("", $result);
}
public function decode($input)
{
$i = 0;
$base = count($this->dictionary);
$input = str_split($input);
foreach($input as $char)
{
$pos = array_search($char, $this->dictionary);
$i = $i * $base + $pos;
}
return $i;
}
}
This is a clarification because I have seen things done in code which are honestly confusing - I think the following example might assist others.
As others have said before - Bitmap inherits from the Abstract Image class
Abstract effectively means you cannot create a New() instance of it.
Image imgBad1 = new Image(); // Bad - won't compile
Image imgBad2 = new Image(200,200); // Bad - won't compile
But you can do the following:
Image imgGood; // Not instantiated object!
// Now you can do this
imgGood = new Bitmap(200, 200);
You can now use imgGood as you would the same bitmap object if you had done the following:
Bitmap bmpGood = new Bitmap(200,200);
The nice thing here is you can draw the imgGood object using a Graphics object
Graphics gr = default(Graphics);
gr = Graphics.FromImage(new Bitmap(1000, 1000));
Rectangle rect = new Rectangle(50, 50, imgGood.Width, imgGood.Height); // where to draw
gr.DrawImage(imgGood, rect);
Here imgGood can be any Image object - Bitmap, Metafile, or anything else that inherits from Image!
Rename filename by searching the last character of name. For example,
Original Filename: TestFile.txt_001
Begin Character need to be removed: _
Result: TestFile.txt
Option Explicit
Dim oWSH
Dim vbsInterpreter
Dim arg1 'As String
Dim arg2 'As String
Dim newFilename 'As string
Set oWSH = CreateObject("WScript.Shell")
vbsInterpreter = "cscript.exe"
ForceConsole()
arg1 = WScript.Arguments(0)
arg2 = WScript.Arguments(1)
WScript.StdOut.WriteLine "This is a test script."
Dim result
result = InstrRev(arg1, arg2, -1)
If result > 0 then
newFilename = Mid(arg1, 1, result - 1)
Dim Fso
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
Fso.MoveFile arg1, newFilename
WScript.StdOut.WriteLine newFilename
End If
Function ForceConsole()
If InStr(LCase(WScript.FullName), vbsInterpreter) = 0 Then
oWSH.Run vbsInterpreter & " //NoLogo " & Chr(34) & WScript.ScriptFullName & Chr(34)
WScript.Quit
End If
End Function
Try the Parse method.
I am assuming that you have enough permissions to create this directory.
To fix your problem, you can either ssh to some other location:
ssh [email protected]
and accept new key - it will create directory ~/.ssh
and known_hosts
underneath, or simply create it manually using
mkdir ~/.ssh
chmod 700 ~/.ssh
Note that chmod 700
is an important step!
After that, ssh-keygen should work without complaints.
In plain-old JavaScript you can do this:
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type.toLowerCase() == 'text') {
alert(inputs[i].value);
}
}
In jQuery, you would just do:
// select all inputs of type 'text' on the page
$("input:text")
// hide all text inputs which are descendants of div class="foo"
$("div.foo input:text").hide();
here's for SQL server, Oracle, PostgreSQL
which support window functions.
SELECT ROW_NUMBER() OVER (ORDER BY first_name, last_name) Sequence_no,
first_name,
last_name
FROM tableName
I asked the original question - @Trott's answer is surely the best.
However with JS being a dynamic language and with there being so many JS runtime environments, the instanceof
operator can fail especially in front-end development when crossing boundaries such as iframes. See:
https://github.com/mrdoob/three.js/issues/5886
If you are ok with duck typing, this should be good:
let isError = function(e){
return e && e.stack && e.message;
}
I personally prefer statically typed languages, but if you are using a dynamic language, it's best to embrace a dynamic language for what it is, rather than force it to behave like a statically typed language.
if you wanted to get a little more precise, you could do this:
let isError = function(e){
return e && e.stack && e.message && typeof e.stack === 'string'
&& typeof e.message === 'string';
}
I will share one misused concept that I fell into one day:
var names = new List<string> {"mercedes", "mazda", "bmw", "fiat", "ferrari"};
var startingWith_M = names.Where(x => x.StartsWith("m"));
var startingWith_F = names.Where(x => x.StartsWith("f"));
// updating existing list
names[0] = "ford";
// Guess what should be printed before continuing
print( startingWith_M.ToList() );
print( startingWith_F.ToList() );
// I was expecting
print( startingWith_M.ToList() ); // mercedes, mazda
print( startingWith_F.ToList() ); // fiat, ferrari
// what printed actualy
print( startingWith_M.ToList() ); // mazda
print( startingWith_F.ToList() ); // ford, fiat, ferrari
As per other answers, the evaluation of the result was deferred until calling ToList
or similar invocation methods for example ToArray
.
So I can rewrite the code in this case as:
var names = new List<string> {"mercedes", "mazda", "bmw", "fiat", "ferrari"};
// updating existing list
names[0] = "ford";
// before calling ToList directly
var startingWith_M = names.Where(x => x.StartsWith("m"));
var startingWith_F = names.Where(x => x.StartsWith("f"));
print( startingWith_M.ToList() );
print( startingWith_F.ToList() );
You can paste it like this:
= "2010-12-20" - 180
And don't forget to format the cell as a Date [CTRL]+[F1] / Number Tab
Here is a tryParseInt method that I am using, this takes the default value as second parameter so it can be anything you require.
function tryParseInt(str, defaultValue) {
return parseInt(str) == str ? parseInt(str) : defaultValue;
}
tryParseInt("", 0);//0
tryParseInt("string", 0);//0
tryParseInt("558", 0);//558
You have a typo.
Change: headers.append('authentication', ${student.token});
To: headers.append('Authentication', student.token);
NOTE the Authentication is capitalized
@OP it doesn't matter, you can just split on a space with explode. Until you want to use those values, iterate over the exploded values and discard blanks.
$str = "A B C D";
$s = explode(" ",$str);
foreach ($s as $a=>$b){
if ( trim($b) ) {
print "using $b\n";
}
}
Using Go to File... which is under the Go menu or using keyboard shortcut:
Then type the file name.
Also be sure to checkout that you can set your own keybindings and that there are cheatsheets available for Windows, macOS and Linux.
You shouldn't edit any code manually jetify should do this job for you, if you are running/building from cli using react-native
you dont' need to do anything but if you are running/building Andriod studio you need to run jetify as pre-build, here is how can you automate this:
1- From the above menu go to edit configurations:
2- Add the bottom of the screen you will find before launch click on the plus and choose Run External Tool
2- Fill the following information, note that the working directory is your project root directory (not the android directory):
3- Make sure this run before anything else, in the end, your configuration should look something like this:
Do you mean you want to use a formula in VBA? Something like:
Dim iVal As Integer
iVal = Application.WorksheetFunction.COUNTIF(Range("A1:A10"),"Green")
should work.
You can do this:
myList.get(3).setEmail("new email");
After ton of time to survey,
Finally, I use invokeAll
method of ExecutorService
to solve this problem.
That will strictly interrupt the task while task running.
Here is example
ExecutorService executorService = Executors.newCachedThreadPool();
try {
List<Callable<Object>> callables = new ArrayList<>();
// Add your long time task (callable)
callables.add(new VaryLongTimeTask());
// Assign tasks for specific execution timeout (e.g. 2 sec)
List<Future<Object>> futures = executorService.invokeAll(callables, 2000, TimeUnit.MILLISECONDS);
for (Future<Object> future : futures) {
// Getting result
}
} catch (InterruptedException e) {
e.printStackTrace();
}
executorService.shutdown();
The pro is you can also submit ListenableFuture
at the same ExecutorService
.
Just slightly change the first line of code.
ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
ListeningExecutorService
is the Listening feature of ExecutorService
at google guava project (com.google.guava) )
The previous answers show 3 approaches
Let me show #4 approach "By using "cbind" and "rename" that works for my case
df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))
new_column = c(0, 0, 0)
df <- cbind(new_column, df)
colnames(df)[1] <- "a"
If your actual concern is the dynamicness of the webapp context (the "AppName" part), then just retrieve it dynamically by HttpServletRequest#getContextPath()
.
<head>
<link rel="stylesheet" href="${pageContext.request.contextPath}/templates/style/main.css" />
<script src="${pageContext.request.contextPath}/templates/js/main.js"></script>
<script>var base = "${pageContext.request.contextPath}";</script>
</head>
<body>
<a href="${pageContext.request.contextPath}/pages/foo.jsp">link</a>
</body>
If you want to set a base path for all relative links so that you don't need to repeat ${pageContext.request.contextPath}
in every relative link, use the <base>
tag. Here's an example with help of JSTL functions.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<head>
<c:set var="url">${pageContext.request.requestURL}</c:set>
<base href="${fn:substring(url, 0, fn:length(url) - fn:length(pageContext.request.requestURI))}${pageContext.request.contextPath}/" />
<link rel="stylesheet" href="templates/style/main.css" />
<script src="templates/js/main.js"></script>
<script>var base = document.getElementsByTagName("base")[0].href;</script>
</head>
<body>
<a href="pages/foo.jsp">link</a>
</body>
This way every relative link (i.e. not starting with /
or a scheme) will become relative to the <base>
.
This is by the way not specifically related to Tomcat in any way. It's just related to HTTP/HTML basics. You would have the same problem in every other webserver.
Linux is a kernel, not a full operating system. There are different windowing systems and gui's that run on top of Linux to provide windowing. Typically X11 is the windowing system used by Linux distros.
I made similar function (only that works to me); sorry it is in C# but easy to translate...
private void WaitForPageLoad () {
while (pageReady == false)
Application.DoEvents();
while (webBrowser1.IsBusy || webBrowser1.ReadyState != WebBrowserReadyState.Complete)
Application.DoEvents();
}
int fileCount = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length; // Will Retrieve count of all files in directry and sub directries
int fileCount = Directory.GetFiles(path, "*.*", SearchOption.TopDirectory).Length; // Will Retrieve count of all files in directry but not sub directries
int fileCount = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories).Length; // Will Retrieve count of files XML extension in directry and sub directries
Either use LINQ:
var value = MyList.First(item => item.name == "foo").value;
(This will just find the first match, of course. There are lots of options around this.)
Or use Find
instead of FindIndex
:
var value = MyList.Find(item => item.name == "foo").value;
I'd strongly suggest using LINQ though - it's a much more idiomatic approach these days.
(I'd also suggest following the .NET naming conventions.)
If you want to start search from root "/" , you will probably see output somethings like:
find: /./proc/1731/fdinfo: Permission denied
find: /./proc/2032/task/2032/fd: Permission denied
It's because of permission. To solve this:
You can use sudo command:
sudo find /. -name 'toBeSearched.file'
It asks super user's password, when enter the password you will see result what you really want. If you don't have permission to use sudo command which means you don't have super user's password, first ask system admin to add you to the sudoers file.
You can use redirect the Standard Error Output from (Generally Display/Screen) to some file and avoid seeing the error messages on the screen! redirect to a special file /dev/null :
find /. -name 'toBeSearched.file' 2>/dev/null
You can use redirect the Standard Error Output from (Generally Display/Screen) to Standard output (Generally Display/Screen), then pipe with grep command with -v "invert" parameter to not to see the output lines which has 'Permission denied' word pairs:
find /. -name 'toBeSearched.file' 2>&1 | grep -v 'Permission denied'
One very quick way around this is, when you're viewing the "Your connection is not private" screen:
type badidea
type thisisunsafe
(credit to The Java Guy for finding the new passphrase)
That will allow the security exception when Chrome is otherwise not allowing the exception to be set via clickthrough, e.g. for this HSTS case.
This is only recommended for local connections and local-network virtual machines, obviously, but it has the advantage of working for VMs being used for development (e.g. on port-forwarded local connections) and not just direct localhost connections.
Note: the Chrome developers have changed this passphrase in the past, and may do so again. If badidea
ceases to work, please leave a note here if you learn the new passphrase. I'll try to do the same.
Edit: as of 30 Jan 2018 this passphrase appears to no longer work.
If I can hunt down a new one I'll post it here. In the meantime I'm going to take the time to set up a self-signed certificate using the method outlined in this stackoverflow post:
How to create a self-signed certificate with openssl?
Edit: as of 1 Mar 2018 and Chrome Version 64.0.3282.186 this passphrase works again for HSTS-related blocks on .dev sites.
Edit: as of 9 Mar 2018 and Chrome Version 65.0.3325.146 the badidea
passphrase no longer works.
Edit 2: the trouble with self-signed certificates seems to be that, with security standards tightening across the board these days, they cause their own errors to be thrown (nginx, for example, refuses to load an SSL/TLS cert that includes a self-signed cert in the chain of authority, by default).
The solution I'm going with now is to swap out the top-level domain on all my .app and .dev development sites with .test or .localhost. Chrome and Safari will no longer accept insecure connections to standard top-level domains (including .app).
The current list of standard top-level domains can be found in this Wikipedia article, including special-use domains:
Wikipedia: List of Internet Top Level Domains: Special Use Domains
These top-level domains seem to be exempt from the new https-only restrictions:
See the answer and link from codinghands to the original question for more information:
I use inline if's
($_POST['category'] == $data['id'] ? 'selected="selected"' : false)
You have two options
INNER JOIN x
ON x.qid = y.qid OR (x.qid IS NULL AND y.qid IS NULL)
or easier
INNER JOIN x
ON x.qid IS NOT DISTINCT FROM y.qid
Try this query it ll change the records ends with .com
UPDATE tablename SET email = replace(email, '.com', '.org') WHERE email LIKE '%.com';
RedirectToAction("actionName", "controllerName");
It has other overloads as well, please check up!
Also, If you are new and you are not using T4MVC, then I would recommend you to use it!
It gives you intellisence for actions,Controllers,views etc (no more magic strings)
There are two alternatives that'll work for sure:
If the above method didn't worked, try the next.
Add the following to build.gradle file at app level
defaultConfig {
multiDexEnabled true
}
SWIFT 3
let VC1 = self.storyboard!.instantiateViewController(withIdentifier: "MyViewController") as! MyViewController
let navController = UINavigationController(rootViewController: VC1)
self.present(navController, animated:true, completion: nil)
This is probably what you need:
$text = str_replace(' ', '_', substr($text, 0, 10));
In my case it was simply a matter of deleting a lock file.
sudo rm -f /tmp/mysql.sock.lock
// General cleanObj function
const cleanObj = (valsToRemoveArr, obj) => {
Object.keys(obj).forEach( (key) =>
if (valsToRemoveArr.includes(obj[key])){
delete obj[key]
}
})
}
cleanObj([undefined, null], obj)
const getObjWithoutVals = (dontReturnValsArr, obj) => {
const cleanObj = {}
Object.entries(obj).forEach( ([key, val]) => {
if(!dontReturnValsArr.includes(val)){
cleanObj[key]= val
}
})
return cleanObj
}
//To get a new object without `null` or `undefined` run:
const nonEmptyObj = getObjWithoutVals([undefined, null], obj)
Using Date pattern yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
and Java 8 you could do
String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date);
Update: For pre 26 use Joda time
String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
LocalDate date = org.joda.time.LocalDate.parse(string, formatter);
In app/build.gradle file, add like this-
dependencies {
compile 'joda-time:joda-time:2.9.4'
}
In general, you can pass any query to mysql
from shell with -e option.
mysql -u username -p -D dbname -e "DROP DATABASE dbname"
This worked for me for on Windows10
curl -d "{"""owner""":"""sasdasdasdasd"""}" -H "Content-Type: application/json" -X PUT http://localhost:8080/api/changeowner/CAR4
I was wondering the same thing so i googled and ended up here. I did a small test in python (extremely simple) just to see and this is what I got:
For:
def for_func(n = 0):
for n in range(500):
n = n + 1
python -m timeit "import for_func; for_func.for_func()" > for_func.txt
10000 loops, best of 3: 40.5 usec per loop
While:
def while_func(n = 0):
while n < 500:
n = n + 1
python -m timeit "import while_func; while_func.while_func()" > while_func.txt
10000 loops, best of 3: 45 usec per loop
Don't use exit(0);
That's bad practice at the best of times. Use Yii::$app->end();
So your code would look like
$this->redirect(['index'], 302);
Yii::$app->end();
That said though the actual problem was stopping POST requests, this is the wrong solution to that problem (although it does work). To stop POST requests you need to use access control.
public function behaviors()
{
return [
'access' => [
'class' => \yii\filters\AccessControl::className(),
'only' => ['create', 'update'],
'rules' => [
// deny all POST requests
[
'allow' => false,
'verbs' => ['POST']
],
// allow authenticated users
[
'allow' => true,
'roles' => ['@'],
],
// everything else is denied
],
],
];
}
SELECT table1.col_a, table1.col_b, table2.col_c
FROM table1
INNER JOIN table2 ON table1.col_a = table2.col_a
This will convert to a numeric value without the need to cast or specify length or digits:
STRING_COL+0.0
If your column is an INT
, can leave off the .0
to avoid decimals:
STRING_COL+0
What about naming your column?
INSERT INTO dbo.rLicenses (name) VALUES ('test')
It's been years since I tried updating via a view so YMMV as HLGEM mentioned.
I would consider an "INSTEAD OF" trigger on the view to allow a simple INSERT dbo.Licenses
(ie the table) in the trigger
Guys this is really simple.
login via ssh
into your pi
execute
vncserver -geometry 1200x1600
This will generate a new session :1
connect with your vnc client at ipaddress:1
Thats it.
FrustratedWithFormsDesigner is correct, PL/pgSQL can do this. Here's the script:
CREATE OR REPLACE FUNCTION truncate_tables(username IN VARCHAR) RETURNS void AS $$
DECLARE
statements CURSOR FOR
SELECT tablename FROM pg_tables
WHERE tableowner = username AND schemaname = 'public';
BEGIN
FOR stmt IN statements LOOP
EXECUTE 'TRUNCATE TABLE ' || quote_ident(stmt.tablename) || ' CASCADE;';
END LOOP;
END;
$$ LANGUAGE plpgsql;
This creates a stored function (you need to do this just once) which you can afterwards use like this:
SELECT truncate_tables('MYUSER');
I had this problem before, and solved it according to React official page isMounted is an Antipattern.
Set a property isMounted
flag to be true in componentDidMount
, and toggle it false in componentWillUnmount
. When you setState()
in your callbacks, check isMounted
first! It works for me.
state = {
isMounted: false
}
componentDidMount() {
this.setState({isMounted: true})
}
componentWillUnmount(){
this.setState({isMounted: false})
}
callback:
if (this.state.isMounted) {
this.setState({'time': remainTimeInfo});}