The normalize function from the BBMisc package was the right tool for me since it can deal with NA values.
Here is how to use it:
Given the following dataset,
ASR_API <- c("CV", "F", "IER", "LS-c", "LS-o")
Human <- c(NA, 5.8, 12.7, NA, NA)
Google <- c(23.2, 24.2, 16.6, 12.1, 28.8)
GoogleCloud <- c(23.3, 26.3, 18.3, 12.3, 27.3)
IBM <- c(21.8, 47.6, 24.0, 9.8, 25.3)
Microsoft <- c(29.1, 28.1, 23.1, 18.8, 35.9)
Speechmatics <- c(19.1, 38.4, 21.4, 7.3, 19.4)
Wit_ai <- c(35.6, 54.2, 37.4, 19.2, 41.7)
dt <- data.table(ASR_API,Human, Google, GoogleCloud, IBM, Microsoft, Speechmatics, Wit_ai)
> dt
ASR_API Human Google GoogleCloud IBM Microsoft Speechmatics Wit_ai
1: CV NA 23.2 23.3 21.8 29.1 19.1 35.6
2: F 5.8 24.2 26.3 47.6 28.1 38.4 54.2
3: IER 12.7 16.6 18.3 24.0 23.1 21.4 37.4
4: LS-c NA 12.1 12.3 9.8 18.8 7.3 19.2
5: LS-o NA 28.8 27.3 25.3 35.9 19.4 41.7
normalized values can be obtained like this:
> dtn <- normalize(dt, method = "standardize", range = c(0, 1), margin = 1L, on.constant = "quiet")
> dtn
ASR_API Human Google GoogleCloud IBM Microsoft Speechmatics Wit_ai
1: CV NA 0.3361245 0.2893457 -0.28468670 0.3247336 -0.18127203 -0.16032655
2: F -0.7071068 0.4875320 0.7715885 1.59862532 0.1700986 1.55068347 1.31594762
3: IER 0.7071068 -0.6631646 -0.5143923 -0.12409420 -0.6030768 0.02512682 -0.01746131
4: LS-c NA -1.3444981 -1.4788780 -1.16064578 -1.2680075 -1.24018782 -1.46198764
5: LS-o NA 1.1840062 0.9323361 -0.02919864 1.3762521 -0.15435044 0.32382788
where hand calculated method just ignores colmuns containing NAs:
> dt %>% mutate(normalizedHuman = (Human - mean(Human))/sd(Human)) %>%
+ mutate(normalizedGoogle = (Google - mean(Google))/sd(Google)) %>%
+ mutate(normalizedGoogleCloud = (GoogleCloud - mean(GoogleCloud))/sd(GoogleCloud)) %>%
+ mutate(normalizedIBM = (IBM - mean(IBM))/sd(IBM)) %>%
+ mutate(normalizedMicrosoft = (Microsoft - mean(Microsoft))/sd(Microsoft)) %>%
+ mutate(normalizedSpeechmatics = (Speechmatics - mean(Speechmatics))/sd(Speechmatics)) %>%
+ mutate(normalizedWit_ai = (Wit_ai - mean(Wit_ai))/sd(Wit_ai))
ASR_API Human Google GoogleCloud IBM Microsoft Speechmatics Wit_ai normalizedHuman normalizedGoogle
1 CV NA 23.2 23.3 21.8 29.1 19.1 35.6 NA 0.3361245
2 F 5.8 24.2 26.3 47.6 28.1 38.4 54.2 NA 0.4875320
3 IER 12.7 16.6 18.3 24.0 23.1 21.4 37.4 NA -0.6631646
4 LS-c NA 12.1 12.3 9.8 18.8 7.3 19.2 NA -1.3444981
5 LS-o NA 28.8 27.3 25.3 35.9 19.4 41.7 NA 1.1840062
normalizedGoogleCloud normalizedIBM normalizedMicrosoft normalizedSpeechmatics normalizedWit_ai
1 0.2893457 -0.28468670 0.3247336 -0.18127203 -0.16032655
2 0.7715885 1.59862532 0.1700986 1.55068347 1.31594762
3 -0.5143923 -0.12409420 -0.6030768 0.02512682 -0.01746131
4 -1.4788780 -1.16064578 -1.2680075 -1.24018782 -1.46198764
5 0.9323361 -0.02919864 1.3762521 -0.15435044 0.32382788
(normalizedHuman is made a list of NAs ...)
regarding the selection of specific columns for calculation, a generic method can be employed like this one:
data_vars <- df_full %>% dplyr::select(-ASR_API,-otherVarNotToBeUsed)
meta_vars <- df_full %>% dplyr::select(ASR_API,otherVarNotToBeUsed)
data_varsn <- normalize(data_vars, method = "standardize", range = c(0, 1), margin = 1L, on.constant = "quiet")
dtn <- cbind(meta_vars,data_varsn)
Believe or not, keytool does not provide such basic functionality like importing private key to keystore. You can try this workaround with merging PKSC12 file with private key to a keystore:
keytool -importkeystore \
-deststorepass storepassword \
-destkeypass keypassword \
-destkeystore my-keystore.jks \
-srckeystore cert-and-key.p12 \
-srcstoretype PKCS12 \
-srcstorepass p12password \
-alias 1
Or just use more user-friendly KeyMan from IBM for keystore handling instead of keytool.
...and on my 64 bit W7 machine, with VB6 installed... in DOS, as Admin, this worked to solve an OCX problem I was having with a VB6 App:
cd C:\Windows\SysWOW64
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb
YES! This solution solved the problem I had using MSCAL.OCX (The Microsoft Calendar Control) in VB6.
Thank you guys! :-)
1 - Change Your tables search engine from 'My ISAM' to 'Inno DB' by Operations tab 2 - you must do this for all tables that you want make relationship between 3 - localhost/phpmyadmin/tbl_relation.php?db=your_database_name&table=your_table_name then replace this url in browser, then you will be able to see the relationship page
Swift 3:
if unknownType is MyClass {
//unknownType is of class type MyClass
}
sudo launchctl list | grep -i mysql
If the result shows anything like: "xxx.xxx.mysqlxxx"
sudo launchctl remove xxx.xxx.mysqlxxx
Example:
sudo launchctl remove org.macports.mysql56-server
sudo launchctl unload -wF /Library/LaunchDaemons/xxx.xxx.mysqlxxx.plist
Example:
sudo launchctl unload -wF /Library/LaunchDaemons/org.macports.mysql56-server.plist
Note: In some cases if you tried "a)" first, you need to reboot again before try b).
I have used the following:
public static double Index2Freq(int i, double samples, int nFFT) {
return (double) i * (samples / nFFT / 2.);
}
public static int Freq2Index(double freq, double samples, int nFFT) {
return (int) (freq / (samples / nFFT / 2.0));
}
The inputs are:
i
: Bin to accesssamples
: Sampling rate in Hertz (i.e. 8000 Hz, 44100Hz, etc.)nFFT
: Size of the FFT vectorAnother fairly simple way to go about this is to make a method like this:
def _write_frame_to_new_sheet(path_to_file=None, sheet_name='sheet', data_frame=None):
book = None
try:
book = load_workbook(path_to_file)
except Exception:
logging.debug('Creating new workbook at %s', path_to_file)
with pd.ExcelWriter(path_to_file, engine='openpyxl') as writer:
if book is not None:
writer.book = book
data_frame.to_excel(writer, sheet_name, index=False)
The idea here is to load the workbook at path_to_file if it exists and then append the data_frame as a new sheet with sheet_name. If the workbook does not exist, it is created. It seems that neither openpyxl or xlsxwriter append, so as in the example by @Stefano above, you really have to load and then rewrite to append.
Got the same problem after importing my Eclipse ADT project to Android Studio. Text and Desing tabs where missing.
Found my Event Log windows reads "Frameworks detected: Android framework is detected in the project Configure"
I click the hyperlink provided and everything was fixed, Text and Desing tabs became visible and functional
I had this problem and I couldn't find the solution here, so I want to share my solution in case someone else has this problem again.
I had this code:
public void finishAction() {
onDestroy();
finish();
}
and solved the problem by deleting the line "onDestroy();"
public void finishAction() {
finish();
}
The reason I wrote the initial code: I know that when you execute "finish()" the activity calls "onDestroy()", but I'm using threads and I wanted to ensure that all the threads are destroyed before starting the next activity, and it looks like "finish()" is not always immediate. I need to process/reduce a lot of “Bitmap” and display big “bitmaps” and I’m working on improving the use of the memory in my app
Now I will kill the threads using a different method and I’ll execute this method from "onDestroy();" and when I think I need to kill all the threads.
public void finishAction() {
onDestroyThreads();
finish();
}
As Sam Dutton answered, a new method for this very purpose has been introduced in ECMAScript 5th Edition. Object.keys()
will do what you want and is supported in Firefox 4, Chrome 6, Safari 5 and IE 9.
You can also very easily implement the method in browsers that don't support it. However, some of the implementations out there aren't fully compatible with Internet Explorer. Here's a more compatible solution:
Object.keys = Object.keys || (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !{toString:null}.propertyIsEnumerable("toString"),
DontEnums = [
'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty',
'isPrototypeOf', 'propertyIsEnumerable', 'constructor'
],
DontEnumsLength = DontEnums.length;
return function (o) {
if (typeof o != "object" && typeof o != "function" || o === null)
throw new TypeError("Object.keys called on a non-object");
var result = [];
for (var name in o) {
if (hasOwnProperty.call(o, name))
result.push(name);
}
if (hasDontEnumBug) {
for (var i = 0; i < DontEnumsLength; i++) {
if (hasOwnProperty.call(o, DontEnums[i]))
result.push(DontEnums[i]);
}
}
return result;
};
})();
Note that the currently accepted answer doesn't include a check for hasOwnProperty() and will return properties that are inherited through the prototype chain. It also doesn't account for the famous DontEnum bug in Internet Explorer where non-enumerable properties on the prototype chain cause locally declared properties with the same name to inherit their DontEnum attribute.
Implementing Object.keys() will give you a more robust solution.
EDIT: following a recent discussion with kangax, a well-known contributor to Prototype, I implemented the workaround for the DontEnum bug based on code for his Object.forIn()
function found here.
From the Apple Developer Forum (account required):
"The compiler and linker are capable of using features and performing optimizations that do not work on older OS versions.
-mmacosx-version-min
tells the tools what OS versions you need to work with, so the tools can disable optimizations that won't run on those OS versions. If you need to run on older OS versions then you must use this flag."The downside to
-mmacosx-version-min
is that the app's performance may be worse on newer OS versions then it could have been if it did not need to be backwards-compatible. In most cases the differences are small."
In case of direct @Value injection, the most elegant way is writing the key-values as an inline json (use ' and " chars to avoid cumbersome escapings) and parsing it using SPEL:
#in yaml file:
my:
map:
is: '{ "key1":"val1",
"key2":"val2" }'
in your @Component or @Bean, :
@Component
public class MyClass{
@Value("#{${my.map.is}}")
Map<String,String> myYamlMap;
}
for a more YAML convenient syntax, you can avoid the json curly braces altogether, directly typing the key value pairs
my:
map:
is: '"a":"b", "foo":"bar"'
and add the missing curly braces directly to your @Value SPEL expression:
@Value("#{{${my.map.is}}}")
Map<String,String> myYamlMap;
the value will be resolved from the yaml, the wrapping curlies will be concatenated to it, and finally the SPEL expression will resolve the string as map.
<img src="file://C:/wamp/www/site/img/mypicture.jpg"/>
I used this code to show the dialog at the bottom of the screen:
Dialog dlg = <code to create custom dialog>;
Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();
wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);
This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about
private void showPictureialog() {
final Dialog dialog = new Dialog(this,
android.R.style.Theme_Translucent_NoTitleBar);
// Setting dialogview
Window window = dialog.getWindow();
window.setGravity(Gravity.CENTER);
window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
dialog.setTitle(null);
dialog.setContentView(R.layout.selectpic_dialog);
dialog.setCancelable(true);
dialog.show();
}
you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment
It depends on whether you process IDNs before or after the IDN toASCII
algorithm (that is, do you see the domain name pa??de??µa.d???µ?
in Greek or as xn--hxajbheg2az3al.xn--jxalpdlp
?).
In the latter case—where you are handling IDNs through the punycode—the old RFC 1123 rules apply:
U+0041 through U+005A (A-Z), U+0061 through U+007A (a-z) case folded as each other, U+0030 through U+0039 (0-9) and U+002D (-).
and U+002E (.) of course; the rules for labels allow the others, with dots between labels.
If you are seeing it in IDN form, the allowed characters are much varied, see http://unicode.org/reports/tr36/idn-chars.html for a handy chart of all valid characters.
Chances are your network code will deal with the punycode, but your display code (or even just passing strings to and from other layers) with the more human-readable form as nobody running a server on the ????????. domain wants to see their server listed as being on .xn--mgberp4a5d4ar
.
I can't comment on the top answer, but a swift implementation would be:
self.tableView.reloadSections([0], with: UITableViewRowAnimation.fade)
you could include as many sections as you want to update in the first argument for reloadSections.
Other animations available from the docs: https://developer.apple.com/reference/uikit/uitableviewrowanimation
fade The inserted or deleted row or rows fade into or out of the table view.
right The inserted row or rows slide in from the right; the deleted row or rows slide out to the right.
left The inserted row or rows slide in from the left; the deleted row or rows slide out to the left.
top The inserted row or rows slide in from the top; the deleted row or rows slide out toward the top.
bottom The inserted row or rows slide in from the bottom; the deleted row or rows slide out toward the bottom.
case none The inserted or deleted rows use the default animations.
middle The table view attempts to keep the old and new cells centered in the space they did or will occupy. Available in iPhone 3.2.
automatic The table view chooses an appropriate animation style for you. (Introduced in iOS 5.0.)
This is based on CMS's answer. The question asked for the timer to be restarted on the blur and stopped on the focus, so I moved it around a little:
$(function () {
var timerId = 0;
$('textarea').focus(function () {
clearInterval(timerId);
});
$('textarea').blur(function () {
timerId = setInterval(function () {
//some code here
}, 1000);
});
});
To change color of the font colour, first select attributed instead of plain like in the image below
You then need to select the text in the attributed field and then select the color button on the right-hand side of the alignments. This will change the color.
You can do this with psutil which is cross-platform:
import psutil
nics = psutil.net_if_addrs()
print [j.address for j in nics[i] for i in nics if i!="lo" and j.family==17]
You can kill all node processes using pkill node
or you can do a ps T
to see all processes on this terminal
then you can kill a specific process ID doing a kill [processID]
example: kill 24491
Additionally, you can do a ps -help
to see all the available options
Since this page is the number 1 result for the google search "c++ floating point exception", I want to add another thing that can cause such a problem: use of undefined variables.
Team Foundation Sidekicks worked fine for me.
The file didn't unlock so I did a undo on pending changes and after that I could delete the file.
angle = Math.toDegrees(Math.atan2(target.x - x, target.y - y));
now for orientation of circular values to keep angle between 0 and 359 can be:
angle = angle + Math.ceil( -angle / 360 ) * 360
With gawk
, you can use match function:
x="hey there how are you"
echo "$x" |awk --re-interval '{match($0,/(.{4})how(.{4})/,a);print a[1],a[2]}'
ere are
If you are ok with perl
, more flexible solution : Following will print three characters before the pattern followed by actual pattern and then 5 character after the pattern.
echo hey there how are you |perl -lne 'print "$1$2$3" if /(.{3})(there)(.{5})/'
ey there how
This can also be applied to words instead of just characters.Following will print one word before the actual matching string.
echo hey there how are you |perl -lne 'print $1 if /(\w+) there/'
hey
Following will print one word after the pattern:
echo hey there how are you |perl -lne 'print $2 if /(\w+) there (\w+)/'
how
Following will print one word before the pattern , then the actual word and then one word after the pattern:
echo hey there how are you |perl -lne 'print "$1$2$3" if /(\w+)( there )(\w+)/'
hey there how
You can simply return
if you want to skip the current iteration.
Since you're in a function, if you return
before doing anything else, then you have effectively skipped execution of the code below the return
statement.
.add_to_cart >>> .form-item:eq(1)
the second .form-item at tree level child from the .add_to_cart
you have to iterate gridview Rows
for (int count = 0; count < grd.Rows.Count; count++)
{
if (((CheckBox)grd.Rows[count].FindControl("yourCheckboxID")).Checked)
{
((Label)grd.Rows[count].FindControl("labelID")).Text
}
}
If there are only two references to test and you are using Java 8, you could use
Object o = null;
Object p = "p";
Object r = Optional.ofNullable( o ).orElse( p );
System.out.println( r ); // p
If you import static Optional the expression is not too bad.
Unfortunately your case with "several variables" is not possible with an Optional-method. Instead you could use:
Object o = null;
Object p = null;
Object q = "p";
Optional<Object> r = Stream.of( o, p, q ).filter( Objects::nonNull ).findFirst();
System.out.println( r.orElse(null) ); // p
Keep in mind that database tables are designed to grow vertically (more rows), not horizontally (more columns)
If you absolutely only want to store the combined field on the model and not the two seperate fields, you could do something like this:
form
attribute on your ModelAdmin
(https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form)save_formset
method on your ModelAdmin
(https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model)I never done something like this so I'm not completely sure how it will work out.
Here's a simple solution, using TypeScript:
convertDateStringToDate(dateStr) {
// Convert a string like '2020-10-04T00:00:00' into '4/Oct/2020'
let months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
let date = new Date(dateStr);
let str = date.getDate()
+ '/' + months[date.getMonth()]
+ '/' + date.getFullYear()
return str;
}
(Yeah, I know the question was about JavaScript, but I'm sure I won't be the only Angular developer coming across this article !)
If you're using V4.1, and according to their docs, don't assign .table-responsive directly to the table. The table should be .table and if you want it to be horizontally scrollable (responsive) add it inside a .table-responsive container (a <div>
, for instance).
Responsive tables allow tables to be scrolled horizontally with ease. Make any table responsive across all viewports by wrapping a .table with .table-responsive.
<div class="table-responsive">
<table class="table">
...
</table>
</div>
doing that, no extra css is needed.
In the OP's code, .table-responsive can be used alongside with the .col-md-12 on the outside .
On submitting, you would get an array as if created like this:
$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );
However, I would suggest changing your form names to this format instead:
name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...
Using that format, it's much easier to loop through the values.
if ( isset( $_POST['diameters'] ) )
{
echo '<table>';
foreach ( $_POST['diameters'] as $diam )
{
// here you have access to $diam['top'] and $diam['bottom']
echo '<tr>';
echo ' <td>', $diam['top'], '</td>';
echo ' <td>', $diam['bottom'], '</td>';
echo '</tr>';
}
echo '</table>';
}
Judging by your above comment, you're OK doing this with jQuery — here goes:
// for every element in the body tag
$("*", "body").each(function() {
// parse out its computed font size, and see if it is less than 12
if ( parseInt($(this).css("font-size"), 10) < 12 )
// if so, then manually give it a CSS property of 12px
$(this).css("font-size", "12px")
});
A cleaner way to do this might be to have a "min-font" class in your CSS that sets font-size: 12px, and just add the class instead:
$("*", "body").each(function() {
if ( parseInt($(this).css("font-size"), 10) < 12 )
$(this).addClass("min-font")
});
Latest revision based on comment from BinaryZebra's comment
and tested here. The addition of command eval
allows for the expression to be kept in the present execution environment while the expressions before are only held for the duration of the eval.
Use $IFS that has no spaces\tabs, just newlines/CR
$ IFS=$'\r\n' GLOBIGNORE='*' command eval 'XYZ=($(cat /etc/passwd))'
$ echo "${XYZ[5]}"
sync:x:5:0:sync:/sbin:/bin/sync
Also note that you may be setting the array just fine but reading it wrong - be sure to use both double-quotes ""
and braces {}
as in the example above
Edit:
Please note the many warnings about my answer in comments about possible glob expansion, specifically gniourf-gniourf's comments about my prior attempts to work around
With all those warnings in mind I'm still leaving this answer here (yes, bash 4 has been out for many years but I recall that some macs only 2/3 years old have pre-4 as default shell)
Other notes:
Can also follow drizzt's suggestion below and replace a forked subshell+cat with
$(</etc/passwd)
The other option I sometimes use is just set IFS into XIFS, then restore after. See also Sorpigal's answer which does not need to bother with this
Set a minimum width at the top most layout.
android:minWidth="300dp"
For example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android" android:minWidth="300dp">
<!-- Put remaining contents here -->
</LinearLayout>
You could write a script to do it in your favourite scripting language. The script would do the following:
SHOW FULL TABLES
.'BASE TABLE'
and not 'VIEW'
.'VIEW'
, issue the appropriate ALTER TABLE
command.I wanto to display the count of rows in the excel sheet after the filter option has been applied.
So I declared the count of last rows as a variable that can be added to the Msgbox
Sub lastrowcall()
Dim hm As Worksheet
Dim dm As Worksheet
Set dm = ActiveWorkbook.Sheets("datecopy")
Set hm = ActiveWorkbook.Sheets("Home")
Dim lngStart As String, lngEnd As String
lngStart = hm.Range("E23").Value
lngEnd = hm.Range("E25").Value
Dim last_row As String
last_row = dm.Cells(Rows.Count, 1).End(xlUp).Row
MsgBox ("Number of test results between the selected dates " + lngStart + "
and " + lngEnd + " are " + last_row + ". Please Select Yes to continue
Analysis")
End Sub
Correct and fast way compute average for List<Integer>
:
private double calculateAverage(List<Integer> marks) {
long sum = 0;
for (Integer mark : marks) {
sum += mark;
}
return marks.isEmpty()? 0: 1.0*sum/marks.size();
}
This solution take into account:
It works coorectly for List, because any list contains less that 2^31 int, and it is possible to use long as accumulator.
PS
Actually foreach allocate memory - you should use old style for() cycle in mission critical parts
You need to subclass ViewPager
. onTouchEvent
has a lot of good things in it that you don't want to change like allowing child views to get touches. onInterceptTouchEvent
is what you want to change. If you look at the code for ViewPager
, you'll see the comment:
/*
* This method JUST determines whether we want to intercept the motion.
* If we return true, onMotionEvent will be called and we do the actual
* scrolling there.
*/
Here's a complete solution:
First, add this class to your src
folder:
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.DecelerateInterpolator;
import android.widget.Scroller;
import java.lang.reflect.Field;
public class NonSwipeableViewPager extends ViewPager {
public NonSwipeableViewPager(Context context) {
super(context);
setMyScroller();
}
public NonSwipeableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
setMyScroller();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
//down one is added for smooth scrolling
private void setMyScroller() {
try {
Class<?> viewpager = ViewPager.class;
Field scroller = viewpager.getDeclaredField("mScroller");
scroller.setAccessible(true);
scroller.set(this, new MyScroller(getContext()));
} catch (Exception e) {
e.printStackTrace();
}
}
public class MyScroller extends Scroller {
public MyScroller(Context context) {
super(context, new DecelerateInterpolator());
}
@Override
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
super.startScroll(startX, startY, dx, dy, 350 /*1 secs*/);
}
}
}
Next, make sure to use this class instead of the regular ViewPager
, which you probably specified as android.support.v4.view.ViewPager
. In your layout file, you'll want to specify it with something like:
<com.yourcompany.NonSwipeableViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
This particular example is in a LinearLayout
and is meant to take up the entire screen, which is why layout_weight
is 1 and layout_height
is 0dp.
And setMyScroller();
method is for smooth transition
In any realistic system, no, creating a stack frame will always be more expensive than an INC and a JMP. That's why really good compilers automatically transform tail recursion into a call to the same frame, i.e. without the overhead, so you get the more readable source version and the more efficient compiled version. A really, really good compiler should even be able to transform normal recursion into tail recursion where that is possible.
You can do this without any JavaScript involved
(Using accepted answer)
HTML
<table class="table table-bordered table-striped">
<tr>
<td><button class="btn" data-target="#collapseme" data-toggle="collapse" type="button">Click to expand</button></td>
</tr>
<tr>
<td class="nopadding">
<div class="collapse" id="collapseme">
<div class="content">
Show me collapsed
</div>
</div>
</td>
</tr>
</table>
CSS
.nopadding {
padding: 0 !important;
}
.content {
padding: 20px;
}
Using the library Datejs you can accomplish this quite elegantly, with its toString
format specifiers: http://jsfiddle.net/TeRnM/1/.
var date = new Date(1324339200000);
date.toString("MMM dd"); // "Dec 20"
In my case (same problem - that Nexus 5 is connected but with "offline" status) the problem was solved by "Invalidate caches and Restart" in Android Studio. Suppose that problem was in adb and restarting Android Studio causes to adb restart.
Using the -I
(that's a capital i) option on the file
command seems to show the file encoding.
file -I {filename}
$value = ( array_key_exists($key, $array) && !empty($array[$key]) )
? $array[$key]
: 'non-existant or empty value key';
use
should work (I've tested in Chrome, Firefox and Edge):
let users = [{username: 'user1'}, {username: 'user2'}, {username: 'user3'}];_x000D_
let favTitle = '';_x000D_
for(let j = 0; j < users.length; j++)_x000D_
favTitle += users[j].username + " ";_x000D_
_x000D_
$("#item").append('<i title="In favorite users: ' + favTitle + '">Favorite</i>');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id = item></div>
_x000D_
Set the form's .TopMost
property to true.
You probably don't want to leave it this way all the time: set it when your external process starts and put it back when it finishes.
vector<char> toVector( const std::string& s ) {
string s = "apple";
vector<char> v(s.size()+1);
memcpy( &v.front(), s.c_str(), s.size() + 1 );
return v;
}
vector<char> v = toVector(std::string("apple"));
// what you were looking for (mutable)
char* c = v.data();
.c_str() works for immutable. The vector will manage the memory for you.
A different approach, just for kicks:
Console.WriteLine(string.Join("\t", list));
Use keydown
event to do it:
input: HTMLDivElement | null = null;
onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>): void => {
// 'keypress' event misbehaves on mobile so we track 'Enter' key via 'keydown' event
if (event.key === 'Enter') {
event.preventDefault();
event.stopPropagation();
this.onSubmit();
}
}
onSubmit = (): void => {
if (input.textContent) {
this.props.onSubmit(input.textContent);
input.focus();
input.textContent = '';
}
}
render() {
return (
<form className="commentForm">
<input
className="comment-input"
aria-multiline="true"
role="textbox"
contentEditable={true}
onKeyDown={this.onKeyDown}
ref={node => this.input = node}
/>
<button type="button" className="btn btn-success" onClick={this.onSubmit}>Comment</button>
</form>
);
}
Use repr
>>> string = "abcd\n"
>>> print(repr(string))
'abcd\n'
Very simple code with Bootstrap and JQuery without any additionnal javascript code :
HTML :
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown button
</button>
<form class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<label class="dropdown-item"><input type="checkbox" name="" value="one">First checkbox</label>
<label class="dropdown-item"><input type="checkbox" name="" value="two">Second checkbox</label>
<label class="dropdown-item"><input type="checkbox" name="" value="three">Third checkbox</label>
</form>
</div>
CSS :
.dropdown-menu label {
display: block;
}
The gcf method is depricated in V 0.14, The below code works for me:
plot = dtf.plot()
fig = plot.get_figure()
fig.savefig("output.png")
You can run conda install --file requirements.txt
instead of the loop, but there is no target directory in conda install. conda install
installs a list of packages into a specified conda environment.
Actually I found this more helpful for functions that return IAsyncAction.
var task = asyncFunction();
while (task.Status == AsyncStatus.Completed) ;
Actually, it is as simple as setting major
and minor
separately:
In [9]: plot([23, 456, 676, 89, 906, 34, 2345])
Out[9]: [<matplotlib.lines.Line2D at 0x6112f90>]
In [10]: yscale('log')
In [11]: grid(b=True, which='major', color='b', linestyle='-')
In [12]: grid(b=True, which='minor', color='r', linestyle='--')
The gotcha with minor grids is that you have to have minor tick marks turned on too. In the above code this is done by yscale('log')
, but it can also be done with plt.minorticks_on()
.
Just for fun:
#!/bin/bash
FILE=$1
if [[ -z $FILE ]]; then
echo "You must pass a filename -- exiting" >&2
exit 1
fi
if [[ ! -f $FILE ]]; then
echo "There is not file '$FILE' here -- exiting" >&2
exit 1
fi
BEFORE=`wc -c "$FILE" | cut --delimiter=' ' --fields=1`
# >>>>>>>>>>
sed -i.bak -e's/[ \t]*$//' "$FILE"
# <<<<<<<<<<
AFTER=`wc -c "$FILE" | cut --delimiter=' ' --fields=1`
if [[ $? != 0 ]]; then
echo "Some error occurred" >&2
else
echo "Filtered '$FILE' from $BEFORE characters to $AFTER characters"
fi
No, not all browsers support the sizes
attribute:
Note that some platforms define specific sizes:
manifest.json
if it is present. Plus, Chrome uses the Apple Touch icon for bookmarks.There are 2 ways to configure custom error pages for ASP.NET sites:
This article explains how to do each:
The reason your error.aspx page is not displaying might be because you have an error in your web.config. Try this instead:
<configuration>
<system.web>
<customErrors defaultRedirect="error.aspx" mode="RemoteOnly">
<error statusCode="404" redirect="error.aspx"/>
</customErrors>
</system.web>
</configuration>
You might need to make sure that Error Pages
in IIS Manager - Feature Delegation is set to Read/Write:
Also, this answer may help you configure the web.config file:
One point I noticed with Primefaces 3.4 and Netbeans 7.2:
Remove the Netbeans auto-filled parameters for function handleFileUpload i.e. (event) otherwise event could be null.
<h:form>
<p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload(event)}"
mode="advanced"
update="messages"
sizeLimit="100000"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>
<p:growl id="messages" showDetail="true"/>
</h:form>
children
const Wrapper = ({children}) => (
<div>
<div>header</div>
<div>{children}</div>
<div>footer</div>
</div>
);
const App = ({name}) => <div>Hello {name}</div>;
const WrappedApp = ({name}) => (
<Wrapper>
<App name={name}/>
</Wrapper>
);
render(<WrappedApp name="toto"/>,node);
This is also known as transclusion
in Angular.
children
is a special prop in React and will contain what is inside your component's tags (here <App name={name}/>
is inside Wrapper
, so it is the children
Note that you don't necessarily need to use children
, which is unique for a component, and you can use normal props too if you want, or mix props and children:
const AppLayout = ({header,footer,children}) => (
<div className="app">
<div className="header">{header}</div>
<div className="body">{children}</div>
<div className="footer">{footer}</div>
</div>
);
const appElement = (
<AppLayout
header={<div>header</div>}
footer={<div>footer</div>}
>
<div>body</div>
</AppLayout>
);
render(appElement,node);
This is simple and fine for many usecases, and I'd recommend this for most consumer apps.
It is possible to pass render functions to a component, this pattern is generally called render prop
, and the children
prop is often used to provide that callback.
This pattern is not really meant for layout. The wrapper component is generally used to hold and manage some state and inject it in its render functions.
Counter example:
const Counter = () => (
<State initial={0}>
{(val, set) => (
<div onClick={() => set(val + 1)}>
clicked {val} times
</div>
)}
</State>
);
You can get even more fancy and even provide an object
<Promise promise={somePromise}>
{{
loading: () => <div>...</div>,
success: (data) => <div>{data.something}</div>,
error: (e) => <div>{e.message}</div>,
}}
</Promise>
Note you don't necessarily need to use children
, it is a matter of taste/API.
<Promise
promise={somePromise}
renderLoading={() => <div>...</div>}
renderSuccess={(data) => <div>{data.something}</div>}
renderError={(e) => <div>{e.message}</div>}
/>
As of today, many libraries are using render props (React context, React-motion, Apollo...) because people tend to find this API more easy than HOC's. react-powerplug is a collection of simple render-prop components. react-adopt helps you do composition.
const wrapHOC = (WrappedComponent) => {
class Wrapper extends React.PureComponent {
render() {
return (
<div>
<div>header</div>
<div><WrappedComponent {...this.props}/></div>
<div>footer</div>
</div>
);
}
}
return Wrapper;
}
const App = ({name}) => <div>Hello {name}</div>;
const WrappedApp = wrapHOC(App);
render(<WrappedApp name="toto"/>,node);
An Higher-Order Component / HOC is generally a function that takes a component and returns a new component.
Using an Higher-Order Component can be more performant than using children
or render props
, because the wrapper can have the ability to short-circuit the rendering one step ahead with shouldComponentUpdate
.
Here we are using PureComponent
. When re-rendering the app, if the WrappedApp
name prop does not change over time, the wrapper has the ability to say "I don't need to render because props (actually, the name) are the same as before". With the children
based solution above, even if the wrapper is PureComponent
, it is not the case because the children element is recreated everytime the parent renders, which means the wrapper will likely always re-render, even if the wrapped component is pure. There is a babel plugin that can help mitigate this and ensure a constant children
element over time.
Higher-Order Components can give you better performance. It's not so complicated but it certainly looks unfriendly at first.
Don't migrate your whole codebase to HOC after reading this. Just remember that on critical paths of your app you might want to use HOCs instead of runtime wrappers for performance reasons, particularly if the same wrapper is used a lot of times it's worth considering making it an HOC.
Redux used at first a runtime wrapper <Connect>
and switched later to an HOC connect(options)(Comp)
for performance reasons (by default, the wrapper is pure and use shouldComponentUpdate
). This is the perfect illustration of what I wanted to highlight in this answer.
Note if a component has a render-prop API, it is generally easy to create a HOC on top of it, so if you are a lib author, you should write a render prop API first, and eventually offer an HOC version. This is what Apollo does with <Query>
render-prop component, and the graphql
HOC using it.
Personally, I use both, but when in doubt I prefer HOCs because:
compose(hoc1,hoc2)(Comp)
) compared to render propsI don't hesitate to use/create HOC versions of my favorite tools:
Context.Consumer
compSubscribe
graphql
HOC of Apollo instead of Query
render propIn my opinion, sometimes render props make the code more readable, sometimes less... I try to use the most pragmatic solution according to the constraints I have. Sometimes readability is more important than performances, sometimes not. Choose wisely and don't bindly follow the 2018 trend of converting everything to render-props.
The best way is to add the directory to the load path and then require
the basename of each file. This is because you want to avoid accidentally requiring the same file twice -- often not the intended behavior. Whether a file will be loaded or not is dependent on whether require
has seen the path passed to it before. For example, this simple irb session shows that you can mistakenly require and load the same file twice.
$ irb
irb(main):001:0> require 'test'
=> true
irb(main):002:0> require './test'
=> true
irb(main):003:0> require './test.rb'
=> false
irb(main):004:0> require 'test'
=> false
Note that the first two lines return true
meaning the same file was loaded both times. When paths are used, even if the paths point to the same location, require
doesn't know that the file was already required.
Here instead, we add a directory to the load path and then require the basename of each *.rb file within.
dir = "/path/to/directory"
$LOAD_PATH.unshift(dir)
Dir[File.join(dir, "*.rb")].each {|file| require File.basename(file) }
If you don't care about the file being required more than once, or your intention is just to load the contents of the file, perhaps load
should be used instead of require
. Use load in this case, because it better expresses what you're trying to accomplish. For example:
Dir["/path/to/directory/*.rb"].each {|file| load file }
In C++ the std::string class implements the comparison operators, so you can perform the comparison using ==
just as you would expect:
if (string == "add") { ... }
When used properly, operator overloading is an excellent C++ feature.
Got it working! I should have been building a JSONArray
of JSONObject
s and then add the array to a final "Addresses" JSONObject
. Observe the following:
JSONObject json = new JSONObject();
JSONArray addresses = new JSONArray();
JSONObject address;
try
{
int count = 15;
for (int i=0 ; i<count ; i++)
{
address = new JSONObject();
address.put("CustomerName" , "Decepticons" + i);
address.put("AccountId" , "1999" + i);
address.put("SiteId" , "1888" + i);
address.put("Number" , "7" + i);
address.put("Building" , "StarScream Skyscraper" + i);
address.put("Street" , "Devestator Avenue" + i);
address.put("City" , "Megatron City" + i);
address.put("ZipCode" , "ZZ00 XX1" + i);
address.put("Country" , "CyberTron" + i);
addresses.add(address);
}
json.put("Addresses", addresses);
}
catch (JSONException jse)
{
}
response.setContentType("application/json");
response.getWriter().write(json.toString());
This worked and returned valid and parse-able JSON. Hopefully this helps someone else in the future. Thanks for your help Marcel
How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)
From RFC 2818 (Section 3.1):
If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.
[...]
In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.
Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).
If you're using keytool
, as of Java 7, keytool
has an option to include a Subject Alternative Name (see the table in the documentation for -ext
): you could use -ext san=dns:www.example.com
or -ext san=ip:10.0.0.1
.
EDIT:
You can request a SAN in OpenSSL by changing openssl.cnf
(it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF
environment variable).
Set the following options (find the appropriate sections within brackets first):
[req]
req_extensions = v3_req
[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com
There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html
You can use the following command :
$ grep "phpmyadmin" $path_to_access.log | grep -Po "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" | sort | uniq | xargs -I% sudo iptables -A INPUT -s % -j DROP
Explanation:
Make sure your IP isn't listed before piping through iptables drop!!
This will first find all lines in $path_to_access.log that have phpmyadmin in them,
then grep out the ip address from the start of the line,
then sort and unique them,
then add a rule to drop them in iptables
Again, just edit in echo %
at the end instead of the iptables command to make sure your IP isn't in there. Don't inadvertently ban your access to the server!
Limitations
You may need to change the grep part of the command if you're on mac or any system that doesn't have grep -P. I'm not sure if all systems start with xargs, so that might need to be installed too. It's super useful anyway if you do a lot of bash.
By default Chrome extensions do not run in Incognito mode. You have to explicitly enable the extension to run in Incognito.
Today I had this same problem with another jar. I tried multiple things people said on Stackoverflow, but nothing worked. Eventually I did this:
Now it works again for me. Perhaps this solves the problem for someone else too.
You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015
> 01/02/2016
because 09
> 01
. You need to either put your date in a comparable string format or compare DateTime
objects which are comparable.
<?php
$date_now = date("Y-m-d"); // this format is string comparable
if ($date_now > '2016-01-02') {
echo 'greater than';
}else{
echo 'Less than';
}
Or
<?php
$date_now = new DateTime();
$date2 = new DateTime("01/02/2016");
if ($date_now > $date2) {
echo 'greater than';
}else{
echo 'Less than';
}
Slightly related, I was looking for the unique combinations and I came up with this method:
def unique_columns(df,columns):
result = pd.Series(index = df.index)
groups = meta_data_csv.groupby(by = columns)
for name,group in groups:
is_unique = len(group) == 1
result.loc[group.index] = is_unique
assert not result.isnull().any()
return result
And if you only want to assert that all combinations are unique:
df1.set_index(['A','B']).index.is_unique
Try doing this:
adb kill-server && adb start-server
(that restarts adb) Also you can try to edit an adb config file .android/adb_usb.ini
and add a line 04e8
after the header. Restart adb required for changes to take effect.
The reason for this error occurs is that you are using the CryptoListPresenter _presenter
without initializing.
I found that CryptoListPresenter _presenter
would have to be initialized to fix because _presenter.loadCurrencies()
is passing through a null variable at the time of instantiation;
there are two ways to initialize
Can be initialized during an declaration, like this
CryptoListPresenter _presenter = CryptoListPresenter();
In the second, initializing(with assigning some value) it when initState
is called, which the framework will call this method once for each state object.
@override
void initState() {
_presenter = CryptoListPresenter(...);
}
Try the following.
Make the resource path "<PathRelativeToThisClassFile>/<ResourceDirectory>"
E.g. if your class path is com.abc.package.MyClass and your resoure files are within src/com/abc/package/resources/:
URL url = MyClass.class.getResource("resources/");
if (url == null) {
// error - missing folder
} else {
File dir = new File(url.toURI());
for (File nextFile : dir.listFiles()) {
// Do something with nextFile
}
}
You can also use
URL url = MyClass.class.getResource("/com/abc/package/resources/");
Floats are okay, but problematic with IE 6 & 7.
I'd prefer using the following on the inner div:
margin-left: auto;
margin-right: 0;
See the IE Double Margin Bug for clarification on why.
You can either create a new Stage
, add your controls into it or if you require the POPUP as Dialog
box, then you may consider using DialogsFX or ControlsFX(Requires JavaFX8)
For creating a new Stage, you can use the following snippet
@Override
public void start(final Stage primaryStage) {
Button btn = new Button();
btn.setText("Open Dialog");
btn.setOnAction(
new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
final Stage dialog = new Stage();
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.initOwner(primaryStage);
VBox dialogVbox = new VBox(20);
dialogVbox.getChildren().add(new Text("This is a Dialog"));
Scene dialogScene = new Scene(dialogVbox, 300, 200);
dialog.setScene(dialogScene);
dialog.show();
}
});
}
If you don't want it to be modal
(block other windows), use:
dialog.initModality(Modality.NONE);
The error SQLSTATE[HY000] [1040] Too many connections
is an SQL error, and has to do with the sql server. There could be other applications connecting to the server. The server has a maximum available connections number.
If you have phpmyadmin, you can use the 'variables' tab to check what the setting is.
You can also query the status table like so:
show status like '%onn%';
Or some variance on that. check the manual for what variables there are
(be aware, 'connections' is not the current connections, check that link :) )
// Try this may help
DateTime myDate = new DateTime();
string us = myDate.Now.Date.ToString("MM/dd/yyyy",new CultureInfo("en-US"));
or
DateTime myDate = new DateTime();
string us = myDate.Now.Date.ToString("dd/MM/yyyy",new CultureInfo("en-GB"));
I am not sure if you can grab that IP from code that runs on the local machine.
You can however build code that runs on a website, say in JSP, and then use something that returns the IP of where the request came from:
request.getRemoteAddr()
Or simply use already-existing services that do this, then parse the answer from the service to find out the IP.
Use a webservice like AWS and others
import java.net.*;
import java.io.*;
URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));
String ip = in.readLine(); //you get the IP as a String
System.out.println(ip);
I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics
If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.
Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.
Based on previous answers. I resolved my issue by removing global variable at package level to procedure, since there was no impact in my case.
Original script was
create or replace PACKAGE BODY APPLICATION_VALIDATION AS
V_ERROR_NAME varchar2(200) := '';
PROCEDURE APP_ERROR_X47_VALIDATION ( PROCESS_ID IN VARCHAR2 ) AS BEGIN
------ rules for validation... END APP_ERROR_X47_VALIDATION ;
/* Some more code
*/
END APPLICATION_VALIDATION; /
Rewritten the same without global variable V_ERROR_NAME
and moved to procedure under package level as
Modified Code
create or replace PACKAGE BODY APPLICATION_VALIDATION AS
PROCEDURE APP_ERROR_X47_VALIDATION ( PROCESS_ID IN VARCHAR2 ) AS
**V_ERROR_NAME varchar2(200) := '';**
BEGIN
------ rules for validation... END APP_ERROR_X47_VALIDATION ;
/* Some more code
*/
END APPLICATION_VALIDATION; /
If you declared different variables then use following simple method:
Int salary=2000;
String abc="I Love Pakistan";
Double pi=3.14;
Console.Writeline=salary+"/n"+abc+"/n"+pi;
Console.readkey();
In the Laravel 6 application the make:auth
command no longer exists.
Laravel UI is a new first-party package that extracts the UI portion of a Laravel project into a separate laravel/ui package. The separate package enables the Laravel team to iterate on the UI package separately from the main Laravel codebase.
You can install the laravel/ui
package via composer:
composer require laravel/ui
ui:auth
CommandBesides the new ui command, the laravel/ui
package comes with another command for generating the auth scaffolding:
php artisan ui:auth
If you run the ui:auth
command, it will generate the auth routes, a HomeController, auth views, and a app.blade.php layout file.
If you want to generate the views alone, type the following command instead:
php artisan ui:auth --views
If you want to generate the auth scaffolding at the same time:
php artisan ui vue --auth
php artisan ui react --auth
php artisan ui vue --auth
command will create all of the views you need for authentication and place them in the resources/views/auth
directory
The ui
command will also create a resources/views/layouts
directory containing a base layout for your application. All of these views use the Bootstrap CSS framework, but you are free to customize them however you wish.
More detail follow. laravel-news & documentation
composer require laravel/ui
php artisan ui:auth
From man curl
:
-x, --proxy <[protocol://][user:password@]proxyhost[:port]>
Use the specified HTTP proxy.
If the port number is not specified, it is assumed at port 1080.
General way:
export http_proxy=http://your.proxy.server:port/
Then you can connect through proxy from (many) application.
And, as per comment below, for https:
export https_proxy=https://your.proxy.server:port/
Place ojdbc6.jar in your project resources folder of eclipse. then add the following dependency code in your pom.xml
<dependency>
<groupId> oracle </groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/ojdbc6.jar</systemPath>
</dependency>
You have to create a new property (ex:selectedCountry) and should use it in [(ngModel)]
and further in component file assign default
value to it.
In your_component_file.ts
this.selectedCountry = default;
In your_component_template.html
<select id="country" formControlName="country" [(ngModel)]="selectedCountry">
<option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select>
While the answer from alireza is correct, it has one gotcha:
You can't install Microsoft Visual C++ 2015 redist (runtime) unless you have Windows Update KB2999226 installed (at least on Windows 7 64-bit SP1).
CSS selectors
single class first match
soup.select_one('.stylelistrow')
list of matches
soup.select('.stylelistrow')
compound class (i.e. AND another class)
soup.select_one('.stylelistrow.otherclassname')
soup.select('.stylelistrow.otherclassname')
Spaces in compound class names e.g. class = stylelistrow otherclassname
are replaced with ".". You can continue to add classes.
list of classes (OR - match whichever present
soup.select_one('.stylelistrow, .otherclassname')
soup.select('.stylelistrow, .otherclassname')
bs4 4.7.1 +
Specific class whose innerText
contains a string
soup.select_one('.stylelistrow:contains("some string")')
soup.select('.stylelistrow:contains("some string")')
Specific class which has a certain child element e.g. a
tag
soup.select_one('.stylelistrow:has(a)')
soup.select('.stylelistrow:has(a)')
Download package rpm package from http://pkg.jenkins-ci.org/redhat/ you can give additional java location like I have default 1.7 java in my system but I am using /opt/jdk1.8.0_60/bin/java for jenkins. Open jenkins startup script /etc/init.d/jenkins and add additional java here, I m case I have added /opt/jdk1.8.0_60/bin/java,
Search usable Java as /usr/bin/java might not point to minimal version required by Jenkins.
See http://www.nabble.com/guinea-pigs-wanted-----Hudson-RPM-for-RedHat-Linux-td25673707.html
candidates=" /opt/jdk1.8.0_60/bin/java
Call the is_path_exists_or_creatable()
function defined below.
Strictly Python 3. That's just how we roll.
The question of "How do I test pathname validity and, for valid pathnames, the existence or writability of those paths?" is clearly two separate questions. Both are interesting, and neither have received a genuinely satisfactory answer here... or, well, anywhere that I could grep.
vikki's answer probably hews the closest, but has the remarkable disadvantages of:
We're gonna fix all that.
Before hurling our fragile meat suits into the python-riddled moshpits of pain, we should probably define what we mean by "pathname validity." What defines validity, exactly?
By "pathname validity," we mean the syntactic correctness of a pathname with respect to the root filesystem of the current system – regardless of whether that path or parent directories thereof physically exist. A pathname is syntactically correct under this definition if it complies with all syntactic requirements of the root filesystem.
By "root filesystem," we mean:
/
).%HOMEDRIVE%
, the colon-suffixed drive letter containing the current Windows installation (typically but not necessarily C:
).The meaning of "syntactic correctness," in turn, depends on the type of root filesystem. For ext4
(and most but not all POSIX-compatible) filesystems, a pathname is syntactically correct if and only if that pathname:
\x00
in Python). This is a hard requirement for all POSIX-compatible filesystems.'a'*256
in Python). A path component is a longest substring of a pathname containing no /
character (e.g., bergtatt
, ind
, i
, and fjeldkamrene
in the pathname /bergtatt/ind/i/fjeldkamrene
).Syntactic correctness. Root filesystem. That's it.
Validating pathnames in Python is surprisingly non-intuitive. I'm in firm agreement with Fake Name here: the official os.path
package should provide an out-of-the-box solution for this. For unknown (and probably uncompelling) reasons, it doesn't. Fortunately, unrolling your own ad-hoc solution isn't that gut-wrenching...
O.K., it actually is. It's hairy; it's nasty; it probably chortles as it burbles and giggles as it glows. But what you gonna do? Nuthin'.
We'll soon descend into the radioactive abyss of low-level code. But first, let's talk high-level shop. The standard os.stat()
and os.lstat()
functions raise the following exceptions when passed invalid pathnames:
FileNotFoundError
.WindowsError
whose winerror
attribute is 123
(i.e., ERROR_INVALID_NAME
).'\x00'
), instances of TypeError
.OSError
whose errcode
attribute is:
errno.ERANGE
. (This appears to be an OS-level bug, otherwise referred to as "selective interpretation" of the POSIX standard.)errno.ENAMETOOLONG
.Crucially, this implies that only pathnames residing in existing directories are validatable. The os.stat()
and os.lstat()
functions raise generic FileNotFoundError
exceptions when passed pathnames residing in non-existing directories, regardless of whether those pathnames are invalid or not. Directory existence takes precedence over pathname invalidity.
Does this mean that pathnames residing in non-existing directories are not validatable? Yes – unless we modify those pathnames to reside in existing directories. Is that even safely feasible, however? Shouldn't modifying a pathname prevent us from validating the original pathname?
To answer this question, recall from above that syntactically correct pathnames on the ext4
filesystem contain no path components (A) containing null bytes or (B) over 255 bytes in length. Hence, an ext4
pathname is valid if and only if all path components in that pathname are valid. This is true of most real-world filesystems of interest.
Does that pedantic insight actually help us? Yes. It reduces the larger problem of validating the full pathname in one fell swoop to the smaller problem of only validating all path components in that pathname. Any arbitrary pathname is validatable (regardless of whether that pathname resides in an existing directory or not) in a cross-platform manner by following the following algorithm:
/troldskog/faren/vild
into the list ['', 'troldskog', 'faren', 'vild']
)./troldskog
) .os.stat()
or os.lstat()
. If that pathname and hence that component is invalid, this call is guaranteed to raise an exception exposing the type of invalidity rather than a generic FileNotFoundError
exception. Why? Because that pathname resides in an existing directory. (Circular logic is circular.)Is there a directory guaranteed to exist? Yes, but typically only one: the topmost directory of the root filesystem (as defined above).
Passing pathnames residing in any other directory (and hence not guaranteed to exist) to os.stat()
or os.lstat()
invites race conditions, even if that directory was previously tested to exist. Why? Because external processes cannot be prevented from concurrently removing that directory after that test has been performed but before that pathname is passed to os.stat()
or os.lstat()
. Unleash the dogs of mind-fellating insanity!
There exists a substantial side benefit to the above approach as well: security. (Isn't that nice?) Specifically:
Front-facing applications validating arbitrary pathnames from untrusted sources by simply passing such pathnames to
os.stat()
oros.lstat()
are susceptible to Denial of Service (DoS) attacks and other black-hat shenanigans. Malicious users may attempt to repeatedly validate pathnames residing on filesystems known to be stale or otherwise slow (e.g., NFS Samba shares); in that case, blindly statting incoming pathnames is liable to either eventually fail with connection timeouts or consume more time and resources than your feeble capacity to withstand unemployment.
The above approach obviates this by only validating the path components of a pathname against the root directory of the root filesystem. (If even that's stale, slow, or inaccessible, you've got larger problems than pathname validation.)
Lost? Great. Let's begin. (Python 3 assumed. See "What Is Fragile Hope for 300, leycec?")
import errno, os
# Sadly, Python fails to provide the following magic number for us.
ERROR_INVALID_NAME = 123
'''
Windows-specific error code indicating an invalid pathname.
See Also
----------
https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-
Official listing of all such codes.
'''
def is_pathname_valid(pathname: str) -> bool:
'''
`True` if the passed pathname is a valid pathname for the current OS;
`False` otherwise.
'''
# If this pathname is either not a string or is but is empty, this pathname
# is invalid.
try:
if not isinstance(pathname, str) or not pathname:
return False
# Strip this pathname's Windows-specific drive specifier (e.g., `C:\`)
# if any. Since Windows prohibits path components from containing `:`
# characters, failing to strip this `:`-suffixed prefix would
# erroneously invalidate all valid absolute Windows pathnames.
_, pathname = os.path.splitdrive(pathname)
# Directory guaranteed to exist. If the current OS is Windows, this is
# the drive to which Windows was installed (e.g., the "%HOMEDRIVE%"
# environment variable); else, the typical root directory.
root_dirname = os.environ.get('HOMEDRIVE', 'C:') \
if sys.platform == 'win32' else os.path.sep
assert os.path.isdir(root_dirname) # ...Murphy and her ironclad Law
# Append a path separator to this directory if needed.
root_dirname = root_dirname.rstrip(os.path.sep) + os.path.sep
# Test whether each path component split from this pathname is valid or
# not, ignoring non-existent and non-readable path components.
for pathname_part in pathname.split(os.path.sep):
try:
os.lstat(root_dirname + pathname_part)
# If an OS-specific exception is raised, its error code
# indicates whether this pathname is valid or not. Unless this
# is the case, this exception implies an ignorable kernel or
# filesystem complaint (e.g., path not found or inaccessible).
#
# Only the following exceptions indicate invalid pathnames:
#
# * Instances of the Windows-specific "WindowsError" class
# defining the "winerror" attribute whose value is
# "ERROR_INVALID_NAME". Under Windows, "winerror" is more
# fine-grained and hence useful than the generic "errno"
# attribute. When a too-long pathname is passed, for example,
# "errno" is "ENOENT" (i.e., no such file or directory) rather
# than "ENAMETOOLONG" (i.e., file name too long).
# * Instances of the cross-platform "OSError" class defining the
# generic "errno" attribute whose value is either:
# * Under most POSIX-compatible OSes, "ENAMETOOLONG".
# * Under some edge-case OSes (e.g., SunOS, *BSD), "ERANGE".
except OSError as exc:
if hasattr(exc, 'winerror'):
if exc.winerror == ERROR_INVALID_NAME:
return False
elif exc.errno in {errno.ENAMETOOLONG, errno.ERANGE}:
return False
# If a "TypeError" exception was raised, it almost certainly has the
# error message "embedded NUL character" indicating an invalid pathname.
except TypeError as exc:
return False
# If no exception was raised, all path components and hence this
# pathname itself are valid. (Praise be to the curmudgeonly python.)
else:
return True
# If any other exception was raised, this is an unrelated fatal issue
# (e.g., a bug). Permit this exception to unwind the call stack.
#
# Did we mention this should be shipped with Python already?
Done. Don't squint at that code. (It bites.)
Testing the existence or creatability of possibly invalid pathnames is, given the above solution, mostly trivial. The little key here is to call the previously defined function before testing the passed path:
def is_path_creatable(pathname: str) -> bool:
'''
`True` if the current user has sufficient permissions to create the passed
pathname; `False` otherwise.
'''
# Parent directory of the passed path. If empty, we substitute the current
# working directory (CWD) instead.
dirname = os.path.dirname(pathname) or os.getcwd()
return os.access(dirname, os.W_OK)
def is_path_exists_or_creatable(pathname: str) -> bool:
'''
`True` if the passed pathname is a valid pathname for the current OS _and_
either currently exists or is hypothetically creatable; `False` otherwise.
This function is guaranteed to _never_ raise exceptions.
'''
try:
# To prevent "os" module calls from raising undesirable exceptions on
# invalid pathnames, is_pathname_valid() is explicitly called first.
return is_pathname_valid(pathname) and (
os.path.exists(pathname) or is_path_creatable(pathname))
# Report failure on non-fatal filesystem complaints (e.g., connection
# timeouts, permissions issues) implying this path to be inaccessible. All
# other exceptions are unrelated fatal issues and should not be caught here.
except OSError:
return False
Done and done. Except not quite.
There exists a caveat. Of course there does.
As the official os.access()
documentation admits:
Note: I/O operations may fail even when
os.access()
indicates that they would succeed, particularly for operations on network filesystems which may have permissions semantics beyond the usual POSIX permission-bit model.
To no one's surprise, Windows is the usual suspect here. Thanks to extensive use of Access Control Lists (ACL) on NTFS filesystems, the simplistic POSIX permission-bit model maps poorly to the underlying Windows reality. While this (arguably) isn't Python's fault, it might nonetheless be of concern for Windows-compatible applications.
If this is you, a more robust alternative is wanted. If the passed path does not exist, we instead attempt to create a temporary file guaranteed to be immediately deleted in the parent directory of that path – a more portable (if expensive) test of creatability:
import os, tempfile
def is_path_sibling_creatable(pathname: str) -> bool:
'''
`True` if the current user has sufficient permissions to create **siblings**
(i.e., arbitrary files in the parent directory) of the passed pathname;
`False` otherwise.
'''
# Parent directory of the passed path. If empty, we substitute the current
# working directory (CWD) instead.
dirname = os.path.dirname(pathname) or os.getcwd()
try:
# For safety, explicitly close and hence delete this temporary file
# immediately after creating it in the passed path's parent directory.
with tempfile.TemporaryFile(dir=dirname): pass
return True
# While the exact type of exception raised by the above function depends on
# the current version of the Python interpreter, all such types subclass the
# following exception superclass.
except EnvironmentError:
return False
def is_path_exists_or_creatable_portable(pathname: str) -> bool:
'''
`True` if the passed pathname is a valid pathname on the current OS _and_
either currently exists or is hypothetically creatable in a cross-platform
manner optimized for POSIX-unfriendly filesystems; `False` otherwise.
This function is guaranteed to _never_ raise exceptions.
'''
try:
# To prevent "os" module calls from raising undesirable exceptions on
# invalid pathnames, is_pathname_valid() is explicitly called first.
return is_pathname_valid(pathname) and (
os.path.exists(pathname) or is_path_sibling_creatable(pathname))
# Report failure on non-fatal filesystem complaints (e.g., connection
# timeouts, permissions issues) implying this path to be inaccessible. All
# other exceptions are unrelated fatal issues and should not be caught here.
except OSError:
return False
Note, however, that even this may not be enough.
Thanks to User Access Control (UAC), the ever-inimicable Windows Vista and all subsequent iterations thereof blatantly lie about permissions pertaining to system directories. When non-Administrator users attempt to create files in either the canonical C:\Windows
or C:\Windows\system32
directories, UAC superficially permits the user to do so while actually isolating all created files into a "Virtual Store" in that user's profile. (Who could have possibly imagined that deceiving users would have harmful long-term consequences?)
This is crazy. This is Windows.
Dare we? It's time to test-drive the above tests.
Since NULL is the only character prohibited in pathnames on UNIX-oriented filesystems, let's leverage that to demonstrate the cold, hard truth – ignoring non-ignorable Windows shenanigans, which frankly bore and anger me in equal measure:
>>> print('"foo.bar" valid? ' + str(is_pathname_valid('foo.bar')))
"foo.bar" valid? True
>>> print('Null byte valid? ' + str(is_pathname_valid('\x00')))
Null byte valid? False
>>> print('Long path valid? ' + str(is_pathname_valid('a' * 256)))
Long path valid? False
>>> print('"/dev" exists or creatable? ' + str(is_path_exists_or_creatable('/dev')))
"/dev" exists or creatable? True
>>> print('"/dev/foo.bar" exists or creatable? ' + str(is_path_exists_or_creatable('/dev/foo.bar')))
"/dev/foo.bar" exists or creatable? False
>>> print('Null byte exists or creatable? ' + str(is_path_exists_or_creatable('\x00')))
Null byte exists or creatable? False
Beyond sanity. Beyond pain. You will find Python portability concerns.
This also works:
...
WHERE
(FirstName IS NULL OR FirstName = ISNULL(@FirstName, FirstName)) AND
(LastName IS NULL OR LastName = ISNULL(@LastName, LastName)) AND
(Title IS NULL OR Title = ISNULL(@Title, Title))
In such cases, you are better off re-adding the whitespace which makes the syntax error immediate apparent:
function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById("content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","data/"+id+".html",true);xmlhttp.send();
}
There's a } too many. Also, after the closing } of the function, you should add a ; before the xmlhttp.open()
And finally, I don't see what that anonymous function does up there. It's never executed or referenced. Are you sure you pasted the correct code?
Try this app http://www.ketzler.de/2011/01/resign-an-iphone-app-insert-new-bundle-id-and-send-to-xcode-organizer-for-upload/
It supposed to help you resign the IPA file. I tried it myself but couldn't get pass an error with Entitlements.plist. Could just be a problem with my project. You should give it a try.
#include<stdio.h>
int main()
{
int a,b,i,c,j;
printf("\n Enter the two no. in between you want to check:");
scanf("%d%d",&a,&c);
printf("%d-%d\n",a,c);
for(j=a;j<=c;j++)
{
b=0;
for(i=1;i<=c;i++)
{
if(j%i==0)
{
b++;
}
}
if(b==2)
{
printf("\nPrime number:%d\n",j);
}
else
{
printf("\n\tNot prime:%d\n",j);
}
}
}
package workouts;
import java.util.Random;
/**
*
* @author Muthu
*/
public class RandomGenerator {
public static void main(String[] args) {
for(int i=0;i<5;i++){
rndFunc();
}
}
public static void rndFunc(){
int[]a= new int[]{1,2,3};
Random rnd= new Random();
System.out.println(a[rnd.nextInt(a.length)]);
}
}
Use this, and you will find all informations at http://www.w3schools.com/html/html5_geolocation.asp
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
You can either set
border-bottom: none;
or
border-bottom: 0;
One sets the border-style
to none
.
One sets the border-width
to 0px
.
div {_x000D_
border: 3px solid #900;_x000D_
_x000D_
background-color: limegreen; _x000D_
width: 28vw;_x000D_
height: 10vw;_x000D_
margin: 1vw;_x000D_
text-align: center;_x000D_
float: left;_x000D_
}_x000D_
_x000D_
.stylenone {_x000D_
border-bottom: none;_x000D_
}_x000D_
.widthzero {_x000D_
border-bottom: 0;_x000D_
}
_x000D_
<div>_x000D_
(full border)_x000D_
</div>_x000D_
<div class="stylenone">_x000D_
(style)<br><br>_x000D_
_x000D_
border-bottom: none;_x000D_
</div>_x000D_
<div class="widthzero">_x000D_
(width)<br><br>_x000D_
border-bottom: 0;_x000D_
</div>
_x000D_
Side Note:
If you ever have to track down why a border is not showing when you expect it to,
It is also good to know that either of these could be the culprit.
Also verify the border-color
is not the same as the background-color
.
I had to edit the C:\Windows\System32\inetsrv\config\applicationHost.config
file and add <requestLimits maxAllowedContentLength="1073741824" />
to the end of the...
<configuration>
<system.webServer>
<security>
<requestFiltering>
section.
I came up with a hack that might produce the result intended in the original answer.
If you have the file you want in two windows in a source control, you can right-click on the file and select compare, you can compare the
If you do compare you will have a new window Called diff, showing you the contents of you file.
This is of course not ideal as the diff window will have the diff colors polluting the text. Note: you can compare the file you want to open to and empty file, and then you will have the window in a very ugly green background.
This is not perfect, it is a hack, but it was the only way I found to really have the same file in two windows.
If you want to check if some string is present in another string, use something like String.contains
If you want to check if some pattern is present in a string, append and prepend the pattern with '.*'. The result will accept strings that contain the pattern.
Example: Suppose you have some regex a(b|c) that checks if a string matches ab
or ac
.*(a(b|c)).*
will check if a string contains a ab
or ac
.
A disadvantage of this method is that it will not give you the location of the match.
You can create a protocol, conforming to the Swift LocalizedError
protocol, with these values:
protocol OurErrorProtocol: LocalizedError {
var title: String? { get }
var code: Int { get }
}
This then enables us to create concrete errors like so:
struct CustomError: OurErrorProtocol {
var title: String?
var code: Int
var errorDescription: String? { return _description }
var failureReason: String? { return _description }
private var _description: String
init(title: String?, description: String, code: Int) {
self.title = title ?? "Error"
self._description = description
self.code = code
}
}
You can convert the value user provides to a double and store it again as nvarchar, with the aid of FormatProviders. CultureInfo is a typical FormatProvider. Assuming you know the culture you are operating,
System.Globalization.CultureInfo EnglishCulture = new System.Globalization.CultureInfo("en-EN");
System.Globalization.CultureInfo GermanCulture = new System.Globalization.CultureInfo("de-de");
will suffice to do the neccesary transformation, like;
double val;
if(double.TryParse("65,89875", System.Globalization.NumberStyles.Float, GermanCulture, out val))
{
string valInGermanFormat = val.ToString(GermanCulture);
string valInEnglishFormat = val.ToString(EnglishCulture);
}
if(double.TryParse("65.89875", System.Globalization.NumberStyles.Float, EnglishCulture, out val))
{
string valInGermanFormat = val.ToString(GermanCulture);
string valInEnglishFormat = val.ToString(EnglishCulture);
}
If you want to append this css
file to header
you can do it using mounted()
function of the vue file. See the example.
Note: Assume you can access the css
file as http://www.yoursite/assets/styles/vendor.css
in the browser.
mounted() {
let style = document.createElement('link');
style.type = "text/css";
style.rel = "stylesheet";
style.href = '/assets/styles/vendor.css';
document.head.appendChild(style);
}
callLog(){
this.http.get('http://localhost:3000/getstudent/'+this.login.email+'/'+this.login.password)
.subscribe(data => {
this.getstud=data as string[];
if(this.getstud.length!==0) {
console.log(data)
this.route.navigate(['home']);// used for routing after importing Router
}
});
}
Here is an implementation using HttpUrlConnection:
class CustomWebviewClient : WebViewClient() {
private val charsetPattern = Pattern.compile(".*?charset=(.*?)(;.*)?$")
override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
try {
val connection: HttpURLConnection = URL(request.url.toString()).openConnection() as HttpURLConnection
connection.requestMethod = request.method
for ((key, value) in request.requestHeaders) {
connection.addRequestProperty(key, value)
}
connection.addRequestProperty("custom header key", "custom header value")
var contentType: String? = connection.contentType
var charset: String? = null
if (contentType != null) {
// some content types may include charset => strip; e. g. "application/json; charset=utf-8"
val contentTypeTokenizer = StringTokenizer(contentType, ";")
val tokenizedContentType = contentTypeTokenizer.nextToken()
var capturedCharset: String? = connection.contentEncoding
if (capturedCharset == null) {
val charsetMatcher = charsetPattern.matcher(contentType)
if (charsetMatcher.find() && charsetMatcher.groupCount() > 0) {
capturedCharset = charsetMatcher.group(1)
}
}
if (capturedCharset != null && !capturedCharset.isEmpty()) {
charset = capturedCharset
}
contentType = tokenizedContentType
}
val status = connection.responseCode
var inputStream = if (status == HttpURLConnection.HTTP_OK) {
connection.inputStream
} else {
// error stream can sometimes be null even if status is different from HTTP_OK
// (e. g. in case of 404)
connection.errorStream ?: connection.inputStream
}
val headers = connection.headerFields
val contentEncodings = headers.get("Content-Encoding")
if (contentEncodings != null) {
for (header in contentEncodings) {
if (header.equals("gzip", true)) {
inputStream = GZIPInputStream(inputStream)
break
}
}
}
return WebResourceResponse(contentType, charset, status, connection.responseMessage, convertConnectionResponseToSingleValueMap(connection.headerFields), inputStream)
} catch (e: Exception) {
e.printStackTrace()
}
return super.shouldInterceptRequest(view, request)
}
private fun convertConnectionResponseToSingleValueMap(headerFields: Map<String, List<String>>): Map<String, String> {
val headers = HashMap<String, String>()
for ((key, value) in headerFields) {
when {
value.size == 1 -> headers[key] = value[0]
value.isEmpty() -> headers[key] = ""
else -> {
val builder = StringBuilder(value[0])
val separator = "; "
for (i in 1 until value.size) {
builder.append(separator)
builder.append(value[i])
}
headers[key] = builder.toString()
}
}
}
return headers
}
}
Note that this does not work for POST requests because WebResourceRequest doesn't provide POST data. There is a Request Data - WebViewClient library which uses a JavaScript injection workaround for intercepting POST data.
There are several tools for converting Matlab to Python code.
The only one that's seen recent activity (last commit from June 2018) is Small Matlab to Python compiler (also developed here: SMOP@chiselapp).
Other options include:
Also, for those interested in an interface between the two languages and not conversion:
pymatlab
: communicate from Python by sending data to the MATLAB workspace, operating on them with scripts and pulling back the resulting data.pymat2
: continuation of the seemingly abandoned PyMat.mlabwrap
, mlabwrap-purepy: make Matlab look like Python library (based on PyMat).oct2py
: run GNU Octave commands from within Python.pymex
: Embeds the Python Interpreter in Matlab, also on File Exchange.matpy
: Access MATLAB in various ways: create variables, access .mat files, direct interface to MATLAB engine (requires MATLAB be installed).Btw might be helpful to look here for other migration tips:
On a different note, though I'm not a fortran
fan at all, for people who might find it useful there is:
In my case the problem was with the content of mail. When I changed content to simpler content without HTML, it worked. But after updating the phpmailer everything solved.
I actually found the right command to use.. its called timeout: http://www.ss64.com/nt/timeout.html
Pure numpy
numpy.loadtxt(open("test.csv", "rb"), delimiter=",", skiprows=1)
Check out the loadtxt documentation.
You can also use python's csv module:
import csv
import numpy
reader = csv.reader(open("test.csv", "rb"), delimiter=",")
x = list(reader)
result = numpy.array(x).astype("float")
You will have to convert it to your favorite numeric type. I guess you can write the whole thing in one line:
result = numpy.array(list(csv.reader(open("test.csv", "rb"), delimiter=","))).astype("float")
Added Hint:
You could also use pandas.io.parsers.read_csv
and get the associated numpy
array which can be faster.
Use an existing library known to handle the quirks involved in dealing with time calculations. My current favorite is moment.js.
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.js"></script>
<script>
var now = moment(); // get "now"
console.log(now.toDate()); // show original date
var thirty = moment(now).add(30,"minutes"); // clone "now" object and add 30 minutes, taking into account weirdness like crossing DST boundries or leap-days, -minutes, -seconds.
console.log(thirty.toDate()); // show new date
</script>
For people having a startTime
(like 12h:30:30) and a duration
(value in minutes like 120), you can guess the endTime
like so:
const startTime = '12:30:00';
const durationInMinutes = '120';
const endTime = moment(startTime, 'HH:mm:ss').add(durationInMinutes, 'minutes').format('HH:mm');
// endTime is equal to "14:30"
One other thing to look at that solved it for me :
In an Eclipse / Maven project, I had Java classes in src/test/java
in which I was using the this.getClass().getResource("someFile.ext");
pattern to look for resources in src/test/resources
where the resource file was in the same package location in the resources source folder as the test class was in the the test source folder. It still failed to locate them.
Right click on the src/test/resources
source folder, Build Path, then "configure inclusion / exclusion filters"; I added a new inclusion filter of **/*.ext
to make sure my files weren't getting scrubbed; my tests now can find their resource files.
You can build a small UI that does the job like this :
function test(){
showURL("http://www.google.com")
}
//
function showURL(href){
var app = UiApp.createApplication().setHeight(50).setWidth(200);
app.setTitle("Show URL");
var link = app.createAnchor('open ', href).setId("link");
app.add(link);
var doc = SpreadsheetApp.getActive();
doc.show(app);
}
If you want to 'show' the URL, just change this line like this :
var link = app.createAnchor(href, href).setId("link");
EDIT : link to a demo spreadsheet in read only because too many people keep writing unwanted things on it (just make a copy to use instead).
EDIT : UiApp was deprecated by Google on 11th Dec 2014, this method could break at any time and needs updating to use HTML service instead!
EDIT : below is an implementation using html service.
function testNew(){
showAnchor('Stackoverflow','http://stackoverflow.com/questions/tagged/google-apps-script');
}
function showAnchor(name,url) {
var html = '<html><body><a href="'+url+'" target="blank" onclick="google.script.host.close()">'+name+'</a></body></html>';
var ui = HtmlService.createHtmlOutput(html)
SpreadsheetApp.getUi().showModelessDialog(ui,"demo");
}
The equals() method on your List implementation should do elementwise comparison, so
assertEquals(argumentComponents, returnedComponents);
is a lot easier.
Got the same error here!
It seems the Intellij cannot verify if the class implementation is a @Service or @Component.
Solve it just changing from Error to Warning(Pressing Alt + Enter).
I think this is what we like to do very much.
--Step 1: (create a new user)
create LOGIN hello WITH PASSWORD='foo', CHECK_POLICY = OFF;
-- Step 2:(deny view to any database)
USE master;
GO
DENY VIEW ANY DATABASE TO hello;
-- step 3 (then authorized the user for that specific database , you have to use the master by doing use master as below)
USE master;
GO
ALTER AUTHORIZATION ON DATABASE::yourDB TO hello;
GO
If you already created a user and assigned to that database before by doing
USE [yourDB]
CREATE USER hello FOR LOGIN hello WITH DEFAULT_SCHEMA=[dbo]
GO
then kindly delete it by doing below and follow the steps
USE yourDB;
GO
DROP USER newlogin;
GO
For more information please follow the links:
Hiding databases for a login on Microsoft Sql Server 2008R2 and above
You need to populate the empty indexes with nulls.
while (arraylist.size() < position)
{
arraylist.add(null);
}
arraylist.add(position, object);
The easiest way to get first day(Monday) of current week is:
strtotime("next Monday") - 604800;
where 604800 - is count of seconds in 1 week(60*60*24*7).
This code get next Monday and decrease it for 1 week. This code will work well in any day of week. Even if today is Monday.
You can use $0 to determine your script name (with full path) - to get the script name only you can trim that variable with
basename $0
Based on a web search, I just found a Chrome plugin called SVG Export.
Available in the Chrome web store: https://chrome.google.com/webstore/detail/svg-export/naeaaedieihlkmdajjefioajbbdbdjgp
The home page is https://svgexport.io
Fake loop that breaks on the first iteration:
$key = $value = NULL;
foreach ($array as $key => $value) {
break;
}
echo "$key = $value\n";
Or use each()
(warning: deprecated as of PHP 7.2.0):
reset($array);
list($key, $value) = each($array);
echo "$key = $value\n";
Assuming you have GNU find:
find . -size +10000k -printf '%s %f\n'
If you want a constant width for the size field, you can do something like:
find . -size +10000k -printf '%10s %f\n'
Note that -size +1000k
selects files of at least 10,240,000 bytes (k
is 1024, not 1000). You said in a comment that you want files bigger than 1M; if that's 1024*1024 bytes, then this:
find . -size +1M ...
will do the trick -- except that it will also print the size and name of files that are exactly 1024*1024 bytes. If that matters, you could use:
find . -size +1048575c ...
You need to decide just what criterion you want.
Try this:
private string GetJArrayValue(JObject yourJArray, string key)
{
foreach (KeyValuePair<string, JToken> keyValuePair in yourJArray)
{
if (key == keyValuePair.Key)
{
return keyValuePair.Value.ToString();
}
}
}
Since you don't state if the form can resize or not there is an easy way if you don't care about resizing (if you do care, go with Mitch Wheats solution):
Select the control -> Format (menu option) -> Center in Window -> Horizontally or Vertically
In Windows, you will have to set the path to the location where you installed Anaconda3 to.
For me, I installed anaconda3 into C:\Anaconda3
. Therefore you need to add C:\Anaconda3
as well as C:\Anaconda3\Scripts\
to your path variable, e.g. set PATH=%PATH%;C:\Anaconda3;C:\Anaconda3\Scripts\
.
You can do this via powershell (see above, https://msdn.microsoft.com/en-us/library/windows/desktop/bb776899(v=vs.85).aspx ), or hit the windows
key ? enter environment
? choose from settings
? edit environment variables for your account
? select Path
variable ? Edit
? New
.
To test it, open a new dos shell, and you should be able to use conda commands now. E.g., try conda --version
.
In C++, use a vector. It's like an array but you can easily add and remove elements and it will take care of allocating and deallocating memory for you.
I know the title of the question says C, but you tagged your question with C and C++...
This is SUPER late and probably not relevant anymore, but if anyone stumbles upon this answer, I believe I know the cause.
So the JSON encoded string is perfectly valid with the degree symbol in it, as the other answer mentions. The problem is most likely in the character encoding that you are reading/writing with. Depending on how you are using Gson, you are probably passing it a java.io.Reader
instance. Any time you are creating a Reader
from an InputStream
, you need to specify the character encoding, or java.nio.charset.Charset
instance (it's usually best to use java.nio.charset.StandardCharsets.UTF_8
). If you don't specify a Charset
, Java will use your platform default encoding, which on Windows is usually CP-1252.
You can use ALTER TABLE
to change the auto_increment initial value:
ALTER TABLE tbl AUTO_INCREMENT = 5;
See the MySQL reference for more details.
In later versions, the plugin has changed name to:
apply plugin: 'com.android.library'
And as already mentioned by some of the other answers, you need the gradle tools in order to use it. Using 3.0.1, you have to use the google repo, not mavenCentral or jcenter:
buildscript {
repositories {
...
//In IntelliJ or older versions of Android Studio
//maven {
// url 'https://maven.google.com'
//}
google()//in newer versions of Android Studio
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
}
very simple in first controllr call
$this->load->model('MyController');
$this->MyController->test();
place file MyController.php to /model patch
MyController.php should be contain
class MyController extends CI_Model {
function __construct() {
parent::__construct();
}
function test()
{
echo 'OK';
}
}
First method you can try this
$department->department_name = $request->department_name;
$department->status = $request->status;
$department->save();
Another way to insert records into the database with create function
$department = new Department;
// Another Way to insert records
$department->create($request->all());
return redirect('admin/departments');
You need to set the filledby in Department model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Department extends Model
{
protected $fillable = ['department_name','status'];
}
Type punning via pointer casts (as opposed to using a union) is a major example of breaking strict aliasing.
Seems to be possible with JQuery's ajax function by specifying
type: "put"
or
type: "delete"
and is not not supported by all browsers, but most of them.
Check out this question for more info on compatibility:
Are the PUT, DELETE, HEAD, etc methods available in most web browsers?
const fs = require("fs");
fs.copyFileSync("filepath1", "filepath2"); //fs.copyFileSync("file1.txt", "file2.txt");
This is what I personally use to copy a file and replace another file using Node.js :)
You can get the PID of a particular process like MySQL by using following commands: ps -e | pgrep mysql
This command will give you the PID of MySQL rocess. e.g, 13954 Now, type following command on terminal. kill -9 13954 This will kill the process of MySQL.
As always, the Jakarta Commons have at least part of the answer :
This can be used to check most whether a given String is a number. You still have to choose what to do in case your String isnt a number ...
For removing older versions of all installed gems, following 2 commands are useful:
gem cleanup --dryrun
Above command will preview what gems are going to be removed.
gem cleanup
Above command will actually remove them.
Nick Vogt at H3XED posted this syntax: https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080
Take this link and replace the expression "VIDEOID" with the (shortened/shared) ID of the video.
Exapmple for ID: i3jNECZ3ybk looks like this: ... /v/i3jNECZ3ybk?version=3&vq=hd1080
What you get as a result is the standalone 1080p video but not in the Tube environment.
If you are using eclipse and maven for handling dependencies, you may need to take these extra steps to make sure eclipse copies the dependencies properly Maven dependencies not visible in WEB-INF/lib (namely the Deployment Assembly for Dynamic web application)
Breakpoint :-
breakpoint will stop executing, and let you examine JavaScript values.
After examining values, you can resume the execution of code (typically with a play button).
Debugger :-
The debugger; stops the execution of JavaScript, and callsthe debugging function.
The debugger statement suspends execution, but it does not close any files or clear any variables.
Example:-
function checkBuggyStuff() {
debugger; // do buggy stuff to examine.
};
Your index.php code is correct. I am including the updated code for common.php below then I will explain the differences.
<?php
$class = ($page == 'one') ? 'class="active"' : '';
$nav = <<<EOD
<div id="nav">
<ul>
<li><a $class href="index.php">Tab1</a>/</li>
<li><a href="two.php">Tab2</a></li>
<li><a href="three.php">Tab3</a></li>
</ul>
</div>
EOD;
?>
The first issue is that you need to make sure that the end declaration for your heredoc -- EOD;
-- is not indented at all. If it is indented, then you will get errors.
As for your issue with the PHP code not running within the heredoc statement, that is because you are looking at it wrong. Using a heredoc statement is not the same as closing the PHP tags. As such, you do not need to try reopening them. That will do nothing for you. The way the heredoc syntax works is that everything between the opening and closing is displayed exactly as written with the exception of variables. Those are replaced with the associated value. I removed your logic from the heredoc and used a tertiary function to determine the class to make this easier to see (though I don't believe any logical statements will work within the heredoc anyway)
To understand the heredoc syntax, it is the same as including it within double quotes ("), but without the need for escaping. So your code could also be written like this:
<?php
$class = ($page == 'one') ? 'class="active"' : '';
$nav = "<div id=\"nav\">
<ul>
<li><a $class href=\"index.php\">Tab1</a>/</li>
<li><a href=\"two.php\">Tab2</a></li>
<li><a href=\"three.php\">Tab3</a></li>
</ul>
</div>";
?>
It will do exactly the same thing, just is written somewhat differently. Another difference between heredoc and the string is that you can escape out of the string in the middle where you can't in the heredoc. Using this logic, you can produce the following code:
<?php
$nav = "<div id=\"nav\">
<ul>
<li><a ".(($page == 'one') ? 'class="active"' : '')." href=\"index.php\">Tab1</a>/</li>
<li><a href=\"two.php\">Tab2</a></li>
<li><a href=\"three.php\">Tab3</a></li>
</ul>
</div>";
?>
Then you can include the logic directly in the string like you originally intended.
Whichever method you choose makes very little (if any) difference in the performance of the script. It mostly boils down to preference. Either way, you need to make sure you understand how each works.
The answer (which I know is not what you're looking for) is:
class SpecialDerived : Base
{
public override void Say()
{
Console.WriteLine("Called from Special Derived.");
base.Say();
}
}
The truth is, you only have direct interaction with the class you inherit from. Think of that class as a layer - providing as much or as little of it or its parent's functionality as it desires to its derived classes.
EDIT:
Your edit works, but I think I would use something like this:
class Derived : Base
{
protected bool _useBaseSay = false;
public override void Say()
{
if(this._useBaseSay)
base.Say();
else
Console.WriteLine("Called from Derived");
}
}
Of course, in a real implementation, you might do something more like this for extensibility and maintainability:
class Derived : Base
{
protected enum Mode
{
Standard,
BaseFunctionality,
Verbose
//etc
}
protected Mode Mode
{
get; set;
}
public override void Say()
{
if(this.Mode == Mode.BaseFunctionality)
base.Say();
else
Console.WriteLine("Called from Derived");
}
}
Then, derived classes can control their parents' state appropriately.
The ?
operand makes match non-greedy. E.g. .*
is greedy while .*?
isn't. So you can use something like <img.*?>
to match the whole tag. Or <img[^>]*>
.
But remember that the whole set of HTML can't be actually parsed with regular expressions.
from within the directory of "my_script.py" you can simply do:
%run ./my_script.py
Migh below code works for you, It works for me perfectly fine:
private void viewDialog() {
try {
Intent vpnIntent = new Intent(context, UtilityVpnService.class);
context.startService(vpnIntent);
final View Dialogview = View.inflate(getBaseContext(), R.layout.alert_open_internet, null);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_DIM_BEHIND,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
windowManager.addView(Dialogview, params);
Button btn_cancel = (Button) Dialogview.findViewById(R.id.btn_canceldialog_internetblocked);
Button btn_okay = (Button) Dialogview.findViewById(R.id.btn_openmainactivity);
RelativeLayout relativeLayout = (RelativeLayout) Dialogview.findViewById(R.id.rellayout_dialog);
btn_cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
try {
if (Dialogview != null) {
// ( (WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE)).removeView(Dialogview);
windowManager.removeView(Dialogview);
}
} catch (final IllegalArgumentException e) {
e.printStackTrace();
// Handle or log or ignore
} catch (final Exception e) {
e.printStackTrace();
// Handle or log or ignore
} finally {
try {
if (windowManager != null && Dialogview != null) {
// ((WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE)).removeView(Dialogview);
windowManager.removeView(Dialogview);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// ((WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE)).removeView(Dialogview);
// windowManager.removeView(Dialogview);
}
});
}
});
btn_okay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
// ((WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE)).removeView(Dialogview);
try {
if (windowManager != null && Dialogview != null)
windowManager.removeView(Dialogview);
Intent intent = new Intent(getBaseContext(), SplashActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
} catch (Exception e) {
windowManager.removeView(Dialogview);
e.printStackTrace();
}
}
});
}
});
} catch (Exception e) {
//` windowManager.removeView(Dialogview);
e.printStackTrace();
}
}
Do not define your view globally if u call it from background service.
If you're using underscore
, you can use bind
.
E.g.
if (this.options.destroyOnHide) {
setTimeout(_.bind(this.tip.destroy, this), 1000);
}
With a running instance of myExecutableName
having a PID 15073
:
hitting Tab twice after $ gdb myExecu
in the command line, will automagically autocompletes to:
$ gdb myExecutableName 15073
and will attach gdb to this process. That's nice!
I've got rid of type mismatch by following code:
Sub ConvertToDate()
Dim r As Range
Dim setdate As Range
'in my case I have a header and no blank cells in used range,
'starting from 2nd row, 1st column
Set setdate = Range(Cells(2, 1), Cells(2, 1).End(xlDown))
With setdate
.NumberFormat = "dd.mm.yyyy" 'I have the data in format "dd.mm.yy"
.Value = .Value
End With
For Each r In setdate
r.Value = CDate(r.Value)
Next r
End Sub
But in my particular case, I have the data in format "dd.mm.yy"
Here is how you do it:
$http.get("/url/to/resource/", {params:{"param1": val1, "param2": val2}})
.then(function (response) { /* */ })...
Angular takes care of encoding the parameters.
Maxim Shoustin's answer does not work ({method:'GET', url:'/search', jsonData}
is not a valid JavaScript literal) and JeyTheva's answer, although simple, is dangerous as it allows XSS (unsafe values are not escaped when you concatenate them).
Here is an alternative that is an incremental improvement on several other answers. Assuming settings.aLengthMenu is not multi-dimensional (it can be when DataTables has row lengths and labels) and the data will not change after page load (for simple DOM-loaded DataTables), this function can be inserted to eliminate paging. It hides several paging-related classes.
Perhaps more robust would be setting paging to false inside the function below, however I don't see an API call for that off-hand.
$('#myTable').on('init.dt', function(evt, settings) {
if (settings && settings.aLengthMenu && settings.fnRecordsTotal && settings.fnRecordsTotal() < settings.aLengthMenu[0]) {
// hide pagination controls, fewer records than minimum length
$(settings.nTableWrapper).find('.dataTables_paginate, .dataTables_length, .dataTables_info').hide();
}
}).DataTable();
Parsing JSON in Swift is an excellent job for code generation. I've created a tool at http://www.guideluxe.com/JsonToSwift to do just that.
You supply a sample JSON object with a class name and the tool will generate a corresponding Swift class, as well as any needed subsidiary Swift classes, to represent the structure implied by the sample JSON. Also included are class methods used to populate Swift objects, including one that utilizes the NSJSONSerialization.JSONObjectWithData method. The necessary mappings from the NSArray and NSDictionary objects are provided.
From the generated code, you only need to supply an NSData object containing JSON that matches the sample provided to the tool.
Other than Foundation, there are no dependencies.
My work was inspired by http://json2csharp.com/, which is very handy for .NET projects.
Here's how to create an NSData object from a JSON file.
let fileUrl: NSURL = NSBundle.mainBundle().URLForResource("JsonFile", withExtension: "json")!
let jsonData: NSData = NSData(contentsOfURL: fileUrl)!
$myTimezone = date_default_timezone_get();
date_default_timezone_set($userTimezone);
$userDay = date('l', $userTimestamp);
date_default_timezone_set($myTimezone);
This should work (didn't test it, so YMMV). It works by storing the script's current timezone, changing it to the one specified by the user, getting the day of the week from the date()
function at the specified timestamp, and then setting the script's timezone back to what it was to begin with.
You might have some adventures with timezone identifiers, though.
You have to select "Refresh Dependencies" in the "Gradle" context menu that appears when you right-click the project in the Package Explorer.
Select * from TableName Where ColumnName LIKE '%[^A-Za-z0-9, ]%'
This will give you all the row which contains any special character.
...
public static final String NOTIFICATION_CHANNEL_ID = MyLocationService.class.getSimpleName();
...
...
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
NOTIFICATION_CHANNEL_ID+"_name",
NotificationManager.IMPORTANCE_HIGH);
NotificationManager notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notifManager.createNotificationChannel(channel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.notification_text))
.setOngoing(true)
.setContentIntent(broadcastIntent)
.setSmallIcon(R.drawable.ic_tracker)
.setPriority(PRIORITY_HIGH)
.setCategory(Notification.CATEGORY_SERVICE);
startForeground(1, builder.build());
...
may be i can help you by this example
In the custom fancybox I show contents with interpolated values.
in the service, in the "open" fancybox method, i do
open: function(html, $compile) {
var el = angular.element(html);
var compiledEl = $compile(el);
$.fancybox.open(el);
}
the $compile returns compiled data. you can check the compiled data
To count all occurrences, use -o
. Try this:
echo afoobarfoobar | grep -o foo | wc -l
And man grep
of course (:
Some suggest to use just grep -co foo
instead of grep -o foo | wc -l
.
Don't.
This shortcut won't work in all cases. Man page says:
-c print a count of matching lines
Difference in these approaches is illustrated below:
1.
$ echo afoobarfoobar | grep -oc foo
1
As soon as the match is found in the line (a{foo}barfoobar
) the searching stops. Only one line was checked and it matched, so the output is 1
. Actually -o
is ignored here and you could just use grep -c
instead.
2.
$ echo afoobarfoobar | grep -o foo
foo
foo
$ echo afoobarfoobar | grep -o foo | wc -l
2
Two matches are found in the line (a{foo}bar{foo}bar
) because we explicitly asked to find every occurrence (-o
). Every occurence is printed on a separate line, and wc -l
just counts the number of lines in the output.
I inherited some real bad code from someone who wasn't using migrations!?, so manually pasted the filenames into the migrations, forgetting to remove the trailing .php
So that caused the 'table exists' error despite the filename and migration matching.
2018_05_07_142737_create_users_table.php - WRONG 2018_05_07_142737_create_users_table - CORRECT
Not the simplest way but if you're a fan of recursion you might be interested in the following method to reverse an ArrayList:
public ArrayList<Object> reverse(ArrayList<Object> list) {
if(list.size() > 1) {
Object value = list.remove(0);
reverse(list);
list.add(value);
}
return list;
}
Or non-recursively:
public ArrayList<Object> reverse(ArrayList<Object> list) {
for(int i = 0, j = list.size() - 1; i < j; i++) {
list.add(i, list.remove(j));
}
return list;
}
Use a keep alive.
On login:
session_start();
$_SESSION['last_action'] = time();
An ajax call every few (eg 20) seconds:
windows.setInterval(keepAliveCall, 20000);
Server side keepalive.php:
session_start();
$_SESSION['last_action'] = time();
On every other action:
session_start();
if ($_SESSION['last_action'] < time() - 30 /* be a little tolerant here */) {
// destroy the session and quit
}
I don't know why you think there's no constructor. See the API.
Below is a snippet of code to set the important parameter for the style attribute using jquery.
$.fn.setFixedStyle = function(styles){
var s = $(this).attr("style");
s = "{"+s.replace(/;/g,",").replace(/'|"/g,"");
s = s.substring(0,s.length-1)+"}";
s = s.replace(/,/g,"\",\"").replace(/{/g,"{\"").replace(/}/g,"\"}").replace(/:/g,"\":\"");
var stOb = JSON.parse(s),st;
if(!styles){
$.each(stOb,function(k,v){
stOb[k] +=" !important";
});
}
else{
$.each(styles,function(k,v){
if(v.length>0){
stOb[k] = v+" !important";
}else{
stOb[k] += " !important";
}
});
}
var ns = JSON.stringify(stOb);
$(this).attr("style",ns.replace(/"|{|}/g,"").replace(/,/g,";"));
};
Usage is pretty simple.Just pass an object containing all the attributes you want to set as important.
$("#i1").setFixedStyle({"width":"50px","height":""});
There are two additional options.
1.To just add important parameter to already present style attribute pass empty string.
2.To add important param for all attributes present dont pass anything. It will set all attributes as important.
Here is it live in action. http://codepen.io/agaase/pen/nkvjr
Not sure from what version, but I use 1.3.14 and you can just use:
window.location.href = '/employee/1';
No need to inject $location
or $window
in the controller and no need to get the current host address.
When testing for directories remember that every directory contains two special files.
One is called '.' and the other '..'
. is the directory's own name while .. is the name of it's parent directory.
To avoid trailing backslash problems just test to see if the directory knows it's own name.
eg:
if not exist %temp%\buffer\. mkdir %temp%\buffer
TCP is appropriate when you have to move a decent amount of data (> ~1 kB), and you require all of it to be delivered. Almost all data that moves across the internet does so via TCP - HTTP, SMTP, BitTorrent, SSH, etc, all use TCP.
UDP is appropriate when you have small messages which you can afford to lose, and would like to send them as efficiently as possible. One reason you might be able to afford to lose them is because you can re-send them if they get lost. The main example on the internet is DNS - DNS consists of small queries saying things like "what is the IP number for stackoverflow.com?", and the responses are correspondingly small. Computers make a lot of these queries, so they should be made efficiently, but if they get lost en route, it's easy to time out and re-send them.
Try Following code
if line.startswith("Path="): return line[5:]
Webkit is the html/css rendering engine used in Apple's Safari browser, and in Google's Chrome. css values prefixes with -webkit- are webkit-specific, they're usually CSS3 or other non-standardised features.
to answer update 2 w3c is the body that tries to standardize these things, they write the rules, then programmers write their rendering engine to interpret those rules. So basically w3c says DIVs should work "This way" the engine-writer then uses that rule to write their code, any bugs or mis-interpretations of the rules cause the compatibility issues.
Fn + Up/Down can scroll Terminal in Mac OS X 10.11
As others have said, @Transient
is used to mark fields which shouldn't be persisted. Consider this short example:
public enum Gender { MALE, FEMALE, UNKNOWN }
@Entity
public Person {
private Gender g;
private long id;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public long getId() { return id; }
public void setId(long id) { this.id = id; }
public Gender getGender() { return g; }
public void setGender(Gender g) { this.g = g; }
@Transient
public boolean isMale() {
return Gender.MALE.equals(g);
}
@Transient
public boolean isFemale() {
return Gender.FEMALE.equals(g);
}
}
When this class is fed to the JPA, it persists the gender
and id
but doesn't try to persist the helper boolean methods - without @Transient
the underlying system would complain that the Entity class Person
is missing setMale()
and setFemale()
methods and thus wouldn't persist Person
at all.
Despite being syntactically similar, Java and C++ have very different paradigms. Writing C++ like Java is bad C++, and writing Java like C++ is bad Java.
With a reflection based IDE like Eclipse, writing the necessarily functionality of a "pair" class is quick and simple. Create class, define two fields, use the various "Generate XX" menu options to fill out the class in a matter of seconds. Maybe you'd have to type a "compareTo" real quick if you wanted the Comparable interface.
With separate declaration / definition options in the language C++ code generators aren't so good, so hand writing little utility classes is more time consuming tedium. Because the pair is a template, you don't have to pay for functions you don't use, and the typedef facility allows assigning meaningful typenames to the code, so the objections about "no semantics" don't really hold up.
Hai sridhar, I found an answer for your prob
ClientScript.RegisterClientScriptBlock(GetType(), "sas", "<script> alert('Inserted successfully');</script>", true);
change false to true
or try this
ScriptManager.RegisterClientScriptBlock(ursavebuttonID, typeof(LinkButton or button), "sas", "<script> alert('Inserted successfully');</script>", true);
So here's my solution.
A simple example for a 3x3 Array. You can keep chaining this to go deeper
Array(3).fill().map(a => Array(3))
Or the following function will generate any level deep you like
f = arr => {
let str = 'return ', l = arr.length;
arr.forEach((v, i) => {
str += i < l-1 ? `Array(${v}).fill().map(a => ` : `Array(${v}` + ')'.repeat(l);
});
return Function(str)();
}
f([4,5,6]) // Generates a 4x5x6 Array
http://www.binaryoverdose.com/2017/02/07/Generating-Multidimensional-Arrays-in-JavaScript/
It's possible to change the path fill color of the svg. See below for the CSS snippet:
To apply the color for all the path: svg > path{ fill: red }
To apply for the first d path: svg > path:nth-of-type(1){ fill: green }
To apply for the second d path: svg > path:nth-of-type(2){ fill: green}
To apply for the different d path, change only the path number:
svg > path:nth-of-type(${path_number}){ fill: green}
To support the CSS in Angular 2 to 8, use the encapsulation concept:
:host::ng-deep svg path:nth-of-type(1){
fill:red;
}
Example
<div ng-controller="ExampleController">
<form name="myform">
Name: <input type="text" ng-model="user.name" /><br>
Email: <input type="email" ng-model="user.email" /><br>
</form>
</div>
<script>
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
//if form is not valid then return the form.
if(!$scope.myform.$valid) {
return;
}
}]);
</script>
Well, first of all that code doesn't compile.
After removing the extra semicolon after i++, it compiles and runs fine for me.
This is quite a misleading status. It should be called "reading and filtering data".
This means that MySQL
has some data stored on the disk (or in memory) which is yet to be read and sent over. It may be the table itself, an index, a temporary table, a sorted output etc.
If you have a 1M records table (without an index) of which you need only one record, MySQL
will still output the status as "sending data" while scanning the table, despite the fact it has not sent anything yet.
Try this.
Use this code in your appdelegate class didFinishLaunchingWithOptions
function:
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
[application setStatusBarHidden:NO];
UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
statusBar.backgroundColor = [UIColor blackColor];
}
srand(time(NULL));
int nRandonNumber = rand()%((nMax+1)-nMin) + nMin;
printf("%d\n",nRandonNumber);
Using plain javascript
<html>
<head>
<!-- define on/off styles -->
<style type="text/css">
.on { background:blue; }
.off { background:red; }
</style>
<!-- define the toggle function -->
<script language="javascript">
function toggleState(item){
if(item.className == "on") {
item.className="off";
} else {
item.className="on";
}
}
</script>
</head>
<body>
<!-- call 'toggleState' whenever clicked -->
<input type="button" id="btn" value="button"
class="off" onclick="toggleState(this)" />
</body>
</html>
Using jQuery
If you use jQuery, you can do it using the toggle function, or using the toggleClass function inside click event handler, like this:
$(document).ready(function(){
$('a#myButton').click(function(){
$(this).toggleClass("btnClicked");
});
});
Using jQuery UI effects, you can animate transitions: http://jqueryui.com/demos/toggleClass/
From the developer docs, to change the color and size of a spannable:
1- create a class:
class RelativeSizeColorSpan(size: Float,@ColorInt private val color: Int): RelativeSizeSpan(size) {
override fun updateDrawState(textPaint: TextPaint?) {
super.updateDrawState(textPaint)
textPaint?.color = color
}
}
2 Create your spannable using that class:
val spannable = SpannableStringBuilder(titleNames)
spannable.setSpan(
RelativeSizeColorSpan(1.5f, Color.CYAN), // Increase size by 50%
titleNames.length - microbe.name.length, // start
titleNames.length, // end
Spannable.SPAN_EXCLUSIVE_INCLUSIVE
)
There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).
Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.
Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.
Old question, but since the question asks "using jQuery", I thought I'd provide an option that lets you do this without introducing any vendor dependency.
While there are a lot of templating engines out there, many of their features have fallen in to disfavour recently, with iteration (<% for
), conditionals (<% if
) and transforms (<%= myString | uppercase %>
) seen as microlanguage at best, and anti-patterns at worst. Modern templating practices encourage simply mapping an object to its DOM (or other) representation, e.g. what we see with properties mapped to components in ReactJS (especially stateless components).
One property you can rely on for keeping the HTML for your template next to the rest of your HTML, is by using a non-executing <script>
type
, e.g. <script type="text/template">
. For your case:
<script type="text/template" data-template="listitem">
<a href="${url}" class="list-group-item">
<table>
<tr>
<td><img src="${img}"></td>
<td><p class="list-group-item-text">${title}</p></td>
</tr>
</table>
</a>
</script>
On document load, read your template and tokenize it using a simple String#split
var itemTpl = $('script[data-template="listitem"]').text().split(/\$\{(.+?)\}/g);
Notice that with our token, you get it in the alternating [text, property, text, property]
format. This lets us nicely map it using an Array#map
, with a mapping function:
function render(props) {
return function(tok, i) { return (i % 2) ? props[tok] : tok; };
}
Where props
could look like { url: 'http://foo.com', img: '/images/bar.png', title: 'Lorem Ipsum' }
.
Putting it all together assuming you've parsed and loaded your itemTpl
as above, and you have an items
array in-scope:
$('.search').keyup(function () {
$('.list-items').append(items.map(function (item) {
return itemTpl.map(render(item)).join('');
}));
});
This approach is also only just barely jQuery - you should be able to take the same approach using vanilla javascript with document.querySelector
and .innerHTML
.
A question to ask yourself is: do you really want/need to define templates as HTML files? You can always componentize + re-use a template the same way you'd re-use most things you want to repeat: with a function.
In es7-land, using destructuring, template strings, and arrow-functions, you can write downright pretty looking component functions that can be easily loaded using the $.fn.html
method above.
const Item = ({ url, img, title }) => `
<a href="${url}" class="list-group-item">
<div class="image">
<img src="${img}" />
</div>
<p class="list-group-item-text">${title}</p>
</a>
`;
Then you could easily render it, even mapped from an array, like so:
$('.list-items').html([
{ url: '/foo', img: 'foo.png', title: 'Foo item' },
{ url: '/bar', img: 'bar.png', title: 'Bar item' },
].map(Item).join(''));
Oh and final note: don't forget to sanitize your properties passed to a template, if they're read from a DB, or someone could pass in HTML (and then run scripts, etc.) from your page.
Try adding the following to your eclipse.ini file:
-vm
C:\Program Files\Java\jdk1.7.0_01\bin\java.exe
You might also have to change the Dosgi.requiredJavaVersion to 1.7 in the same file.
x if y else z
is the syntax for the expression you're returning for each element. Thus you need:
[ x if x%2 else x*100 for x in range(1, 10) ]
The confusion arises from the fact you're using a filter in the first example, but not in the second. In the second example you're only mapping each value to another, using a ternary-operator expression.
With a filter, you need:
[ EXP for x in seq if COND ]
Without a filter you need:
[ EXP for x in seq ]
and in your second example, the expression is a "complex" one, which happens to involve an if-else
.
Use square bracket around variable name.
var objname = 'myobject';
{[objname]}.value = 'value';
I've added the <%%
literal tag delimiter as an answer to this because of its obscurity. This will tell erb not to interpret the <%
part of the tag which is necessary for js apps like displaying chart.js tooltips etc.
Update (Fixed broken link)
Everything about ERB can now be found here: https://puppet.com/docs/puppet/5.3/lang_template_erb.html#tags
There's a C implementation here:
http://www.cs.rit.edu/~ncs/color/t_convert.html
Should be very straightforward to convert to C#, as almost no functions are called - just calculations.
found via Google
For Swift 3 and Xcode 8:
var dataTask: URLSessionDataTask?
if let url = URL(string: urlString) {
self.dataTask = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if let error = error {
print(error.localizedDescription)
} else if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
// You can use data received.
self.process(data: data as Data?)
}
})
}
}
//Note: You can always use debugger to check error
In XAMPP Version 1.7.4 server does not have extension=php_openssl.dll line in php ini file. We have to add extension=php_openssl.dll in php.ini file
also works if you do a "display: block;" on the td, destroying the td identity, but works!
There are multiple number groups and some particular numbers that will never be allocated:
Consider using one of these (the obviously invalid 000-00-0000 would be a good one IMO).
(Answer has been updated to provide source information beyond Wikipedia and remove information that is no longer accurate after the SSA made its randomization change in mid 2011.)
Like this:
#include <vector>
// ...
std::vector<std::vector<int>> A(dimension, std::vector<int>(dimension));
(Pre-C++11 you need to leave whitespace between the angled brackets.)
if you are using html agility pack use getattributeValue:
$doc2.DocumentNode.SelectNodes("//div[@class='className']/div[@class='InternalClass']/a[@class='InternalClass']").GetAttributeValue("href","")
if anyone else need the solution
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed(); return true;
}
return super.onOptionsItemSelected(item);
}
This parameter is is working for me:
--enable-easy-off-store-extension-install
Do the following:
--enable-easy-off-store-extension-install
chrome.exe --enable-easy-off-store-extension-install
Parse the dates and compare them as you would numbers:
function isLater(str1, str2)
{
return new Date(str1) > new Date(str2);
}
If you need to support other date format consider a library such as date.js.
Just import AVFoundation and use AVMakeRectWithAspectRatioInsideRect(CGRectCurrentSize, CGRectMake(0, 0, YOUR_WIDTH, CGFLOAT_MAX)