I wrote a drawable lib to custom round corner position, it looks like this:
You can get this lib at here:
Make it work, in values-v21 styles or theme xml needs to use this attribute:
<item name="android:windowTranslucentStatus">true</item>
That make the magic!
My Project Build Target of android-support-v7-appcompat was with API 19 just changed it to API 20 it worked for me
Right click on android-support-v7-appcompat
library project
Go to properties
Click on Android
Change project build Target from Android 4.x.x to Android 5.0
This helped me hopefully it helps others too.
Sorry with my English, When you create a new android project, you should choose api of high level, for example: from api 17 to api 21, It will not have appcompat and very easy to share project. If you did it with lower API, you just edit in Android Manifest to have upper API :), after that, you can delete Appcompat V7.
I just found the solution. It is really very simple:
mDrawerToggle.setDrawerIndicatorEnabled(false);
Hope it will help you.
What are the steps for that? where is AppCompat located?
Download the support library here:
http://developer.android.com/tools/support-library/setup.html
If you are using Eclipse:
Go to the tabs at the top and select ( Windows -> Android SDK Manager ). Under the 'extras' section, check 'Android Support Library' and check it for installation.
After that, the AppCompat library can be found at:
android-sdk/extras/android/support/v7/appcompat
You need to reference this AppCompat library in your Android project.
Import the library into Eclipse.
Follow @reVerse answer but in my case, I already had some property in my AppTheme
like
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
...
<item name="android:textColor">#111</item>
<item name="android:textSize">13sp</item>
</style>
I solved it by
1) Change the import from android.app.AlertDialog
to
android.support.v7.app.AlertDialog
2) I override 2 property in AppTheme
with null value
<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
<!-- Used for the buttons -->
<item name="colorAccent">#FFC107</item>
<!-- Used for the title and text -->
<item name="android:textColorPrimary">#FFFFFF</item>
<!-- Used for the background -->
<item name="android:background">#4CAF50</item>
<item name="android:textColor">@null</item>
<item name="android:textSize">@null</item>
</style>
.
AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.MyAlertDialogStyle);
Hope it help another people
This worked for me: Add compile 'com.android.support:appcompat-v7:21.0.3' to the gradle. Change the sdk target to 21. Hope it works for you!
my solucion is compile with other version
build.gradle (app)
compileSdkVersion 21
Good Luck
I just commented it and used androidx and now it's working all good!
import androidx.appcompat.app.AppCompatActivity;
// import android.support.v7.app.AppCompatActivity;
I had a similar problem. I wished to colour a complex drawable background for a view based on a color (int) value. I succeeded by using the code:
ColorStateList csl = new ColorStateList(new int[][]{{}}, new int[]{color});
textView.setBackgroundTintList(csl);
Where color is an int value representing the colour required. This represents the simple xml ColorStateList:
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:color="color here"/>
</selector>
Hope this helps.
So my collegue pushed their local.properties
which broke everything. I copied my sdk path from another app and did:
File -> Sync Project with Gradle Files
again this is all in the link you supplied
to change the text to white all you have to do is change the theme.
use this theme
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_my_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
AppCompat doesn't do that for dialogs (not yet at least)
EDIT: it does now. make sure to use android.support.v7.app.AlertDialog
It is actually quite easy to do this, if you are using android.support.v7
library.
Declare a menu item
<item android:id="@+id/action_search"
android:title="Search"
android:icon="@drawable/abc_ic_search_api_mtrl_alpha"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView" />
Extend AppCompatActivity
and in the onCreateOptionsMenu
setup the SearchView.
import android.support.v7.widget.SearchView;
...
public class YourActivity extends AppCompatActivity {
...
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home, menu);
// Retrieve the SearchView and plug it into SearchManager
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
return true;
}
...
}
NOTE1: All com.android.support
libraries must use the exact same version specification (mixing versions can lead to runtime crashes).
NOTE2: Support library should not use a different version than the compileSdkVersion
For API 28 you can use:
implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
implementation 'com.android.support:recyclerview-v7:28.0.0-alpha1'
https://mvnrepository.com/artifact/com.android.support/appcompat-v7/28.0.0-alpha1 https://mvnrepository.com/artifact/com.android.support/recyclerview-v7/28.0.0-alpha1
All support libraries: https://mvnrepository.com/artifact/com.android.support
which theme you have used in activity add below one line code
for white
<style name="AppTheme.NoActionBar">
<item name="android:tint">#ffffff</item>
</style>
or
<style name="AppThemeName" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:tint">#ffffff</item>
</style>
for black
<style name="AppTheme.NoActionBar">
<item name="android:tint">#000000</item>
</style>
or
<style name="AppThemeName" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:tint">#000000</item>
</style>
In addition to Kassim's answer:
As Peter says, they won't be in Maven Central
Either use maven-android-sdk-deployer to deploy the libraries to your local repository
Or from Android SDK Manager download the Android Support Repository (in Extras) and an M2 repo of the support libraries will be downloaded to your Android SDK directory
I also had to update the "Local Maven repository for Support Libraries" in Android SDK Manager.
If you are using the Support Library provided DrawerLayout as suggested in the Creating a navigation drawer training, you can use the newly added android.support.v7.app.ActionBarDrawerToggle (note: different from the now deprecated android.support.v4.app.ActionBarDrawerToggle):
shows a Hamburger icon when drawer is closed and an arrow when drawer is open. It animates between these two states as the drawer opens.
While the training hasn't been updated to take the deprecation/new class into account, you should be able to use it almost exactly the same code - the only difference in implementing it is the constructor.
For this you have to do below things 1.right click the project click.
2.open module settings->in properties tab->change the compile sdk and build tool version into 26,26.0.0.
3.click ok.
Its working for me after an hour tried.
Your application has an AppCompat theme
<application
android:theme="@style/AppTheme">
But, you overwrote the Activity (which extends AppCompatActivity) with a theme that isn't descendant of an AppCompat theme
<activity android:name=".MainActivity"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
You could define your own fullscreen theme like so (notice AppCompat
in the parent=
)
<style name="AppFullScreenTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowNoTitle">true</item>
<item name="android:windowActionBar">false</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowContentOverlay">@null</item>
</style>
Then set that on the Activity.
<activity android:name=".MainActivity"
android:theme="@style/AppFullScreenTheme" >
Note: There might be an AppCompat theme that's already full screen, but don't know immediately
The reason for my answer on this is because the most upvoted answer itself failed to solve my problem. I have figured out this problem by doing this.
<activity android:name="NAME OF YOUR ACTIVITY"
android:label="" />
Hope this will help others too.
Edit: After updating to appcompat-v7:22.1.1 and using AppCompatActivity
instead of ActionBarActivity
my styles.xml looks like:
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="theme">@style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
</style>
Note: This means I am using a Toolbar
provided by the framework (NOT included in an XML file).
This worked for me:
styles.xml file:
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="windowActionBar">false</item>
<item name="theme">@style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
</style>
Update: A quote from Gabriele Mariotti's blog.
With the new Toolbar you can apply a style and a theme. They are different! The style is local to the Toolbar view, for example the background color. The app:theme is instead global to all ui elements inflated in the Toolbar, for example the color of the title and icons.
It supports after KITKAT. Just add following code inside onCreate method of your Activity. No need any modifications to Manifest file.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow(); // in Activity's onCreate() for instance
w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
This worked for me:
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setLogo(R.drawable.ic_logo);
getSupportActionBar().setDisplayShowTitleEnabled(false); //optional
as well as:
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.drawable.ic_logo); //also displays wide logo
getSupportActionBar().setDisplayShowTitleEnabled(false); //optional
All I did is:
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
And it works on V3 API.
I know it is been answered long time ago, but i would like to share this also:
This code works very well:
SQLiteDatabase db = this.getReadableDatabase();
long taskCount = DatabaseUtils.queryNumEntries(db, TABLE_TODOTASK);
BUT what if i dont want to count all rows and i have a condition to apply?
DatabaseUtils have another function for this: DatabaseUtils.longForQuery
long taskCount = DatabaseUtils.longForQuery(db, "SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
new String[] { String.valueOf(tasklist_Id) });
The longForQuery
documentation says:
Utility method to run the query on the db and return the value in the first column of the first row.
public static long longForQuery(SQLiteDatabase db, String query, String[] selectionArgs)
It is performance friendly and save you some time and boilerplate code
Hope this will help somebody someday :)
While you're waiting.. Curved corner (border-radius) cross browser
You can get the duplicated like this :
List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 4, 4);
Set<Integer> duplicated = numbers
.stream()
.filter(n -> numbers
.stream()
.filter(x -> x == n)
.count() > 1)
.collect(Collectors.toSet());
This worked for me within an ASP.NET site. To enable validation on some hidden fields use this code
$("form").data("validator").settings.ignore = ":hidden:not(#myitem)";
To enable validation for all elements of form use this one
$("form").data("validator").settings.ignore = "";
Note that use them within $(document).ready(function() { })
There is a library for this BarCode PHP. You just need to include a few files:
require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');
You can generate many types of barcodes, namely 1D or 2D. Add the required library:
require_once('class/BCGcode39.barcode.php');
Generate the colours:
// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);
After you have added all the codes, you will get this way:
Example
Since several have asked for an example here is what I was able to do to get it done
require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');
require_once('class/BCGcode128.barcode.php');
header('Content-Type: image/png');
$color_white = new BCGColor(255, 255, 255);
$code = new BCGcode128();
$code->parse('HELLO');
$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);
$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);
If you want to actually create the image file so you can save it then change
$drawing = new BCGDrawing('', $color_white);
to
$drawing = new BCGDrawing('image.png', $color_white);
Apple cares about security and as you know it is not possible to install any application on a real iOS device. Apple has several legal ways to do it:
Development Provisioning Profile
allows you to do itDistribution Provisioning Profile
[About] and Apple after review reassign it by they own keyDevelopment Provisioning Profile
is stored on device and contains:
Xcode
by default take cares about
On many popular devices the market name of the device is not available. For example, on the Samsung Galaxy S6 the value of Build.MODEL
could be "SM-G920F"
, "SM-G920I"
, or "SM-G920W8"
.
I created a small library that gets the market (consumer friendly) name of a device. It gets the correct name for over 10,000 devices and is constantly updated. If you wish to use my library click the link below:
If you do not want to use the library above, then this is the best solution for getting a consumer friendly device name:
/** Returns the consumer friendly device name */
public static String getDeviceName() {
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
if (model.startsWith(manufacturer)) {
return capitalize(model);
}
return capitalize(manufacturer) + " " + model;
}
private static String capitalize(String str) {
if (TextUtils.isEmpty(str)) {
return str;
}
char[] arr = str.toCharArray();
boolean capitalizeNext = true;
String phrase = "";
for (char c : arr) {
if (capitalizeNext && Character.isLetter(c)) {
phrase += Character.toUpperCase(c);
capitalizeNext = false;
continue;
} else if (Character.isWhitespace(c)) {
capitalizeNext = true;
}
phrase += c;
}
return phrase;
}
Example from my Verizon HTC One M8:
// using method from above
System.out.println(getDeviceName());
// Using https://github.com/jaredrummler/AndroidDeviceNames
System.out.println(DeviceName.getDeviceName());
Result:
HTC6525LVW
HTC One (M8)
It's a long pointer to a constant, wide string (i.e. a string of wide characters).
Since it's a wide string, you want to make your constant look like: L"TestWindow"
. I wouldn't create the intermediate a
either, I'd just pass L"TestWindow"
for the parameter:
ghTest = FindWindowEx(NULL, NULL, NULL, L"TestWindow");
If you want to be pedantically correct, an "LPCTSTR" is a "text" string -- a wide string in a Unicode build and a narrow string in an ANSI build, so you should use the appropriate macro:
ghTest = FindWindow(NULL, NULL, NULL, _T("TestWindow"));
Few people care about producing code that can compile for both Unicode and ANSI character sets though, and if you don't getting it to really work correctly can be quite a bit of extra work for little gain. In this particular case, there's not much extra work, but if you're manipulating strings, there's a whole set of string manipulation macros that resolve to the correct functions.
Menu File → Preference → Settings →
Check the "Trim Trailing Whitespace" option - "When enabled, will trim trailing whitespace when saving a file".
Note that if a cookie is secure, you cannot check in client side for its existence using document.cookie
(which all of the answers are using). Such cookie can be checked only at sever side.
In Facebook version 11.0.0.11.23 (3002850) fb://profile/
and fb://page/
no longer work. I decompiled the Facebook app and found that you can use fb://facewebmodal/f?href=[YOUR_FACEBOOK_PAGE]
. Here is the method I have been using in production:
/**
* <p>Intent to open the official Facebook app. If the Facebook app is not installed then the
* default web browser will be used.</p>
*
* <p>Example usage:</p>
*
* {@code newFacebookIntent(ctx.getPackageManager(), "https://www.facebook.com/JRummyApps");}
*
* @param pm
* The {@link PackageManager}. You can find this class through {@link
* Context#getPackageManager()}.
* @param url
* The full URL to the Facebook page or profile.
* @return An intent that will open the Facebook page/profile.
*/
public static Intent newFacebookIntent(PackageManager pm, String url) {
Uri uri = Uri.parse(url);
try {
ApplicationInfo applicationInfo = pm.getApplicationInfo("com.facebook.katana", 0);
if (applicationInfo.enabled) {
// http://stackoverflow.com/a/24547437/1048340
uri = Uri.parse("fb://facewebmodal/f?href=" + url);
}
} catch (PackageManager.NameNotFoundException ignored) {
}
return new Intent(Intent.ACTION_VIEW, uri);
}
The following will Return All Procedures in selected database
SELECT * FROM sys.procedures
As a small helper function:
def rindex(mylist, myvalue):
return len(mylist) - mylist[::-1].index(myvalue) - 1
You'll want to use a URL in the following format...
https://api.whatsapp.com/send?text=text
Then you can have it send whatever text you'd like. You also have the option to specify a phone number...
https://api.whatsapp.com/send?text=text&phone=1234
What you CANNOT DO is use the following:
https://wa.me/send?text=text
You will get...
We couldn't find the page you were looking for
wa.me
, though, will work if you supply both a phone number and text. But, for the most part, if you're trying to make a sharing link, you really don't want to indicate the phone number, because you want the user to select someone. In that event, if you don't supply the number and use wa.me
as URL, all of your sharing links will fail. Please use app.whatsapp.com
.
For getting selected value use
$('#dropDownId').val();
and for getting selected item text use this line:
$("#dropDownId option:selected").text();
Quote: I would like to know how to display the div in the middle of the screen, whether user has scrolled up/down.
Change
position: absolute;
To
position: fixed;
W3C specifications for position: absolute
and for position: fixed
.
It happens when you don't properly close the code block:
if (condition){
// your code goes here*
{ // This doesn't close the code block
Correct way:
if (condition){
// your code goes here
} // Close the code block
Why use an external lib, when google play services (since version 7.8.0) includes a barcode decoder.
var str = "IAMA JavaScript Developer";
var a=str.split(''), b = a.length;
for (var i=0; i<b; i++) {
a.unshift(a.splice(1+i,1).shift())
}
a.shift();
alert(a.join(''));
use trap
to pause and check command line (in color using tput
) before running it
trap 'tput setaf 1;tput bold;echo $BASH_COMMAND;read;tput init' DEBUG
press any key to continue
use with
set -x
to debug command line
A built-in Map type is now available in JavaScript. It can be used instead of simply using Object. It is supported by current versions of all major browsers.
Maps do not support the [subscript]
notation used by Objects. That syntax implicitly casts the subscript
value to a primitive string or symbol. Maps support any values as keys, so you must use the methods .get(key)
, .set(key, value)
and .has(key)
.
var m = new Map();_x000D_
var key1 = 'key1';_x000D_
var key2 = {};_x000D_
var key3 = {};_x000D_
_x000D_
m.set(key1, 'value1');_x000D_
m.set(key2, 'value2');_x000D_
_x000D_
console.assert(m.has(key2), "m should contain key2.");_x000D_
console.assert(!m.has(key3), "m should not contain key3.");
_x000D_
Objects only supports primitive strings and symbols as keys, because the values are stored as properties. If you were using Object, it wouldn't be able to to distinguish key2
and key3
because their string representations would be the same:
var o = new Object();_x000D_
var key1 = 'key1';_x000D_
var key2 = {};_x000D_
var key3 = {};_x000D_
_x000D_
o[key1] = 'value1';_x000D_
o[key2] = 'value2';_x000D_
_x000D_
console.assert(o.hasOwnProperty(key2), "o should contain key2.");_x000D_
console.assert(!o.hasOwnProperty(key3), "o should not contain key3."); // Fails!
_x000D_
git checkout master -- myplugin.js
master = branch name
myplugin.js = file name
"bad enough not having a traditional for(;;) looper"?? What?
Are you trying to do
import string
for c in string.lowercase:
...do something with c...
Or perhaps you're using string.uppercase
or string.letters
?
Python doesn't have for(;;)
because there are often better ways to do it. It also doesn't have character math because it's not necessary, either.
Or use diff
method of numpy:
import numpy as np
def allthesame(l):
return np.all(np.diff(l)==0)
And to call:
print(allthesame([1,1,1]))
Output:
True
<target name="check-abc">
<available file="abc.txt" property="abc.present"/>
</target>
<target name="do-if-abc" depends="check-abc" if="abc.present">
...
</target>
Ditto most of what others have said.
In the good old days before C was invented, when the only high level languages were things like COBOL and FORTRAN, there were lots of things that just weren't possible to do without resorting to assembler. It was the only way to get the full breadth of flexibility, to be able to access all the devices, etc. But then C was invented, and almost anything that was possible in assembly was possible in C. I have written very little assembly since then.
That said, I think it is a very useful exercise for new programmers to learn to write in assembler. Not because they would actually use it much, but because then you understand what is really happening inside the computer. I've seen lots of programming errors and inefficient code from programmers who clearly have no idea what's really happening with the bits and bytes and registers.
For executing pure SQL statements (I Don't Know About the FRAMEWORK- CodeIGNITER!!!) you can use SUB QUERY! The Syntax Would be as follows
SELECT t1.id
FROM example t1 INNER JOIN
(select id from (example2 t1
join example3 t2
on t1
.id
= t2
.id
)) as t2 ON t1.id = t2.id;
Hope you Get My Point!
For the multi-class case, everything you need can be found from the confusion matrix. For example, if your confusion matrix looks like this:
Then what you're looking for, per class, can be found like this:
Using pandas/numpy, you can do this for all classes at once like so:
FP = confusion_matrix.sum(axis=0) - np.diag(confusion_matrix)
FN = confusion_matrix.sum(axis=1) - np.diag(confusion_matrix)
TP = np.diag(confusion_matrix)
TN = confusion_matrix.values.sum() - (FP + FN + TP)
# Sensitivity, hit rate, recall, or true positive rate
TPR = TP/(TP+FN)
# Specificity or true negative rate
TNR = TN/(TN+FP)
# Precision or positive predictive value
PPV = TP/(TP+FP)
# Negative predictive value
NPV = TN/(TN+FN)
# Fall out or false positive rate
FPR = FP/(FP+TN)
# False negative rate
FNR = FN/(TP+FN)
# False discovery rate
FDR = FP/(TP+FP)
# Overall accuracy
ACC = (TP+TN)/(TP+FP+FN+TN)
I did the following and it works fine.. and is simple and easy to understand..
CATransition* transition = [CATransition animation];
transition.duration = 0.5;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionFade; //kCATransitionMoveIn; //, kCATransitionPush, kCATransitionReveal, kCATransitionFade
//transition.subtype = kCATransitionFromTop; //kCATransitionFromLeft, kCATransitionFromRight, kCATransitionFromTop, kCATransitionFromBottom
[self.navigationController.view.layer addAnimation:transition forKey:nil];
[[self navigationController] popViewControllerAnimated:NO];
And the same thing for push..
Swift 3.0 version:
let transition = CATransition()
transition.duration = 0.5
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = kCATransitionFade
self.navigationController?.view.layer.add(transition, forKey: nil)
_ = self.navigationController?.popToRootViewController(animated: false)
That's a tricky one... Your storage letter must be capical. For example "C:\..."
What platform? If using .NET, use System.Uri.TryCreate
, not a regex.
For example:
static bool IsValidUrl(string urlString)
{
Uri uri;
return Uri.TryCreate(urlString, UriKind.Absolute, out uri)
&& (uri.Scheme == Uri.UriSchemeHttp
|| uri.Scheme == Uri.UriSchemeHttps
|| uri.Scheme == Uri.UriSchemeFtp
|| uri.Scheme == Uri.UriSchemeMailto
/*...*/);
}
// In test fixture...
[Test]
void IsValidUrl_Test()
{
Assert.True(IsValidUrl("http://www.example.com"));
Assert.False(IsValidUrl("javascript:alert('xss')"));
Assert.False(IsValidUrl(""));
Assert.False(IsValidUrl(null));
}
(Thanks to @Yoshi for the tip about javascript:
)
As of jquery 3.0 you can use $.uniqueSort(ARRAY)
Example
array = ["1","2","1","2"]
$.uniqueSort(array)
=> ["1", "2"]
You can use plain javascript, this will call your_func once, after 5 seconds:
setTimeout(function() { your_func(); }, 5000);
If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)
There is also a plugin I've used once. It has oneTime
and everyTime
methods.
Below command is working for me. Which is working with variables
sed -i "/\<$E\>/c $D" "$B"
There is no SINGLE standard, but I have seen 3 styles you mention ("Pascal/Microsoft", "Java" (camelCase
) and "C" (underscores, snake_case
)) -- as well as at least one more, kebab-case
like longer-name
).
It mostly seems to depend on what background developers of the service in question had; those with c/c++ background (or languages that adopt similar naming, which includes many scripting languages, ruby etc) often choose underscore variant; and rest similarly (Java vs .NET). Jackson library that was mentioned, for example, assumes Java bean naming convention (camelCase
)
UPDATE: my definition of "standard" is a SINGLE convention. So while one could claim "yes, there are many standards", to me there are multiple Naming Conventions
, none of which is "The" standard overall. One of them could be considered the standard for specific platform, but given that JSON is used for interoperability between platforms that may or may not make much sense.
Tossing my hat in the ring for fun, added advantage of memoizing
const callOnce = (fn, i=0, memo) => () => i++ ? memo : (memo = fn());
// usage
const myExpensiveFunction = () => { return console.log('joe'),5; }
const memoed = callOnce(myExpensiveFunction);
memoed(); //logs "joe", returns 5
memoed(); // returns 5
memoed(); // returns 5
...
As of jackson 2.7.4 (or earlier maybe), the class is in jacskon-jaxrs-base.jar, which is contained in jackson-jaxrs-json-provider
It's used for raising errors.
if something:
raise Exception('My error!')
Some examples here
I needed to kill processes on different ports so I created a bash script:
killPort() {
PID=$(echo $(lsof -n -i4TCP:$1) | awk 'NR==1{print $11}')
kill -9 $PID
}
Just add that to your .bashrc and run it like this:
killPort 8080
You can pass whatever port number you wish
If you are using PHP you might also want to take a look at minify which can minify and combine JavaScript files. The integration is pretty easy and can be done by defined groups of files or an easy query string. Minified files are also cached to reduce the server load and you can add expire headers through minify.
Change . to / as the path separator and use getResourceAsStream
:
reader = new BufferedReader(new InputStreamReader(
getClass().getClassLoader().getResourceAsStream(
"com/company/app/dao/sql/SqlQueryFile.sql")));
or
reader = new BufferedReader(new InputStreamReader(
getClass().getResourceAsStream(
"/com/company/app/dao/sql/SqlQueryFile.sql")));
Note the leading slash when using Class.getResourceAsStream()
vs ClassLoader.getResourceAsStream
.
getSystemResourceAsStream
uses the system classloader which isn't what you want.
I suspect that using slashes instead of dots would work for ClassPathResource
too.
The following is Yet Another Way (tm) - still involves a little calculation but provides an example of using EXTRACT to pull the individual fields out of an INTERVAL:
DECLARE
SUBTYPE BIG_INTERVAL IS INTERVAL DAY(9) TO SECOND;
i BIG_INTERVAL;
nSeconds NUMBER := 86400000;
FUNCTION INTERVAL_TO_HMS_STRING(inv IN BIG_INTERVAL)
RETURN VARCHAR2
IS
nHours NUMBER;
nMinutes NUMBER;
nSeconds NUMBER;
strHour_format VARCHAR2(10) := '09';
workInv INTERVAL DAY(9) TO SECOND(9);
BEGIN
nHours := EXTRACT(HOUR FROM inv) + (EXTRACT(DAY FROM inv) * 24);
strHour_format := TRIM(RPAD(' ', LENGTH(TRIM(TO_CHAR(ABS(nHours)))), '0') || '9');
nMinutes := ABS(EXTRACT(MINUTE FROM inv));
nSeconds := ABS(EXTRACT(SECOND FROM inv));
RETURN TRIM(TO_CHAR(nHours, strHour_format)) || ':' ||
TRIM(TO_CHAR(nMInutes, '09')) || ':' ||
TRIM(TO_CHAR(nSeconds, '09'));
END INTERVAL_TO_HMS_STRING;
BEGIN
i := NUMTODSINTERVAL(nSeconds, 'SECOND');
DBMS_OUTPUT.PUT_LINE('i (fields) = ' || INTERVAL_TO_HMS_STRING(i));
END;
The code which extracts the fields, etc, still has to contain a calculation to convert the DAY field to equivalent hours, and is not the prettiest, but wrapped up neatly in a procedure it's not too bad to use.
Share and enjoy.
This one is just extension of article you found.
public class WebClientEx : WebClient
{
public WebClientEx(CookieContainer container)
{
this.container = container;
}
public CookieContainer CookieContainer
{
get { return container; }
set { container= value; }
}
private CookieContainer container = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest r = base.GetWebRequest(address);
var request = r as HttpWebRequest;
if (request != null)
{
request.CookieContainer = container;
}
return r;
}
protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
{
WebResponse response = base.GetWebResponse(request, result);
ReadCookies(response);
return response;
}
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse response = base.GetWebResponse(request);
ReadCookies(response);
return response;
}
private void ReadCookies(WebResponse r)
{
var response = r as HttpWebResponse;
if (response != null)
{
CookieCollection cookies = response.Cookies;
container.Add(cookies);
}
}
}
When my button's FlatStyle is set to system, it looks flat. And when it's set to popup, it only pops up when mouses over. Either is what I want. I want it to look sunken when checked and raised when unchecked and no change while mousing over (the button is really a checkbox but the checkbox's appearance property is set to button).
I end up setting the FlatStyle to flat and wrote a new Paint event handler.
private void checkbox_paint(object sender, PaintEventArgs e)
{
CheckBox myCheckbox = (CheckBox)sender;
Rectangle borderRectangle = myCheckbox.ClientRectangle;
if (myCheckbox.Checked)
{
ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,
Border3DStyle.Sunken);
}
else
{
ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,
Border3DStyle.Raised);
}
}
I give a similar answer to this question: C# winforms button with solid border, like 3d Sorry for double posting.
Seems that EditText apply the hintTextColor only if the text is empty. So simple solution will be like this
Editable text = mEditText.getText();
mEditText.setText(null);
mEditText.setHintTextColor(color);
mEditText.setText(text);
If you have multiple fields, you can extend the EditText and write a method which executes this logic and use that method instead.
You can set the variable 'fileencodings' in your .vimrc.
This is a list of character encodings considered when starting to edit an existing file. When a file is read, Vim tries to use the first mentioned character encoding. If an error is detected, the next one in the list is tried. When an encoding is found that works, 'fileencoding' is set to it. If all fail, 'fileencoding' is set to an empty string, which means the value of 'encoding' is used.
See :help filencodings
If you often work with e.g. cp1252, you can add it there:
set fileencodings=ucs-bom,utf-8,cp1252,default,latin9
The way is to convert to binary and then to correct encoding
FYI, you can substitute the /*csv*/
for other formats as well including /*xml*/
and /*html*/
.
select /*xml*/ * from emp
would return an xml document with the query results for example.
I came across this article while looking for an easy way to return xml from a query.
I found the solution after a few tries, I hope this can help you. Add the following to your <ReactTable>
component:
getTrProps={(state, rowInfo) => {
if (rowInfo && rowInfo.row) {
return {
onClick: (e) => {
this.setState({
selected: rowInfo.index
})
},
style: {
background: rowInfo.index === this.state.selected ? '#00afec' : 'white',
color: rowInfo.index === this.state.selected ? 'white' : 'black'
}
}
}else{
return {}
}
}
In your state
don't forget to add a null selected
value, like:
state = { selected: null }
The argument of func is accepting double-pointer variable. Hope this helps...
#include <stdio.h>
int func(int **B){
}
int main(void){
int *B[10];
func(B);
return 0;
}
%u is used for unsigned integer. Since the memory address given by the signed integer address operator %d is -12, to get this value in unsigned integer, Compiler returns the unsigned integer value for this address.
Looks like something is wrong with your data, it isn't in the format you are expecting. It could be a new line character or a blank space in the data that is tinkering with your code.
<select name="career" id="career" onchange="location = this.value;">
<option value="resume" selected> All Applications </option>
<option value="resume&j=14">Seo Expert</option>
<option value="resume&j=21">Project Manager</option>
<option value="resume&j=33">Php Developer</option>
</select>
In this case it is just coding style.
Use of var
is only necessary when dealing with anonymous types.
In other situations it's a matter of taste.
See “Herb Sutter "Back to the Basics! Essentials of Modern C++ Style”. Among other topics, he reviews the parameter passing advice that’s been given in the past, and new ideas that come in with C++11 and specifically looks at the idea of passing strings by value.
The benchmarks show that passing std::string
s by value, in cases where the function will copy it in anyway, can be significantly slower!
This is because you are forcing it to always make a full copy (and then move into place), while the const&
version will update the old string which may reuse the already-allocated buffer.
See his slide 27: For “set” functions, option 1 is the same as it always was. Option 2 adds an overload for rvalue reference, but this gives a combinatorial explosion if there are multiple parameters.
It is only for “sink” parameters where a string must be created (not have its existing value changed) that the pass-by-value trick is valid. That is, constructors in which the parameter directly initializes the member of the matching type.
If you want to see how deep you can go in worrying about this, watch Nicolai Josuttis’s presentation and good luck with that (“Perfect — Done!” n times after finding fault with the previous version. Ever been there?)
This is also summarized as ?F.15 in the Standard Guidelines.
Build lists of matched lines - several flavors:
def lines_that_equal(line_to_match, fp):
return [line for line in fp if line == line_to_match]
def lines_that_contain(string, fp):
return [line for line in fp if string in line]
def lines_that_start_with(string, fp):
return [line for line in fp if line.startswith(string)]
def lines_that_end_with(string, fp):
return [line for line in fp if line.endswith(string)]
Build generator of matched lines (memory efficient):
def generate_lines_that_equal(string, fp):
for line in fp:
if line == string:
yield line
Print all matching lines (find all matches first, then print them):
with open("file.txt", "r") as fp:
for line in lines_that_equal("my_string", fp):
print line
Print all matching lines (print them lazily, as we find them)
with open("file.txt", "r") as fp:
for line in generate_lines_that_equal("my_string", fp):
print line
Generators (produced by yield) are your friends, especially with large files that don't fit into memory.
For an uglier version of unshift
use splice
:
TheArray.splice(0, 0, TheNewObject);
An alternative to BouncyCastle for AES-GCM encryption is libsodium-net. It wraps the libsodium C library. One nice advantage is that it uses the AES-NI extension in CPUs for very fast encryption. The down side is that it won't work at all if the CPU doesn't have the extension. There's no software fall back.
It's more convenient to use a session, this way you don't have to remember to set headers each time:
session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})
session.get('https://httpbin.org/headers')
By default, session also manages cookies for you. In case you want to disable that, see this question.
command to remove cordova and ionic
sudo npm uninstall -g ionic
To send an objective-c message in this instance you would do
[self score];
I suggest you read the Objective-C programming guide Objective-C Programming Guide
yes there are some telltale signs for common CMSs like Drupal, Joomla, Pligg, and RoR etc .. .. ASP.NET stuff is easy to spot too .. but as the framework becomes more obscure it gets harder to deduce ..
What I usually is compare the site i am snooping with another site that I know is built using a particular tech. That sometimes works ..
Try Like this
Thread thread = new Thread() {
@Override
public void run() {
Looper.prepare();
while(true){
Log.d("Current Thread", "Running");
try{
Thread.sleep(1000);
}catch(Exeption exception){ }
}
}
};
thread.start();
thread.interrupt();
Simply add it to your current code, then call (new Date()).getWeek()
<script>
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(), 0, 1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
}
var weekNumber = (new Date()).getWeek();
var dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var now = new Date();
document.write(dayNames[now.getDay()] + " (" + weekNumber + ").");
</script>
As of RHEL 8, you can install python3 directly from the official repositories:
$ podman run --rm -ti ubi8 bash
[root@453fc5c55104 /]# yum install python3
Updating Subscription Management repositories.
Unable to read consumer identity
Subscription Manager is operating in container mode.
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
...
Installed:
platform-python-pip-9.0.3-16.el8.noarch
python3-pip-9.0.3-16.el8.noarch
python3-setuptools-39.2.0-5.el8.noarch
python36-3.6.8-2.module+el8.1.0+3334+5cb623d7.x86_64
Complete!
You can even get python 3.8:
[root@453fc5c55104 /]# yum install python38
Installed:
python38-3.8.0-6.module+el8.2.0+5978+503155c0.x86_64
python38-libs-3.8.0-6.module+el8.2.0+5978+503155c0.x86_64
python38-pip-19.2.3-5.module+el8.2.0+5979+f9f0b1d2.noarch
python38-pip-wheel-19.2.3-5.module+el8.2.0+5979+f9f0b1d2.noarch
python38-setuptools-41.6.0-4.module+el8.2.0+5978+503155c0.noarch
python38-setuptools-wheel-41.6.0-4.module+el8.2.0+5978+503155c0.noarch
Complete!
I used the logic suggested by Andrew which is very effective. And this is my version:
$('body').on('keydown', 'input, select', function(e) {
if (e.key === "Enter") {
var self = $(this), form = self.parents('form:eq(0)'), focusable, next;
focusable = form.find('input,a,select,button,textarea').filter(':visible');
next = focusable.eq(focusable.index(this)+1);
if (next.length) {
next.focus();
} else {
form.submit();
}
return false;
}
});
KeyboardEvent's keycode (i.e: e.keycode
) depreciation notice :- https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
Updated 2018
See if this example helps: http://bootply.com/mQh8DyRfWY
The brand is centered using..
.navbar-brand
{
position: absolute;
width: 100%;
left: 0;
top: 0;
text-align: center;
margin: auto;
}
Your markup is for Bootstrap 2, not 3. There is no longer a navbar-inner
.
EDIT - Another approach is using transform: translateX(-50%);
.navbar-brand {
transform: translateX(-50%);
left: 50%;
position: absolute;
}
http://www.bootply.com/V7vKDfk46G
In Bootstrap 4, mx-auto
or flexbox can be used to center the brand and other elements. See How to position navbar contents in Bootstrap 4 for an explanation.
Also see:
This CORS issue wasn't further elaborated (for other causes).
I'm having this issue currently under different reason. My front end is returning 'Access-Control-Allow-Origin' header error as well.
Just that I've pointed the wrong URL so this header wasn't reflected properly (in which i kept presume it did). localhost (front end) -> call to non secured http (supposed to be https), make sure the API end point from front end is pointing to the correct protocol.
Also, you can give valgrind
a try: if you install valgrind
and run
valgrind --leak-check=full <program>
then it will run your program and display stack traces for any segfaults, as well as any invalid memory reads or writes and memory leaks. It's really quite useful.
I had a similar problem recently. I had a form and PHP function that to be run once the form is submitted. However, I needed to run a javascript first.
// This variable is used in order to determine if we already did our js fun
var window.alreadyClicked = "NO"
$("form:not('#press')").bind("submit", function(e){
// Check if we already run js part
if(window.alreadyClicked == "NO"){
// Prevent page refresh
e.preventDefault();
// Change variable value so next time we submit the form the js wont run
window.alreadyClicked = "YES"
// Here is your actual js you need to run before doing the php part
xxxxxxxxxx
// Submit the form again but since we changed the value of our variable js wont be run and page can reload (and php can do whatever you told it to)
$("form:not('#press')").submit()
}
});
I doubt css understands left
by itself. You need to use it specifying position. You are using .css() correctly
position: relative/absolute/whatever;
left: 900px;
heres a fiddle of it working
and without the position here's what you get
Change your if statement to be like this - with quotes around -900px
var n = $("items").css("left");
if(n == '-900px'){
$(".items span").fadeOut("slow");
}
By far the neatest way to get the first N elements of a Swift array is using prefix(_ maxLength: Int)
:
let someArray = [1, 2, 3, 4, 5, 6, 7]
let first5 = someArray.prefix(5) // 1, 2, 3, 4, 5
This has the benefit of being bounds safe. If the count you pass to prefix
is larger than the array count then it just returns the whole array.
NOTE: as pointed out in the comments, Array.prefix
actually returns an ArraySlice
, not an Array
. In most cases this shouldn't make a difference but if you need to assign the result to an Array
type or pass it to a method that's expecting an Array
param you will need to force the result into an Array
type: let first5 = Array(someArray.prefix(5))
It would involve the cURL PHP extension.
$ch = curl_init('http://www.provider.com/process.jsp');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "id=12345&name=John");
curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1); // RETURN THE CONTENTS OF THE CALL
$resp = curl_exec($ch);
Information provided by @Gord
As of September 2019 pywin32
is now available from PyPI and installs the latest version (currently version 224). This is done via the pip
command
pip install pywin32
If you wish to get an older version the sourceforge link below would probably have the desired version, if not you can use the command, where xxx
is the version you require, e.g. 224
pip install pywin32==xxx
This differs to the pip
command below as that one uses pypiwin32
which currently installs an older (namely 223)
Browsing the docs I see no reason for these commands to work for all python3.x
versions, I am unsure on python2.7
and below so you would have to try them and if they do not work then the solutions below will work.
Probably now undesirable solutions but certainly still valid as of September 2019
There is no version of specific version ofwin32api
. You have to get the pywin32
module which currently cannot be installed via pip
. It is only available from this link at the moment.
https://sourceforge.net/projects/pywin32/files/pywin32/Build%20220/
The install does not take long and it pretty much all done for you. Just make sure to get the right version of it depending on your python
version :)
EDIT
Since I posted my answer there are other alternatives to downloading the win32api
module.
It is now available to download through pip
using this command;
pip install pypiwin32
Also it can be installed from this GitHub repository as provided in comments by @Heath
A note in response to Belter's comment on fedtuck's accepted answer above, since I lack the reputation to add comments.
This is not true for any of which I am aware, in line with the Mozilla docs
disabled equals to true or false
When the disabled attribute is present the element is disabled regardless of value. See this example
<input placeholder="i can be changed"/>
<input disabled placeholder="i can NOT be changed"/>
<input disabled="true" placeholder="i can NOT be changed"/>
<input disabled="false" placeholder="i can NOT be changed"/>
If it is a console application, use Ctrl + F5.
if you have FK constraints and you don't want to remove the constraint from the table. use "index" instead of primary. then you will be able to alter it's type to auto increment
This combines both Rob's original answer and Pilau's update for 2016
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
// At least Safari 3+: "[object HTMLElementConstructor]"
var isChrome = !!window.chrome && !isOpera; // Chrome 1+
var isIE = /*@cc_on!@*/false || !!document.documentMode;
// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+
var output = 'Detecting browsers by ducktyping:<hr>';
output += 'isFirefox: ' + isFirefox + '<br>';
output += 'isChrome: ' + isChrome + '<br>';
output += 'isSafari: ' + isSafari + '<br>';
output += 'isOpera: ' + isOpera + '<br>';
output += 'isIE: ' + isIE + '<br>';
output += 'isIE Edge: ' + isEdge + '<br>';
document.body.innerHTML = output;
After installing Microsoft.Web.Infrastructure through Nuget-Package Manager
PM> Install-Package Microsoft.Web.Infrastructure
Copy the Microsoft.Web.Infrastructure.dll
manually from the Nuget-Package
folder on your web application and then paste it in your bin folder of your web application deployed on the web server.
packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll
It worked for me.
The problem is that omega
in your case is matrix
of dimensions 1 * 1
. You should convert it to a vector if you wish to multiply t(X) %*% X
by a scalar (that is omega
)
In particular, you'll have to replace this line:
omega = rgamma(1,a0,1) / L0
with:
omega = as.vector(rgamma(1,a0,1) / L0)
everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.)
or c(t(.))
. Both are equivalent.
Here's the modified code that should work:
gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1,
a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
m0 = c(m01, m02)
C0 = matrix(nrow = 2, ncol = 2)
C0[1,1] = 1 / k01
C0[1,2] = 0
C0[2,1] = 0
C0[2,2] = 1 / k02
beta = mvrnorm(1,m0,C0)
omega = as.vector(rgamma(1,a0,1) / L0)
draws = matrix(ncol = 3,nrow = ndraw)
it = -nburn
while (it < ndraw) {
it = it + 1
C1 = solve(solve(C0) + omega * t(X) %*% X)
m1 = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
beta = mvrnorm(1, m1, C1)
a1 = a0 + n / 2
L1 = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2
omega = as.vector(rgamma(1, a1, 1) / L1)
if (it > 0) {
draws[it,1] = beta[1]
draws[it,2] = beta[2]
draws[it,3] = omega
}
}
return(draws)
}
In .NET 4.0 you can use LINQ:
if (yourText.All(char.IsLetterOrDigit))
{
//just letters and digits.
}
yourText.All
will stop execute and return false
the first time char.IsLetterOrDigit
reports false
since the contract of All
cannot be fulfilled then.
Note! this answer do not strictly check alphanumerics (which typically is A-Z, a-z and 0-9). This answer allows local characters like åäö
.
Update 2018-01-29
The syntax above only works when you use a single method that has a single argument of the correct type (in this case char
).
To use multiple conditions, you need to write like this:
if (yourText.All(x => char.IsLetterOrDigit(x) || char.IsWhiteSpace(x)))
{
}
You can use calc (100% - 100px) on the fluid element, along with display:inline-block for both elements.
Be aware that there should not be any space between the tags, otherwise you will have to consider that space in your calc too.
.left{
display:inline-block;
width:100px;
}
.right{
display:inline-block;
width:calc(100% - 100px);
}
<div class=“left”></div><div class=“right”></div>
Quick example: http://jsfiddle.net/dw689mt4/1/
Add an END
at last before alias name.
CASE WHEN countries LIKE '%'+@selCountry+'%'
THEN 'national' ELSE 'regional'
END AS validity
For example:
SELECT CASE WHEN countries LIKE '%'+@selCountry+'%'
THEN 'national' ELSE 'regional'
END AS validity
FROM TableName
/*This code will use gridview sum inside data list*/
SumOFdata(grd_DataDetail);
private void SumOFEPFWages(GridView grd)
{
Label lbl_TotAmt = (Label)grd.FooterRow.FindControl("lblTotGrossW");
/*Sum of the total Amount of the day*/
foreach (GridViewRow gvr in grd.Rows)
{
Label lbl_Amount = (Label)gvr.FindControl("lblGrossS");
lbl_TotAmt.Text = (Convert.ToDouble(lbl_Amount.Text) + Convert.ToDouble(lbl_TotAmt.Text)).ToString();
}
}
That DateTime format is actually ISO 8601 DateTime. JSON does not specify any particular format for dates/times. If you Google a bit, you will find plenty of implementations to parse it in Java.
If you are open to using something other than Java's built-in Date/Time/Calendar classes, I would also suggest Joda Time. They offer (among many things) a ISODateTimeFormat
to parse these kinds of strings.
the above code for chrome is working fine. i have tried like this in mozila but its not working. i found the solution for that
For mozila
input[type=number] {
-moz-appearance: textfield;
appearance: textfield;
margin: 0;
}
Thanks Sanjib
Another solution is to user axios:
npm install axios
Code will be like:
const url = `${this.env.someMicroservice.address}/v1/my-end-point`;
const { data } = await axios.get<MyInterface>(url, {
auth: {
username: this.env.auth.user,
password: this.env.auth.pass
}
});
return data;
After spending a lot of time trying to resolve this issue, finally found a solution that works. The solution makes use of Spring's ResourceUtils. Should work for json files as well.
Thanks for the well written page by Lokesh Gupta : Blog
package utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.io.File;
public class Utils {
private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class.getName());
public static Properties fetchProperties(){
Properties properties = new Properties();
try {
File file = ResourceUtils.getFile("classpath:application.properties");
InputStream in = new FileInputStream(file);
properties.load(in);
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
return properties;
}
}
To answer a few concerns on the comments :
Pretty sure I had this running on Amazon EC2 using java -jar target/image-service-slave-1.0-SNAPSHOT.jar
Look at my github repo : https://github.com/johnsanthosh/image-service to figure out the right way to run this from a JAR.
In my case, I was using MySQL WorkBench and
ALTER TABLE table_name RENAME COLUMN old_name new_name varchar(50) not null;
// without TO and specify data type of that column
was enough to change the column name!
With recent version of Pandas, you can do
df.N.hist(by=df.Letter)
Just like with the solutions above, the axes will be different for each subplot. I have not solved that one yet.
var form = $('#job-request-form')[0];
var formData = new FormData(form);
event.preventDefault();
$.ajax({
url: "/send_resume/", // the endpoint
type: "POST", // http method
processData: false,
contentType: false,
data: formData,
It worked for me! just set processData and contentType False.
There is a good solution to this issue:
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper objectMapper = new ObjectMapper();
***DTO premierDriverInfoDTO = objectMapper.convertValue(jsonString, ***DTO.class);
Map<String, String> map = objectMapper.convertValue(jsonString, Map.class);
Why did this issue occur? I guess you didn't specify the specific type when converting a string to the object, which is a class with a generic type, such as, User <T>.
Maybe there is another way to solve it, using Gson instead of ObjectMapper. (or see here Deserializing Generic Types with GSON)
Gson gson = new GsonBuilder().create();
Type type = new TypeToken<BaseResponseDTO<List<PaymentSummaryDTO>>>(){}.getType();
BaseResponseDTO<List<PaymentSummaryDTO>> results = gson.fromJson(jsonString, type);
BigDecimal revenue = results.getResult().get(0).getRevenue();
In addition to @Malk, I wanted to clear all fields in the popup, except the hidden fields. To do that just use this:
$('.modal').on('hidden.bs.modal', function () {
$(this)
.find("input:not([type=hidden]),textarea,select")
.val('')
.end()
.find("input[type=checkbox], input[type=radio]")
.prop("checked", "")
.end();
});
This will clear all fields, except the hidden ones.
It seems that for m, I dragged the files into the project and after that didn't work, clicked file "add files to project". Both were the incorrect approach. just drag it into the projects folder (in finder) that houses the other .h and .m files.
function chgAction( action_name )
{
if( action_name=="aaa" ) {
document.search-theme-form.action = "/AAA";
}
else if( action_name=="bbb" ) {
document.search-theme-form.action = "/BBB";
}
else if( action_name=="ccc" ) {
document.search-theme-form.action = "/CCC";
}
}
And your form needs to have name
in this case:
<form action="/" accept-charset="UTF-8" method="post" name="search-theme-form" id="search-theme-form">
The syntax you are using is new to SQL Server 2008:
INSERT INTO [MyDB].[dbo].[MyTable]
([FieldID]
,[Description])
VALUES
(1000,N'test'),(1001,N'test2')
For SQL Server 2005, you will have to use multiple INSERT
statements:
INSERT INTO [MyDB].[dbo].[MyTable]
([FieldID]
,[Description])
VALUES
(1000,N'test')
INSERT INTO [MyDB].[dbo].[MyTable]
([FieldID]
,[Description])
VALUES
(1001,N'test2')
One other option is to use UNION ALL
:
INSERT INTO [MyDB].[dbo].[MyTable]
([FieldID]
,[Description])
SELECT 1000, N'test' UNION ALL
SELECT 1001, N'test2'
Just try below a simple solution:
JsonObject body=new JsonObject();
body.add("orders", (JsonElement) orders);
whenever my JSON request is like:
{
"role": "RT",
"orders": [
{
"order_id": "ORDER201908aPq9Gs",
"cart_id": 164444,
"affiliate_id": 0,
"orm_order_status": 9,
"status_comments": "IC DUE - Auto moved to Instruction Call Due after 48hrs",
"status_date": "2020-04-15",
}
]
}
Edit 2
I finally found a solution by implementing my forward action like that:
private void applyForward() {
FacesContext facesContext = FacesContext.getCurrentInstance();
// Find where to redirect the user.
String redirect = getTheFromOutCome();
// Change the Navigation context.
NavigationHandler myNav = facesContext.getApplication().getNavigationHandler();
myNav.handleNavigation(facesContext, null, redirect);
// Update the view root
UIViewRoot vr = facesContext.getViewRoot();
if (vr != null) {
// Get the URL where to redirect the user
String url = facesContext.getExternalContext().getRequestContextPath();
url = url + "/" + vr.getViewId().replace(".xhtml", ".jsf");
Object obj = facesContext.getExternalContext().getResponse();
if (obj instanceof HttpServletResponse) {
HttpServletResponse response = (HttpServletResponse) obj;
try {
// Redirect the user now.
response.sendRedirect(response.encodeURL(url));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
It works (at least regarding my first tests), but I still don't like the way it is implemented... Any better idea?
Edit This solution does not work. Indeed, when the doForward()
function is called, the JSF lifecycle has already been started, and then recreate a new request is not possible.
One idea to solve this issue, but I don't really like it, is to force the doForward()
action during one of the setBindedInputHidden()
method:
private boolean actionDefined = false;
private boolean actionParamDefined = false;
public void setHiddenActionParam(HtmlInputHidden hiddenActionParam) {
this.hiddenActionParam = hiddenActionParam;
String actionParam = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("actionParam");
this.hiddenActionParam.setValue(actionParam);
actionParamDefined = true;
forwardAction();
}
public void setHiddenAction(HtmlInputHidden hiddenAction) {
this.hiddenAction = hiddenAction;
String action = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("action");
this.hiddenAction.setValue(action);
actionDefined = true;
forwardAction();
}
private void forwardAction() {
if (!actionDefined || !actionParamDefined) {
// As one of the inputHidden was not binded yet, we do nothing...
return;
}
// Now, both action and actionParam inputHidden are binded, we can execute the forward...
doForward(null);
}
This solution does not involve any Javascript call, and works does not work.
Pong doesn't mean web service on the server is running; it merely means that server is replying to ICMP echo. I would recommend using curl and check its return value.
To select rows according to one 'cell_type' (e.g. 'hesc'), use ==
:
expr[expr$cell_type == "hesc", ]
To select rows according to two or more different 'cell_type', (e.g. either 'hesc' or 'bj fibroblast'), use %in%
:
expr[expr$cell_type %in% c("hesc", "bj fibroblast"), ]
In Microsoft SQL Server Management Studio you can right-click on the database you wish to backup and click Tasks -> Generate Scripts.
This pops open a wizard where you can set the following in order to perform a decent backup of your database, even on a remote server:
Once it's done its thing, you'll have a backup script ready in front of you. Create a new local (or remote) database, and change the first 'USE' statement in the script to use your new database. Save the script in a safe place, and go ahead and run it against your new empty database. This should create you a (nearly) duplicate local database you can then backup as you like.
If you have full access to the remote database, you can choose to check 'script all objects' in the wizard's first window and then change the 'Script Database' option to True on the next window. Watch out though, you'll need to perform a full search & replace of the database name in the script to a new database which in this case you won't have to create before running the script. This should create a more accurate duplicate but is sometimes not available due to permissions restrictions.
You need to add overflow:auto
to your parent div for it to encompass the inner floated div:
<div style="margin:0 auto;width: 960px; min-height: 100px; background-color:orange;overflow:auto">
<div style="width:500px; height:200px; background-color:black; float:right">
</div>
</div>
Check out this link for more details.
To find files which are created in last one hour in current directory, you can use -amin
find . -amin -60 -type f
This will find files which are created with in last 1 hour.
did you try this ?
$("#yourdiv").load(url, function(){
your functions goes here !!!
});
Base on this.
Step by step:
On your remote server:
sudo wget -O /usr/local/bin/rsub https://raw.github.com/aurora/rmate/master/rmate
sudo chmod a+x /usr/local/bin/rsub
Just keep your ST3 editor open, and you can easily edit remote files with
rsub myfile.txt
EDIT: if you get "no such file or directory", it's because your /usr/local/bin is not in your PATH. Just add the directory to your path:
echo "export PATH=\"$PATH:/usr/local/bin\"" >> $HOME/.bashrc
Now just log off, log back in, and you'll be all set.
Just one more thing that hasn't been added yet
In Python 2, if you want to print a variable that has unicode and use .format()
, then do this (make the base string that is being formatted a unicode string with u''
:
>>> text = "Université de Montréal"
>>> print(u"This is unicode: {}".format(text))
>>> This is unicode: Université de Montréal
var sortedArray = [];
for(var i=0; i < sortingArr.length; i++) {
var found = false;
for(var j=0; j < itemsArray.length && !found; j++) {
if(itemsArray[j][1] == sortingArr[i]) {
sortedArray.push(itemsArray[j]);
itemsArray.splice(j,1);
found = true;
}
}
}
Resulting order: Bob,Jason,Henry,Thomas,Anne,Andrew
You can use an HTTP Handler (.ashx) to download a file, like this:
DownloadFile.ashx:
public class DownloadFile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition",
"attachment; filename=" + fileName + ";");
response.TransmitFile(Server.MapPath("FileDownload.csv"));
response.Flush();
response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
Then you can call the HTTP Handler from the button click event handler, like this:
Markup:
<asp:Button ID="btnDownload" runat="server" Text="Download File"
OnClick="btnDownload_Click"/>
Code-Behind:
protected void btnDownload_Click(object sender, EventArgs e)
{
Response.Redirect("PathToHttpHandler/DownloadFile.ashx");
}
Passing a parameter to the HTTP Handler:
You can simply append a query string variable to the Response.Redirect()
, like this:
Response.Redirect("PathToHttpHandler/DownloadFile.ashx?yourVariable=yourValue");
Then in the actual handler code you can use the Request
object in the HttpContext
to grab the query string variable value, like this:
System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
string yourVariableValue = request.QueryString["yourVariable"];
// Use the yourVariableValue here
Note - it is common to pass a filename as a query string parameter to suggest to the user what the file actually is, in which case they can override that name value with Save As...
What is gone is gone. The only protection I know of is regular backup.
You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .
public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
try{
JSONObject value = json.getJSONObject(key);
parse(value,out);
}catch(Exception e){
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
public static void main(String[] args) throws JSONException {
String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";
JSONObject object = new JSONObject(json);
JSONObject info = object.getJSONObject("ipinfo");
Map<String,String> out = new HashMap<String, String>();
parse(info,out);
String latitude = out.get("latitude");
String longitude = out.get("longitude");
String city = out.get("city");
String state = out.get("state");
String country = out.get("country");
String postal = out.get("postal_code");
System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);
System.out.println("ALL VALUE " + out);
}
Output:
Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}
Problem statement – Getting java.awt.HeadlessException while trying to initialize java.awt.Component from the application as the tomcat environment does not have any head(terminal).
Issue – The linux virtual environment was setup without a virtual display terminal. Tried to install virtual display – Xvfb, but Xvfb has been taken off by the redhat community.
Solution – Installed ‘xorg-x11-drv-vmware.x86_64’ using yum install xorg-x11-drv-vmware.x86_64 and executed startx. Finally set the display to :0.0 using export DISPLAY=:0.0 and then executed xhost +
Client side For disabling validation for a form, multiple options based on my research is given below. One of them would would hopefully work for you.
Option 1
I prefer this, and this works perfectly for me.
(function ($) {
$.fn.turnOffValidation = function (form) {
var settings = form.validate().settings;
for (var ruleIndex in settings.rules) {
delete settings.rules[ruleIndex];
}
};
})(jQuery);
and invoking it like
$('#btn').click(function () {
$(this).turnOffValidation(jQuery('#myForm'));
});
Option 2
$('your selector here').data('val', false);
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
Option 3
var settings = $.data($('#myForm').get(0), 'validator').settings;
settings.ignore = ".input";
Option 4
$("form").get(0).submit();
jQuery('#createForm').unbind('submit').submit();
Option 5
$('input selector').each(function () {
$(this).rules('remove');
});
Server Side
Create an attribute and mark your action method with that attribute. Customize this to adapt to your specific needs.
[AttributeUsage(AttributeTargets.All)]
public class IgnoreValidationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var modelState = filterContext.Controller.ViewData.ModelState;
foreach (var modelValue in modelState.Values)
{
modelValue.Errors.Clear();
}
}
}
A better approach has been described here Enable/Disable mvc server side validation dynamically
To accept both @PathVariable
and @RequestParam
in the same /user
endpoint:
@GetMapping(path = {"/user", "/user/{data}"})
public void user(@PathVariable(required=false,name="data") String data,
@RequestParam(required=false) Map<String,String> qparams) {
qparams.forEach((a,b) -> {
System.out.println(String.format("%s -> %s",a,b));
}
if (data != null) {
System.out.println(data);
}
}
Testing with curl:
Adding "-EA Stop" solved this for me.
I have used the following code. It works fine for me.
$('a').bind('click', function(e) {
e.stopPropagation();
});
It's also important to note that not all supported languages compair consistently with thrift or protobuf. At this point it's a matter of the modules implementation in addition to the underlying serialization. Take care to check benchmarks for whatever language you plan to use.
If you want to detach existing object follow @Slauma's advice. If you want to load objects without tracking changes use:
var data = context.MyEntities.AsNoTracking().Where(...).ToList();
As mentioned in comment this will not completely detach entities. They are still attached and lazy loading works but entities are not tracked. This should be used for example if you want to load entity only to read data and you don't plan to modify them.
Did you try adb remount
after giving adb root
?
The syntax is
pid_t waitpid(pid_t pid, int *statusPtr, int options);
1.where pid is the process of the child it should wait.
2.statusPtr is a pointer to the location where status information for the terminating process is to be stored.
3.specifies optional actions for the waitpid function. Either of the following option flags may be specified, or they can be combined with a bitwise inclusive OR operator:
WNOHANG WUNTRACED WCONTINUED
If successful, waitpid returns the process ID of the terminated process whose status was reported. If unsuccessful, a -1 is returned.
benifits over wait
1.Waitpid can used when you have more than one child for the process and you want to wait for particular child to get its execution done before parent resumes
2.waitpid supports job control
3.it supports non blocking of the parent process
You can created AVD, select API Level equal your tagetApi andr compileApi, it works for me.
I had the same issue. The problem was because 'ng-controller' was defined twice (in routing and also in the HTML).
Type-check with the -is operator returns false for any null value. In most cases, if not all, $value -is [System.Object] will be true for any possible non-null value. (In all cases, it will be false for any null-value.)
My value is nothing if not an object.
You asked why, and the other answers, imo, don't really say why it's ok to call your super's constructor, but only if it's the very first line. The reason is that you're not really calling the constructor. In C++, the equivalent syntax is
MySubClass: MyClass {
public:
MySubClass(int a, int b): MyClass(a+b)
{
}
};
When you see the initializer clause on its own like that, before the open brace, you know it's special. It runs before any of the rest of the constructor runs and in fact before any of the member variables are initialized. It's not that different for Java. There's a way to get some code (other constructors) to run before the constructor really starts, before any members of the subclass are initialized. And that way is to put the "call" (eg super
) on the very first line. (In a way, that super
or this
is kind of before the first open brace, even though you type it after, because it will be executed before you get to the point that everything is fully constructed.) Any other code after the open brace (like int c = a + b;
) makes the compiler say "oh, ok, no other constructors, we can initialize everything then." So it runs off and initializes your super class and your members and whatnot and then starts executing the code after the open brace.
If, a few lines later, it meets some code saying "oh yeah when you're constructing this object, here are the parameters I want you to pass along to the constructor for the base class", it's too late and it doesn't make any sense. So you get a compiler error.
In the iframe: So that means you have to add some code in the iframe page. Simply add this script to your code IN THE IFRAME:
<body onload="parent.alertsize(document.body.scrollHeight);">
In the holding page: In the page holding the iframe (in my case with ID="myiframe") add a small javascript:
<script>
function alertsize(pixels){
pixels+=32;
document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
What happens now is that when the iframe is loaded it triggers a javascript in the parent window, which in this case is the page holding the iframe.
To that JavaScript function it sends how many pixels its (iframe) height is.
The parent window takes the number, adds 32 to it to avoid scrollbars, and sets the iframe height to the new number.
That's it, nothing else is needed.
But if you like to know some more small tricks keep on reading...
DYNAMIC HEIGHT IN THE IFRAME? If you like me like to toggle content the iframe height will change (without the page reloading and triggering the onload). I usually add a very simple toggle script I found online:
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
}
</script>
to that script just add:
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
parent.alertsize(document.body.scrollHeight); // ADD THIS LINE!
}
</script>
How you use the above script is easy:
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
For those that like to just cut and paste and go from there here is the two pages. In my case I had them in the same folder, but it should work cross domain too (I think...)
Complete holding page code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>THE IFRAME HOLDER</title>
<script>
function alertsize(pixels){
pixels+=32;
document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
</head>
<body style="background:silver;">
<iframe src='theiframe.htm' style='width:458px;background:white;' frameborder='0' id="myiframe" scrolling="auto"></iframe>
</body>
</html>
Complete iframe code: (this iframe named "theiframe.htm")
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>IFRAME CONTENT</title>
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
parent.alertsize(document.body.scrollHeight);
}
</script>
</head>
<body onload="parent.alertsize(document.body.scrollHeight);">
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
THE END
</body>
</html>
I recently had this problem and think these steps are easy to follow if any prior solution or link is missing detail.
How to create a .jar
using IntelliJ IDEA 14.1.5:
I was not able to get notifyDataSetChanged() to work on updating my SimpleAdapter, so instead I tried first removing all views that were attached to the parent layout using removeAllViews(), then adding the ListView, and that worked, allowing me to update the UI:
LinearLayout results = (LinearLayout)findViewById(R.id.results);
ListView lv = new ListView(this);
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
SimpleAdapter adapter = new SimpleAdapter( this, list, R.layout.directory_row,
new String[] { "name", "dept" }, new int[] { R.id.name, R.id.dept } );
for (...) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", name);
map.put("dept", dept);
list.add(map);
}
lv.setAdapter(adapter);
results.removeAllViews();
results.addView(lv);
;
to separate command \\
on any backslashes \
. "'
for passing safe address to switch command like "'PATH'".This ps1 command install locale pfx certificate.
powershell -Command "$pfxPassword = ConvertTo-SecureString -String "12345678" -Force -AsPlainText ; Import-PfxCertificate -FilePath "'C:\\Program Files\\VpnManagement\\resources\\assets\\cert\\localhost.pfx'" Cert:\\LocalMachine\\My -Password $pfxPassword ; Import-PfxCertificate -FilePath "'C:\\Program Files\\VpnManagement\\resources\\assets\\cert\\localhost.pfx'" Cert:\\LocalMachine\\Root -Password $pfxPassword"
<img title="<a href="javascript:alert('hello world')">The Link</a>" />
This is exactly how it worked for me. For some reason the above code failed.
This one runs a check every 3 minutes for any files in there and auto moves it to the destination folder. If you need to be prompted for conflicts then change the /y to /-y
:backup
move /y "D:\Dropbox\Dropbox\Camera Uploads\*.*" "D:\Archive\Camera Uploads\"
timeout 360
goto backup
instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0;
once your window has scrolled pass a certain height:
jQuery
$(window).scroll(function(){
if ($(this).scrollTop() > 135) {
$('#task_flyout').addClass('fixed');
} else {
$('#task_flyout').removeClass('fixed');
}
});
css
.fixed {position:fixed; top:0; left:0;}
IF you have Windows PowerShell installed (I think it's included since XP) you can just run from cmd.exe:
Head Command:
powershell -command "& {Get-Content *filename* -TotalCount *n*}"
Tail Command:
powershell -command "& {Get-Content *filename* | Select-Object -last *n*}"
or, directly from PowerShell:
Get-Content *filename* -TotalCount *n*
Get-Content *filename* | Select-Object -last *n*
update
PowerShell 3.0 (Windows 8 and higher) added Tail
command with alias Last
.
Head
and First
aliases to TotalCount
were also added.
So, commands can be re-written as
Get-Content *filename* -Head *n*
Get-Content *filename* -Tail *n*
Since Marco's answer is deprecated, you must use the following syntax (according jasonlfunk's comment) :
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://www.example.com/user/create', [
'form_params' => [
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword',
]
]);
$response = $client->request('POST', 'http://www.example.com/files/post', [
'multipart' => [
[
'name' => 'file_name',
'contents' => fopen('/path/to/file', 'r')
],
[
'name' => 'csv_header',
'contents' => 'First Name, Last Name, Username',
'filename' => 'csv_header.csv'
]
]
]);
// PUT
$client->put('http://www.example.com/user/4', [
'body' => [
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword',
],
'timeout' => 5
]);
// DELETE
$client->delete('http://www.example.com/user');
Usefull for long server operations.
$client = new \GuzzleHttp\Client();
$promise = $client->requestAsync('POST', 'http://www.example.com/user/create', [
'form_params' => [
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword',
]
]);
$promise->then(
function (ResponseInterface $res) {
echo $res->getStatusCode() . "\n";
},
function (RequestException $e) {
echo $e->getMessage() . "\n";
echo $e->getRequest()->getMethod();
}
);
According to documentation, you can set headers :
// Set various headers on a request
$client->request('GET', '/get', [
'headers' => [
'User-Agent' => 'testing/1.0',
'Accept' => 'application/json',
'X-Foo' => ['Bar', 'Baz']
]
]);
If you want more details information, you can use debug
option like this :
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://www.example.com/user/create', [
'form_params' => [
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword',
],
// If you want more informations during request
'debug' => true
]);
Documentation is more explicits about new possibilities.
I tried all this and in the end, simply using a title="text here"
worked for my system. Note there is no blank option
<select name="Restrictions" class="selectpicker show-tick form-control"
data-live-search="true" multiple="multiple" title="Choose Multiple">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Here is another fancy way of doing this:
$ ls | grep .java | xargs -I {} javac {} ; jar -cf myJar.jar *.class
Which will grab all the .java files ( ls | grep .java
) from your current directory and compile them into .class (xargs -I {} javac {}
) and then create the jar file from the previously compiled classes (jar -cf myJar.jar *.class
).
Use attributed string:
// Define attributes
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :Dictionary = [NSFontAttributeName : labelFont]
// Create attributed string
var attrString = NSAttributedString(string: "Foo", attributes:attributes)
label.attributedText = attrString
You need to define attributes.
Using attributed string you can mix colors, sizes, fonts etc within one text
How about changing
<input type='checkbox' ng-click='onCompleteTodo(todo)' ng-model="todo.done">
to
<input type='checkbox' ng-change='onCompleteTodo(todo)' ng-model="todo.done">
From docs:
Evaluate given expression when user changes the input. The expression is not evaluated when the value change is coming from the model.
Note, this directive requires
ngModel
to be present.
I got this working.
log4j.appender.file.File=${LogFilePath}
-DLogFilePath=C:\work\MyLogFile.log
for activity
findViewById(android.R.id.content).setBackgroundColor(color)
It's an old question, however might be useful for someone like me.
lodash
has _.inRange()
function https://lodash.com/docs/4.17.4#inRange
Example:
_.inRange(3, 2, 4);
// => true
Please note that this method utilizes the Lodash
utility library, and requires access to an installed version of Lodash.
Inside template this working finely.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="">
<input ng-model="name" value="0">
<p>My first expression: {{ (name-0) + 5 }}</p>
</div>
</body>
</html>
FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
/* print some text */
const char *text = "Write this to the file";
fprintf(f, "Some text: %s\n", text);
/* print integers and floats */
int i = 1;
float py = 3.1415927;
fprintf(f, "Integer: %d, float: %f\n", i, py);
/* printing single chatacters */
char c = 'A';
fprintf(f, "A character: %c\n", c);
fclose(f);
user@host> g++ hw.cpp
user@host> ./a.out
You can use a method proposed by @Yar (with some modification):
#define mustOverride() @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"%s must be overridden in a subclass/category", __PRETTY_FUNCTION__] userInfo:nil]
#define setMustOverride() NSLog(@"%@ - method not implemented", NSStringFromClass([self class])); mustOverride()
Here you will get a message like:
<Date> ProjectName[7921:1967092] <Class where method not implemented> - method not implemented
<Date> ProjectName[7921:1967092] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[<Base class (if inherited or same if not> <Method name>] must be overridden in a subclass/category'
Or assertion:
NSAssert(![self respondsToSelector:@selector(<MethodName>)], @"Not implemented");
In this case you will get:
<Date> ProjectName[7926:1967491] *** Assertion failure in -[<Class Name> <Method name>], /Users/kirill/Documents/Projects/root/<ProjectName> Services/Classes/ViewControllers/YourClass:53
Also you can use protocols and other solutions - but this is one of the simplest ones.
Dont work for me, need to put scope in plural
validates_uniqueness_of :teacher_id, :scopes => [:semester_id, :class_id]
If you want to do it on page load you can use useLayoutEffect, and useRef.
import React, { useRef, useLayoutEffect } from 'react'
const ScrollDemo = () => {
const myRef = useRef(null)
useLayoutEffect(() => {
window.scrollTo({
behavior: "smooth",
top: myRef.current.offsetTop,
});
}, [myRef.current]);
return (
<>
<div ref={myRef}>I wanna be seen</div>
</>
)
}
If you're parsing the file with a FOR command in a batch file a semicolon works (;)
REM test.bat contents
for /F "tokens=1-3 delims=," %%a in (test.csv) do @Echo %%a, %%b, %%c
;test.csv contents (this line is a comment)
;1,ignore this line,no it shouldn't
2,parse this line,yes it should!
;3,ignore this line,no it shouldn't
4,parse this line,yes it should!
OUTPUT:
2, parse this line, yes it should!
4, parse this line, yes it should!
The problem is with navbar-fixed-top, which will overlay your content unless specify body-padding. No solution provided here works in 100% cases. The JQuery solution blink/shift the page after the page is loaded, which looks weird.
The real solution for me is not to use navbar-fixed-top, but navbar-static-top.
.navbar { margin-bottom:0px;} //for jumtron support, see http://stackoverflow.com/questions/23911242/gap-between-navbar-and-jumbotron
<nav class="navbar navbar-inverse navbar-static-top">
...
</nav>
If you are using angular-cli, there is yet another option:
Angular CLI provides environment files in src/environments
(default ones are environment.ts
(dev) and environment.prod.ts
(production)).
Note that you need to provide the config parameters in all environment.*
files, e.g.,
environment.ts:
export const environment = {
production: false,
apiEndpoint: 'http://localhost:8000/api/v1'
};
environment.prod.ts:
export const environment = {
production: true,
apiEndpoint: '__your_production_server__'
};
and use them in your service (the correct environment file is chosen automatically):
api.service.ts
// ... other imports
import { environment } from '../../environments/environment';
@Injectable()
export class ApiService {
public apiRequest(): Observable<MyObject[]> {
const path = environment.apiEndpoint + `/objects`;
// ...
}
// ...
}
Read more on application environments on Github (Angular CLI version 6) or in the official Angular guide (version 7).
To elaborate on previous answers about the "every x units" part, here is what I came up with:
# Draw 5 vertical lines
n = 5
# ... evenly spaced between x0 and x1
x0 = 1.0
x1 = 2.0
dx = (x1-x0)/(n-1.0)
# ... each line going from y0 to y1
y0 = 0
y1 = 10
do for [i = 0:n-1] {
x = x0 + i*dx
set arrow from x,y0 to x,y1 nohead linecolor "blue" # add other styling options if needed
}
Simple, In first Activity-
EditText name= (EditText) findViewById(R.id.editTextName);
Button button= (Button) findViewById(R.id.buttonGo);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,Main2Activity.class);
i.putExtra("name",name.getText().toString());
startActivity(i);
}
});
In second Activity-
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
TextView t = (TextView) findViewById(R.id.textView);
Bundle bundle=getIntent().getExtras();
String s=bundle.getString("name");
t.setText(s);
}
You can add if/else conditions if you want.
Here's a simple example of how to load JSON data into an Angular model.
I have a JSON 'GET' web service which returns a list of Customer details, from an online copy of Microsoft's Northwind SQL Server database.
http://www.iNorthwind.com/Service1.svc/getAllCustomers
It returns some JSON data which looks like this:
{
"GetAllCustomersResult" :
[
{
"CompanyName": "Alfreds Futterkiste",
"CustomerID": "ALFKI"
},
{
"CompanyName": "Ana Trujillo Emparedados y helados",
"CustomerID": "ANATR"
},
{
"CompanyName": "Antonio Moreno Taquería",
"CustomerID": "ANTON"
}
]
}
..and I want to populate a drop down list with this data, to look like this...
I want the text of each item to come from the "CompanyName" field, and the ID to come from the "CustomerID" fields.
How would I do it ?
My Angular controller would look like this:
function MikesAngularController($scope, $http) {
$scope.listOfCustomers = null;
$http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
.success(function (data) {
$scope.listOfCustomers = data.GetAllCustomersResult;
})
.error(function (data, status, headers, config) {
// Do some error handling here
});
}
... which fills a "listOfCustomers" variable with this set of JSON data.
Then, in my HTML page, I'd use this:
<div ng-controller='MikesAngularController'>
<span>Please select a customer:</span>
<select ng-model="selectedCustomer" ng-options="customer.CustomerID as customer.CompanyName for customer in listOfCustomers" style="width:350px;"></select>
</div>
And that's it. We can now see a list of our JSON data on a web page, ready to be used.
The key to this is in the "ng-options" tag:
customer.CustomerID as customer.CompanyName for customer in listOfCustomers
It's a strange syntax to get your head around !
When the user selects an item in this list, the "$scope.selectedCustomer" variable will be set to the ID (the CustomerID field) of that Customer record.
The full script for this example can be found here:
Mike
In first statement you define variable, which common for all of the objects (class static field).
In the second statement you define variable, which belongs to each created object (a lot of copies).
In your case you should use the first one.
I know you asked for GET and POST but I will provide CRUD since others may need this just in case: (this was tested in Python 3.7)
#!/usr/bin/env python3
import http.client
import json
print("\n GET example")
conn = http.client.HTTPSConnection("httpbin.org")
conn.request("GET", "/get")
response = conn.getresponse()
data = response.read().decode('utf-8')
print(response.status, response.reason)
print(data)
print("\n POST example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body = {'text': 'testing post'}
json_data = json.dumps(post_body)
conn.request('POST', '/post', json_data, headers)
response = conn.getresponse()
print(response.read().decode())
print(response.status, response.reason)
print("\n PUT example ")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing put'}
json_data = json.dumps(post_body)
conn.request('PUT', '/put', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)
print("\n delete example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing delete'}
json_data = json.dumps(post_body)
conn.request('DELETE', '/delete', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)
bash
has a "built-in" command called "echo":
$ type echo
echo is a shell builtin
Additionally, there is an "echo" command that is a proper executable (that is, the shell forks and execs /bin/echo
, as opposed to interpreting echo
and executing it):
$ ls -l /bin/echo
-rwxr-xr-x 1 root root 22856 Jul 21 2011 /bin/echo
The behavior of either echo
's WRT to \c
and -n
varies. Your best bet is to use printf
, which is available on four different *NIX flavors that I looked at:
$ printf "a line without trailing linefeed"
$ printf "a line with trailing linefeed\n"
You can do this more easy way. And 100% works that you want
<?php
$servername = "localhost";
$username = "root";
$password = ""; //your database password
$dbname = "demo"; //your database name
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
else
{
//echo ("Connect Successfully");
}
$query = "SELECT Date_time, Tempout FROM alarm_value"; // select column
$aresult = $con->query($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Massive Electronics</title>
<script type="text/javascript" src="loder.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
var data = google.visualization.arrayToDataTable([
['Date_time','Tempout'],
<?php
while($row = mysqli_fetch_assoc($aresult)){
echo "['".$row["Date_time"]."', ".$row["Tempout"]."],";
}
?>
]);
var options = {
title: 'Date_time Vs Room Out Temp',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.AreaChart(document.getElementById('areachart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="areachart" style="width: 900px; height: 400px"></div>
</body>
</html>
loder.js link here loder.js
ClickOnce applications DO reside in a subdirectory of C:\Documents & Settings. They don't have "clean" installation directories because the local files are essentially "temporarily" downloaded to allow the application to run on the local PC and execution of the application is controlled from the ClickOnce server that they are deployed on depending on publishing settings (Checking for updates, version requirements, etc).
ObservableCollection < T > has a constructor overload which takes IEnumerable < T >
Example for a List of int
:
ObservableCollection<int> myCollection = new ObservableCollection<int>(myList);
One more example for a List of ObjectA
:
ObservableCollection<ObjectA> myCollection = new ObservableCollection<ObjectA>(myList as List<ObjectA>);
Create a one xml file in drawable folder
<stroke
android:width="2dp"
android:color="#B40404" />
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp" />
<corners android:radius="4dp" />
Now call this xml to your small layout background
android:background="@drawable/yourxml"
This worked for me.
var number = 8008
number = number + "";
numberreverse = number.split("").reverse().join('');
console.log ("The number if reversed is: " +numberreverse);
if (number == numberreverse)
console.log("Yes, this is a palindrome");
else
console.log("Nope! It isnt a palindrome");
Use np.ravel (for a 1D view) or np.ndarray.flatten (for a 1D copy) or np.ndarray.flat (for an 1D iterator):
In [12]: a = np.array([[1,2,3], [4,5,6]])
In [13]: b = a.ravel()
In [14]: b
Out[14]: array([1, 2, 3, 4, 5, 6])
Note that ravel()
returns a view
of a
when possible. So modifying b
also modifies a
. ravel()
returns a view
when the 1D elements are contiguous in memory, but would return a copy
if, for example, a
were made from slicing another array using a non-unit step size (e.g. a = x[::2]
).
If you want a copy rather than a view, use
In [15]: c = a.flatten()
If you just want an iterator, use np.ndarray.flat
:
In [20]: d = a.flat
In [21]: d
Out[21]: <numpy.flatiter object at 0x8ec2068>
In [22]: list(d)
Out[22]: [1, 2, 3, 4, 5, 6]
https://github.com/requery/sqlite-android allows you to query JSON fields (and arrays in them, I've tried it and am using it). Before that I was just storing JSON strings into a TEXT column. It supports FTS3, FTS4, & JSON1
As of July 2019, it still gets version bumps every now and then, so it isn't a dead project.
This happened to me when I did not refer to the master branch of the origin. So, you can try the following:
git pull origin master
This creates a reference to the master branch of the origin in the local repository. Then you can push the local repository to the origin.
git push -u origin master
(Java) Avoiding usage of Map, List data structures:
private String getUniqueStr(String someStr) {
StringBuilder uniqueStr = new StringBuilder();
if(someStr != null) {
for(int i=0; i <someStr.length(); i++) {
if(uniqueStr.indexOf(String.valueOf(someStr.charAt(i))) == -1) {
uniqueStr.append(someStr.charAt(i));
}
}
}
return uniqueStr.toString();
}
You must remove the data from the TableModel
used for the table.
If using the DefaultTableModel
, just set the row count to zero. This will delete the rows and fire the TableModelEvent
to update the GUI.
JTable table; … DefaultTableModel model = (DefaultTableModel) table.getModel(); model.setRowCount(0);
If you are using other TableModel
, please check the documentation.
When I ran into this problem, trying to run an async method synchronicity from either a setter or a constructor got me into a deadlock on the UI thread, and using an event handler required too many changes in the general design.
The solution was, as often is, to just write explicitly what I wanted to happen implicitly, which was to have another thread handle the operation and to get the main thread to wait for it to finish:
string someValue=null;
var t = new Thread(() =>someValue = SomeAsyncMethod().Result);
t.Start();
t.Join();
You could argue that I abuse the framework, but it works.
You are missing a comma after
'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' }
Also, if you want return_first
to hold the result of your anonymous function, you need to make a function call:
var return_first = function () {
var tmp = null;
$.ajax({
'async': false,
'type': "POST",
'global': false,
'dataType': 'html',
'url': "ajax.php?first",
'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' },
'success': function (data) {
tmp = data;
}
});
return tmp;
}();
Note ()
at the end.
I'm sitting at a computer with none of the relevant bits of software, but from memory that code looks wrong. You're executing the command but discarding the RecordSet
that objMyCommand.Execute
returns.
I'd do:
Set objMyRecordset = objMyCommand.Execute
...and then lose the "open recordset" part.
USe this function for date comparison in javascript:
function fn_DateCompare(DateA, DateB) {
var a = new Date(DateA);
var b = new Date(DateB);
var msDateA = Date.UTC(a.getFullYear(), a.getMonth()+1, a.getDate());
var msDateB = Date.UTC(b.getFullYear(), b.getMonth()+1, b.getDate());
if (parseFloat(msDateA) < parseFloat(msDateB))
return -1; // less than
else if (parseFloat(msDateA) == parseFloat(msDateB))
return 0; // equal
else if (parseFloat(msDateA) > parseFloat(msDateB))
return 1; // greater than
else
return null; // error
}
in bash:
vim ~/.bash_profile
add
export PATH="/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin:$PATH"
:wq
to savejava -version
But actually this path points to jre not jdk.
If you want to point the path to JDK, you need
PATH="/Library/Java/JavaVirtualMachines/jdk1.8.0_221.jdk"
, you can go to /Library/Java/JavaVirtualMachines
to make sure you have installed the version of JDK you expected.Unfortunately that approach is not portable C++ (so far).
All standard names are in namespace std
and moreover you cannot know which names are NOT defined by including and header (in other words it's perfectly legal for an implementation to declare the name std::string
directly or indirectly when using #include <vector>
).
Despite this however you are required by the language to know and tell the compiler which standard header includes which part of the standard library. This is a source of portability bugs because if you forget for example #include <map>
but use std::map
it's possible that the program compiles anyway silently and without warnings on a specific version of a specific compiler, and you may get errors only later when porting to another compiler or version.
In my opinion there are no valid technical excuses because this is necessary for the general user: the compiler binary could have all standard namespace built in and this could actually increase the performance even more than precompiled headers (e.g. using perfect hashing for lookups, removing standard headers parsing or loading/demarshalling and so on).
The use of standard headers simplifies the life of who builds compilers or standard libraries and that's all. It's not something to help users.
However this is the way the language is defined and you need to know which header defines which names so plan for some extra neurons to be burnt in pointless configurations to remember that (or try to find and IDE that automatically adds the standard headers you use and removes the ones you don't... a reasonable alternative).
Another option is to add the M2_HOME variable at: IntelliJ IDEA=>Preferences=>IDE Settings=>Path Variables
After a restart of IntelliJ, IntelliJ IDEA=>Preferences=>Project Settings=>Maven=>Maven home directory
should be set to your M2_HOME variable.
Even it is not a good way of doing what you want try this hint: var url = MUST BE A NUMER FIRST
function nextImage (){
url = url + 1;
location.href='http://mywebsite.com/' + url+'.html';
}
You could wrap the textbox and button in an ASP:Panel, and set the DefaultButton property of the Panel to the Id of your Submit button.
<asp:Panel ID="Panel1" runat="server" DefaultButton="SubmitButton">
<asp:TextBox ID="TextBox1" runat="server" />
<asp:Button ID="SubmitButton" runat="server" Text="Submit" OnClick="SubmitButton_Click" />
</asp:Panel>
Now anytime the focus is within the Panel, the 'SubmitButton_Click' event will fire when enter is pressed.
Add a contextmenu to your form and then assign it in the control's properties under ContextMenuStrip. Hope this helps :).
Hope this helps:
ContextMenu cm = new ContextMenu();
cm.MenuItems.Add("Item 1");
cm.MenuItems.Add("Item 2");
pictureBox1.ContextMenu = cm;
You just need to do:
#!/bin/bash
count=$(cat last_queries.txt | wc -l)
$(perl test.pl test2 $count)
However, if you want to call your Perl command later, and that's why you want to assign it to a variable, then:
#!/bin/bash
count=$(cat last_queries.txt | wc -l)
var="perl test.pl test2 $count" # You need double quotes to get your $count value substituted.
...stuff...
eval $var
As per Bash's help:
~$ help eval
eval: eval [arg ...]
Execute arguments as a shell command.
Combine ARGs into a single string, use the result as input to the shell,
and execute the resulting commands.
Exit Status:
Returns exit status of command or success if command is null.
Update: use Darin's / John Resig answer, just keep in mind that you dont need to specifiy thisArg for min
, so Math.min.apply(null, arr)
will work just fine.
or you can just sort the array and get value #1:
[2,6,7,4,1].sort()[0]
[!] But without supplying custom number sorting function, this will only work in one, very limited case: positive numbers less than 10. See how it would break:
var a = ['', -0.1, -2, -Infinity, Infinity, 0, 0.01, 2, 2.0, 2.01, 11, 1, 1e-10, NaN];
// correct:
a.sort( function (a,b) { return a === b ? 0 : a < b ? -1: 1} );
//Array [NaN, -Infinity, -2, -0.1, 0, "", 1e-10, 0.01, 1, 2, 2, 2.01, 11, Infinity]
// incorrect:
a.sort();
//Array ["", -0.1, -2, -Infinity, 0, 0.01, 1, 11, 1e-10, 2, 2, 2.01, Infinity, NaN]
And, also, array is changed in-place, which might not be what you want.
If you do not need to use JavaHL, Subclipse also provides a pure-Java SVN API library -- SVNKit (http://svnkit.com). Just install the SVNKit client adapter and library plugins from the Subclipse update site and then choose it in the preferences under Team > SVN.
With regard to Brent.Longborough's answer (appering only on page 2 onward), perhaps you need to set the \thispagestyle{} after \begin{document}. I wonder if the letter class is setting the first page style to empty.
Just checked in Excel 2016 and this piece of code worked for me:
Sub ImmediateClear()
Application.VBE.Windows("Immediate").SetFocus
Application.SendKeys "^{END} ^+{HOME}{DEL}"
End Sub
If you need the same rows but just a random sample then,
import random
new_array = random.sample(old_array,x)
Here x, has to be an 'int' defining the number of rows you want to randomly pick.
This is for Greek Encoding in MySql tables when we want to access them using Java:
Use the following connection setup in your JBoss connection pool (mysql-ds.xml)
<connection-url>jdbc:mysql://192.168.10.123:3308/mydatabase</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<user-name>nts</user-name>
<password>xaxaxa!</password>
<connection-property name="useUnicode">true</connection-property>
<connection-property name="characterEncoding">greek</connection-property>
If you don't want to put this in a JNDI connection pool, you can configure it as a JDBC-url like the next line illustrates:
jdbc:mysql://192.168.10.123:3308/mydatabase?characterEncoding=greek
For me and Nick, so we never forget it and waste time anymore.....
Right click your project and choose properties in the properties dialog check the Java Compiler settings, maybe you have different workspace settings.
Python 3.3 and later now uses the 2010 compiler. To best way to solve the issue is to just install Visual C++ Express 2010 for free.
Now comes the harder part for 64 bit users and to be honest I just moved to 32 bit but 2010 express doesn't come with a 64 bit compiler (you get a new error, ValueError: ['path'] ) so you have to install Microsoft SDK 7.1 and follow the directions here to get the 64 bit compiler working with python: Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7
It may just be easier for you to use the 32 bit version for now. In addition to getting the compiler working, you can bypass the need to compile many modules by getting the binary wheel file from this locaiton http://www.lfd.uci.edu/~gohlke/pythonlibs/
Just download the .whl file you need, shift + right click the download folder and select "open command window here" and run
pip install module-name.whl
I used that method on 64 bit 3.4.3 before I broke down and decided to just get a working compiler for pip compiles modules from source by default, which is why the binary wheel files work and having pip build from source doesn't.
People getting this (vcvarsall.bat) error on Python 2.7 can instead install "Microsoft Visual C++ Compiler for Python 2.7"
this could help..
curl 'http://example.com' > /dev/null
git reset --hard origin/master
will remove all commits not in origin/master
where origin
is the repo name and master
is the name of the branch.
Actually, if you're working with jQuery, as of version 1.4.3 1.4.4 (because of the bug as mentioned in the comments below), data-*
attributes are supported through .data()
:
As of jQuery 1.4.3 HTML 5
data-
attributes will be automatically pulled in to jQuery's data object.Note that strings are left intact while JavaScript values are converted to their associated value (this includes booleans, numbers, objects, arrays, and null). The
data-
attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).
The jQuery.fn.data
function will return all of the data-
attribute inside an object as key-value pairs, with the key being the part of the attribute name after data-
and the value being the value of that attribute after being converted following the rules stated above.
I've also created a simple demo if that doesn't convince you: http://jsfiddle.net/yijiang/WVfSg/
I'm gathering from your question that userPick
is a String
value. You can compare it like this:
if (userPick.equalsIgnoreCase(computerPick.name())) . . .
As an aside, if you are guaranteed that computer
is always one of the values 1
, 2
, or 3
(and nothing else), you can convert it to a Gesture
enum with:
Gesture computerPick = Gesture.values()[computer - 1];
In case the WebSocket server initiative disconnects the
ws
link after a few minutes there no messages sent between the server and client.
client sends a custom ping
message, to keep alive by using the keepAlive
function
server ignore the ping
message and response a custom pong
message
var timerID = 0;
function keepAlive() {
var timeout = 20000;
if (webSocket.readyState == webSocket.OPEN) {
webSocket.send('');
}
timerId = setTimeout(keepAlive, timeout);
}
function cancelKeepAlive() {
if (timerId) {
clearTimeout(timerId);
}
}
Just use the style float: left
in this way:
<p style="float: left"> Lorem Ipsum </p>
<form style="float: left">
<input type='submit'/>
</form>
<p style="float: left"> Lorem Ipsum </p>
You can simple try String(); to remove the quotes.
Refer the first example here: https://www.w3schools.com/jsref/jsref_string.asp
Thank me later.
PS: TO MODs: don't mistaken me for digging the dead old question. I faced this issue today and I came across this post while searching for the answer and I'm just posting the answer.
Well, I can think of a CSS hack that will resolve this issue.
You could add the following line in your CSS file:
* html .blog_list div.postbody img { width:75px; height: SpecifyHeightHere; }
The above code will only be seen by IE6. The aspect ratio won't be perfect, but you could make it look somewhat normal. If you really wanted to make it perfect, you would need to write some javascript that would read the original picture width, and set the ratio accordingly to specify a height.
Array(5)
gives you an array with length 5 but no values, hence you can't iterate over it.
Array.apply(null, Array(5)).map(function () {})
gives you an array with length 5 and undefined as values, now it can be iterated over.
Array.apply(null, Array(5)).map(function (x, i) { return i; })
gives you an array with length 5 and values 0,1,2,3,4.
Array(5).forEach(alert)
does nothing, Array.apply(null, Array(5)).forEach(alert)
gives you 5 alerts
ES6
gives us Array.from
so now you can also use Array.from(Array(5)).forEach(alert)
If you want to initialize with a certain value, these are good to knows...
Array.from('abcde')
, Array.from('x'.repeat(5))
or Array.from({length: 5}, (v, i) => i) // gives [0, 1, 2, 3, 4]
And here is the non jQuery answer.
Fiddle: http://jsfiddle.net/J7m7m/7/
function changeText(value) {
document.getElementById('count').value = 500 * value;
}
HTML slight modification:
Product price: $500
<br>
Total price: $500
<br>
<input type="button" onclick="changeText(2)" value="2
Qty">
<input type="button" class="mnozstvi_sleva" value="4
Qty" onClick="changeText(4)">
<br>
Total <input type="text" id="count" value="1"/>
EDIT: It is very clear that this is a non-desired way as pointed out below (I had it coming). So in essence, this is how you would do it in plain old javascript. Most people would suggest you to use jQuery (other answer has the jQuery version) for good reason.
prepend
parent.prepend(newChild) // [newChild, child1, child2]
This is modern JS! It is more readable than previous options. It is currently available in Chrome, FF, and Opera.
The equivalent for adding to the end is append
, replacing the old appendChild
parent.append(newChild) // [child1, child2, newChild]
...
).Examples:
parent.prepend(newChild, "foo") // [newChild, "foo", child1, child2]
const list = ["bar", newChild]
parent.append(...list, "fizz") // [child1, child2, "bar", newChild, "fizz"]
I faced similar problem on windows server 2012 STD 64 bit , my problem is resolved after updating windows with all available windows updates.
To change specifically C# (OmniSharp) formatting settings you can use a json file:
User: ~/.omnisharp/omnisharp.json
or %USERPROFILE%\.omnisharp\omnisharp.json
Workspace: omnisharp.json
file in the working directory which OmniSharp has been pointed at.
Example:
{
"FormattingOptions": {
"NewLinesForBracesInMethods": false,
"NewLinesForBracesInProperties": false,
"NewLinesForBracesInAccessors": false,
"NewLinesForBracesInAnonymousMethods": false,
"NewLinesForBracesInControlBlocks": false,
"NewLinesForBracesInObjectCollectionArrayInitializers": false,
"NewLinesForBracesInLambdaExpressionBody": false
}
}
Details on this post | omnisharp.json schema (it's already in vscode, you can just CTRL+SPACE it)
Other language extensions may have similar files for setting it.
The urls are different.
http://localhost/AccountSvc/DataInquiry.asmx
vs.
/acctinqsvc/portfolioinquiry.asmx
Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.
You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx
, and specify the desired method/operation in the SOAPAction header.
The SOAPAction header values are different.
http://localhost/AccountSvc/DataInquiry.asmx/ + methodName
vs.
http://tempuri.org/GetMyName
You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl
There should be a <soap:operation>
tag underneath the <wsdl:operation>
tag that matches the operation you are attempting to execute, which appears to be GetMyName
.
There is no XML declaration in the request body that includes your SOAP XML.
You specify text/xml
in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii
, but there's no telling if you aren't specifying them!
The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8
Hope that helps!
You might want to use the detach program. You use it like nohup
but it doesn't produce an output log unless you tell it to. Here is the man page:
NAME
detach - run a command after detaching from the terminal
SYNOPSIS
detach [options] [--] command [args]
Forks a new process, detaches is from the terminal, and executes com-
mand with the specified arguments.
OPTIONS
detach recognizes a couple of options, which are discussed below. The
special option -- is used to signal that the rest of the arguments are
the command and args to be passed to it.
-e file
Connect file to the standard error of the command.
-f Run in the foreground (do not fork).
-i file
Connect file to the standard input of the command.
-o file
Connect file to the standard output of the command.
-p file
Write the pid of the detached process to file.
EXAMPLE
detach xterm
Start an xterm that will not be closed when the current shell exits.
AUTHOR
detach was written by Robbert Haarman. See http://inglorion.net/ for
contact information.
Note I have no affiliation with the author of the program. I'm only a satisfied user of the program.
WKWebView using Swift in iOS 8..
The whole ViewController.swift file now looks like this:
import UIKit
import WebKit
class ViewController: UIViewController {
@IBOutlet var containerView : UIView! = nil
var webView: WKWebView?
override func loadView() {
super.loadView()
self.webView = WKWebView()
self.view = self.webView!
}
override func viewDidLoad() {
super.viewDidLoad()
var url = NSURL(string:"http://www.kinderas.com/")
var req = NSURLRequest(URL:url)
self.webView!.loadRequest(req)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}