You might want to see this page:
http://blog.niklasottosson.com/?p=1914
I guess you can go something like this:
DEMO:http://jsfiddle.net/g9eL6768/2/
HTML:
<table id="mytable"><thead>
<tr>
<th id="sl">S.L.</th>
<th id="nm">name</th>
</tr>
....
JS:
// sortTable(f,n)
// f : 1 ascending order, -1 descending order
// n : n-th child(<td>) of <tr>
function sortTable(f,n){
var rows = $('#mytable tbody tr').get();
rows.sort(function(a, b) {
var A = getVal(a);
var B = getVal(b);
if(A < B) {
return -1*f;
}
if(A > B) {
return 1*f;
}
return 0;
});
function getVal(elm){
var v = $(elm).children('td').eq(n).text().toUpperCase();
if($.isNumeric(v)){
v = parseInt(v,10);
}
return v;
}
$.each(rows, function(index, row) {
$('#mytable').children('tbody').append(row);
});
}
var f_sl = 1; // flag to toggle the sorting order
var f_nm = 1; // flag to toggle the sorting order
$("#sl").click(function(){
f_sl *= -1; // toggle the sorting order
var n = $(this).prevAll().length;
sortTable(f_sl,n);
});
$("#nm").click(function(){
f_nm *= -1; // toggle the sorting order
var n = $(this).prevAll().length;
sortTable(f_nm,n);
});
Hope this helps.
No you don’t need quotes.
Yes you can. But note that relative URLs are resolved from the URL of your stylesheet.
Better don’t use quotes. I think there are clients that don’t understand them.
I already had index.html in the WebContent folder but it was not showing up , finally i added the following piece of code in my projects web.xml and it started showing up
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
INSERT INTO TARGET_TABLE SELECT * FROM SOURCE_TABLE;
EDIT: or if the tables have different structures you can also:
INSERT INTO TARGET_TABLE (`col1`,`col2`) SELECT `col1`,`col2` FROM SOURCE_TABLE;
EDIT: to constrain this..
INSERT INTO TARGET_TABLE (`col1_`,`col2_`) SELECT `col1`,`col2` FROM SOURCE_TABLE WHERE `foo`=1
I believe that the body height being returned is the visible height. If you need the total page height, you could wrap your div tags in a containing div and get the height of that.
In my case, with Windows Server 2008, I had to change the PATH
variable.
The former version of PHP (VC9) was inside it.
I have changed it with the newer version of PHP (VC11).
After a restart of Apache, it was okay.
A duplicate in the database should be a 409 CONFLICT
.
I recommend using 422 UNPROCESSABLE ENTITY
for validation errors.
I give a longer explanation of 4xx codes here: http://parker0phil.com/2014/10/16/REST_http_4xx_status_codes_syntax_and_sematics/
If you are using parallelMap
you'll need to export custom functions to the slave jobs, otherwise you get an error "could not find function ".
If you set a non-missing level on parallelStart
the same argument should be passed to parallelExport
, else you get the same error. So this should be strictly followed:
parallelStart(mode = "<your mode here>", N, level = "<task.level>")
parallelExport("<myfun>", level = "<task.level>")
Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.
git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67
Then, abort the rebase again.
You can paste these methods in the ViewController of each view that needs to be portrait:
override func shouldAutorotate() -> Bool {
return false
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.Portrait
}
// UITableViewCell set Identify "Cell"
// UITableView Name is tableReport
UIViewController,UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var tableReport: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableReport.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "Report Name"
return cell;
}
}
Yes - you would probably be arrested for your terriable abuse of strcat !
Take a look at getline() it reads the data a line at a time but importantly it can limit the number of characters you read, so you don't overflow the buffer.
Strcat is relatively slow because it has to search the entire string for the end on every character insertion. You would normally keep a pointer to the current end of the string storage and pass that to getline as the position to read the next line into.
I had the same issue. I found this.
ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’
This is because you are not running the mysqld
daemon before launching the MySQL client. The file /var/lib/mysql/mysql.sock
will be automatically created upon running the first instance of MySQL.
To fix:
First start the MySQL daemon, then type mysql
:
/etc/init.d/mysqld start
mysql
By default, the root password is empty for the MySQL database. It is a good idea to change the MySQL root password to a new one from a security point of view.
mysql> USE mysql;
mysql> UPDATE user SET Password=PASSWORD('newpassword') WHERE user='root';
mysql> FLUSH PRIVILEGES;
Once done, check by logging in:
mysql -u root -p
Enter Password: <your new password>
IF (EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'd020915'))
BEGIN
declare @result int
set @result=1
select @result as result
END
Set positioning to absolute. That will solve the problem immediately, but might cause some problems in layout later. You can always figure out a way around them ;)
Example:
position:absolute;
When you use routerLink like this, then you need to pass the value of the route it should go to. But when you use routerLink with the property binding syntax, like this: [routerLink]
, then it should be assigned a name of the property the value of which will be the route it should navigate the user to.
So to fix your issue, replace this routerLink="['/about']"
with routerLink="/about"
in your HTML.
There were other places where you used property binding syntax when it wasn't really required. I've fixed it and you can simply use the template syntax below:
<nav class="main-nav>
<ul
class="main-nav__list"
ng-sticky
addClass="main-sticky-link"
[ngClass]="ref.click ? 'Navbar__ToggleShow' : ''">
<li class="main-nav__item" routerLinkActive="active">
<a class="main-nav__link" routerLink="/">Home</a>
</li>
<li class="main-nav__item" routerLinkActive="active">
<a class="main-nav__link" routerLink="/about">About us</a>
</li>
</ul>
</nav>
It also needs to know where exactly should it load the template for the Component corresponding to the route it has reached. So for that, don't forget to add a <router-outlet></router-outlet>
, either in your template provided above or in a parent component.
There's another issue with your AppRoutingModule
. You need to export the RouterModule
from there so that it is available to your AppModule
when it imports it. To fix that, export it from your AppRoutingModule
by adding it to the exports
array.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { MainLayoutComponent } from './layout/main-layout/main-layout.component';
import { AboutComponent } from './components/about/about.component';
import { WhatwedoComponent } from './components/whatwedo/whatwedo.component';
import { FooterComponent } from './components/footer/footer.component';
import { ProjectsComponent } from './components/projects/projects.component';
const routes: Routes = [
{ path: 'about', component: AboutComponent },
{ path: 'what', component: WhatwedoComponent },
{ path: 'contacts', component: FooterComponent },
{ path: 'projects', component: ProjectsComponent},
];
@NgModule({
imports: [
CommonModule,
RouterModule.forRoot(routes),
],
exports: [RouterModule],
declarations: []
})
export class AppRoutingModule { }
for i in $(seq 1 254); do ping -c1 192.168.11.$i; done
Sometimes you will still get errors if you use this way (https://stackoverflow.com/a/12859093/801426).
Try this:
if(! $rootScope.$root.$$phase) {
...
This worked for me, combo of two answers from above:
You could try this:
{% if not profile.user.first_name.value %}
<p> -- </p>
{% else %}
{{ profile.user.first_name }} {{ profile.user.last_name }}
{% endif %}
This way, you're essentially checking to see if the form field first_name
has any value associated with it. See {{ field.value }}
in Looping over the form's fields in Django Documentation.
I'm using Django 3.0.
<form action="Delegate_update.php" method="post">
Name
<input type="text" name= "Name" value= "<?php echo $row['Name']; ?> "size=10>
Username
<input type="text" name= "Username" value= "<?php echo $row['Username']; ?> "size=10>
Password
<input type="text" name= "Password" value= "<?php echo $row['Password']; ?>" size=17>
<input type="submit" name= "submit" value="Update">
</form>
You didnt closed your opening Form in the first place, plus your code is very very messy. I wont go into the "use pdo or mysqli statements, instead of mysql" thats for you to find out on yourself. Also you have a php tag open and close below it, not sure what is needed there. Something else is that your code refers to an external page, which you didnt post, so if something isnt working there, might be handy to post it too.
Please also note that you had spaces between your $row array variables in the form. You have to link those up together by removing the space (see edited section from me). PHP isn't forgiving when it comes to those mistakes.
Then your HTML. I took the liberty to correct that too
<html>
<head>
<title> Delegate edit form</title>
</head>
<body>
<p>Delegate update form</p>
<?php
$usernm="root";
$passwd="";
$host="localhost";
$database="swift";
mysql_connect($host,$usernm,$passwd);
mysql_select_db($database);
$sql = "SELECT * FROM usermaster WHERE User_name='".$Username."'"; // Please look at this too.
$result = mysql_query($sql) or die (mysql_error()); // dont put spaces in between it, else your code wont recognize it the query that needs to be executed
while ($row = mysql_fetch_array($result)){ // here too, you put a space between it
$Name=$row['Name'];
$Username=$row['User_name'];
$Password=$row['User_password'];
}
?>
Also, try to be specific. "It doesnt work" doesnt help us much, a specific error type is commonly helpful, plus any indication what the code should do (well, it was kinda obvious here, since its a login/register edit here, but for larger chunks of code it should always be explained)
Anyway, welcome to Stack Overflow
My issue was resolved After adding
sessionFactory.setPackagesToScan(
new String[] { "com.springhibernate.model" });
Tested this Functionality in spring boot latest version 2.1.2.
Full Method:
@Bean( name="sessionFactoryConfig")
public LocalSessionFactoryBean sessionFactoryConfig() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSourceConfig());
sessionFactory.setPackagesToScan(
new String[] { "com.springhibernate.model" });
sessionFactory.setHibernateProperties(hibernatePropertiesConfig());
return sessionFactory;
}
WebViewClient provides the following callback methods, with which you can interfere in how WebView
makes a transition to the next content.
void doUpdateVisitedHistory (WebView view, String url, boolean isReload)
void onFormResubmission (WebView view, Message dontResend, Message resend)
void onLoadResource (WebView view, String url)
void onPageCommitVisible (WebView view, String url)
void onPageFinished (WebView view, String url)
void onPageStarted (WebView view, String url, Bitmap favicon)
void onReceivedClientCertRequest (WebView view, ClientCertRequest request)
void onReceivedError (WebView view, int errorCode, String description, String failingUrl)
void onReceivedError (WebView view, WebResourceRequest request, WebResourceError error)
void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host, String realm)
void onReceivedHttpError (WebView view, WebResourceRequest request, WebResourceResponse errorResponse)
void onReceivedLoginRequest (WebView view, String realm, String account, String args)
void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error)
boolean onRenderProcessGone (WebView view, RenderProcessGoneDetail detail)
void onSafeBrowsingHit (WebView view, WebResourceRequest request, int threatType, SafeBrowsingResponse callback)
void onScaleChanged (WebView view, float oldScale, float newScale)
void onTooManyRedirects (WebView view, Message cancelMsg, Message continueMsg)
void onUnhandledKeyEvent (WebView view, KeyEvent event)
WebResourceResponse shouldInterceptRequest (WebView view, WebResourceRequest request)
WebResourceResponse shouldInterceptRequest (WebView view, String url)
boolean shouldOverrideKeyEvent (WebView view, KeyEvent event)
boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request)
boolean shouldOverrideUrlLoading (WebView view, String url)
WebChromeClient provides the following callback methods, with which your Activity
or Fragment
can update the surroundings of WebView
.
Bitmap getDefaultVideoPoster ()
View getVideoLoadingProgressView ()
void getVisitedHistory (ValueCallback<String[]> callback)
void onCloseWindow (WebView window)
boolean onConsoleMessage (ConsoleMessage consoleMessage)
void onConsoleMessage (String message, int lineNumber, String sourceID)
boolean onCreateWindow (WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg)
void onExceededDatabaseQuota (String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, WebStorage.QuotaUpdater quotaUpdater)
void onGeolocationPermissionsHidePrompt ()
void onGeolocationPermissionsShowPrompt (String origin, GeolocationPermissions.Callback callback)
void onHideCustomView ()
boolean onJsAlert (WebView view, String url, String message, JsResult result)
boolean onJsBeforeUnload (WebView view, String url, String message, JsResult result)
boolean onJsConfirm (WebView view, String url, String message, JsResult result)
boolean onJsPrompt (WebView view, String url, String message, String defaultValue, JsPromptResult result)
boolean onJsTimeout ()
void onPermissionRequest (PermissionRequest request)
void onPermissionRequestCanceled (PermissionRequest request)
void onProgressChanged (WebView view, int newProgress)
void onReachedMaxAppCacheSize (long requiredStorage, long quota, WebStorage.QuotaUpdater quotaUpdater)
void onReceivedIcon (WebView view, Bitmap icon)
void onReceivedTitle (WebView view, String title)
void onReceivedTouchIconUrl (WebView view, String url, boolean precomposed)
void onRequestFocus (WebView view)
void onShowCustomView (View view, int requestedOrientation, WebChromeClient.CustomViewCallback callback)
void onShowCustomView (View view, WebChromeClient.CustomViewCallback callback)
boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
Also in the many IDEs now, ex: VSC, you can install an extension for AWS and simply click upload from there, no effort of typing all those commands + region.
Here's an example:
To populate the drop-down select box in laravel we have to follow the below steps.
From controller we have to get the value like this:
public function addCustomerLoyaltyCardDetails(){
$loyalityCardMaster = DB::table('loyality_cards')->pluck('loyality_card_id', 'loyalityCardNumber');
return view('admin.AddCustomerLoyaltyCardScreen')->with('loyalityCardMaster',$loyalityCardMaster);
}
And the same we can display in view:
<select class="form-control" id="loyalityCardNumber" name="loyalityCardNumber" >
@foreach ($loyalityCardMaster as $id => $name)
<option value="{{$name}}">{{$id}}</option>
@endforeach
</select>
This key value in drop down you can use as per your requirement. Hope it may help someone.
Steps:
See Step by Step guide on Java remote debugging for full details.
It may be that your condas channels need a wakeup call... with
conda update --all
For me it worked. More information: https://www.anaconda.com/keeping-anaconda-date/
On Windows 10, just uninstall git and install it again. It will set the environment variable automatically for you. I had removed the environment variable by mistake and I couldn't use git inside my IDE. Reinstalling git fixed this issue.
As it was mentioned above CasperJS is the best tool to fill and send forms. Simplest possible example of how to fill & submit form using fill() function:
casper.start("http://example.com/login", function() {
//searches and fills the form with id="loginForm"
this.fill('form#loginForm', {
'login': 'admin',
'password': '12345678'
}, true);
this.evaluate(function(){
//trigger click event on submit button
document.querySelector('input[type="submit"]').click();
});
});
You can use the -f operator
$a = "{0:D}" -f (get-date)
$a = "{0:dddd}" -f (get-date)
Spécificator Type Example (with [datetime]::now)
d Short date 26/09/2002
D Long date jeudi 26 septembre 2002
t Short Hour 16:49
T Long Hour 16:49:31
f Date and hour jeudi 26 septembre 2002 16:50
F Long Date and hour jeudi 26 septembre 2002 16:50:51
g Default Date 26/09/2002 16:52
G Long default Date and hour 26/09/2009 16:52:12
M Month Symbol 26 septembre
r Date string RFC1123 Sat, 26 Sep 2009 16:54:50 GMT
s Sortable string date 2009-09-26T16:55:58
u Sortable string date universal local hour 2009-09-26 16:56:49Z
U Sortable string date universal GMT hour samedi 26 septembre 2009 14:57:22 (oups)
Y Year symbol septembre 2002
Spécificator Type Example Output Example
dd Jour {0:dd} 10
ddd Name of the day {0:ddd} Jeu.
dddd Complet name of the day {0:dddd} Jeudi
f, ff, … Fractions of seconds {0:fff} 932
gg, … position {0:gg} ap. J.-C.
hh Hour two digits {0:hh} 10
HH Hour two digits (24 hours) {0:HH} 22
mm Minuts 00-59 {0:mm} 38
MM Month 01-12 {0:MM} 12
MMM Month shortcut {0:MMM} Sep.
MMMM complet name of the month {0:MMMM} Septembre
ss Seconds 00-59 {0:ss} 46
tt AM or PM {0:tt} ““
yy Years, 2 digits {0:yy} 02
yyyy Years {0:yyyy} 2002
zz Time zone, 2 digits {0:zz} +02
zzz Complete Time zone {0:zzz} +02:00
: Separator {0:hh:mm:ss} 10:43:20
/ Separator {0:dd/MM/yyyy} 10/12/2002
Here is how it works:
1. Get XML element string with FOR XML
Adding FOR XML PATH to the end of a query allows you to output the results of the query as XML elements, with the element name contained in the PATH argument. For example, if we were to run the following statement:
SELECT ',' + name
FROM temp1
FOR XML PATH ('')
By passing in a blank string (FOR XML PATH('')), we get the following instead:
,aaa,bbb,ccc,ddd,eee
2. Remove leading comma with STUFF
The STUFF statement literally "stuffs” one string into another, replacing characters within the first string. We, however, are using it simply to remove the first character of the resultant list of values.
SELECT abc = STUFF((
SELECT ',' + NAME
FROM temp1
FOR XML PATH('')
), 1, 1, '')
FROM temp1
The parameters of STUFF
are:
So we end up with:
aaa,bbb,ccc,ddd,eee
3. Join on id to get full list
Next we just join this on the list of id in the temp table, to get a list of IDs with name:
SELECT ID, abc = STUFF(
(SELECT ',' + name
FROM temp1 t1
WHERE t1.id = t2.id
FOR XML PATH (''))
, 1, 1, '') from temp1 t2
group by id;
And we have our result:
Id | Name |
---|---|
1 | aaa,bbb,ccc,ddd,eee |
Hope this helps!
Update: Unless you love resizing icons one by one, check out Schmoudi's answer. It's just a lot easier.
Above image from Designing for iOS 9. They are the same for iOS 10.
Click Assets.xcassets in the Project navigator and then choose AppIcon.
This will give you an empty app icon set.
Now just drag the right sized image (in .png format) from Finder onto every blank in the app set. The app icon should be all set up now.
The image at the very top tells the pixels sizes for for each point size that is required in iOS 9. However, even if I don't get this answer updated for future versions of iOS, you can still figure out the correct pixel sizes using the method below.
Look at how many points (pt) each blank on the empty image set is. If the image is 1x then the pixels are the same as the points. For 2x double the points and 3x triple the points. So, for example, in the first blank above (29pt 2x) you would need a 58x58 pixel image.
You can start with a 1024x1024 pixel image and then downsize it to the correct sizes. You can do it yourself or there are also websites and scripts for getting the right sizes. Do a search for "ios app icon generator" or something similar.
I don't think the names matter as long as you get the dimensions right, but the general naming convention is as follows:
Icon-29.png // 29x29 pixels
[email protected] // 58x58 pixels
[email protected] // 87x87 pixels
Although you can use an image for the launch screen, consider using a launch screen storyboard file. This will conveniently resize for every size and orientation. Check out this SO answer or the following documentation for help with this.
The Xcode images in this post were created with Xcode 7.
string s = "hello";
char c = s[1];
// now c == 'e'
See also Substring
, to return more than one character.
You can use fileWriter
with a flag set to true
, for appending.
try
{
String filename= "MyFile.txt";
FileWriter fw = new FileWriter(filename,true); //the true will append the new data
fw.write("add a line\n");//appends the string to the file
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
To collect in a mutable list:
targetList = sourceList.stream()
.filter(i -> i > 100) //apply filter
.collect(Collectors.toList());
To collect in a immutable list:
targetList = sourceList.stream()
.filter(i -> i > 100) //apply filter
.collect(Collectors.toUnmodifiableList());
Explanation of collect
from the JavaDoc:
Performs a mutable reduction operation on the elements of this stream using a Collector. A Collector encapsulates the functions used as arguments to collect(Supplier, BiConsumer, BiConsumer), allowing for reuse of collection strategies and composition of collect operations such as multiple-level grouping or partitioning. If the stream is parallel, and the Collector is concurrent, and either the stream is unordered or the collector is unordered, then a concurrent reduction will be performed (see Collector for details on concurrent reduction.)
This is a terminal operation.
When executed in parallel, multiple intermediate results may be instantiated, populated, and merged so as to maintain isolation of mutable data structures. Therefore, even when executed in parallel with non-thread-safe data structures (such as ArrayList), no additional synchronization is needed for a parallel reduction.
Following are the ways
From the code (the way you have mentioned) ->
displayBox.Text += sent + "\r\n";
or
displayBox.Text += sent + Environment.NewLine;
From the UI
a) WPF
Set TextWrapping="Wrap" and AcceptsReturn="True"
Press Enter key to the textbox and new line will be created
b) Winform text box
Set TextBox.MultiLine and TextBox.AcceptsReturn to true
try this
In your controller use
> $scope.onMapOverlayCompleted = onMapOverlayCompleted;
>
> function onMapOverlayCompleted(e) {
>
> e.overlay.getPath().getArray().forEach(function (position) {
> console.log('lat', position.lat());
> console.log('lng', position.lng());
> });
>
> }
**In Your html page , include drawning manaer**
<ng-map id="geofence-map" zoom="8" center="current" default-style="true" class="map-layout map-area"
tilt="45"
heading="90">
<drawing-manager
on-overlaycomplete="onMapOverlayCompleted()"
drawing-control-options="{position: 'TOP_CENTER',drawingModes:['polygon','circle']}"
drawingControl="true"
drawingMode="null"
markerOptions="{icon:'www.example.com/icon'}"
rectangleOptions="{fillColor:'#B43115'}"
circleOptions="{fillColor: '#F05635',fillOpacity: 0.50,strokeWeight: 5,clickable: false,zIndex: 1,editable: true}">
</drawing-manager>
</ng-map>
:hover
is a pseudoclass, so you can put your CSS declarations there:
a:hover {
color: #f00;
}
You can also use a list of selectors to apply CSS declarations to a hovered element or an element with a certain class:
.some-class,
a:hover {
color: #f00;
}
sudo apt-get install python-dev # for python2.x installs
sudo apt-get install python3-dev # for python3.x installs
It will install any missing headers. It solved my issue
I started by using the answers here, but modified it to use YouTube's new iframe
embedding...
$('a.more').on('click', function(event) {
event.preventDefault();
$.fancybox({
'type' : 'iframe',
// hide the related video suggestions and autoplay the video
'href' : this.href.replace(new RegExp('watch\\?v=', 'i'), 'embed/') + '?rel=0&autoplay=1',
'overlayShow' : true,
'centerOnScroll' : true,
'speedIn' : 100,
'speedOut' : 50,
'width' : 640,
'height' : 480
});
});
Here is how you can do it:
BOOL flag = NO;
NSLog(flag ? @"YES" : @"NO");
ALTER TABLE [TableName] ADD CONSTRAINT [constraintName] UNIQUE ([columns])
Two ways to do it...
GROUP BY
SELECT RES.[CUSTOMER ID], RES,NAME, SUM(INV.AMOUNT) AS [TOTAL AMOUNT]
FROM RES_DATA RES
JOIN INV_DATA INV ON RES.[CUSTOMER ID] INV.[CUSTOMER ID]
GROUP BY RES.[CUSTOMER ID], RES,NAME
OVER
SELECT RES.[CUSTOMER ID], RES,NAME,
SUM(INV.AMOUNT) OVER (PARTITION RES.[CUSTOMER ID]) AS [TOTAL AMOUNT]
FROM RES_DATA RES
JOIN INV_DATA INV ON RES.[CUSTOMER ID] INV.[CUSTOMER ID]
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null
, neither of which would seem to be what you want. If status
is null, Elvis says true
. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find
calls, just use an intermediate variable.
This is a way to create tables dynamically using T-SQL stored procedures:
declare @cmd nvarchar(1000), @MyTableName nvarchar(100);
set @MyTableName = 'CustomerDetails';
set @cmd = 'CREATE TABLE dbo.' + quotename(@MyTableName, '[') + '(ColumnName1 int not null,ColumnName2 int not null);';
Execute it as:
exec(@cmd);
Adding my 2 cents on this topic after loosing 4h.
I'm coding a vue app that's compiled with webpack. By default Webpack minifies the HTML, and does it like a butcher. It removes the double quotes from many attributes.
And Whatsapp hates that ! It just skips field not properly formated with quotes around attributes' values.
Turn off the minifaction of your index and things will be fine !
Here's how with Vue-CLI, add this on the vue.config.js file :
module.exports = {
chainWebpack: config => {
config.plugin('html')
.tap(args => {
args[0].minify = false
return args
})
}
from : https://github.com/vuejs/vue-cli/issues/4328#issuecomment-595682922
Yet another massive win for Python's import system. I think the reason there is no consensus is that what works probably depends on your environment and the tools you are using on top of it.
I'm using this from VS Code, in the test explorer under Windows in a conda environment, Python 3.8.
The setup I have got to work is:
mypkg/
__init__.py
app.py
view.py
tests/
test_app.py
test_view.py
Under this setup intellisense works and so does test discovery.
Note that I originally tried the following, as recommended here.
src/
mypkg/
__init__.py
app.py
view.py
tests/
test_app.py
test_view.py
I could find no way of getting this to work from VS Code because the src
folder just blew the mind of the import system. I can imagine there is a way of getting this to work from the command line. As a relatively new convert to Python programming it gives me a nostalgic feeling of working with COM, but being slightly less fun.
If you have an unsorted vector, then you can simply swap with the last vector element then resize()
.
With an ordered container, you'll be best off with ?std::vector::erase()
. Note that there is a std::remove()
defined in <algorithm>
, but that doesn't actually do the erasing. (Read the documentation carefully).
let MAX : UInt32 = 9
let MIN : UInt32 = 1
func randomNumber()
{
var random_number = Int(arc4random_uniform(MAX) + MIN)
print ("random = ", random_number);
}
MS Expression Encoder can do mp4/h.264. not sure about ogg though.
You haven't at time of writing described what you are going to do with the response or what its content type is. An answer already contains a very basic usage of MSXML2.XMLHTTP
(I recommend the more explicit MSXML2.XMLHTTP.3.0
progID) however you may need to do different things with the response, it may not be text.
The XMLHTTP also has a responseBody
property which is a byte array version of the reponse and there is a responseStream
which is an IStream
wrapper for the response.
Note that in a server-side requirement (e.g., VBScript hosted in ASP) you would use MSXML.ServerXMLHTTP.3.0
or WinHttp.WinHttpRequest.5.1
(which has a near identical interface).
Here is an example of using XmlHttp to fetch a PDF file and store it:-
Dim oXMLHTTP
Dim oStream
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.3.0")
oXMLHTTP.Open "GET", "http://someserver/folder/file.pdf", False
oXMLHTTP.Send
If oXMLHTTP.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write oXMLHTTP.responseBody
oStream.SaveToFile "c:\somefolder\file.pdf"
oStream.Close
End If
This is what you're looking for:
List<String> dan = Arrays.asList("Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue");
boolean contains = dan.contains(say.getText());
If you have a list of not repeated values, prefer using a Set<String>
which has the same contains method
The 3rd option is to create a "Policy" table, then a "SectionsMain" table that stores all of the fields that are in common across the types of sections. Then create other tables for each type of section that only contain the fields that are not in common.
Deciding which is best depends mostly on how many fields you have and how you want to write your SQL. They would all work. If you have just a few fields then I would probably go with #1. With "lots" of fields I would lean towards #2 or #3.
As already stated, you have too many methods (more than 65k) in your project and libs.
Since often the Google Play services is one of the main suspects in "wasting" methods with its 20k+ methods. Google Play services version 6.5 or later, it is possible for you to include Google Play services in your application using a number of smaller client libraries. For example, if you only need GCM and maps you can choose to use these dependencies only:
dependencies {
compile 'com.google.android.gms:play-services-base:6.5.+'
compile 'com.google.android.gms:play-services-maps:6.5.+'
}
The full list of sub libraries and it's responsibilities can be found in the official google doc.
Update: Since Support Library v4 v24.2.0 it was split up into the following modules:
support-compat
,support-core-utils
,support-core-ui
,support-media-compat
andsupport-fragment
dependencies {
compile 'com.android.support:support-fragment:24.2.+'
}
Do note however, if you use support-fragment
, it will have dependencies to all the other modules (ie. if you use android.support.v4.app.Fragment
there is no benefit)
See here the official release notes for support-v4 lib
Since Lollipop (aka build tools 21+) it is very easy to handle. The approach is to work around the 65k methods per dex file problem to create multiple dex files for your app. Add the following to your gradle build file (this is taken from the official google doc on applications with more than 65k methods):
android {
compileSdkVersion 21
buildToolsVersion "21.1.0"
defaultConfig {
...
// Enabling multidex support.
multiDexEnabled true
}
...
}
dependencies {
compile 'com.android.support:multidex:1.0.1'
}
The second step is to either prepare your Application class or if you don't extend Application use the MultiDexApplication
in your Android Manifest:
Either add this to your Application.java
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
or use the provided application from the mutlidex lib
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.myapplication">
<application
...
android:name="android.support.multidex.MultiDexApplication">
...
</application>
</manifest>
As further tip, if you run into OutOfMemory
exceptions during the build phase you could enlarge the heap with
android {
...
dexOptions {
javaMaxHeapSize "4g"
}
}
which would set the heap to 4 gigabytes.
See this question for more detail on the dex heap memory issue.
To analyze the source of the methods the gradle plugin https://github.com/KeepSafe/dexcount-gradle-plugin can help in combination with the dependency tree provided by gradle with e.g.
.\gradlew app:dependencies
See this answer and question for more information on method count in android
I would suggest a very simple way:
import numpy as np
l = [10, 22, 8, 8, 11]
print(np.argmax(l))
print(np.argmin(l))
Hope it helps.
This happens when JDK and JRE have different versions installed on your system. Update the JDK with the matching version of JRE. Also verify that System variable path has bin value from same JDK version.
In order to answer you questions;
"?v=1" this is written only beacuse to download a fresh copy of the css and js files instead of using from the cache of the browser.
If you mention this query string parameter at the end of your stylesheet or the js file then it forces the browser to download a new file, Due to which the recent changes in the .css and .js files are made effetive in your browser.
If you dont use this versioning then you may need to clear the cache of refresh the page in order to view the recent changes in those files.
Here is an article that explains this thing How and Why to make versioning of CSS and JS files
Above Solutions will only convert dictionary into string but you can't convert back that string to dictionary. For that it is the better way.
Convert to String
NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:yourDictionary options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%@",myString);
Convert Back to Dictionary
NSError * err;
NSData *data =[myString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary * response;
if(data!=nil){
response = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
}
If the XML is well formed then you can convert it to Document. By using the XPath you can get the XML Elements.
String xml = "<stackusers><name>Yash</name><age>30</age></stackusers>";
Form XML-String Create Document and find the elements using its XML-Path.
Document doc = getDocument(xml, true);
public static Document getDocument(String xmlData, boolean isXMLData) throws Exception {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
dbFactory.setIgnoringComments(true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc;
if (isXMLData) {
InputSource ips = new org.xml.sax.InputSource(new StringReader(xmlData));
doc = dBuilder.parse(ips);
} else {
doc = dBuilder.parse( new File(xmlData) );
}
return doc;
}
Use
org.apache.xpath.XPathAPI
to get Node or NodeList.
System.out.println("XPathAPI:"+getNodeValue(doc, "/stackusers/age/text()"));
NodeList nodeList = getNodeList(doc, "/stackusers");
System.out.println("XPathAPI NodeList:"+ getXmlContentAsString(nodeList));
System.out.println("XPathAPI NodeList:"+ getXmlContentAsString(nodeList.item(0)));
public static String getNodeValue(Document doc, String xpathExpression) throws Exception {
Node node = org.apache.xpath.XPathAPI.selectSingleNode(doc, xpathExpression);
String nodeValue = node.getNodeValue();
return nodeValue;
}
public static NodeList getNodeList(Document doc, String xpathExpression) throws Exception {
NodeList result = org.apache.xpath.XPathAPI.selectNodeList(doc, xpathExpression);
return result;
}
Using
javax.xml.xpath.XPathFactory
System.out.println("javax.xml.xpath.XPathFactory:"+getXPathFactoryValue(doc, "/stackusers/age"));
static XPath xpath = javax.xml.xpath.XPathFactory.newInstance().newXPath();
public static String getXPathFactoryValue(Document doc, String xpathExpression) throws XPathExpressionException, TransformerException, IOException {
Node node = (Node) xpath.evaluate(xpathExpression, doc, XPathConstants.NODE);
String nodeStr = getXmlContentAsString(node);
return nodeStr;
}
Using Document Element.
System.out.println("DocumentElementText:"+getDocumentElementText(doc, "age"));
public static String getDocumentElementText(Document doc, String elementName) {
return doc.getElementsByTagName(elementName).item(0).getTextContent();
}
Get value in between two strings.
String nodeVlaue = org.apache.commons.lang.StringUtils.substringBetween(xml, "<age>", "</age>");
System.out.println("StringUtils.substringBetween():"+nodeVlaue);
Full Example:
public static void main(String[] args) throws Exception {
String xml = "<stackusers><name>Yash</name><age>30</age></stackusers>";
Document doc = getDocument(xml, true);
String nodeVlaue = org.apache.commons.lang.StringUtils.substringBetween(xml, "<age>", "</age>");
System.out.println("StringUtils.substringBetween():"+nodeVlaue);
System.out.println("DocumentElementText:"+getDocumentElementText(doc, "age"));
System.out.println("javax.xml.xpath.XPathFactory:"+getXPathFactoryValue(doc, "/stackusers/age"));
System.out.println("XPathAPI:"+getNodeValue(doc, "/stackusers/age/text()"));
NodeList nodeList = getNodeList(doc, "/stackusers");
System.out.println("XPathAPI NodeList:"+ getXmlContentAsString(nodeList));
System.out.println("XPathAPI NodeList:"+ getXmlContentAsString(nodeList.item(0)));
}
public static String getXmlContentAsString(Node node) throws TransformerException, IOException {
StringBuilder stringBuilder = new StringBuilder();
NodeList childNodes = node.getChildNodes();
int length = childNodes.getLength();
for (int i = 0; i < length; i++) {
stringBuilder.append( toString(childNodes.item(i), true) );
}
return stringBuilder.toString();
}
OutPut:
StringUtils.substringBetween():30
DocumentElementText:30
javax.xml.xpath.XPathFactory:30
XPathAPI:30
XPathAPI NodeList:<stackusers>
<name>Yash</name>
<age>30</age>
</stackusers>
XPathAPI NodeList:<name>Yash</name><age>30</age>
Another way would be adding __getitem__, __setitem__ function
def __getitem__(self, key):
return getattr(self, key)
You can use self[key] to access now.
On parent div you can add
overflow-y: scroll;
overflow-x: hidden;
Apparently, action
was required prior to HTML5 (and #
was just a stand in), but you no longer have to use it.
See The Action Attribute:
When specified with no attributes, as below, the data is sent to the same page that the form is present on:
<form>
One of the major advantages of MVC which has not mentioned here is that MVC provides RESTful urls which enables SEO. When you name your Controllers and Actions wisely, it makes it easier for search engines to find your site if they only take a look at your site Urls. For example you have a car sale website and a page which displays available Lamborghini Veneno cars, instead of having www.MyCarSale.com/product/6548 referring to the page you can choose www.MyCarSale.com/SportCar/Lamborghini-Veneno url for SEO purpose.
Here is a good answer to MVC Advantages and here is an article How to create a SEO friendly Url.
One-liner command to restore the generated SQL from mysqldump
mysql -u <username> -p<password> -e "source <path to sql file>;"
Below statement works. Note that you need to mention the data type again for the column name (redeclare the data type the column was before).
ALTER TABLE document
MODIFY COLUMN document_id int AUTO_INCREMENT;
Related, if you open a file that uses both tabs and spaces, assuming you've got
set expandtab ts=4 sw=4 ai
You can replace all the tabs with spaces in the entire file with
:%retab
I always use this my function to generate a custom random alphanumeric string... Hope this help.
<?php
function random_alphanumeric($length) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12345689';
$my_string = '';
for ($i = 0; $i < $length; $i++) {
$pos = mt_rand(0, strlen($chars) -1);
$my_string .= substr($chars, $pos, 1);
}
return $my_string;
}
echo random_alphanumeric(50); // 50 characters
?>
It generates for example: Y1FypdjVbFCFK6Gh9FDJpe6dciwJEfV6MQGpJqAfuijaYSZ86g
If you want compare with another string to be sure that is a unique sequence you can use this trick...
$string_1 = random_alphanumeric(50);
$string_2 = random_alphanumeric(50);
while ($string_1 == $string_2) {
$string_1 = random_alphanumeric(50);
$string_2 = random_alphanumeric(50);
if ($string_1 != $string_2) {
break;
}
}
echo $string_1;
echo "<br>\n";
echo $string_2;
it generate two unique strings:
qsBDs4JOoVRfFxyLAOGECYIsWvpcpMzAO9pypwxsqPKeAmYLOi
Ti3kE1WfGgTNxQVXtbNNbhhvvapnaUfGMVJecHkUjHbuCb85pF
Hope this is what you are looking for...
case 2:
case 5:
do something
break;
You can use the NotMapped
attribute data annotation to instruct Code-First to exclude a particular property
public class Customer
{
public int CustomerID { set; get; }
public string FirstName { set; get; }
public string LastName{ set; get; }
[NotMapped]
public int Age { set; get; }
}
[NotMapped]
attribute is included in the System.ComponentModel.DataAnnotations
namespace.
You can alternatively do this with Fluent API
overriding OnModelCreating
function in your DBContext
class:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Ignore(t => t.LastName);
base.OnModelCreating(modelBuilder);
}
http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx
The version I checked is EF 4.3
, which is the latest stable version available when you use NuGet.
Edit : SEP 2017
Data annotation
If you are using asp.net core (2.0 at the time of this writing), The [NotMapped]
attribute can be used on the property level.
public class Customer
{
public int Id { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
[NotMapped]
public int FullName { set; get; }
}
Fluent API
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
base.OnModelCreating(modelBuilder);
}
public DbSet<Customer> Customers { get; set; }
}
Assuming you use the declarative style (i.e. ORM classes), it is pretty easy:
query = db_session.query(User.id, User.name).filter(User.id.in_([123,456]))
results = query.all()
db_session
is your database session here, while User
is the ORM class with __tablename__
equal to "users"
.
My problem is that the toolbar does not cast any shadow if I don't set the "elevation" attribute. Is that the normal behavior or I'm doing something wrong?
That's the normal behavior. Also see the FAQ at the end of this post.
I had the same problem. The problem was that the labels were in a column format while it expected it in a row.
use np.ravel()
knn.score(training_set, np.ravel(training_labels))
Hope this solves it.
ResponseEntity<Resource>
from a handler methodContent-Type
explicitlyContent-Disposition
if necessary:
inline
to force preview in a browserattachment
to force a download@Controller
public class DownloadController {
@GetMapping("/downloadPdf.pdf")
// 1.
public ResponseEntity<Resource> downloadPdf() {
FileSystemResource resource = new FileSystemResource("/home/caco3/Downloads/JMC_Tutorial.pdf");
// 2.
MediaType mediaType = MediaTypeFactory
.getMediaType(resource)
.orElse(MediaType.APPLICATION_OCTET_STREAM);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(mediaType);
// 3
ContentDisposition disposition = ContentDisposition
// 3.2
.inline() // or .attachment()
// 3.1
.filename(resource.getFilename())
.build();
headers.setContentDisposition(disposition);
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
}
}
Return ResponseEntity<Resource>
When you return a ResponseEntity<Resource>
, the ResourceHttpMessageConverter
kicks in and writes an appropriate response.
The resource
could be:
Be aware of possibly wrong Content-Type
header set (see FileSystemResource is returned with content type json). That's why this answer suggests setting the Content-Type
explicitly.
Specify Content-Type
explicitly:
Some options are:
MediaTypeFactory
from Spring.The MediaTypeFactory
allows to discover the MediaType
appropriate for the Resource
(see also /org/springframework/http/mime.types
file)
Set Content-Disposition
if necessary:
Sometimes it is necessary to force a download in a browser or to make the browser open a file as a preview. You can use the Content-Disposition
header to satisfy this requirement:
The first parameter in the HTTP context is either
inline
(default value, indicating it can be displayed inside the Web page, or as the Web page) orattachment
(indicating it should be downloaded; most browsers presenting a 'Save as' dialog, prefilled with the value of the filename parameters if present).
In the Spring Framework a ContentDisposition
can be used.
To preview a file in a browser:
ContentDisposition disposition = ContentDisposition
.builder("inline") // Or .inline() if you're on Spring MVC 5.3+
.filename(resource.getFilename())
.build();
To force a download:
ContentDisposition disposition = ContentDisposition
.builder("attachment") // Or .attachment() if you're on Spring MVC 5.3+
.filename(resource.getFilename())
.build();
Use InputStreamResource
carefully:
Since an InputStream
can be read only once, Spring won't write Content-Length
header if you return an InputStreamResource
(here is a snippet of code from ResourceHttpMessageConverter
):
@Override
protected Long getContentLength(Resource resource, @Nullable MediaType contentType) throws IOException {
// Don't try to determine contentLength on InputStreamResource - cannot be read afterwards...
// Note: custom InputStreamResource subclasses could provide a pre-calculated content length!
if (InputStreamResource.class == resource.getClass()) {
return null;
}
long contentLength = resource.contentLength();
return (contentLength < 0 ? null : contentLength);
}
In other cases it works fine:
~ $ curl -I localhost:8080/downloadPdf.pdf | grep "Content-Length"
Content-Length: 7554270
I have put my working gmail java class up on pastebin for your review, pay special attention to the "startSessionWithTLS" method and you may be able adjust JavaMail to provide the same functionality. http://pastebin.com/VE8Mqkqp
I am creating a program that reads a file and if the first line of the file is not blank, it reads the next four lines. Calculations are performed on those lines and then the next line is read.
Something like this should work:
for line in infile:
next_lines = []
if line.strip():
for i in xrange(4):
try:
next_lines.append(infile.next())
except StopIteration:
break
# Do your calculation with "4 lines" here
fgets would work for you. here is very good documentation on this :-
http://www.cplusplus.com/reference/cstdio/fgets/
If you don't want to use fgets, following method will work for you :-
int readline(FILE *f, char *buffer, size_t len)
{
char c;
int i;
memset(buffer, 0, len);
for (i = 0; i < len; i++)
{
int c = fgetc(f);
if (!feof(f))
{
if (c == '\r')
buffer[i] = 0;
else if (c == '\n')
{
buffer[i] = 0;
return i+1;
}
else
buffer[i] = c;
}
else
{
//fprintf(stderr, "read_line(): recv returned %d\n", c);
return -1;
}
}
return -1;
}
A common mistake is
mainWB.Sheets.Add(After:=Sheets.Count)
which leads to Error 1004. Although it is not clear at all from the official documentation, it turns out that the 'After' parameter cannot be an integer, it must be a reference to a sheet in the same workbook.
fmt.Sprintf("%v",value);
If you know the specific type of value use the corresponding formatter for example %d
for int
More info - fmt
We use these settings:
etc/my.cnf
innodb_buffer_pool_size = 384M
key_buffer = 256M
query_cache_size = 1M
query_cache_limit = 128M
thread_cache_size = 8
max_connections = 400
innodb_lock_wait_timeout = 100
for a server with the following specifications:
Dell Server
CPU cores: Two
Processor(s): 1x Dual Xeon
Clock Speed: >= 2.33GHz
RAM: 2 GBytes
Disks: 1×250 GB SATA
From the Java API specification:
Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable.
Write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.
I think what you are looking for is:
list(im.getdata())
or, if the image is too big to load entirely into memory, so something like that:
for pixel in iter(im.getdata()):
print pixel
from PIL documentation:
getdata
im.getdata() => sequence
Returns the contents of an image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on.
Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations, including iteration and basic sequence access. To convert it to an ordinary sequence (e.g. for printing), use list(im.getdata()).
This it the best way to calculate the size of a directory. Only other way would still use recursion but be a bit easier to use and isn't as flexible.
float folderSize = 0.0f;
FileInfo[] files = Directory.GetFiles(folder, "*", SearchOption.AllDirectories);
foreach(FileInfo file in files) folderSize += file.Length;
In Tomcat6, You can conditionally enable from your HTTP Listener Class:
public void contextInitialized(ServletContextEvent event) {
if (Boolean.getBoolean("HTTP_ONLY_SESSION")) HttpOnlyConfig.enable(event);
}
Using this class
import java.lang.reflect.Field;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import org.apache.catalina.core.StandardContext;
public class HttpOnlyConfig
{
public static void enable(ServletContextEvent event)
{
ServletContext servletContext = event.getServletContext();
Field f;
try
{ // WARNING TOMCAT6 SPECIFIC!!
f = servletContext.getClass().getDeclaredField("context");
f.setAccessible(true);
org.apache.catalina.core.ApplicationContext ac = (org.apache.catalina.core.ApplicationContext) f.get(servletContext);
f = ac.getClass().getDeclaredField("context");
f.setAccessible(true);
org.apache.catalina.core.StandardContext sc = (StandardContext) f.get(ac);
sc.setUseHttpOnly(true);
}
catch (Exception e)
{
System.err.print("HttpOnlyConfig cant enable");
e.printStackTrace();
}
}
}
https://github.com/cognitom/paper-css seems to solve all my needs.
Front-end printing solution - previewable and live-reloadable!
in my case this fixed the problem:
sudo apt-get install libssl-dev libcurl4-openssl-dev python-dev
as explained here
If your environment is using both Guice and Spring and using the constructor @Inject, for example, with Play Framework, you will also run into this issue if you have mistakenly auto-completed the import with an incorrect choice of:
import com.google.inject.Inject;
Then you get the same missing default constructor
error even though the rest of your source with @Inject looks exactly the same way as other working components in your project and compile without an error.
Correct that with:
import javax.inject.Inject;
Do not write a default constructor with construction time injection.
You can get to the parent node and then query all the nodes with the class that is being searched. then we get the size
var parent = document.getElementById("parentId");_x000D_
var nodesSameClass = parent.getElementsByClassName("test");_x000D_
console.log(nodesSameClass.length);
_x000D_
<div id="parentId">_x000D_
<p class="prueba">hello word1</p>_x000D_
<p class="test">hello word2</p>_x000D_
<p class="test">hello word3</p>_x000D_
<p class="test">hello word4</p>_x000D_
</div>
_x000D_
From the bottom of the ?mutate_each
(at least in dplyr 0.5) it looks like that function, as in @docendo discimus's answer, will be deprecated and replaced with more flexible alternatives mutate_if
, mutate_all
, and mutate_at
. The one most similar to what @hadley mentions in his comment is probably using mutate_at
. Note the order of the arguments is reversed, compared to mutate_each
, and vars()
uses select()
like semantics, which I interpret to mean the ?select_helpers
functions.
dat %>% mutate_at(vars(starts_with("fac")),funs(factor)) %>%
mutate_at(vars(starts_with("dbl")),funs(as.numeric))
But mutate_at
can take column numbers instead of a vars()
argument, and after reading through this page, and looking at the alternatives, I ended up using mutate_at
but with grep
to capture many different kinds of column names at once (unless you always have such obvious column names!)
dat %>% mutate_at(grep("^(fac|fctr|fckr)",colnames(.)),funs(factor)) %>%
mutate_at(grep("^(dbl|num|qty)",colnames(.)),funs(as.numeric))
I was pretty excited about figuring out mutate_at
+ grep
, because now one line can work on lots of columns.
EDIT - now I see matches()
in among the select_helpers, which handles regex, so now I like this.
dat %>% mutate_at(vars(matches("fac|fctr|fckr")),funs(factor)) %>%
mutate_at(vars(matches("dbl|num|qty")),funs(as.numeric))
Another generally-related comment - if you have all your date columns with matchable names, and consistent formats, this is powerful. In my case, this turns all my YYYYMMDD columns, which were read as numbers, into dates.
mutate_at(vars(matches("_DT$")),funs(as.Date(as.character(.),format="%Y%m%d")))
If you are willing to change your uri, you could also use PathVariable
.
@RequestMapping(value="/mapping/foo/{foo}/{bar}", method=RequestMethod.GET)
public String process(@PathVariable String foo,@PathVariable String bar) {
//Perform logic with foo and bar
}
NB: The first foo is part of the path, the second one is the PathVariable
Describe Formatted/Extended will show the data definition of the table in hive
hive> describe Formatted dbname.tablename;
I know you've found another solution, but for those like me who find this question, looking for the same thing, it can be achieved with requests as follows:
Firstly, as Marcus did, check the source of the login form to get three pieces of information - the url that the form posts to, and the name attributes of the username and password fields. In his example, they are inUserName and inUserPass.
Once you've got that, you can use a requests.Session()
instance to make a post request to the login url with your login details as a payload. Making requests from a session instance is essentially the same as using requests normally, it simply adds persistence, allowing you to store and use cookies etc.
Assuming your login attempt was successful, you can simply use the session instance to make further requests to the site. The cookie that identifies you will be used to authorise the requests.
Example
import requests
# Fill in your details here to be posted to the login form.
payload = {
'inUserName': 'username',
'inUserPass': 'password'
}
# Use 'with' to ensure the session context is closed after use.
with requests.Session() as s:
p = s.post('LOGIN_URL', data=payload)
# print the html returned or something more intelligent to see if it's a successful login page.
print p.text
# An authorised request.
r = s.get('A protected web page url')
print r.text
# etc...
If the adapter is already set, setting it again will not refresh the listview. Instead first check if the listview has a adapter and then call the appropriate method.
I think its not a very good idea to create a new instance of the adapter while setting the list view. Instead, create an object.
BuildingAdapter adapter = new BuildingAdapter(context);
if(getListView().getAdapter() == null){ //Adapter not set yet.
setListAdapter(adapter);
}
else{ //Already has an adapter
adapter.notifyDataSetChanged();
}
Also you might try to run the refresh list on UI Thread:
activity.runOnUiThread(new Runnable() {
public void run() {
//do your modifications here
// for example
adapter.add(new Object());
adapter.notifyDataSetChanged()
}
});
I think this is the simplest way:
Foo[] array = list.toArray(new Foo[0]);
Also you can try this, if you want to focus on same text after error.
If you wants to show this error message in a paragraph then you can use this one:
$(document).ready(function () {
$("#submit").click(function () {
if($('#selBooks').val() === '') {
$("#Paragraph_id").text("Please select a book and then proceed.").show();
$('#selBooks').focus();
return false;
}
});
});
I use CTEs to help compose complicated SQL queries but not all RDBMS' support them. You can think of them as query scope views. Here is an example in t-sql on SQL server.
With localView1 as (
select c1,
c2,
c3,
c4,
((c2-c4)*(3))+c1 as "complex"
from realTable1)
, localView2 as (
select case complex WHEN 0 THEN 'Empty' ELSE 'Not Empty' end as formula1,
complex * complex as formula2
from localView1)
select *
from localView2
List<Person> list = new ArrayList<Person>();
Criteria criteria = this.getSessionFactory().getCurrentSession().createCriteria(Person.class);
for (final Object o : criteria.list()) {
list.add((Person) o);
}
Other posters are probably correct...there might be spaces mixed in with your tabs. Try doing a search & replace to replace all tabs with a few spaces.
Try this:
import sys
def Factorial(n): # return factorial
result = 1
for i in range (1,n):
result = result * i
print "factorial is ",result
return result
print Factorial(10)
its
selenium.getTable("tablename".rowNumber.colNumber)
not
selenium.getTable("tablename".colNumber.rowNumber)
I had this issue. Just move blabla to another location temporarily, tell svn to revert it, and then move it back. It is treated as a new addition. Simple!
Old question, but not among the answers is my favorite command to get a quick and short overview of all loaded packages:
(.packages())
To see which version is installed of all loaded packages, just use the above command to subset installed.packages()
.
installed.packages()[(.packages()),3]
By changing the column number (3 for package version) you can get any other information stored in installed.packages()
in an easy-to-read matrix. Below is an example for version number and dependency:
installed.packages()[(.packages()),c(3,5)]
Here is the ng repeat with ng click function and to append with slider
<script>
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
$scope.employees = [
{ 'id': '001', 'name': 'Alpha', 'joinDate': '05/17/2015', 'age': 37 },
{ 'id': '002', 'name': 'Bravo', 'joinDate': '03/25/2016', 'age': 27 },
{ 'id': '003', 'name': 'Charlie', 'joinDate': '09/11/2015', 'age': 29 },
{ 'id': '004', 'name': 'Delta', 'joinDate': '09/11/2015', 'age': 19 },
{ 'id': '005', 'name': 'Echo', 'joinDate': '03/09/2014', 'age': 32 }
]
//This will hide the DIV by default.
$scope.IsVisible = false;
$scope.ShowHide = function () {
//If DIV is visible it will be hidden and vice versa.
$scope.IsVisible = $scope.IsVisible ? false : true;
}
});
</script>
</head>
<body>
<div class="container" ng-app="MyApp" ng-controller="MyController">
<input type="checkbox" value="checkbox1" ng-click="ShowHide()" /> checkbox1
<div id="mixedSlider">
<div class="MS-content">
<div class="item" ng-repeat="emps in employees" ng-show = "IsVisible">
<div class="subitem">
<p>{{emps.id}}</p>
<p>{{emps.name}}</p>
<p>{{emps.age}}</p>
</div>
</div>
</div>
<div class="MS-controls">
<button class="MS-left"><i class="fa fa-angle-left" aria-hidden="true"></i></button>
<button class="MS-right"><i class="fa fa-angle-right" aria-hidden="true"></i></button>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="js/multislider.js"></script>
<script>
$('#mixedSlider').multislider({
duration: 750,
interval: false
});
</script>
The appearance of the scroll bars can be controlled with WebKit's -webkit-scrollbar
pseudo-elements [blog]. You can disable the default appearance and behaviour by setting -webkit-appearance
[docs] to none
.
Because you're removing the default style, you'll also need to specify the style yourself or the scroll bar will never show up. The following CSS recreates the appearance of the hiding scroll bars:
.frame::-webkit-scrollbar {
-webkit-appearance: none;
}
.frame::-webkit-scrollbar:vertical {
width: 11px;
}
.frame::-webkit-scrollbar:horizontal {
height: 11px;
}
.frame::-webkit-scrollbar-thumb {
border-radius: 8px;
border: 2px solid white; /* should match background, can't be transparent */
background-color: rgba(0, 0, 0, .5);
}
.frame::-webkit-scrollbar-track {
background-color: #fff;
border-radius: 8px;
}
WebKit (Chrome) Screenshot
You can do inline ifs with
return y == 20 ? 1 : 2;
which will give you 1 if true and 2 if false.
As benjymous pointed out, you can use Newtonsoft.Json with a temporary object and deserialize/serialize.
var obj = JsonConvert.DeserializeObject(jsonString);
var formatted = JsonConvert.SerializeObject(obj, Formatting.Indented);
If you're using SQL Server 2008, there's a new featured called a User Defined Table Type. Here is an example of how to use it:
Create your User Defined Table Type:
CREATE TYPE [dbo].[StringList] AS TABLE(
[Item] [NVARCHAR](MAX) NULL
);
Next you need to use it properly in your stored procedure:
CREATE PROCEDURE [dbo].[sp_UseStringList]
@list StringList READONLY
AS
BEGIN
-- Just return the items we passed in
SELECT l.Item FROM @list l;
END
Finally here's some sql to use it in c#:
using (var con = new SqlConnection(connstring))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("exec sp_UseStringList @list", con))
{
using (var table = new DataTable()) {
table.Columns.Add("Item", typeof(string));
for (int i = 0; i < 10; i++)
table.Rows.Add("Item " + i.ToString());
var pList = new SqlParameter("@list", SqlDbType.Structured);
pList.TypeName = "dbo.StringList";
pList.Value = table;
cmd.Parameters.Add(pList);
using (var dr = cmd.ExecuteReader())
{
while (dr.Read())
Console.WriteLine(dr["Item"].ToString());
}
}
}
}
To execute this from SSMS
DECLARE @list AS StringList
INSERT INTO @list VALUES ('Apple')
INSERT INTO @list VALUES ('Banana')
INSERT INTO @list VALUES ('Orange')
-- Alternatively, you can populate @list with an INSERT-SELECT
INSERT INTO @list
SELECT Name FROM Fruits
EXEC sp_UseStringList @list
This is simple code to do it, I avoided all checks but this is the main idea.
public String parse(String jsonLine) {
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("data");
JsonArray jarray = jobject.getAsJsonArray("translations");
jobject = jarray.get(0).getAsJsonObject();
String result = jobject.get("translatedText").getAsString();
return result;
}
To make the use more generic - you will find that Gson's javadocs are pretty clear and helpful.
In a pinch, just type 'notepad (filename)' and notepad will pop up with the file you want to edit in it. Otherwise Vim or some such will have to be installed.
There is no installation per se.
You download jQuery and include it in your html files like this:
<script src="jquery.js" type="text/javascript"></script>
Of course, modify the filename so that it's the same as the downloaded script file.
Done!
You can have Xcode run the preprocessor over your Info.plist file:
<key>CFBundleShortVersionString</key> #ifdef DEBUG <string>1.0 (debug)</string> #else <string>1.0</string> #endif
See http://developer.apple.com/technotes/tn2007/tn2175.html for details.
You can loop through a hash map like this
<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);
%>
<c:forEach items="${itemList}" var="itemrow">
<input type="text" value="<c:out value='${itemrow.test}'/>"/>
</c:forEach>
For more JSTL functionality look here
Here's a better approach where you don't have to delete/move anything for Android Studio 3.+.
File > Close Project
.In iOS 10 beta 4.The right code in HTML5 is
<video src="file.mp4" webkit-playsinline="true" playsinline="true">
webkit-playsinline
is for iOS < 10, and playsinline
is for iOS >= 10
See details via https://webkit.org/blog/6784/new-video-policies-for-ios/
In EF Core you can enter the command Remove-Migration
in the package manager console after you've added your erroneous migration.
The console suggests you do so if your migration could involve a loss of data:
An operation was scaffolded that may result in the loss of data. Please review the migration for accuracy. To undo this action, use Remove-Migration.
(You're not searching through "JSON", you're searching through an array -- the JSON string has already been deserialized into an object graph, in this case an array.)
Some options:
If you're in control of the generation of this thing, does it have to be an array? Because if not, there's a much simpler way.
Say this is your original data:
[
{"id": "one", "pId": "foo1", "cId": "bar1"},
{"id": "two", "pId": "foo2", "cId": "bar2"},
{"id": "three", "pId": "foo3", "cId": "bar3"}
]
Could you do the following instead?
{
"one": {"pId": "foo1", "cId": "bar1"},
"two": {"pId": "foo2", "cId": "bar2"},
"three": {"pId": "foo3", "cId": "bar3"}
}
Then finding the relevant entry by ID is trivial:
id = "one"; // Or whatever
var entry = objJsonResp[id];
...as is updating it:
objJsonResp[id] = /* New value */;
...and removing it:
delete objJsonResp[id];
This takes advantage of the fact that in JavaScript, you can index into an object using a property name as a string -- and that string can be a literal, or it can come from a variable as with id
above.
(Dumb idea, predates the above. Kept for historical reasons.)
It looks like you need this to be an array, in which case there isn't really a better way than searching through the array unless you want to put a map on it, which you could do if you have control of the generation of the object. E.g., say you have this originally:
[
{"id": "one", "pId": "foo1", "cId": "bar1"},
{"id": "two", "pId": "foo2", "cId": "bar2"},
{"id": "three", "pId": "foo3", "cId": "bar3"}
]
The generating code could provide an id-to-index map:
{
"index": {
"one": 0, "two": 1, "three": 2
},
"data": [
{"id": "one", "pId": "foo1", "cId": "bar1"},
{"id": "two", "pId": "foo2", "cId": "bar2"},
{"id": "three", "pId": "foo3", "cId": "bar3"}
]
}
Then getting an entry for the id in the variable id
is trivial:
var index = objJsonResp.index[id];
var obj = objJsonResp.data[index];
This takes advantage of the fact you can index into objects using property names.
Of course, if you do that, you have to update the map when you modify the array, which could become a maintenance problem.
But if you're not in control of the generation of the object, or updating the map of ids-to-indexes is too much code and/ora maintenance issue, then you'll have to do a brute force search.
Somewhat OT (although you did ask if there was a better way :-) ), but your code for looping through an array is incorrect. Details here, but you can't use for..in
to loop through array indexes (or rather, if you do, you have to take special pains to do so); for..in
loops through the properties of an object, not the indexes of an array. Your best bet with a non-sparse array (and yours is non-sparse) is a standard old-fashioned loop:
var k;
for (k = 0; k < someArray.length; ++k) { /* ... */ }
or
var k;
for (k = someArray.length - 1; k >= 0; --k) { /* ... */ }
Whichever you prefer (the latter is not always faster in all implementations, which is counter-intuitive to me, but there we are). (With a sparse array, you might use for..in
but again taking special pains to avoid pitfalls; more in the article linked above.)
Using for..in
on an array seems to work in simple cases because arrays have properties for each of their indexes, and their only other default properties (length
and their methods) are marked as non-enumerable. But it breaks as soon as you set (or a framework sets) any other properties on the array object (which is perfectly valid; arrays are just objects with a bit of special handling around the length
property).
'Effectively final' is a variable which would not give compiler error if it were to be appended by 'final'
From a article by 'Brian Goetz',
Informally, a local variable is effectively final if its initial value is never changed -- in other words, declaring it final would not cause a compilation failure.
@( condition ? "true" : "false" )
I am using Windows 8 and found the missing scripts in the path below:
C:\Users\YourUsername\Documents\SQL Server Management Studio\Backup Files
Have you tried:
For one cell:
ActiveCell.Select
For multiple selected cells:
Selection.Range
For example:
Dim rng As Range
Set rng = Range(Selection.Address)
SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.
One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.
so exclusively open SOAP Port in Firewalls
Accepted answer is great, just know that if you are sending a DateTime2 to the frontend - it gets rounded to the normal DateTime equivalent.
This caused a problem for me because in a solution of mine I had to compare what was sent with what was on the database when resubmitted, and my simple comparison '==' didn't allow for rounding. So it had to be added.
a = ['a1','b2','c3']
b = ['a1','b2','c3']
c = ['b2','a1','c3']
# if you care about order
a == b # True
a == c # False
# if you don't care about order AND duplicates
set(a) == set(b) # True
set(a) == set(c) # True
By casting a
, b
and c
as a set, you remove duplicates and order doesn't count. Comparing sets is also much faster and more efficient than comparing lists.
You can use the "New Class" dialog, but that leaves other steps you need to do by hand (e.g. adding an entry to the manifest file). If you want those steps to be automated, you can create the activity via the manifest editor like this:
When you click Finish from the new class dialog, it'll take you to your new activity class so you can start coding.
Five steps might seem a lot, but I'm just trying to be extra detailed here so that it's clear. It's pretty quick when you actually do it.
You could count the total length of the string first, and pass it to the StringBuilder constructor. And you do not need to convert the Set first.
Set<String> abc = new HashSet<String>();
abc.add("A");
abc.add("B");
abc.add("C");
String separator = ", ";
int total = abc.size() * separator.length();
for (String s : abc) {
total += s.length();
}
StringBuilder sb = new StringBuilder(total);
for (String s : abc) {
sb.append(separator).append(s);
}
String result = sb.substring(separator.length()); // remove leading separator
You should write in file:
<script>
//write your JavaScript code here
</script>
save it with .html extension and open with browser.
For example:
// this is test.html
<script>
alert("Hello");
var a = 5;
function incr(arg){
arg++;
return arg;
}
alert(a);
</script>
Swift 3 For check Empty String best way
if !string.isEmpty{
// do stuff
}
yum install python-devel
will work.
If yum
doesn't work then use
apt-get install python-dev
You can place an empty file called index.html
into each directory that you don't want listed. This has several advantages:
.htaccess
files, this can lead to lots of "Error 500 - internal server error" messages for your users!). Theoretically, the autoindexing might be triggered by a different file (this is controlled by the DirectoryIndex
option), but I have yet to encounter this in the real world.
After a quick google:
__STDC__
and __STDC_VERSION__
, see here
You can put in this directory your Xampp control panel shortcut
it will work fine (it will automatically start after windows startup) as @wajahat-hashmi answered above:
C:\Users\User-Name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
About aditional windows script or programs that we need to run automatically...
I needed to create some additional scripts to initialize some windows services. If someone has the same need you can put in that same directory, they will all run right after windows startup.
For me, Xampp auto start and other scripts and shortcuts worked fine in windows 8.1, I think it will work fine in any windows version.
I hope it works well for anyone who has the same need.
No one mentions anything about the --single-transaction option. People should use it by default for InnoDB tables to ensure data consistency. In this case:
mysqldump --single-transaction -h [remoteserver.com] -u [username] -p [password] [yourdatabase] > [dump_file.sql]
This makes sure the dump is run in a single transaction that's isolated from the others, preventing backup of a partial transaction.
For instance, consider you have a game server where people can purchase gears with their account credits. There are essentially 2 operations against the database:
Now if the dump happens in between these operations, the next time you restore the backup would result in the user losing the purchased item, because the second operation isn't dumped in the SQL dump file.
While it's just an option, there are basically not much of a reason why you don't use this option with mysqldump.
You will need to use the slugify function.
>>> from django.template.defaultfilters import slugify
>>> slugify("b b b b")
u'b-b-b-b'
>>>
You can call slugify
automatically by overriding the save
method:
class Test(models.Model):
q = models.CharField(max_length=30)
s = models.SlugField()
def save(self, *args, **kwargs):
self.s = slugify(self.q)
super(Test, self).save(*args, **kwargs)
Be aware that the above will cause your URL to change when the q
field is edited, which can cause broken links. It may be preferable to generate the slug only once when you create a new object:
class Test(models.Model):
q = models.CharField(max_length=30)
s = models.SlugField()
def save(self, *args, **kwargs):
if not self.id:
# Newly created object, so set slug
self.s = slugify(self.q)
super(Test, self).save(*args, **kwargs)
The ::
is called scope resolution operator.
Can be used like this:
::
identifier
class-name ::
identifier
namespace ::
identifier
You can read about it here
https://docs.microsoft.com/en-us/cpp/cpp/scope-resolution-operator?view=vs-2017
For whatever reason, for me, the tmp file created by git diff was being deleted before it opened in beyond compare. I had to copy it out to another location first.
cp -r $2 "/cygdrive/c/temp$2"
cygstart /cygdrive/c/Program\ Files\ \(x86\)/Beyond\ Compare\ 3/BCompare.exe "C:/temp$2" "$5"
Update for ECMAScript 2017:
Math.clamp(x, lower, upper)
But note that as of today, it's a Stage 1 proposal. Until it gets widely supported, you can use a polyfill.
Read the W3C spec. (this is CSS 2.1, find the appropriate version for your assumption of browsers)
edit: relevant paragraph follows:
In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-z0-9] and ISO 10646 characters U+00A1 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".
edit 2: as @mipadi points out in Triptych's answer, there's this caveat, also in the same webpage:
In CSS, identifiers may begin with '-' (dash) or '_' (underscore). Keywords and property names beginning with '-' or '_' are reserved for vendor-specific extensions. Such vendor-specific extensions should have one of the following formats:
'-' + vendor identifier + '-' + meaningful name '_' + vendor identifier + '-' + meaningful name
Example(s):
For example, if XYZ organization added a property to describe the color of the border on the East side of the display, they might call it -xyz-border-east-color.
Other known examples:
-moz-box-sizing -moz-border-radius -wap-accesskey
An initial dash or underscore is guaranteed never to be used in a property or keyword by any current or future level of CSS. Thus typical CSS implementations may not recognize such properties and may ignore them according to the rules for handling parsing errors. However, because the initial dash or underscore is part of the grammar, CSS 2.1 implementers should always be able to use a CSS-conforming parser, whether or not they support any vendor-specific extensions.
Authors should avoid vendor-specific extensions
HigLabo.Mail is easy to use. Here is a sample usage:
using (Pop3Client cl = new Pop3Client())
{
cl.UserName = "MyUserName";
cl.Password = "MyPassword";
cl.ServerName = "MyServer";
cl.AuthenticateMode = Pop3AuthenticateMode.Pop;
cl.Ssl = false;
cl.Authenticate();
///Get first mail of my mailbox
Pop3Message mg = cl.GetMessage(1);
String MyText = mg.BodyText;
///If the message have one attachment
Pop3Content ct = mg.Contents[0];
///you can save it to local disk
ct.DecodeData("your file path");
}
you can get it from https://github.com/higty/higlabo or Nuget [HigLabo]
Up until the C99 standard, all declarations had to come before any statements in a block:
void foo()
{
int i, j;
double k;
char *c;
// code
if (c)
{
int m, n;
// more code
}
// etc.
}
C99 allowed for mixing declarations and statements (like C++). Many compilers still default to C89, and some compilers (such as Microsoft's) don't support C99 at all.
So, you will need to do the following:
Determine if your compiler supports C99 or later; if it does, configure it so that it's compiling C99 instead of C89;
If your compiler doesn't support C99 or later, you will either need to find a different compiler that does support it, or rewrite your code so that all declarations come before any statements within the block.
.contains() is the best method for lists, but for maps you will need to use .containsKey() or .containsValue()
[a:1,b:2,c:3].containsValue(3)
[a:1,b:2,c:3].containsKey('a')
Just set the property as follows:
When the user press "clear button" or "delete key" do
dtpData.CustomFormat = " " 'An empty SPACE
dtpData.Format = DateTimePickerFormat.Custom
On DateTimePicker1_ValueChanged
event do
dtpData.CustomFormat = "dd/MM/yyyy hh:mm:ss"
Modern browsers have added classList which provides methods to make it easier to manipulate classes without needing a library:
document.getElementById("MyElement").classList.add('MyClass');
document.getElementById("MyElement").classList.remove('MyClass');
if ( document.getElementById("MyElement").classList.contains('MyClass') )
document.getElementById("MyElement").classList.toggle('MyClass');
Unfortunately, these do not work in Internet Explorer prior to v10, though there is a shim to add support for it to IE8 and IE9, available from this page. It is, though, getting more and more supported.
The standard JavaScript way to select an element is using document.getElementById("Id")
, which is what the following examples use - you can of course obtain elements in other ways, and in the right situation may simply use this
instead - however, going into detail on this is beyond the scope of the answer.
To replace all existing classes with one or more new classes, set the className attribute:
document.getElementById("MyElement").className = "MyClass";
(You can use a space-delimited list to apply multiple classes.)
To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:
document.getElementById("MyElement").className += " MyClass";
To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:
document.getElementById("MyElement").className =
document.getElementById("MyElement").className.replace
( /(?:^|\s)MyClass(?!\S)/g , '' )
/* Code wrapped for readability - above is all one statement */
An explanation of this regex is as follows:
(?:^|\s) # Match the start of the string or any single whitespace character
MyClass # The literal text for the classname to remove
(?!\S) # Negative lookahead to verify the above is the whole classname
# Ensures there is no non-space character following
# (i.e. must be the end of the string or space)
The g
flag tells the replace to repeat as required, in case the class name has been added multiple times.
The same regex used above for removing a class can also be used as a check as to whether a particular class exists:
if ( document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) )
Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as onclick="this.className+=' MyClass'"
) this is not recommended behaviour. Especially on larger applications, more maintainable code is achieved by separating HTML markup from JavaScript interaction logic.
The first step to achieving this is by creating a function, and calling the function in the onclick attribute, for example:
<script type="text/javascript">
function changeClass(){
// Code examples from above
}
</script>
...
<button onclick="changeClass()">My Button</button>
(It is not required to have this code in script tags, this is simply for the brevity of example, and including the JavaScript in a distinct file may be more appropriate.)
The second step is to move the onclick event out of the HTML and into JavaScript, for example using addEventListener
<script type="text/javascript">
function changeClass(){
// Code examples from above
}
window.onload = function(){
document.getElementById("MyElement").addEventListener( 'click', changeClass);
}
</script>
...
<button id="MyElement">My Button</button>
(Note that the window.onload part is required so that the contents of that function are executed after the HTML has finished loading - without this, the MyElement might not exist when the JavaScript code is called, so that line would fail.)
The above code is all in standard JavaScript, however, it is common practice to use either a framework or a library to simplify common tasks, as well as benefit from fixed bugs and edge cases that you might not think of when writing your code.
Whilst some people consider it overkill to add a ~50 KB framework for simply changing a class, if you are doing any substantial amount of JavaScript work or anything that might have unusual cross-browser behavior, it is well worth considering.
(Very roughly, a library is a set of tools designed for a specific task, whilst a framework generally contains multiple libraries and performs a complete set of duties.)
The examples above have been reproduced below using jQuery, probably the most commonly used JavaScript library (though there are others worth investigating too).
(Note that $
here is the jQuery object.)
$('#MyElement').addClass('MyClass');
$('#MyElement').removeClass('MyClass');
if ( $('#MyElement').hasClass('MyClass') )
In addition, jQuery provides a shortcut for adding a class if it doesn't apply, or removing a class that does:
$('#MyElement').toggleClass('MyClass');
$('#MyElement').click(changeClass);
or, without needing an id:
$(':button:contains(My Button)').click(changeClass);
docker rmi $(docker images -q) --force
This is the natural javascript option
var myArray = ['1','2',3,4]_x000D_
_x000D_
myArray.forEach(function(value){_x000D_
console.log(value);_x000D_
});
_x000D_
However it won't work if you're using await inside the forEach loop because forEach is not asynchronous. you'll be forced to use the second answer or some other equivalent:
let myArray = ["a","b","c","d"];_x000D_
for (let item of myArray) {_x000D_
console.log(item);_x000D_
}
_x000D_
Or you could create an asyncForEach explained here:
https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404
Steps for Mac:
The best way to see the supported list is to start up the emulator in the latest version and open the "Custom Locale" app. This will list all of the supported languages and locales for that version of Android.
Issue can be solved by adding CRT of msvcrtd.lib in the linker library. Because cryptlib.lib used CRT version of debug.
I had to accept the XCode license after my first install before I could run it. You can run the following to get the license prompt via command line. You have to type agree
and confirm as well.
sudo xcodebuild -license
Instructions for Tortoise SVN
Navigate to the directory where you see this error. If you do not have any changes perform the following
a. Right click and do a 'Revert'
b. Select all the files
c. Then update the directory again
I was having similar issue and I think if we simply ignore the ssl
verification will work like charm as it worked for me. So connecting to server with https
scheme but directing them not to verify the certificate.
Using requests
. Just mention verify=False
instead of None
requests.post(url, data=payload, headers=headers, verify=False)
Hoping this will work for those who needs :).
When you push to a remote and you use the --set-upstream
flag git sets the branch you are pushing to as the remote tracking branch of the branch you are pushing.
Adding a remote tracking branch means that git then knows what you want to do when you git fetch
, git pull
or git push
in future. It assumes that you want to keep the local branch and the remote branch it is tracking in sync and does the appropriate thing to achieve this.
You could achieve the same thing with git branch --set-upstream-to
or git checkout --track
. See the git help pages on tracking branches for more information.
The keyword you need is flatten an array. Modern javascript array comes with a flat method. You can use third party libraries like underscorejs in case you need to support older browsers.
Native Ex:
var response=[1,2,3,4[12,15],[20,21]];
var data=response.flat(); //data=[1,2,3,4,12,15,20,21]
Underscore Ex:
var response=[1,2,3,4[12,15],[20,21]];
var data=_.flatten(response);
The best way for paging in sql server 2012 is by using offset and fetch next in a stored procedure. OFFSET Keyword - If we use offset with the order by clause then the query will skip the number of records we specified in OFFSET n Rows.
FETCH NEXT Keywords - When we use Fetch Next with an order by clause only it will returns the no of rows you want to display in paging, without Offset then SQL will generate an error. here is the example given below.
create procedure sp_paging
(
@pageno as int,
@records as int
)
as
begin
declare @offsetcount as int
set @offsetcount=(@pageno-1)*@records
select id,bs,variable from salary order by id offset @offsetcount rows fetch Next @records rows only
end
you can execute it as follow.
exec sp_paging 2,3
Let me propose an improved method when the values of the dictionnary are lists with the same lenght :
import numpy
def dctToNdarray (dd, szFormat = 'f8'):
'''
Convert a 'rectangular' dictionnary to numpy NdArray
entry
dd : dictionnary (same len of list
retrun
data : numpy NdArray
'''
names = dd.keys()
firstKey = dd.keys()[0]
formats = [szFormat]*len(names)
dtype = dict(names = names, formats=formats)
values = [tuple(dd[k][0] for k in dd.keys())]
data = numpy.array(values, dtype=dtype)
for i in range(1,len(dd[firstKey])) :
values = [tuple(dd[k][i] for k in dd.keys())]
data_tmp = numpy.array(values, dtype=dtype)
data = numpy.concatenate((data,data_tmp))
return data
dd = {'a':[1,2.05,25.48],'b':[2,1.07,9],'c':[3,3.01,6.14]}
data = dctToNdarray(dd)
print data.dtype.names
print data
Using CMD you can run a console .net core project if .net core SDK is installed in your machine :
To run console project using windows command-Line, choose the specific path from your directory and type following below command
dotnet run
Note that :
typeof $(this)
is JQuery object.
and
typeof $(this)[0]
is HTMLElement object
then :
if you want to apply .val()
on HTMLElement , you can add this extension .
HTMLElement.prototype.val=function(v){
if(typeof v!=='undefined'){this.value=v;return this;}
else{return this.value}
}
Then :
document.getElementById('myDiv').val() ==== $('#myDiv').val()
And
document.getElementById('myDiv').val('newVal') ==== $('#myDiv').val('newVal')
?????
INVERSE :Conversely? if you want to add value property to jQuery object , follow those steps :
Download the full source code (not minified) i.e: example http://code.jquery.com/jquery-1.11.1.js .
Insert Line after L96 , add this code value:""
to init this new prop
Search on jQuery.fn.init
, it will be almost Line 2747
value
prop : (Before return statment add this.value=jQuery(selector).val()
)
cat > filename.txt
enter the text until EOF for save the text use : ctrl+d
if you want to read that .txt file use
cat filename.txt
and one thing .txt is not mandatory, its for your reference.
The solution that worked for me was to right click on the project --> Maven --> Update Project then click OK.
I think there's a more elegant way to solve the problem: send the stdout/stderr to syslog with an identifier and instruct your syslog manager to split its output by program name.
Use the following properties in your systemd service unit file:
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=<your program identifier> # without any quote
Then, assuming your distribution is using rsyslog to manage syslogs, create a file in /etc/rsyslog.d/<new_file>.conf
with the following content:
if $programname == '<your program identifier>' then /path/to/log/file.log
& stop
Now make the log file writable by syslog:
# ls -alth /var/log/syslog
-rw-r----- 1 syslog adm 439K Mar 5 19:35 /var/log/syslog
# chown syslog:adm /path/to/log/file.log
Restart rsyslog (sudo systemctl restart rsyslog
) and enjoy! Your program stdout/stderr will still be available through journalctl (sudo journalctl -u <your program identifier>
) but they will also be available in your file of choice.
Try something like:-
ALTER TABLE table_name ADD CONSTRAINT [DF_table_name_Created]
DEFAULT (getdate()) FOR [created_at];
replacing table_name
with the name of your table.
Here's a technical consideration: will the image be generated dynamically? It tends to be a lot easier to generate the <img>
tag in HTML than to try to dynamically edit a CSS property.
In Swift 3.0
Edit your AppDelegate.swift
by adding the following code to your application function:
// Override point for customization after application launch.
// Remove border in navigationBar
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
Old question, but if you want to do locale-aware sorting without setting locale.LC_ALL
you can do so by using the PyICU library as suggested by this answer:
import icu # PyICU
def sorted_strings(strings, locale=None):
if locale is None:
return sorted(strings)
collator = icu.Collator.createInstance(icu.Locale(locale))
return sorted(strings, key=collator.getSortKey)
Then call with e.g.:
new_list = sorted_strings(list_of_strings, "de_DE.utf8")
This worked for me without installing any locales or changing other system settings.
(This was already suggested in a comment above, but I wanted to give it more prominence, because I missed it myself at first.)
Check whether your app has the needed permissions.I was also getting the same error and I checked the logcat debug log which showed this:
04-15 13:38:25.387: E/AndroidRuntime(694): java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:555-555-5555 cmp=com.android.phone/.OutgoingCallBroadcaster } from ProcessRecord{44068640 694:rahulserver.test/10055} (pid=694, uid=10055) requires android.permission.CALL_PHONE
I then gave the needed permission in my android-manifest which worked for me.
Store the lines in some type of list. When it comes time to paint them, iterate the list and draw each one. Like this:
Screenshot
DrawLines
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.geom.Line2D;
import javax.swing.JOptionPane;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import java.util.ArrayList;
import java.util.Random;
class DrawLines {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
LineComponent lineComponent = new LineComponent(400,400);
for (int ii=0; ii<30; ii++) {
lineComponent.addLine();
}
JOptionPane.showMessageDialog(null, lineComponent);
}
};
SwingUtilities.invokeLater(r);
}
}
class LineComponent extends JComponent {
ArrayList<Line2D.Double> lines;
Random random;
LineComponent(int width, int height) {
super();
setPreferredSize(new Dimension(width,height));
lines = new ArrayList<Line2D.Double>();
random = new Random();
}
public void addLine() {
int width = (int)getPreferredSize().getWidth();
int height = (int)getPreferredSize().getHeight();
Line2D.Double line = new Line2D.Double(
random.nextInt(width),
random.nextInt(height),
random.nextInt(width),
random.nextInt(height)
);
lines.add(line);
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.white);
g.fillRect(0, 0, getWidth(), getHeight());
Dimension d = getPreferredSize();
g.setColor(Color.black);
for (Line2D.Double line : lines) {
g.drawLine(
(int)line.getX1(),
(int)line.getY1(),
(int)line.getX2(),
(int)line.getY2()
);
}
}
}
/*The simplest way to get/display total physical memory in VB.net (Tested)
public sub get_total_physical_mem()
dim total_physical_memory as integer
total_physical_memory=CInt((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024))
MsgBox("Total Physical Memory" + CInt((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024)).ToString + "Mb" )
end sub
*/
//The simplest way to get/display total physical memory in C# (converted Form http://www.developerfusion.com/tools/convert/vb-to-csharp)
public void get_total_physical_mem()
{
int total_physical_memory = 0;
total_physical_memory = Convert.ToInt32((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024));
Interaction.MsgBox("Total Physical Memory" + Convert.ToInt32((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024)).ToString() + "Mb");
}
In short:
static_cast<>()
gives you a compile time checking ability, C-Style
cast doesn't.static_cast<>()
is more readable and can be spotted easily
anywhere inside a C++ source code, C_Style cast is'nt.More Explanation:
The static cast performs conversions between compatible types. It is similar to the C-style cast, but is more restrictive. For example, the C-style cast would allow an integer pointer to point to a char.
char c = 10; // 1 byte
int *p = (int*)&c; // 4 bytes
Since this results in a 4-byte pointer ( a pointer to 4-byte datatype) pointing to 1 byte of allocated memory, writing to this pointer will either cause a run-time error or will overwrite some adjacent memory.
*p = 5; // run-time error: stack corruption
In contrast to the C-style cast, the static cast will allow the compiler to check that the pointer and pointee data types are compatible, which allows the programmer to catch this incorrect pointer assignment during compilation.
int *q = static_cast<int*>(&c); // compile-time error
You can also check this page on more explanation on C++ casts : Click Here
I don't know JavaScript and I just started to learn PHP, so what helped for me from all those responses was:
<iframe name="email" style=""></iframe>
<form action="email.php" method="post" target="email">
<input type="email" name="email" >
<input type="submit" name="Submit" value="Submit">
</form>
<?php
if (isset($_POST['Submit'])){
$email = $_POST['email'];
echo $email;
}
?>
<?php
if (isset($_POST['Submit'])){
$to = $_POST['email'];
$subject = "Test email";
$message = "Test message";
$headers = "From: [email protected] \r\n";
$headers .= "Reply-To: [email protected] \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to, $subject, $message, $headers);
}
?>
Hope this helps for all other rookies like me :)
Leaving this here for myself,
If I get this error, I probably used const char*
when I should be using char* const
.
This makes the pointer constant, and not the contents of the string.
const char* const
makes it so the value and the pointer is constant also.
For just in case if someone wants to pass a callback (or delegate
) as an optional parameter, can do it this way.
Optional Callback parameter:
public static bool IsOnlyOneElement(this IList lst, Action callbackOnTrue = (Action)((null)), Action callbackOnFalse = (Action)((null)))
{
var isOnlyOne = lst.Count == 1;
if (isOnlyOne && callbackOnTrue != null) callbackOnTrue();
if (!isOnlyOne && callbackOnFalse != null) callbackOnFalse();
return isOnlyOne;
}
use <sys/time.h>
struct timeval tp;
gettimeofday(&tp, NULL);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;
refer this.
take a look at generic method to print all elements in an array
but in short, the Arrays.toString(arr) is just a easy way of printing the content of a primative array.
A good rule of thumb is for anything that you need to compare in the loop condition against something that is naturally a std::size_t
itself.
std::size_t
is the type of any sizeof
expression and as is guaranteed to be able to express the maximum size of any object (including any array) in C++. By extension it is also guaranteed to be big enough for any array index so it is a natural type for a loop by index over an array.
If you are just counting up to a number then it may be more natural to use either the type of the variable that holds that number or an int
or unsigned int
(if large enough) as these should be a natural size for the machine.
Made some changes, but I think I got the effect you want using visibility
. http://jsfiddle.net/9dsGP/49/
I also made these changes:
position: absolute; /* so it doesn't expand the button background */
top: calc(1em + 8px); /* so it's under the "button" */
left:8px; /* so it's shifted by padding-left */
width: 182px; /* so it fits nicely under the button, width - padding-left - padding-right - border-left-width - border-right-width, 200 - 8 - 8 - 1 - 1 = 182 */
Alternatively, you could put .content as a sibling of .button, but I didn't make an example for this.
hash {}
hash[:a] = 'a'
hash[:b] = 'b'
hash = {:a => 'a' , :b = > b}
You might get your key and value from user input, so you can use Ruby .to_sym can convert a string to a symbol, and .to_i will convert a string to an integer.
For example:
movies ={}
movie = gets.chomp
rating = gets.chomp
movies[movie.to_sym] = rating.to_int
# movie will convert to a symbol as a key in our hash, and
# rating will be an integer as a value.
Extending your PATH
with:
export PATH=/usr/local/share/npm/bin:$PATH
isn't a terrible idea. Having said that, you shouldn't have to do it.
Run this:
npm config get prefix
The default on OS X is /usr/local
, which means that npm will symlink binaries into /usr/local/bin
, which should already be on your PATH
(especially if you're using Homebrew).
So:
npm config set prefix /usr/local
if it's something else, andsudo
with npm! According to the jslint docs, you should just be able to npm install
it.If you installed npm as sudo (sudo brew install
), try reinstalling it with plain ol' brew install
. Homebrew is supposed to help keep you sudo
-free.
$$
is the current script's pid$!
is the pid of the last background processHere's a sample transcript from a bash session (%1
refers to the ordinal number of background process as seen from jobs
):
$ echo $$
3748
$ sleep 100 &
[1] 192
$ echo $!
192
$ kill %1
[1]+ Terminated sleep 100
As mentioned in other answers, unittest produces some nice output for comparing dicts, but in this example we don't want to have to build a whole test first.
Scraping the unittest source, it looks like you can get a fair solution with just this:
import difflib
import pprint
def diff_dicts(a, b):
if a == b:
return ''
return '\n'.join(
difflib.ndiff(pprint.pformat(a, width=30).splitlines(),
pprint.pformat(b, width=30).splitlines())
)
so
dictA = dict(zip(range(7), map(ord, 'python')))
dictB = {0: 112, 1: 'spam', 2: [1,2,3], 3: 104, 4: 111}
print diff_dicts(dictA, dictB)
Results in:
{0: 112,
- 1: 121,
- 2: 116,
+ 1: 'spam',
+ 2: [1, 2, 3],
3: 104,
- 4: 111,
? ^
+ 4: 111}
? ^
- 5: 110}
Where:
Like in unittest, the only caveat is that the final mapping can be thought to be a diff, due to the trailing comma/bracket.
Try:
cl /v
Actually, any time I give cl an argument, it prints out the version number on the first line.
You could just feed it a garbage argument and then parse the first line of the output, which contains the verison number.
Even though it's stated in many of the other answers here, the component should either:
implement shouldComponentUpdate
to render only when state or properties change
switch to extending a PureComponent, which already implements a shouldComponentUpdate
method internally for shallow comparisons.
Here's an example that uses shouldComponentUpdate
, which works only for this simple use case and demonstration purposes. When this is used, the component no longer re-renders itself on each click, and is rendered when first displayed, and after it's been clicked once.
var TimeInChild = React.createClass({_x000D_
render: function() {_x000D_
var t = new Date().getTime();_x000D_
_x000D_
return (_x000D_
<p>Time in child:{t}</p>_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
var Main = React.createClass({_x000D_
onTest: function() {_x000D_
this.setState({'test':'me'});_x000D_
},_x000D_
_x000D_
shouldComponentUpdate: function(nextProps, nextState) {_x000D_
if (this.state == null)_x000D_
return true;_x000D_
_x000D_
if (this.state.test == nextState.test)_x000D_
return false;_x000D_
_x000D_
return true;_x000D_
},_x000D_
_x000D_
render: function() {_x000D_
var currentTime = new Date().getTime();_x000D_
_x000D_
return (_x000D_
<div onClick={this.onTest}>_x000D_
<p>Time in main:{currentTime}</p>_x000D_
<p>Click me to update time</p>_x000D_
<TimeInChild/>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
ReactDOM.render(<Main/>, document.body);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
_x000D_
You can build one with the HttpListener
class to listen for incoming requests and the HttpWebRequest
class to relay the requests.
Example Code
public class Person {
public String firstName { get; set; }
public String lastName { get; set; }
}
// Instantiate Person
var person = new Person { firstName = "Albert", lastName = "Einstein" };
// We can print fullname of the above person as follows
Console.WriteLine("Full-Name - " + person.firstName + " " + person.lastName);
Console.WriteLine("Full-Name - {0} {1}", person.firstName, person.lastName);
Console.WriteLine($"Full-Name - {person.firstName} {person.lastName}");
Output
Full-Name - Albert Einstein
Full-Name - Albert Einstein
Full-Name - Albert Einstein
It is Interpolated Strings. You can use an interpolated string anywhere you can use a string literal. When running your program would execute the code with the interpolated string literal, the code computes a new string literal by evaluating the interpolation expressions. This computation occurs each time the code with the interpolated string executes.
Following example produces a string value where all the string interpolation values have been computed. It is the final result and has type string. All occurrences of double curly braces (“{{“ and “}}”)
are converted to a single curly brace.
string text = "World";
var message = $"Hello, {text}";
After executing above 2 lines, variable message
contains "Hello, World".
Console.WriteLine(message); // Prints Hello, World
Reference - MSDN
override
is a C++11 keyword which means that a method is an "override" from a method from a base class. Consider this example:
class Foo
{
public:
virtual void func1();
}
class Bar : public Foo
{
public:
void func1() override;
}
If B::func1()
signature doesn't equal A::func1()
signature a compilation error will be generated because B::func1()
does not override A::func1()
, it will define a new method called func1()
instead.
It might be not direct solution, but I've created a lib that allows you to use 3 fingers touch instead of shake to open dev menu, when in development mode
https://github.com/pie6k/react-native-dev-menu-on-touch
You only have to wrap your app inside:
import DevMenuOnTouch from 'react-native-dev-menu-on-touch'; // or: import { DevMenuOnTouch } from 'react-native-dev-menu-on-touch'
class YourRootApp extends Component {
render() {
return (
<DevMenuOnTouch>
<YourApp />
</DevMenuOnTouch>
);
}
}
It's really useful when you have to debug on real device and you have co-workers sitting next to you.
As usual, create an SSH key and paste the public key to GitHub. Add the private key to ssh-agent. (I assume this is what you have done.)
To check everything is correct, use ssh -T [email protected]
Next, don't forget to modify the remote point as follows:
git remote set-url origin [email protected]:username/your-repository.git
Make two static cultures, one for comma and one for point.
var commaCulture = new CultureInfo("en")
{
NumberFormat =
{
NumberDecimalSeparator = ","
}
};
var pointCulture = new CultureInfo("en")
{
NumberFormat =
{
NumberDecimalSeparator = "."
}
};
Then use each one respectively, depending on the input (using a function):
public double ConvertToDouble(string input)
{
input = input.Trim();
if (input == "0") {
return 0;
}
if (input.Contains(",") && input.Split(',').Length == 2)
{
return Convert.ToDouble(input, commaCulture);
}
if (input.Contains(".") && input.Split('.').Length == 2)
{
return Convert.ToDouble(input, pointCulture);
}
throw new Exception("Invalid input!");
}
Then loop through your arrays
var strings = new List<string> {"0,12", "0.122", "1,23", "00,0", "0.00", "12.5000", "0.002", "0,001"};
var doubles = new List<double>();
foreach (var value in strings) {
doubles.Add(ConvertToDouble(value));
}
This should work even though the host environment and culture changes.
In cases where you are hosting a Wordpress site on Linux and have server access you can save some headaches by installing msmtp which allows you to send via smtp from the standard php mail() function. msmtp is a simpler alternative to postfix which requires a bit more configuration.
Here are the steps:
Install msmtp
sudo apt-get install msmtp-mta ca-certificates
Create a new configuration file:
sudo nano /etc/msmtprc
...with the following configuration information:
# Set defaults.
defaults
# Enable or disable TLS/SSL encryption.
tls on
tls_starttls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
# Set up a default account's settings.
account default
host <smtp.example.net>
port 587
auth on
user <[email protected]>
password <password>
from <[email protected]>
syslog LOG_MAIL
You need to replace the configuration data represented by everything within "<" and ">" (inclusive, remove these). For host/username/password, use your normal credentials for sending mail through your mail provider.
Tell PHP to use it
sudo nano /etc/php5/apache2/php.ini
Add this single line:
sendmail_path = /usr/bin/msmtp -t
Complete documention can be found here:
$(document).on('click', 'selector', handler);
Where click
is an event name, and handler
is an event handler, like reference to a function or anonymous function function() {}
PS: if you know the particular node you're adding dynamic elements to - you could specify it instead of document
.
This is not the exact answer, but this might be helpful for the people looking to solve some problem with the approach of ordering row before group by in mysql.
I came to this thread, when I wanted to find the latest row(which is order by date desc
but get the only one result for a particular column type, which is group by column name
).
One other approach to solve such problem is to make use of aggregation.
So, we can let the query run as usual, which sorted asc and introduce new field as max(doc) as latest_doc
, which will give the latest date, with grouped by the same column.
Suppose, you want to find the data of a particular column now and max aggregation cannot be done.
In general, to finding the data of a particular column, you can make use of GROUP_CONCAT aggregator
, with some unique separator which can't be present in that column, like GROUP_CONCAT(string SEPARATOR ' ') as new_column
, and while you're accessing it, you can split/explode the new_column field.
Again, this might not sound to everyone. I did it, and liked it as well because I had written few functions and I couldn't run subqueries. I am working on codeigniter framework for php.
Not sure of the complexity as well, may be someone can put some light on that.
Regards :)
Sometimes I'm shelled into a remote box where my plugins and .vimrc cannot help me, or sometimes NerdCommenter gets it wrong (eg JavaScript embedded inside HTML).
In these cases a low-tech alternative is the built-in norm
command, which just runs any arbitrary vim commands at each line in your specified range. For example:
Commenting with #
:
1. visually select the text rows (using V as usual)
2. :norm i#
This inserts "#" at the start of each line. Note that when you type : the range will be filled in, so it will really look like :'<,'>norm i#
Uncommenting #
:
1. visually select the text as before (or type gv to re-select the previous selection)
2. :norm x
This deletes the first character of each line. If I had used a 2-char comment such as // then I'd simply do :norm xx
to delete both chars.
If the comments are indented as in the OP's question, then you can anchor your deletion like this:
:norm ^x
which means "go to the first non-space character, then delete one character". Note that unlike block selection, this technique works even if the comments have uneven indentation!
Note: Since norm
is literally just executing regular vim commands, you're not limited to comments, you could also do some complex editing to each line. If you need the escape character as part of your command sequence, type ctrl-v then hit the escape key (or even easier, just record a quick macro and then use norm to execute that macro on each line).
Note 2: You could of course also add a mapping if you find yourself using norm
a lot. Eg putting the following line in ~/.vimrc lets you type ctrl-n
instead of :norm
after making your visual selection
vnoremap <C-n> :norm
Note 3: Bare-bones vim sometimes doesn't have the norm
command compiled into it, so be sure to use the beefed up version, ie typically /usr/bin/vim, not /bin/vi
(Thanks to @Manbroski and @rakslice for improvements incorporated into this answer)
To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm.dll
, please install or use the JRE or JDK that contains these missing components.
Follow these steps:
Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)
After that, go to C:/Program files/java/jre7/bin
Here, create an folder called Server
Now go into the C:/Program files/java/jre7/bin/client
folder
Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server
folder
If you prefer to use a step by step approach you could consider a solution like follows
import numpy as np
import matplotlib.pyplot as plt
mean = 0; std = 1; variance = np.square(std)
x = np.arange(-5,5,.01)
f = np.exp(-np.square(x-mean)/2*variance)/(np.sqrt(2*np.pi*variance))
plt.plot(x,f)
plt.ylabel('gaussian distribution')
plt.show()
I realize I am a little late here, (5 years or so), but I think there is a better answer than the accepted one as follows:
$("#addComment").click(function() {
if(typeof TinyMCE === "undefined") {
$.ajax({
url: "tinymce.js",
dataType: "script",
cache: true,
success: function() {
TinyMCE.init();
}
});
}
});
The getScript()
function actually prevents browser caching. If you run a trace you will see the script is loaded with a URL that includes a timestamp parameter:
http://www.yoursite.com/js/tinymce.js?_=1399055841840
If a user clicks the #addComment
link multiple times, tinymce.js
will be re-loaded from a differently timestampped URL. This defeats the purpose of browser caching.
===
Alternatively, in the getScript()
documentation there is a some sample code that demonstrates how to enable caching by creating a custom cachedScript()
function as follows:
jQuery.cachedScript = function( url, options ) {
// Allow user to set any option except for dataType, cache, and url
options = $.extend( options || {}, {
dataType: "script",
cache: true,
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax( options );
};
// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
console.log( textStatus );
});
===
Or, if you want to disable caching globally, you can do so using ajaxSetup()
as follows:
$.ajaxSetup({
cache: true
});
Node has builtin support for gzip and deflate via the zlib module:
var zlib = require('zlib');
zlib.gunzip(gzipBuffer, function(err, result) {
if(err) return console.error(err);
console.log(result);
});
Edit: You can even pipe
the data directly through e.g. Gunzip
(using request):
var request = require('request'),
zlib = require('zlib'),
fs = require('fs'),
out = fs.createWriteStream('out');
// Fetch http://example.com/foo.gz, gunzip it and store the results in 'out'
request('http://example.com/foo.gz').pipe(zlib.createGunzip()).pipe(out);
For tar archives, there is Isaacs' tar module, which is used by npm.
Edit 2: Updated answer as zlib
doesn't support the zip
format. This will only work for gzip
.
Place this at the top of your script. It will cause the script to prompt the user for a password. The resulting password can then be used elsewhere in your script via $pw.
Param(
[Parameter(Mandatory=$true, Position=0, HelpMessage="Password?")]
[SecureString]$password
)
$pw = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
If you want to debug and see the value of the password you just read, use:
write-host $pw
Be aware that the line-height
approach fails if you have a long sentence in the span
which breaks the line because there's not enough space. In this case, you would have two lines with a gap with the height of the N pixels specified in the property.
I stuck into it when I wanted to show an image with vertically centered text on its right side which works in a responsive web application. As a base I use the approach suggested by Eric Nickus and Felipe Tadeo.
If you want to achieve:
and this:
.container {_x000D_
background: url( "https://i.imgur.com/tAlPtC4.jpg" ) no-repeat;_x000D_
display: inline-block;_x000D_
background-size: 40px 40px; /* image's size */_x000D_
height: 40px; /* image's height */_x000D_
padding-left: 50px; /* image's width plus 10 px (margin between text and image) */_x000D_
}_x000D_
_x000D_
.container span {_x000D_
height: 40px; /* image's height */_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<span class="container">_x000D_
<span>This is a centered sentence next to an image</span>_x000D_
</span>
_x000D_
This Worked for me:
$ sudo easy_install pip
$ sudo easy_install --upgrade six
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/tensorflow-0.9.0-py2-none-any.whl
$ sudo pip install --upgrade $TF_BINARY_URL