Just Add HttpClientModule
in 'imports' array of app.module.ts
file.
...
import {HttpClientModule} from '@angular/common/http'; // add this line
@NgModule({
declarations: [
AppComponent,
HeaderComponent
],
imports: [
BrowserModule,
HttpClientModule, //add this line
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
and then you can use HttpClient
in your project through constructor injection
import {HttpClient} from '@angular/common/http';
export class Services{
constructor(private http: HttpClient) {}
.NET Core is a free and open-source, managed computer software framework for Windows, Linux, and macOS operating systems. It is an open source, cross platform successor to .NET Framework.
.NET Core applications are supported on Windows, Linux, and macOS. In a nutshell .NET Core is similar to .NET framework, but it is cross-platform, i.e., it allows the .NET applications to run on Windows, Linux and MacOS. .NET framework applications can only run on the Windows system. So the basic difference between .NET framework and .NET core is that .NET Core is cross platform and .NET framework only runs on Windows.
Furthermore, .NET Core has built-in dependency injection by Microsoft and you do not have to use third-party software/DLL files for dependency injection.
To do this task download.js library can be used. Here is an example from library docs:
download("data:image/gif;base64,R0lGODlhRgAVAIcAAOfn5+/v7/f39////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////yH5BAAAAP8ALAAAAABGABUAAAj/AAEIHAgggMGDCAkSRMgwgEKBDRM+LBjRoEKDAjJq1GhxIMaNGzt6DAAypMORJTmeLKhxgMuXKiGSzPgSZsaVMwXUdBmTYsudKjHuBCoAIc2hMBnqRMqz6MGjTJ0KZcrz5EyqA276xJrVKlSkWqdGLQpxKVWyW8+iJcl1LVu1XttafTs2Lla3ZqNavAo37dm9X4eGFQtWKt+6T+8aDkxUqWKjeQUvfvw0MtHJcCtTJiwZsmLMiD9uplvY82jLNW9qzsy58WrWpDu/Lp0YNmPXrVMvRm3T6GneSX3bBt5VeOjDemfLFv1XOW7kncvKdZi7t/S7e2M3LkscLcvH3LF7HwSuVeZtjuPPe2d+GefPrD1RpnS6MGdJkebn4/+oMSAAOw==", "dlDataUrlBin.gif", "image/gif");
you can save the xlsx file as a tab-delimited text file and do
BULK INSERT TableName
FROM 'C:\SomeDirectory\my table.txt'
WITH
(
FIELDTERMINATOR = '\t',
ROWTERMINATOR = '\n'
)
GO
What you can do to resolve your conflict is
svn resolve --accept working -R <path>
where <path>
is where you have your conflict (can be the root of your repo).
Explanations:
resolve
asks svn
to resolve the conflictaccept working
specifies to keep your working files-R
stands for recursiveHope this helps.
EDIT:
To sum up what was said in the comments below:
<path>
should be the directory in conflict (C:\DevBranch\
in the case of the OP)svn switch
commandSwitch working copy to new branch/tag
option at branch creationi wrote a small win32 (WinXP 32bit testet) stupid cmd (commandline) script which looks for all java versions in program files and adds a cert to them. The Password needs to be the default "changeit" or change it yourself in the script :-)
@echo off
for /F %%d in ('dir /B %ProgramFiles%\java') do (
%ProgramFiles%\Java\%%d\bin\keytool.exe -import -noprompt -trustcacerts -file some-exported-cert-saved-as.crt -keystore %ProgramFiles%\Java\%%d\lib\security\cacerts -storepass changeit
)
pause
Your Code is Fine just you need to place it inside the ready function.
$(document).ready( function() {
$("#cpa-form").submit(function(e){
e.preventDefault();
});
}
Adding the following to my stored procedure, solved the time out error by me:
SET NOCOUNT ON;
SET ARITHABORT ON;
How about Application.EnableCancelKey - Use the Esc button
On Error GoTo handleCancel
Application.EnableCancelKey = xlErrorHandler
MsgBox "This may take a long time: press ESC to cancel"
For x = 1 To 1000000 ' Do something 1,000,000 times (long!)
' do something here
Next x
handleCancel:
If Err = 18 Then
MsgBox "You cancelled"
End If
Snippet from http://msdn.microsoft.com/en-us/library/aa214566(office.11).aspx
In my case, this error was caused by renaming my client machine. I used a new name longer than 13 characters (despite the warning), which resulted in the NETBIOS name being truncated and being different from the full machine name. Once I re-renamed the client to a shorter name, the error went away.
I have been having issues connecting to a Gitolite repo using SSH from Windows and it turned out that my problem was PLINK! It kept asking me for a password, but the ssh gitolite@[host] would return the repo list fine.
Check your environment variable: GIT_SSH. If it is set to Plink, then try it without any value ("set GIT_SSH=") and see if that works.
Based on the plethora of other answers, I came up with this in C#:
/// <param name="rotation">The number of rotations (if negative, the <see cref="Matrix{TValue}"/> is rotated counterclockwise;
/// otherwise, it's rotated clockwise). A single (positive) rotation is equivalent to 90° or -270°; a single (negative) rotation is
/// equivalent to -90° or 270°. Matrices may be rotated by 90°, 180°, or 270° only (or multiples thereof).</param>
/// <returns></returns>
public Matrix<TValue> Rotate(int rotation)
{
var result = default(Matrix<TValue>);
//This normalizes the requested rotation (for instance, if 10 is specified, the rotation is actually just +-2 or +-180°, but all
//correspond to the same rotation).
var d = rotation.ToDouble() / 4d;
d = d - (int)d;
var degree = (d - 1d) * 4d;
//This gets the type of rotation to make; there are a total of four unique rotations possible (0°, 90°, 180°, and 270°).
//Each correspond to 0, 1, 2, and 3, respectively (or 0, -1, -2, and -3, if in the other direction). Since
//1 is equivalent to -3 and so forth, we combine both cases into one.
switch (degree)
{
case -3:
case +1:
degree = 3;
break;
case -2:
case +2:
degree = 2;
break;
case -1:
case +3:
degree = 1;
break;
case -4:
case 0:
case +4:
degree = 0;
break;
}
switch (degree)
{
//The rotation is 0, +-180°
case 0:
case 2:
result = new TValue[Rows, Columns];
break;
//The rotation is +-90°
case 1:
case 3:
result = new TValue[Columns, Rows];
break;
}
for (uint i = 0; i < Columns; ++i)
{
for (uint j = 0; j < Rows; ++j)
{
switch (degree)
{
//If rotation is 0°
case 0:
result._values[j][i] = _values[j][i];
break;
//If rotation is -90°
case 1:
//Transpose, then reverse each column OR reverse each row, then transpose
result._values[i][j] = _values[j][Columns - i - 1];
break;
//If rotation is +-180°
case 2:
//Reverse each column, then reverse each row
result._values[(Rows - 1) - j][(Columns - 1) - i] = _values[j][i];
break;
//If rotation is +90°
case 3:
//Transpose, then reverse each row
result._values[i][j] = _values[Rows - j - 1][i];
break;
}
}
}
return result;
}
Where _values
corresponds to a private two-dimensional array defined by Matrix<TValue>
(in the form of [][]
). result = new TValue[Columns, Rows]
is possible via implicit operator overload and converts the two-dimensional array to Matrix<TValue>
.
The two properties Columns
and Rows
are public properties that get the number of columns and rows of the current instance:
public uint Columns
=> (uint)_values[0].Length;
public uint Rows
=> (uint)_values.Length;
Assuming, of course, that you prefer to work with unsigned indices ;-)
All of this allows you to specify how many times it should be rotated and whether it should be rotated left (if less than zero) or right (if greater than zero). You can improve this to check for rotation in actual degrees, but then you'd want to throw an exception if the value isn't a multiple of 90. With that input, you could change the method accordingly:
public Matrix<TValue> Rotate(int rotation)
{
var _rotation = (double)rotation / 90d;
if (_rotation - Math.Floor(_rotation) > 0)
{
throw new NotSupportedException("A matrix may only be rotated by multiples of 90.").
}
rotation = (int)_rotation;
...
}
Since a degree is more accurately expressed by double
than int
, but a matrix can only rotate in multiples of 90, it is far more intuitive to make the argument correspond to something else that can be accurately represented by the data structure used. int
is perfect because it can tell you how many times to rotate it up to a certain unit (90) as well as the direction. double
may very well be able to tell you that also, but it also includes values that aren't supported by this operation (which is inherently counter-intuitive).
If you are triggering the change with JS, let's say on click, there is a nice workaround.
You see, the problem happens because the animation is ignored on display:none
element but browser applies all the changes at once and the element is never display:block
while not animated at the same time.
The trick is to ask the browser to render the frame after changing the visibility but before triggering the animation.
Here is a JQuery example:
$('.child').css({"display":"block"});
//now ask the browser what is the value of the display property
$('.child').css("display"); //this will trigger the browser to apply the change. this costs one frame render
//now a change to opacity will trigger the animation
$('.child').css("opacity":100);
To add to @BrianBeech's answer, this is even more trimmed down in java 8:
jdbcTemplate.query("select string1,string2 from table where x=1", (ResultSet rs) -> {
HashMap<String,String> results = new HashMap<>();
while (rs.next()) {
results.put(rs.getString("string1"), rs.getString("string2"));
}
return results;
});
If you need more control (perhaps you need to state the table name) you can also do the following:
Model.joins(:another_model_table_name)
.where('another_model_table_name.id IN (?)', your_id_array)
Check for the existence by retrieving its object_id:
if object_id('tempdb..##clients_keyword') is not null
drop table ##clients_keyword
An independent parent is the best practice for sharing configuration and options across otherwise uncoupled components. Apache has a parent pom project to share legal notices and some common packaging options.
If your top-level project has real work in it, such as aggregating javadoc or packaging a release, then you will have conflicts between the settings needed to do that work and the settings you want to share out via parent. A parent-only project avoids that.
A common pattern (ignoring #1 for the moment) is have the projects-with-code use a parent project as their parent, and have it use the top-level as a parent. This allows core things to be shared by all, but avoids the problem described in #2.
The site plugin will get very confused if the parent structure is not the same as the directory structure. If you want to build an aggregate site, you'll need to do some fiddling to get around this.
Apache CXF is an example the pattern in #2.
You could create a list of Object like List<Object> list = new ArrayList<Object>()
. As all classes implementation extends implicit or explicit from java.lang.Object
class, this list can hold any object, including instances of Employee
, Integer
, String
etc.
When you retrieve an element from this list, you will be retrieving an Object
and no longer an Employee
, meaning you need to perform a explicit cast in this case as follows:
List<Object> list = new ArrayList<Object>();
list.add("String");
list.add(Integer.valueOf(1));
list.add(new Employee());
Object retrievedObject = list.get(2);
Employee employee = (Employee)list.get(2); // explicit cast
If you use Db Browser for sqlite ,then it will be easy for you to modify the table. you can add foreign key in existing table without writing a query.
that's it. You successfully added foreign key in existing table.
I know the question is really old, but with generics one can add a more generalized method with will work for all types.
public static <T> T getValueOrDefault(T value, T defaultValue) {
return value == null ? defaultValue : value;
}
The standard streams have a boolalpha
flag that determines what gets displayed -- when it's false, they'll display as 0
and 1
. When it's true, they'll display as false
and true
.
There's also an std::boolalpha
manipulator to set the flag, so this:
#include <iostream>
#include <iomanip>
int main() {
std::cout<<false<<"\n";
std::cout << std::boolalpha;
std::cout<<false<<"\n";
return 0;
}
...produces output like:
0
false
For what it's worth, the actual word produced when boolalpha
is set to true is localized--that is, <locale>
has a num_put
category that handles numeric conversions, so if you imbue a stream with the right locale, it can/will print out true
and false
as they're represented in that locale. For example,
#include <iostream>
#include <iomanip>
#include <locale>
int main() {
std::cout.imbue(std::locale("fr"));
std::cout << false << "\n";
std::cout << std::boolalpha;
std::cout << false << "\n";
return 0;
}
...and at least in theory (assuming your compiler/standard library accept "fr" as an identifier for "French") it might print out faux
instead of false
. I should add, however, that real support for this is uneven at best--even the Dinkumware/Microsoft library (usually quite good in this respect) prints false
for every language I've checked.
The names that get used are defined in a numpunct
facet though, so if you really want them to print out correctly for particular language, you can create a numpunct
facet to do that. For example, one that (I believe) is at least reasonably accurate for French would look like this:
#include <array>
#include <string>
#include <locale>
#include <ios>
#include <iostream>
class my_fr : public std::numpunct< char > {
protected:
char do_decimal_point() const { return ','; }
char do_thousands_sep() const { return '.'; }
std::string do_grouping() const { return "\3"; }
std::string do_truename() const { return "vrai"; }
std::string do_falsename() const { return "faux"; }
};
int main() {
std::cout.imbue(std::locale(std::locale(), new my_fr));
std::cout << false << "\n";
std::cout << std::boolalpha;
std::cout << false << "\n";
return 0;
}
And the result is (as you'd probably expect):
0
faux
It's been a long time since this question was asked but if someone is still interested - I recently ran into similar icons. I was compiling a C#.net project using VS 2008. I found VS could not locate the assemblies for those references. When I double clicked VS refreshed the references and removed the icons on some of those[EDIT: which it could NOW locate]. For remaining references, I had to compile the respective assemblies.
Might be worth it to add something like the free Papertrail plan to your app. Zero configuration, and you get 7 days worth of logging data up to 10MB/day, and can search back through 2 days of logs.
This very annoying error so what I did: Under Windows:
Edit system environment variables - > Edit Variables -> New
then fill
MAVEN_OPTS
-Xms512m -Xmx2048m -XX:MaxPermSize=512m
Then restart the console and run the maven build again. No more Maven space/perm size problems.
Here you can see the difference between the way that deceze offered comparing to the simple array_values
approach:
The Array:
$array['a'][0] = array('x' => 1, 'y' => 2, 'z' => 3);
$array['a'][5] = array('x' => 4, 'y' => 5, 'z' => 6);
$array['b'][1] = array('x' => 7, 'y' => 8, 'z' => 9);
$array['b'][7] = array('x' => 10, 'y' => 11, 'z' => 12);
In deceze
way, here is your output:
$array = array_map('array_values', $array);
print_r($array);
/* Output */
Array
(
[a] => Array
(
[0] => Array
(
[x] => 1
[y] => 2
[z] => 3
)
[1] => Array
(
[x] => 4
[y] => 5
[z] => 6
)
)
[b] => Array
(
[0] => Array
(
[x] => 7
[y] => 8
[z] => 9
)
[1] => Array
(
[x] => 10
[y] => 11
[z] => 12
)
)
)
And here is your output if you only use array_values
function:
$array = array_values($array);
print_r($array);
/* Output */
Array
(
[0] => Array
(
[0] => Array
(
[x] => 1
[y] => 2
[z] => 3
)
[5] => Array
(
[x] => 4
[y] => 5
[z] => 6
)
)
[1] => Array
(
[1] => Array
(
[x] => 7
[y] => 8
[z] => 9
)
[7] => Array
(
[x] => 10
[y] => 11
[z] => 12
)
)
)
following this link:
How To: Eclipse Maven install build jar with dependencies
i found out that this is not workable solution because the class loader doesn't load jars from within jars, so i think that i will unpack the dependencies inside the jar.
Best way to do what you want is to add another server block:
server {
#implemented by default, change if you need different ip or port
#listen *:80 | *:8000;
server_name test.com;
return 301 $scheme://www.test.com$request_uri;
}
And edit your main server block server_name variable as following:
server_name www.test.com;
Important: New server
block is the right way to do this, if
is evil. You must use locations and servers instead of if
if it's possible. Rewrite
is sometimes evil too, so replaced it with return
.
Just to extend on the WiredPrairie's answer a little, a mini component that can be opened and closed.
Can be used like:
<Pretty data={this.state.data}/>
export default React.createClass({
style: {
backgroundColor: '#1f4662',
color: '#fff',
fontSize: '12px',
},
headerStyle: {
backgroundColor: '#193549',
padding: '5px 10px',
fontFamily: 'monospace',
color: '#ffc600',
},
preStyle: {
display: 'block',
padding: '10px 30px',
margin: '0',
overflow: 'scroll',
},
getInitialState() {
return {
show: true,
};
},
toggle() {
this.setState({
show: !this.state.show,
});
},
render() {
return (
<div style={this.style}>
<div style={this.headerStyle} onClick={ this.toggle }>
<strong>Pretty Debug</strong>
</div>
{( this.state.show ?
<pre style={this.preStyle}>
{JSON.stringify(this.props.data, null, 2) }
</pre> : false )}
</div>
);
}
});
A more modern approach (now that createClass is on the way out)
import styles from './DebugPrint.css'
import autoBind from 'react-autobind'
import classNames from 'classnames'
import React from 'react'
export default class DebugPrint extends React.PureComponent {
constructor(props) {
super(props)
autoBind(this)
this.state = {
show: false,
}
}
toggle() {
this.setState({
show: !this.state.show,
});
}
render() {
return (
<div style={styles.root}>
<div style={styles.header} onClick={this.toggle}>
<strong>Debug</strong>
</div>
{this.state.show
? (
<pre style={styles.pre}>
{JSON.stringify(this.props.data, null, 2) }
</pre>
)
: null
}
</div>
)
}
}
And your style file
.root { backgroundColor: '#1f4662'; color: '#fff'; fontSize: '12px'; }
.header { backgroundColor: '#193549'; padding: '5px 10px'; fontFamily: 'monospace'; color: '#ffc600'; }
.pre { display: 'block'; padding: '10px 30px'; margin: '0'; overflow: 'scroll'; }
When you did:
(function (msg){alert(msg)});
('SO');
You ended the function before ('SO')
because of the semicolon. If you just write:
(function (msg){alert(msg)})
('SO');
It will work.
Working example: http://jsfiddle.net/oliverni/dbVjg/
You can also use percentages, and/or specify in the column headers:
<table width="300">
<tr>
<th width="20%">Column 1</th>
<th width="20%">Column 2</th>
<th width="20%">Column 3</th>
<th width="20%">Column 4</th>
<th width="20%">Column 5</th>
</tr>
<tr>
<!--- row data -->
</tr>
</table>
The bonus with percentages is lower code maintenance: you can change your table width without having to re-specify the column widths.
Caveat: It is my understanding that table width specified in pixels isn't supported in HTML 5; you need to use CSS instead.
You could use git remote like:
git fetch origin
and then setup a local branch to track the remote branch like below:
git branch --track [local-branch-name] origin/remote-branch-name
You would now have the contents of the remote github branch in local-branch-name.
You could switch to that local-branch-name and start work:
git checkout [local-branch-name]
I use this function to indent my output (for example to print a tree structure). The indent
is the number of spaces before the string.
void print_with_indent(int indent, char * string)
{
printf("%*s%s", indent, "", string);
}
use this artisan command for create shortcut in public folder
php artisan storage:link
Than you will able to access posted img or file
Step 1: first we have to add permissions in manifest file like
<uses-permission android:name="android.permission.RECEIVE_SMS" android:protectionLevel="signature" />
<uses-permission android:name="android.permission.READ_SMS" />
Step 2: then add service sms receiver class for receiving sms
<receiver android:name="com.aquadeals.seller.services.SmsReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
Step 3: Add run time permission
private boolean checkAndRequestPermissions()
{
int sms = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS);
if (sms != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS}, REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
Step 4: Add this classes in your app and test Interface class
public interface SmsListener {
public void messageReceived(String messageText);
}
SmsReceiver.java
public class SmsReceiver extends BroadcastReceiver {
private static SmsListener mListener;
public Pattern p = Pattern.compile("(|^)\\d{6}");
@Override
public void onReceive(Context context, Intent intent) {
Bundle data = intent.getExtras();
Object[] pdus = (Object[]) data.get("pdus");
for(int i=0;i<pdus.length;i++)
{
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
String sender = smsMessage.getDisplayOriginatingAddress();
String phoneNumber = smsMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber ;
String messageBody = smsMessage.getMessageBody();
try{
if(messageBody!=null){
Matcher m = p.matcher(messageBody);
if(m.find()) {
mListener.messageReceived(m.group(0));
}
}
}
catch(Exception e){}
}
}
public static void bindListener(SmsListener listener) {
mListener = listener;
}
}
Why are you including the getClassLoader step? If you say "this.getClass().getResource()" you should be getting resources relative to the calling class. I've never used ClassLoader.getResource(), though from a quick look at the Java Docs it sounds like that will get you the first resource of that name found in any current classpath.
var currentDate = moment('2015-10-30');
var futureMonth = moment(currentDate).add(1, 'M');
var futureMonthEnd = moment(futureMonth).endOf('month');
if(currentDate.date() != futureMonth.date() && futureMonth.isSame(futureMonthEnd.format('YYYY-MM-DD'))) {
futureMonth = futureMonth.add(1, 'd');
}
console.log(currentDate);
console.log(futureMonth);
EDIT
moment.addRealMonth = function addRealMonth(d) {
var fm = moment(d).add(1, 'M');
var fmEnd = moment(fm).endOf('month');
return d.date() != fm.date() && fm.isSame(fmEnd.format('YYYY-MM-DD')) ? fm.add(1, 'd') : fm;
}
var nextMonth = moment.addRealMonth(moment());
try this
function demoShow() {
document.getElementById("but1").style.display="none";
}
<input type="button" value="click me" onclick="demoShow()" id="but" />
<input type="button" value="hide" id="but1" />
Just for contrast, I like using the object_id function as shown below. It's a bit easier to read, and you don't have to worry about sys.objects vs. sysobjects vs. sys.all_objects vs. sys.tables. Basic form:
IF object_id('MyTable') is not null
PRINT 'Present!'
ELSE
PRINT 'Not accounted for'
Of course this will show as "Present" if there is any object present with that name. If you want to check just tables, you'd need:
IF object_id('MyTable', 'U') is not null
PRINT 'Present!'
ELSE
PRINT 'Not accounted for'
It works for temp tables as well:
IF object_id('tempdb.dbo.#MyTable') is not null
PRINT 'Present!'
ELSE
PRINT 'Not accounted for'
The "traditional" Windows equivalent would be the Protected Storage subsystem, used by IE (pre IE 7), Outlook Express, and a few other programs. I believe it's encrypted with your login password, which prevents some offline attacks, but once you're logged in, any program that wants to can read it. (See, for example, NirSoft's Protected Storage PassView.)
Windows also provides the CryptoAPI and Data Protection API that might help. Again, though, I don't think that Windows does anything to prevent processes running under the same account from seeing each other's passwords.
It looks like the book Mechanics of User Identification and Authentication provides more details on all of these.
Eclipse (via its Secure Storage feature) implements something like this, if you're interested in seeing how other software does it.
select count(*),sum(decode(status, 'ACTIVE',1,0)) from v$session where type= 'USER'
See http://angular-ui.github.io/bootstrap/#/collapse
function CollapseDemoCtrl($scope) {
$scope.isCollapsed = false;
}
<div ng-controller="CollapseDemoCtrl">
<button class="btn" ng-click="isCollapsed = !isCollapsed">Toggle collapse</button>
<hr>
<div collapse="isCollapsed">
<div class="well well-large">Some content</div>
</div>
</div>
I had same issue when first start Android Studio in Window 10, with java jdk 1.8.0_66. The solution that worked is:
Step 1: Close Android Studio
Step 2: Delete Folder C:\Users\Anna\.gradle (Anna is my username)
Step 3: Open Android Studio as Administrator
Step 4: If you are currently in an opened project, close current project by select File > Close Project.
Step 5: Now you seeing this Quick Start GUI:
Wait for gradle to build again (it would download all the dependency in your build.gradle for every module in your project)
If it has not worked till now, you could restart your computer. Do step 1 again.
This happens sometime when I changed Android Studio version or recently upgrade Window. Hope that helps !
Do not do it. I might want to run my car on monkey blood. I have my reasons, but sometimes it's better to stick with using things the way they were designed even if it doesn't "absolutely perfectly" match the exact look you are driving for.
To back up my argument I submit the following.
onclick="location.href"
model. (This is a real-life production example from my predecessor) This can make users hesitant to click on the link, since they have no idea where it is taking them, for starters.You are also making Search engine optimization more difficult IMO as well as making the debugging and reading of your code/HTML more complex. A submit button should submit a form. Why should you(the development community) try to create a non-standard UI?
Use this query:
UPDATE `table` SET date_date=now();
Sample code can be:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("UPDATE `table` SET date_date=now()");
mysql_close($con);
?>
I wrote my thoughts of static classes in an earlier Stack Overflow answer: Class with single method -- best approach?
I used to love utility classes filled up with static methods. They made a great consolidation of helper methods that would otherwise lie around causing redundancy and maintenance hell. They're very easy to use, no instantiation, no disposal, just fire'n'forget. I guess this was my first unwitting attempt at creating a service-oriented architecture - lots of stateless services that just did their job and nothing else. As a system grows however, dragons be coming.
Polymorphism
Say we have the method UtilityClass.SomeMethod that happily buzzes along. Suddenly we need to change the functionality slightly. Most of the functionality is the same, but we have to change a couple of parts nonetheless. Had it not been a static method, we could make a derivate class and change the method contents as needed. As it's a static method, we can't. Sure, if we just need to add functionality either before or after the old method, we can create a new class and call the old one inside of it - but that's just gross.
Interface woes
Static methods cannot be defined through interfaces for logic reasons. And since we can't override static methods, static classes are useless when we need to pass them around by their interface. This renders us unable to use static classes as part of a strategy pattern. We might patch some issues up by passing delegates instead of interfaces.
Testing
This basically goes hand in hand with the interface woes mentioned above. As our ability of interchanging implementations is very limited, we'll also have trouble replacing production code with test code. Again, we can wrap them up, but it'll require us to change large parts of our code just to be able to accept wrappers instead of the actual objects.
Fosters blobs
As static methods are usually used as utility methods and utility methods usually will have different purposes, we'll quickly end up with a large class filled up with non-coherent functionality - ideally, each class should have a single purpose within the system. I'd much rather have a five times the classes as long as their purposes are well defined.
Parameter creep
To begin with, that little cute and innocent static method might take a single parameter. As functionality grows, a couple of new parameters are added. Soon further parameters are added that are optional, so we create overloads of the method (or just add default values, in languages that support them). Before long, we have a method that takes 10 parameters. Only the first three are really required, parameters 4-7 are optional. But if parameter 6 is specified, 7-9 are required to be filled in as well... Had we created a class with the single purpose of doing what this static method did, we could solve this by taking in the required parameters in the constructor, and allowing the user to set optional values through properties, or methods to set multiple interdependent values at the same time. Also, if a method has grown to this amount of complexity, it most likely needs to be in its own class anyway.
Demanding consumers to create an instance of classes for no reason
One of the most common arguments is: Why demand that consumers of our class create an instance for invoking this single method, while having no use for the instance afterwards? Creating an instance of a class is a very very cheap operation in most languages, so speed is not an issue. Adding an extra line of code to the consumer is a low cost for laying the foundation of a much more maintainable solution in the future. And finally, if you want to avoid creating instances, simply create a singleton wrapper of your class that allows for easy reuse - although this does make the requirement that your class is stateless. If it's not stateless, you can still create static wrapper methods that handle everything, while still giving you all the benefits in the long run. Finally, you could also make a class that hides the instantiation as if it was a singleton: MyWrapper.Instance is a property that just returns new MyClass();
Only a Sith deals in absolutes
Of course, there are exceptions to my dislike of static methods. True utility classes that do not pose any risk to bloat are excellent cases for static methods - System.Convert as an example. If your project is a one-off with no requirements for future maintenance, the overall architecture really isn't very important - static or non static, doesn't really matter - development speed does, however.
Standards, standards, standards!
Using instance methods does not inhibit you from also using static methods, and vice versa. As long as there's reasoning behind the differentiation and it's standardised. There's nothing worse than looking over a business layer sprawling with different implementation methods.
the diff
method returns the difference in milliseconds. Instantiating moment(diff)
isn't meaningful.
You can define a variable :
var dayInMilliseconds = 1000 * 60 * 60 * 24;
and then use it like so :
diff / dayInMilliseconds // --> 15
Edit
actually, this is built into the diff
method, dubes' answer is better
I wouldn't use HttpListener or something like that, in that way you'll come across so many issues.
Most importantly it'll be a huge pain to support:
What you need to do is:
I wrote 2 different HTTP proxies in .NET with different requirements and I can tell you that this is the best way to do it.
Mentalis doing this, but their code is "delegate spaghetti", worse than GoTo :)
You only need BOOST_ROOT
, but you're going to want to disable searching the system for your local Boost if you have multiple installations or cross-compiling for iOS or Android. In which case add Boost_NO_SYSTEM_PATHS
is set to false.
set( BOOST_ROOT "" CACHE PATH "Boost library path" )
set( Boost_NO_SYSTEM_PATHS on CACHE BOOL "Do not search system for Boost" )
Normally this is passed on the CMake command-line using the syntax -D<VAR>=value
.
Officially speaking the FindBoost page states these variables should be used to 'hint' the location of Boost.
This module reads hints about search locations from variables:
BOOST_ROOT - Preferred installation prefix
(or BOOSTROOT)
BOOST_INCLUDEDIR - Preferred include directory e.g. <prefix>/include
BOOST_LIBRARYDIR - Preferred library directory e.g. <prefix>/lib
Boost_NO_SYSTEM_PATHS - Set to ON to disable searching in locations not
specified by these hint variables. Default is OFF.
Boost_ADDITIONAL_VERSIONS
- List of Boost versions not known to this module
(Boost install locations may contain the version)
This makes a theoretically correct incantation:
cmake -DBoost_NO_SYSTEM_PATHS=TRUE \
-DBOOST_ROOT=/path/to/boost-dir
include( ExternalProject )
set( boost_URL "http://sourceforge.net/projects/boost/files/boost/1.63.0/boost_1_63_0.tar.bz2" )
set( boost_SHA1 "9f1dd4fa364a3e3156a77dc17aa562ef06404ff6" )
set( boost_INSTALL ${CMAKE_CURRENT_BINARY_DIR}/third_party/boost )
set( boost_INCLUDE_DIR ${boost_INSTALL}/include )
set( boost_LIB_DIR ${boost_INSTALL}/lib )
ExternalProject_Add( boost
PREFIX boost
URL ${boost_URL}
URL_HASH SHA1=${boost_SHA1}
BUILD_IN_SOURCE 1
CONFIGURE_COMMAND
./bootstrap.sh
--with-libraries=filesystem
--with-libraries=system
--with-libraries=date_time
--prefix=<INSTALL_DIR>
BUILD_COMMAND
./b2 install link=static variant=release threading=multi runtime-link=static
INSTALL_COMMAND ""
INSTALL_DIR ${boost_INSTALL} )
set( Boost_LIBRARIES
${boost_LIB_DIR}/libboost_filesystem.a
${boost_LIB_DIR}/libboost_system.a
${boost_LIB_DIR}/libboost_date_time.a )
message( STATUS "Boost static libs: " ${Boost_LIBRARIES} )
Then when you call this script you'll need to include the boost.cmake script (mine is in the a subdirectory), include the headers, indicate the dependency, and link the libraries.
include( boost )
include_directories( ${boost_INCLUDE_DIR} )
add_dependencies( MyProject boost )
target_link_libraries( MyProject
${Boost_LIBRARIES} )
This minimal CMakeLists.txt
file compiles a simple shared library:
cmake_minimum_required(VERSION 2.8)
project (test)
set(CMAKE_BUILD_TYPE Release)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
add_library(test SHARED src/test.cpp)
However, I have no experience copying files to a different destination with CMake. The file command with the COPY/INSTALL signature looks like it might be useful.
This will work for any resolution,
button{
position:absolute;
bottom: 5%;
right:20%;
}
I'm using latest TS and node (v2.6 and v8.9 respectively) and I can do:
let myMap = new Map<string, boolean>();
myMap.set("a", true);
for (let [k, v] of myMap) {
console.log(k + "=" + v);
}
are you familiar with handlers? I think it's what you are looking for. Move the restart from hadoop_master.yml
to roles/hadoop_primary/handlers/main.yml
:
- name: start hadoop jobtracker services
service: name=hadoop-0.20-mapreduce-jobtracker state=started
and now call use notify
in hadoop_master.yml
:
- name: Install the namenode and jobtracker packages
apt: name={{item}} force=yes state=latest
with_items:
- hadoop-0.20-mapreduce-jobtracker
- hadoop-hdfs-namenode
- hadoop-doc
- hue-plugins
notify: start hadoop jobtracker services
Short:
In you have this problem with a pure Web API project (and thus don't need razor), try to add it anyway, rebuild, then remove it.
Long story:
I had this problem with a brand-new pure Web API project, except that the stacktrace pointed "System.Web.Mvc" as Calling assembly (see Darin's answer).
No reference to MVC, Razor or anything like that in my project though...
I decided to add the MVC packages (AspNet.Mvc, AspNet.WebPages and AspNet.Razor) to check if there was any subsequent problem.
The WebApi app then launched perfectly fine. Then I removed the exact same packages and everything was still OK.
Hope it helps someone.
After formatting the previous answer to my own code, I have found an efficient way to copy all necessary data if you are attempting to paste the values returned via AutoFilter
to a separate sheet.
With .Range("A1:A" & LastRow)
.Autofilter Field:=1, Criteria1:="=*" & strSearch & "*"
.Offset(1,0).SpecialCells(xlCellTypeVisible).Cells.Copy
Sheets("Sheet2").activate
DestinationRange.PasteSpecial
End With
In this block, the AutoFilter
finds all of the rows that contain the value of strSearch
and filters out all of the other values. It then copies the cells (using offset in case there is a header), opens the destination sheet and pastes the values to the specified range on the destination sheet.
inputelement.onchange= inputelement.onkeyup= function isnumber(e){
e= window.event? e.srcElement: e.target;
while(e.value && parseFloat(e.value)+''!= e.value){
e.value= e.value.slice(0, -1);
}
}
l = [1,2,3,4,5]
sum = 0
for x in l:
sum = sum + x
And you can change l for any list you want.
CryptoJS is no longer supported. If you want to continue using it, you may switch to this url:
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>
The main reason to avoid using the matrix
class is that a) it's inherently 2-dimensional, and b) there's additional overhead compared to a "normal" numpy array. If all you're doing is linear algebra, then by all means, feel free to use the matrix class... Personally I find it more trouble than it's worth, though.
For arrays (prior to Python 3.5), use dot
instead of matrixmultiply
.
E.g.
import numpy as np
x = np.arange(9).reshape((3,3))
y = np.arange(3)
print np.dot(x,y)
Or in newer versions of numpy, simply use x.dot(y)
Personally, I find it much more readable than the *
operator implying matrix multiplication...
For arrays in Python 3.5, use x @ y
.
The initial problem is that the the configuration specifies a property suffix=".jsp"
so the ViewResolver implementing class will add .jsp
to the end of the view name being returned from your method.
However since you commented out the InternalResourceViewResolver
then, depending on the rest of your application configuration, there might not be any other ViewResolver registered. You might find that nothing is working now.
Since .html
files are static and do not require processing by a servlet then it is more efficient, and simpler, to use an <mvc:resources/>
mapping. This requires Spring 3.0.4+.
For example:
<mvc:resources mapping="/static/**" location="/static/" />
which would pass through all requests starting with /static/
to the webapp/static/
directory.
So by putting index.html
in webapp/static/
and using return "static/index.html";
from your method, Spring should find the view.
in Bootstrap, web inspector says the Headings are set to 'inherit'
all i needed to set my page to the new font was
div, p {font-family: Algerian}
that's in .scss
I'm not sure if you used OAuth to login to Stack Overflow, like the "Login with Google" option, but when you use this feature, Stack Overflow is simply asking Google if it knows who you are:
"Yo Google, this Vinesh fella claims that [email protected] is him, is that true?"
If you're logged in already, Google will say YES. If not, Google will say:
"Hang on a sec Stack Overflow, I'll authenticate this fella and if he can enter the right password for his Google account, then it's him".
When you enter your Google password, Google then tells Stack Overflow you are who you say you are, and Stack Overflow logs you in.
Here's where developers new to OAuth sometimes get a little confused... Google and Stack Overflow, Assembla, Vinesh's-very-cool-slick-webapp, are all different entities, and Google knows nothing about your account on Vinesh's cool webapp, and vice versa, aside from what's exposed via the API you're using to access profile information.
When your user logs out, he or she isn't logging out of Google, he/she is logging out of your app, or Stack Overflow, or Assembla, or whatever web application used Google OAuth to authenticate the user.
In fact, I can log out of all of my Google accounts and still be logged into Stack Overflow. Once your app knows who the user is, that person can log out of Google. Google is no longer needed.
With that said, what you're asking to do is log the user out of a service that really doesn't belong to you. Think about it like this: As a user, how annoyed do you think I would be if I logged into 5 different services with my Google account, then the first time I logged out of one of them, I have to login to my Gmail account again because that app developer decided that, when I log out of his application, I should also be logged out of Google? That's going to get old really fast. In short, you really don't want to do this...
With that said, if you still do want to log a user out of Google, and realize that you may very well be disrupting their workflow, you could dynamically build the logout url from one of their Google services logout button, and then invoke that using an img element or a script tag:
<script type="text/javascript"
src="https://mail.google.com/mail/u/0/?logout&hl=en" />
OR
<img src="https://mail.google.com/mail/u/0/?logout&hl=en" />
OR
window.location = "https://mail.google.com/mail/u/0/?logout&hl=en";
If you redirect your user to the logout page, or invoke it from an element that isn't cross-domain restricted, the user will be logged out of Google.
Note that this does not necessarily mean the user will be logged out of your application, only Google. :)
What's important for you to keep in mind is that, when you logout of your app, you don't need to make the user re-enter a password. That's the whole point! It authenticates against Google so the user doesn't have to enter his or her password over and over and over again in each web application he or she uses. It takes some getting used to, but know that, as long as the user is logged into Google, your app doesn't need to worry about whether or not the user is who he/she says he/she is.
I have the same implementation in a project as you do, using the Google Profile information with OAuth. I tried the very same thing you're looking to try, and it really started making people angry when they had to login to Google over and over again, so we stopped logging them out of Google. :)
In JDK7:
if ({"a", "b", "c"}.contains("a")) {
Assuming the Project Coin collections literals project goes through.
Edit: It didn't.
Use ampersand to specify the parent selector.
SCSS syntax:
p {
margin: 2em auto;
> a {
color: red;
}
&:before {
content: "";
}
&:after {
content: "* * *";
}
}
On Mac OSX, manually delete these 2 directories under your pathToPython/site-packages/ will work:
for example, to remove pyasn1, which is a distutils installed project:
To find out where is your site-packages:
python -m site
For me it was a Problem with character encoding and unix filemode running eclipse on Windows:
Just marked the complete code, cutted and pasted it back (in short: CtrlA-CtrlX-CtrlV) and everything was fine - no more "No grammar constraints..." warnings
One pitfall I ran into was a parent element having the 'overflow' attribute set to 'auto'. This negates child div elements with the page-break-inside attribute in the print version. Otherwise, page-break-inside: avoid
works fine on Chrome for me.
I found solution in this post. In my context I wish deactivate vertical scroll when I'm scrolling horizontally inside a
Like this =>
let scrollContainer = document.getElementById('scroll-container');
document.getElementById('scroll-container').addEventListener(
"wheel",
(event) => {
event.preventDefault();
scrollContainer.scrollLeft += event.deltaY;
},
{
// allow preventDefault()
passive: false
}
);
Adding username
and password
has worked for me: For e.g.
https://myUserName:myPassWord@myGitRepositoryAddress/myAuthentificationName/myRepository.git
Here my solution without going backward and without a temporary list
while (listBox1.Items.Count > 0)
{
string s = listBox1.Items[0] as string;
// do something with s
listBox1.Items.RemoveAt(0);
}
EDIT 2013-12-11 - This answer is very old. It is still valid and correct, but people looking at this should prefer the new format syntax.
You can use string formatting like this:
>>> print '%5s' % 'aa'
aa
>>> print '%5s' % 'aaa'
aaa
>>> print '%5s' % 'aaaa'
aaaa
>>> print '%5s' % 'aaaaa'
aaaaa
Basically:
%
character informs python it will have to substitute something to a tokens
character informs python the token will be a string5
(or whatever number you wish) informs python to pad the string with spaces up to 5 characters.In your specific case a possible implementation could look like:
>>> dict_ = {'a': 1, 'ab': 1, 'abc': 1}
>>> for item in dict_.items():
... print 'value %3s - num of occurances = %d' % item # %d is the token of integers
...
value a - num of occurances = 1
value ab - num of occurances = 1
value abc - num of occurances = 1
SIDE NOTE: Just wondered if you are aware of the existence of the itertools
module. For example you could obtain a list of all your combinations in one line with:
>>> [''.join(perm) for i in range(1, len(s)) for perm in it.permutations(s, i)]
['a', 'b', 'c', 'd', 'ab', 'ac', 'ad', 'ba', 'bc', 'bd', 'ca', 'cb', 'cd', 'da', 'db', 'dc', 'abc', 'abd', 'acb', 'acd', 'adb', 'adc', 'bac', 'bad', 'bca', 'bcd', 'bda', 'bdc', 'cab', 'cad', 'cba', 'cbd', 'cda', 'cdb', 'dab', 'dac', 'dba', 'dbc', 'dca', 'dcb']
and you could get the number of occurrences by using combinations
in conjunction with count()
.
The initialize
method is called after all @FXML
annotated members have been injected. Suppose you have a table view you want to populate with data:
class MyController {
@FXML
TableView<MyModel> tableView;
public MyController() {
tableView.getItems().addAll(getDataFromSource()); // results in NullPointerException, as tableView is null at this point.
}
@FXML
public void initialize() {
tableView.getItems().addAll(getDataFromSource()); // Perfectly Ok here, as FXMLLoader already populated all @FXML annotated members.
}
}
If you just want a number to come back try this.
create temp sequence temp_seq;
SELECT inline_v1.ROWNUM,inline_v1.c1
FROM
(
select nextval('temp_seq') as ROWNUM, c1
from sometable
)inline_v1;
You can add a order by to the inline_v1 SQL so your ROWNUM has some sequential meaning to your data.
select nextval('temp_seq') as ROWNUM, c1
from sometable
ORDER BY c1 desc;
Might not be the fastest, but it's an option if you really do need them.
I know this is an old thread but it might be useful for some people such as myself that months after are hitting this issue for the first time.
Here is some code that resizes the image every time you reload the image. I am aware this is not optimal at all, but I provide it as a proof of concept.
Also, sorry for using jQuery for simple selectors but I just feel too comfortable with the syntax.
$(document).on('ready', createImage);_x000D_
$(window).on('resize', createImage);_x000D_
_x000D_
var createImage = function(){_x000D_
var canvas = document.getElementById('myCanvas');_x000D_
canvas.width = window.innerWidth || $(window).width();_x000D_
canvas.height = window.innerHeight || $(window).height();_x000D_
var ctx = canvas.getContext('2d');_x000D_
img = new Image();_x000D_
img.addEventListener('load', function () {_x000D_
ctx.drawImage(this, 0, 0, w, h);_x000D_
});_x000D_
img.src = 'http://www.ruinvalor.com/Telanor/images/original.jpg';_x000D_
};
_x000D_
html, body{_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
background: #000;_x000D_
}_x000D_
canvas{_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
z-index: 0;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>Canvas Resize</title>_x000D_
</head>_x000D_
<body>_x000D_
<canvas id="myCanvas"></canvas>_x000D_
</body>_x000D_
</html>
_x000D_
My createImage function is called once when the document is loaded and after that it is called every time the window receives a resize event.
I tested it in Chrome 6 and Firefox 3.6, both on the Mac. This "technique" eats processor as it if was ice cream in the summer, but it does the trick.
and doesnt give any clues
Yes it does, unfortunately your code is ignoring all of those clues. Take a look at your exception handler:
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
All you're examining is the source of the exception. Which, in this case, is "Microsoft Access Database Engine". You're not examining the error message itself, or the stack trace, or any inner exception, or anything useful about the exception.
Don't ignore the exception, it contains information about what went wrong and why.
There are various logging tools out there (NLog, log4net, etc.) which can help you log useful information about an exception. Failing that, you should at least capture the exception message, stack trace, and any inner exception(s). Currently you're ignoring the error, which is why you're not able to solve the error.
In your debugger, place a breakpoint inside the catch
block and examine the details of the exception. You'll find it contains a lot of information.
As others indicated you can use dynamic_cast. But generally using dynamic_cast for finding out the type of the derived class you are working upon indicates the bad design. If you are overriding a function that takes pointer of A as the parameter then it should be able to work with the methods/data of class A itself and should not depend on the the data of class B. In your case instead of overriding if you are sure that the method you are writing will work with only class B, then you should write a new method in class B.
Try this: really quick + worked for me:
ps: excuse image below for different language :)
If any one's trying to fetch all headers that were passed then just simply use:
dict(request.headers)
it gives you all the headers in a dict from which you can actually do whatever ops you want to. In my use case I had to forward all headers to another API since the python API was a proxy
I was having the same issue, I even added style="display: none" to each cell.
In the end I used HTML comments
<!-- [HTML] -->
In this context, the word "stub" is used in place of "mock", but for the sake of clarity and precision, the author should have used "mock", because "mock" is a sort of stub, but for testing. To avoid further confusion, we need to define what a stub is.
In the general context, a stub is a piece of program (typically a function or an object) that encapsulates the complexity of invoking another program (usually located on another machine, VM, or process - but not always, it can also be a local object). Because the actual program to invoke is usually not located on the same memory space, invoking it requires many operations such as addressing, performing the actual remote invocation, marshalling/serializing the data/arguments to be passed (and same with the potential result), maybe even dealing with authentication/security, and so on. Note that in some contexts, stubs are also called proxies (such as dynamic proxies in Java).
A mock is a very specific and restrictive kind of stub, because a mock is a replacement of another function or object for testing. In practice we often use mocks as local programs (functions or objects) to replace a remote program in the test environment. In any case, the mock may simulate the actual behaviour of the replaced program in a restricted context.
Most famous kinds of stubs are obviously for distributed programming, when needing to invoke remote procedures (RPC) or remote objects (RMI, CORBA). Most distributed programming frameworks/libraries automate the generation of stubs so that you don't have to write them manually. Stubs can be generated from an interface definition, written with IDL for instance (but you can also use any language to define interfaces).
Typically, in RPC, RMI, CORBA, and so on, one distinguishes client-side stubs, which mostly take care of marshaling/serializing the arguments and performing the remote invocation, and server-side stubs, which mostly take care of unmarshaling/deserializing the arguments and actually execute the remote function/method. Obviously, client stubs are located on the client side, while sever stubs (often called skeletons) are located on the server side.
Writing good efficient and generic stubs becomes quite challenging when dealing with object references. Most distributed object frameworks such as RMI and CORBA deal with distributed objects references, but that's something most programmers avoid in REST environments for instance. Typically, in REST environments, JavaScript programmers make simple stub functions to encapsulate the AJAX invocations (object serialization being supported by JSON.parse
and JSON.stringify
). The Swagger Codegen project provides an extensive support for automatically generating REST stubs in various languages.
Basic Availability: The database appears to work most of the time.
Soft State: Stores don’t have to be write-consistent or mutually consistent all the time.
Eventual consistency: Data should always be consistent, with regards how any number of changes are performed.
simply you can use jquery plugin to get/set the content of the div.
var divContent = $('#'DIV1).html(); $('#'DIV2).html(divContent );
for this you need to include jquery library.
In my case it was a simple bug in the code, using a variable before it was created. Worth checking that out before trying the above solutions. Why I got this particular error message, Lord knows.
Since 1.8, I thought this might be an additional solution worth adding to the responses:
Path java.nio.file.Files.write(Path path, Iterable lines, OpenOption... options) throws IOException
StringBuilder sb = new StringBuilder();
sb.append(jTextField1.getText());
sb.append(jTextField2.getText());
sb.append(System.lineSeparator());
Files.write(Paths.get("file.txt"), sb.toString().getBytes());
If appending to the same file, perhaps use an Append flag with Files.write()
Files.write(Paths.get("file.txt"), sb.toString().getBytes(), StandardOpenOption.APPEND);
Seems you forgot the ''
of your string.
In [43]: df['Value'] = df.apply(lambda row: my_test(row['a'], row['c']), axis=1)
In [44]: df
Out[44]:
a b c Value
0 -1.674308 foo 0.343801 0.044698
1 -2.163236 bar -2.046438 -0.116798
2 -0.199115 foo -0.458050 -0.199115
3 0.918646 bar -0.007185 -0.001006
4 1.336830 foo 0.534292 0.268245
5 0.976844 bar -0.773630 -0.570417
BTW, in my opinion, following way is more elegant:
In [53]: def my_test2(row):
....: return row['a'] % row['c']
....:
In [54]: df['Value'] = df.apply(my_test2, axis=1)
public class Splash extends Activity {
Location location;
LocationManager locationManager;
LocationListener locationlistener;
ImageView image_view;
ublic static ProgressDialog progressdialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
progressdialog = new ProgressDialog(Splash.this);
image_view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
locationManager.requestLocationUpdates("gps", 100000, 1, locationlistener);
Toast.makeText(getApplicationContext(), "Getting Location plz wait...", Toast.LENGTH_SHORT).show();
progressdialog.setMessage("getting Location");
progressdialog.show();
Intent intent = new Intent(Splash.this,Show_LatLng.class);
// }
});
}
Text here:-
use this for getting activity
context for progressdialog
progressdialog = new ProgressDialog(Splash.this);
or progressdialog = new ProgressDialog(this);
use this for getting application context for BroadcastListener
not for progressdialog
.
progressdialog = new ProgressDialog(getApplicationContext());
progressdialog = new ProgressDialog(getBaseContext());
package com.dataload;
public class insertCSV
{
public static void main(String args[])
{
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationcontext.xml");
// retrieve configured instance
JobLauncher launcher = context.getBean("laucher", JobLauncher.class);
Job job = context.getBean("job", Job.class);
JobParameters jobParameters = context.getBean("jobParameters", JobParameters.class);
}
}
If you only have to view it, I've used this:
print cast(dbo.f_functiondeliveringbigformattedtext(seed) as text)
The end result is that I get line feeds and all the content in the messages window of SMSS. Of course, it only allows for a single cell - if you want to do a single cell from a number of rows, you could do this:
declare @T varchar(max)=''
select @T=@T
+ isnull(dbo.f_functiondeliveringbigformattedtext(x.a),'NOTHINGFOUND!')
+ replicate(char(13),4)
from x -- table containing multiple rows and a value in column a
print @T
I use this to validate JSON strings generated by SQL code. Too hard to read otherwise!
Try the Terminal Services PowerShell Module:
Get-TSSession -ComputerName comp1 -UserName user1 | Stop-TSSession -Force
For variety's sake:
var actions = {input1: "action1.php", input2: "action2.php"};
$("#input1, #input2").click(function() {
$(this).closest("form").attr("action", actions[this.id]);
});
The answer is .IsPostBack
as suggested by @Kundan Singh Chouhan. Just to add to it, move your code into a separate method from Page_Load
private void PopulateFields()
{
using(SqlConnection con1 = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True"))
{
DataTable dt = new DataTable();
con1.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from customer_registration where username='" + Session["username"] + "'", con1);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
TextBoxPassword.Text = (myReader["password"].ToString());
TextBoxRPassword.Text = (myReader["retypepassword"].ToString());
DropDownListGender.SelectedItem.Text = (myReader["gender"].ToString());
DropDownListMonth.Text = (myReader["birth"].ToString());
DropDownListYear.Text = (myReader["birth"].ToString());
TextBoxAddress.Text = (myReader["address"].ToString());
TextBoxCity.Text = (myReader["city"].ToString());
DropDownListCountry.SelectedItem.Text = (myReader["country"].ToString());
TextBoxPostcode.Text = (myReader["postcode"].ToString());
TextBoxEmail.Text = (myReader["email"].ToString());
TextBoxCarno.Text = (myReader["carno"].ToString());
}
con1.Close();
}//end using
}
Then call it in your Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
PopulateFields();
}
}
You can try webshims, which is available on cdn + only loads the polyfill, if it is needed.
Here is a demo with CDN: http://jsfiddle.net/trixta/BMEc9/
<!-- cdn for modernizr, if you haven't included it already -->
<script src="http://cdn.jsdelivr.net/webshim/1.12.4/extras/modernizr-custom.js"></script>
<!-- polyfiller file to detect and load polyfills -->
<script src="http://cdn.jsdelivr.net/webshim/1.12.4/polyfiller.js"></script>
<script>
webshims.setOptions('waitReady', false);
webshims.setOptions('forms-ext', {types: 'date'});
webshims.polyfill('forms forms-ext');
</script>
<input type="date" />
In case the default configuration does not satisfy, there are many ways to configure it. Here you find the datepicker configurator.
Note: While there might be new bugfix releases for webshim in the future. There won't be any major releases anymore. This includes support for jQuery 3.0 or any new features.
Not exactly. You can't get two Stream
s out of one; this doesn't make sense -- how would you iterate over one without needing to generate the other at the same time? A stream can only be operated over once.
However, if you want to dump them into a list or something, you could do
stream.forEach((x) -> ((x == 0) ? heads : tails).add(x));
# function to insert a number in an sorted list
def pstatement(value_returned):
return print('new sorted list =', value_returned)
def insert(input, n):
print('input list = ', input)
print('number to insert = ', n)
print('range to iterate is =', len(input))
first = input[0]
print('first element =', first)
last = input[-1]
print('last element =', last)
if first > n:
list = [n] + input[:]
return pstatement(list)
elif last < n:
list = input[:] + [n]
return pstatement(list)
else:
for i in range(len(input)):
if input[i] > n:
break
list = input[:i] + [n] + input[i:]
return pstatement(list)
# Input values
listq = [2, 4, 5]
n = 1
insert(listq, n)
I created an alternative directive that doesn't have ngApp
's limitations. It's called ngModule
. This is what you code would look like when you use it:
<!DOCTYPE html>
<html>
<head>
<script src="angular.js"></script>
<script src="angular.ng-modules.js"></script>
<script>
var moduleA = angular.module("MyModuleA", []);
moduleA.controller("MyControllerA", function($scope) {
$scope.name = "Bob A";
});
var moduleB = angular.module("MyModuleB", []);
moduleB.controller("MyControllerB", function($scope) {
$scope.name = "Steve B";
});
</script>
</head>
<body>
<div ng-modules="MyModuleA, MyModuleB">
<h1>Module A, B</h1>
<div ng-controller="MyControllerA">
{{name}}
</div>
<div ng-controller="MyControllerB">
{{name}}
</div>
</div>
<div ng-module="MyModuleB">
<h1>Just Module B</h1>
<div ng-controller="MyControllerB">
{{name}}
</div>
</div>
</body>
</html>
You can get the source code at:
http://www.simplygoodcode.com/2014/04/angularjs-getting-around-ngapp-limitations-with-ngmodule/
It's essentially the same code used internally by AngularJS without the limitations.
If you want this in kotlin . And perfectly working
private fun exportDbFile() {
try {
//Existing DB Path
val DB_PATH = "/data/packagename/databases/mydb.db"
val DATA_DIRECTORY = Environment.getDataDirectory()
val INITIAL_DB_PATH = File(DATA_DIRECTORY, DB_PATH)
//COPY DB PATH
val EXTERNAL_DIRECTORY: File = Environment.getExternalStorageDirectory()
val COPY_DB = "/mynewfolder/mydb.db"
val COPY_DB_PATH = File(EXTERNAL_DIRECTORY, COPY_DB)
File(COPY_DB_PATH.parent!!).mkdirs()
val srcChannel = FileInputStream(INITIAL_DB_PATH).channel
val dstChannel = FileOutputStream(COPY_DB_PATH).channel
dstChannel.transferFrom(srcChannel,0,srcChannel.size())
srcChannel.close()
dstChannel.close()
} catch (excep: Exception) {
Toast.makeText(this,"ERROR IN COPY $excep",Toast.LENGTH_LONG).show()
Log.e("FILECOPYERROR>>>>",excep.toString())
excep.printStackTrace()
}
}
Another possibility:
bash << EOF
echo "Hello"
echo "World"
EOF
There are many cases in which gaps are desired in a chart.
I am currently trying to make a plot of flow rate in a heating system vs. the time of day. I have data for two months. I want to plot only vs. the time of day from 00:00 to 23:59, which causes lines to be drawn between 23:59 and 00:01 of the next day which extend across the chart and disturb the otherwise regular daily variation.
Using the NA() formula (in German NV()) causes Excel to ignore the cells, but instead the previous and following points are simply connected, which has the same problem with lines across the chart.
The only solution I have been able to find is to delete the formulas from the cells which should create the gaps.
Using an IF formula with "" as its value for the gaps makes Excel interpret the X-values as string labels (shudder) for the chart instead of numbers (and makes me swear about the people who wrote that requirement).
The problem here is that the rendering of a RadioButtonList wraps the individual radio buttons (ListItems) in span tags and even when you assign a client-side event handler to the list item directly using Attributes it assigns the event to the span. Assigning the event to the RadioButtonList assigns it to the table it renders in.
The trick here is to add the ListItems on the aspx page and not from the code behind. You can then assign the JavaScript function to the onClick property. This blog post; attaching client-side event handler to radio button list by Juri Strumpflohner explains it all.
This only works if you know the ListItems in advance and does not help where the items in the RadioButtonList need to be dynamically added using the code behind.
I use:
netstat –aon | find "<port number>"
here o represents process ID. now you can do whatever with the process ID. To terminate the process, for e.g., use:
taskkill /F /pid <process ID>
just for someone else who wanna register a broadcast dynamicly:
BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (checkWifiConnect()) {
Log.d(TAG, "wifi has connected");
// TODO
}
}
};
private void registerWifiReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
mContext.registerReceiver(mWifiReceiver, filter);
}
private void unregisterWifiReceiver() {
mContext.unregisterReceiver(mWifiReceiver);
}
private boolean checkWifiConnect() {
ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo != null
&& networkInfo.getType() == ConnectivityManager.TYPE_WIFI
&& networkInfo.isConnected()) {
return true;
}
return false;
}
A bit late to the party, but Krux has created a script for this, called Postscribe. We were able to use this to get past this issue.
The best threads tutorial I know of is here:
https://computing.llnl.gov/tutorials/pthreads/
I like that it's written about the API, rather than about a particular implementation, and it gives some nice simple examples to help you understand synchronization.
dplyr now has a function case_when
that offers a vectorised if. The syntax is a little strange compared to mosaic:::derivedFactor
as you cannot access variables in the standard dplyr way, and need to declare the mode of NA, but it is considerably faster than mosaic:::derivedFactor
.
df %>%
mutate(g = case_when(a %in% c(2,5,7) | (a==1 & b==4) ~ 2L,
a %in% c(0,1,3,4) | c == 4 ~ 3L,
TRUE~as.integer(NA)))
EDIT: If you're using dplyr::case_when()
from before version 0.7.0 of the package, then you need to precede variable names with '.$
' (e.g. write .$a == 1
inside case_when
).
Benchmark: For the benchmark (reusing functions from Arun 's post) and reducing sample size:
require(data.table)
require(mosaic)
require(dplyr)
require(microbenchmark)
set.seed(42) # To recreate the dataframe
DT <- setDT(lapply(1:6, function(x) sample(7, 10000, TRUE)))
setnames(DT, letters[1:6])
DF <- as.data.frame(DT)
DPLYR_case_when <- function(DF) {
DF %>%
mutate(g = case_when(a %in% c(2,5,7) | (a==1 & b==4) ~ 2L,
a %in% c(0,1,3,4) | c==4 ~ 3L,
TRUE~as.integer(NA)))
}
DT_fun <- function(DT) {
DT[(a %in% c(0,1,3,4) | c == 4), g := 3L]
DT[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]
}
DPLYR_fun <- function(DF) {
mutate(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L,
ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}
mosa_fun <- function(DF) {
mutate(DF, g = derivedFactor(
"2" = (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)),
"3" = (a == 0 | a == 1 | a == 4 | a == 3 | c == 4),
.method = "first",
.default = NA
))
}
perf_results <- microbenchmark(
dt_fun <- DT_fun(copy(DT)),
dplyr_ifelse <- DPLYR_fun(copy(DF)),
dplyr_case_when <- DPLYR_case_when(copy(DF)),
mosa <- mosa_fun(copy(DF)),
times = 100L
)
This gives:
print(perf_results)
Unit: milliseconds
expr min lq mean median uq max neval
dt_fun 1.391402 1.560751 1.658337 1.651201 1.716851 2.383801 100
dplyr_ifelse 1.172601 1.230351 1.331538 1.294851 1.390351 1.995701 100
dplyr_case_when 1.648201 1.768002 1.860968 1.844101 1.958801 2.207001 100
mosa 255.591301 281.158350 291.391586 286.549802 292.101601 545.880702 100
The issue turned out to be certificate-related. The WCF service called by the console app uses an X509 cert for authentication, which is installed on the servers that this script is hosted and run from.
On other servers, where the same services are consumed, the certificates were configured as follows:
winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "NETWORK SERVICE"
As they ran within the context of IIS. However, when the script was being run as it would in production, it's under the context of the user themselves. So, the script needed to be modified to the following:
winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "USERS"
Once that change was made, all was well. Thanks to everyone who offered assistance.
You need to be aware about how AngularJS works in order to understand it.
First and foremost, AngularJS defines a concept of a so-called digest cycle. This cycle can be considered as a loop, during which AngularJS checks if there are any changes to all the variables watched by all the $scope
s. So if you have $scope.myVar
defined in your controller and this variable was marked for being watched, then you are implicitly telling AngularJS to monitor the changes on myVar
in each iteration of the loop.
A natural follow-up question would be: Is everything attached to $scope
being watched? Fortunately, no. If you would watch for changes to every object in your $scope
, then quickly a digest loop would take ages to evaluate and you would quickly run into performance issues. That is why the AngularJS team gave us two ways of declaring some $scope
variable as being watched (read below).
There are two ways of declaring a $scope
variable as being watched.
<span>{{myVar}}</span>
$watch
serviceAd 1)
This is the most common scenario and I'm sure you've seen it before, but you didn't know that this has created a watch in the background. Yes, it had! Using AngularJS directives (such as ng-repeat
) can also create implicit watches.
Ad 2)
This is how you create your own watches. $watch
service helps you to run some code when some value attached to the $scope
has changed. It is rarely used, but sometimes is helpful. For instance, if you want to run some code each time 'myVar' changes, you could do the following:
function MyController($scope) {
$scope.myVar = 1;
$scope.$watch('myVar', function() {
alert('hey, myVar has changed!');
});
$scope.buttonClicked = function() {
$scope.myVar = 2; // This will trigger $watch expression to kick in
};
}
You can think of the $apply
function as of an integration mechanism. You see, each time you change some watched variable attached to the $scope
object directly, AngularJS will know that the change has happened. This is because AngularJS already knew to monitor those changes. So if it happens in code managed by the framework, the digest cycle will carry on.
However, sometimes you want to change some value outside of the AngularJS world and see the changes propagate normally.
Consider this - you have a $scope.myVar
value which will be modified within a jQuery's $.ajax()
handler. This will happen at some point in future. AngularJS can't wait for this to happen, since it hasn't been instructed to wait on jQuery.
To tackle this, $apply
has been introduced. It lets you start the digestion cycle explicitly. However, you should only use this to migrate some data to AngularJS (integration with other frameworks), but never use this method combined with regular AngularJS code, as AngularJS will throw an error then.
Well, you should really follow the tutorial again, now that you know all this. The digest cycle will make sure that the UI and the JavaScript code stay synchronised, by evaluating every watcher attached to all $scope
s as long as nothing changes. If no more changes happen in the digest loop, then it's considered to be finished.
You can attach objects to the $scope
object either explicitly in the Controller, or by declaring them in {{expression}}
form directly in the view.
I hope that helps to clarify some basic knowledge about all this.
Further readings:
You can use goto
, return
, or perhaps call abort ()
, exit ()
etc.
I think that CONTAINS
took longer and used Merge
because you had a dash("-") in your query adventure-works.com
.
The dash is a break word so the CONTAINS
searched the full-text index for adventure
and than it searched for works.com
and merged the results.
Contrary to the answers here, you DON'T need to worry about encoding if the bytes don't need to be interpreted!
Like you mentioned, your goal is, simply, to "get what bytes the string has been stored in".
(And, of course, to be able to re-construct the string from the bytes.)
For those goals, I honestly do not understand why people keep telling you that you need the encodings. You certainly do NOT need to worry about encodings for this.
Just do this instead:
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
// Do NOT use on arbitrary bytes; only use on GetBytes's output on the SAME system
static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
As long as your program (or other programs) don't try to interpret the bytes somehow, which you obviously didn't mention you intend to do, then there is nothing wrong with this approach! Worrying about encodings just makes your life more complicated for no real reason.
Additional benefit to this approach: It doesn't matter if the string contains invalid characters, because you can still get the data and reconstruct the original string anyway!
It will be encoded and decoded just the same, because you are just looking at the bytes.
If you used a specific encoding, though, it would've given you trouble with encoding/decoding invalid characters.
For those using Mac and you get a command not found error, what you need to do is
type
./adb install "yourapk.apk"
You are testing if the values of the variables error
and Already
are present in RepoOutput[RepoName.index(repo)]
. If these variables don't exist then an undefined object is used.
Both of your if
and elif
tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].
I think you wanted to test if certain strings are in the value instead:
{% if "error" in RepoOutput[RepoName.index(repo)] %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
<td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>
Other corrections I made:
{% elif ... %}
instead of {$ elif ... %}
.</tr>
tag out of the if
conditional structure, it needs to be there always.id
attributeNote that most likely you want to use a class
attribute instead here, not an id
, the latter must have a value that must be unique across your HTML document.
Personally, I'd set the class value here and reduce the duplication a little:
{% if "Already" in RepoOutput[RepoName.index(repo)] %}
{% set row_class = "good" %}
{% else %}
{% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>
hmm. why don't you use onClick()
<select id="mySelect" onChange="enable();">
<option onClick="disable();">No</option>
<option onClick="enable();">Yes</option>
</select>
This : /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i
is not working for below Gmail case
[email protected] [email protected]
Below Regex will cover all the E-mail Points: I have tried the all Possible Points and my Test case get also pass because of below regex
I found this Solution from this URL:
/(?:((?:[\w-]+(?:\.[\w-]+)*)@(?:(?:[\w-]+\.)*\w[\w-]{0,66})\.(?:[a-z]{2,6}(?:\.[a-z]{2})?));*)/g
This is how I would write using more functional way
. Here is the code:
new List<Money>()
{
new Money() { Amount = 10, Type = "US"},
new Money() { Amount = 20, Type = "US"}
}
.ForEach(money =>
{
Console.WriteLine($"amount is {money.Amount}, and type is {money.Type}");
});
The reset_index() is a pandas DataFrame method that will transfer index values into the DataFrame as columns. The default setting for the parameter is drop=False (which will keep the index values as columns).
All you have to do add .reset_index(inplace=True)
after the name of the DataFrame:
df.reset_index(inplace=True)
Below query will help to find postgres configuration file.
postgres=# SHOW config_file;
config_file
-------------------------------------
/var/lib/pgsql/data/postgresql.conf
(1 row)
[root@node1 usr]# cd /var/lib/pgsql/data/
[root@node1 data]# ls -lrth
total 48K
-rw------- 1 postgres postgres 4 Nov 25 13:58 PG_VERSION
drwx------ 2 postgres postgres 6 Nov 25 13:58 pg_twophase
drwx------ 2 postgres postgres 6 Nov 25 13:58 pg_tblspc
drwx------ 2 postgres postgres 6 Nov 25 13:58 pg_snapshots
drwx------ 2 postgres postgres 6 Nov 25 13:58 pg_serial
drwx------ 4 postgres postgres 36 Nov 25 13:58 pg_multixact
-rw------- 1 postgres postgres 20K Nov 25 13:58 postgresql.conf
-rw------- 1 postgres postgres 1.6K Nov 25 13:58 pg_ident.conf
-rw------- 1 postgres postgres 4.2K Nov 25 13:58 pg_hba.conf
drwx------ 3 postgres postgres 60 Nov 25 13:58 pg_xlog
drwx------ 2 postgres postgres 18 Nov 25 13:58 pg_subtrans
drwx------ 2 postgres postgres 18 Nov 25 13:58 pg_clog
drwx------ 5 postgres postgres 41 Nov 25 13:58 base
-rw------- 1 postgres postgres 92 Nov 25 14:00 postmaster.pid
drwx------ 2 postgres postgres 18 Nov 25 14:00 pg_notify
-rw------- 1 postgres postgres 57 Nov 25 14:00 postmaster.opts
drwx------ 2 postgres postgres 32 Nov 25 14:00 pg_log
drwx------ 2 postgres postgres 4.0K Nov 25 14:00 global
drwx------ 2 postgres postgres 25 Nov 25 14:20 pg_stat_tmp
You can do it using dynamic
instead of object
:
dynamic item = AnyFunction(....);
string value = item.name;
Note that the Dynamic Language Runtime (DLR) has built-in caching mechanisms, so subsequent calls are very fast.
it clears stdin
buffer before reading. From the man page:
For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function. For input streams, fflush() discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application.
Note: This is Linux-specific, using fflush()
on input streams is undefined by the standard, however, most implementations behave the same as in Linux.
Try adding this to your dependencies:
compile 'org.apache.httpcomponents:httpclient:4.4-alpha1'
And generally if you want to use a library and you are searching for the Gradle dependency line you can use Gradle Please
EDIT: Check this one too.
You can use
git reset
to undo the recently added local files
git reset file_name
to undo the changes for a specific file
Try to load your scripts in Head section.
Moreover, it will be better if you define your scripts under some call like: document.ready
, if you defined these scripts in body section
this is the pattern I would use
$string = preg_replace('@[\s]{2,}@',' ',$string);
map
is the most logical solution for this problem.
let xs = [1, 2, 3];
xs = xs.map(x => 42);
xs // -> [42, 42, 42]
However, if there is a chance that the array is sparse, you'll need to use for
or, even better, for .. of
.
See:
Refer Below code which give the date in String form.
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test{
public static void main(String[] args) {
long val = 1346524199000l;
Date date=new Date(val);
SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
String dateText = df2.format(date);
System.out.println(dateText);
}
}
Ensure that Enhanced session mode settings are enabled on the Hyper-V host.
Start Hyper-V Manager, and in the Actions section, select "Hyper-V Settings".
Make sure that enhanced session mode is allowed in the Server section. Then, make sure that the enhanced session mode is available in the User section.
Enable Hyper-V Guest Services for your virtual machine
Right-click on Virtual Machine > Settings. Select the Integration Services in the left-lower corner of the menu. Check Guest Service and click OK.
Start a virtual machine and click Show Options in the pop-up windows.
Or click "Edit Session Settings..." in the Actions panel on the right
It may only appear when you're (able to get) connected to it. If it doesn't appear try Starting and then Connecting to the VM while paying close attention to the panel in the Hyper-V Manager.
View local resources. Then, select the "More..." menu.
From there, you can choose which devices to share. Removable drives are especially useful for file sharing.
Choose to "Save my settings for future connections to this virtual machine".
Click Connect. Drive sharing is now complete, and you will see the shared drive in this PC > Network Locations section of Windows Explorer after using the enhanced session mode to sigh to the VM. You should now be able to copy files from a physical machine and paste them into a virtual machine, and vice versa.
Source (and for more info): Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine
Your code (or some code called by you) is making a call to a COM method which is returning an unknown value. If you can find that then you're half way there.
You could try breaking when the exception is thrown. Go to Debug > Exceptions... and use the Find... option to locate System.Runtime.InteropServices.COMException
. Tick the option to break when it's thrown and then debug your application.
Hopefully it will break somewhere meaningful and you'll be able to trace back and find the source of the error.
MAKE THIS YOUR config.js file code
CKEDITOR.editorConfig = function( config ) {
// config.enterMode = 2; //disabled <p> completely
config.enterMode = CKEDITOR.ENTER_BR // pressing the ENTER KEY input <br/>
config.shiftEnterMode = CKEDITOR.ENTER_P; //pressing the SHIFT + ENTER KEYS input <p>
config.autoParagraph = false; // stops automatic insertion of <p> on focus
};
So to make your expression work, changing &&
for -a
will do the trick.
It is correct like this:
if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
then ....
or like
if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
then ....
or even
if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
then ....
You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.
This is an adapted version of the answer given by Vivien Barousse with the update from Vulcan applied. In this example I use sliders to dynamically retreive the RGB values from three sliders and display that color in a rectangle. Then in method toHex() I use the values to create a color and display the respective Hex color code.
This example does not include the proper constraints for the GridBagLayout. Though the code will work, the display will look strange.
public class HexColor
{
public static void main (String[] args)
{
JSlider sRed = new JSlider(0,255,1);
JSlider sGreen = new JSlider(0,255,1);
JSlider sBlue = new JSlider(0,255,1);
JLabel hexCode = new JLabel();
JPanel myPanel = new JPanel();
GridBagLayout layout = new GridBagLayout();
JFrame frame = new JFrame();
//set frame to organize components using GridBagLayout
frame.setLayout(layout);
//create gray filled rectangle
myPanel.paintComponent();
myPanel.setBackground(Color.GRAY);
//In practice this code is replicated and applied to sGreen and sBlue.
//For the sake of brevity I only show sRed in this post.
sRed.addChangeListener(
new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent e){
myPanel.setBackground(changeColor());
myPanel.repaint();
hexCode.setText(toHex());
}
}
);
//add each component to JFrame
frame.add(myPanel);
frame.add(sRed);
frame.add(sGreen);
frame.add(sBlue);
frame.add(hexCode);
} //end of main
//creates JPanel filled rectangle
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawRect(360, 300, 10, 10);
g.fillRect(360, 300, 10, 10);
}
//changes the display color in JPanel
private Color changeColor()
{
int r = sRed.getValue();
int b = sBlue.getValue();
int g = sGreen.getValue();
Color c;
return c = new Color(r,g,b);
}
//Displays hex representation of displayed color
private String toHex()
{
Integer r = sRed.getValue();
Integer g = sGreen.getValue();
Integer b = sBlue.getValue();
Color hC;
hC = new Color(r,g,b);
String hex = Integer.toHexString(hC.getRGB() & 0xffffff);
while(hex.length() < 6){
hex = "0" + hex;
}
hex = "Hex Code: #" + hex;
return hex;
}
}
A huge thank you to both Vivien and Vulcan. This solution works perfectly and was super simple to implement.
$sUrl = 'http://www.linktopage.com/login/';
$params = array('http' => array(
'method' => 'POST',
'content' => 'username=admin195&password=d123456789'
));
$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if(!$fp) {
throw new Exception("Problem with $sUrl, $php_errormsg");
}
$response = @stream_get_contents($fp);
if($response === false) {
throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}
Despite this being against the general SO policy on these matters, this seems to be what the OP genuinely wants:
http://www.google.com/search?btnG=1&pws=0&q=java+executable+wrapper
If you'd like, you could also try creating the appropriate batch or script file containing the single line:
java -jar MyJar.jar
Or in many cases on windows just double clicking the executable jar.
If you want to find the last populated cell in a particular column, the best method is:
Range("A" & Rows.Count).End(xlUp).Row
This code uses the very last cell in the entire column (65536 for Excel 2003, 1048576 in later versions), and then find the first populated cell above it. This has the ability to ignore "breaks" in your data and find the true last row.
Simply by adding below text in the httpd.conf file will solve this issue.
Header set Access-Control-Allow-Origin "*"
A side from the very long complete accepted answer there is an important point to make about IndexOutOfRangeException
compared with many other exception types, and that is:
Often there is complex program state that maybe difficult to have control over at a particular point in code e.g a DB connection goes down so data for an input cannot be retrieved etc... This kind of issue often results in an Exception of some kind that has to bubble up to a higher level because where it occurs has no way of dealing with it at that point.
IndexOutOfRangeException
is generally different in that it in most cases it is pretty trivial to check for at the point where the exception is being raised. Generally this kind of exception get thrown by some code that could very easily deal with the issue at the place it is occurring - just by checking the actual length of the array. You don't want to 'fix' this by handling this exception higher up - but instead by ensuring its not thrown in the first instance - which in most cases is easy to do by checking the array length.
Another way of putting this is that other exceptions can arise due to genuine lack of control over input or program state BUT IndexOutOfRangeException
more often than not is simply just pilot (programmer) error.
None of these pure css solutions work properly with dynamically resizing content (at least on firefox and Safari) e.g., if you have a background set on the container div, the page and then resize (adding a few rows) table inside the div, the table can stick out of the bottom of the styled area, i.e., you can have half the table in white on black theme and half the table complete white because both the font-color and background color is white. It's basically unfixable with themeroller pages.
Nested div multi-column layout is an ugly hack and the 100% min-height body/container div for sticking footer is an uglier hack.
The only none-script solution that works on all the browsers I've tried: a much simpler/shorter table with thead (for header)/tfoot (for footer)/tbody (td's for any number of columns) and 100% height. But this have perceived semantic and SEO disadvantages (tfoot must appear before tbody. ARIA roles may help decent search engines though).
After doing some research, it seems I cannot have two connections opened to the same database with the TransactionScope block. I needed to modify my code to look like this:
public void MyAddUpdateMethod()
{
using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
using(SQLServer Sql = new SQLServer(this.m_connstring))
{
//do my first add update statement
}
//removed the method call from the first sql server using statement
bool DoesRecordExist = this.SelectStatementCall(id)
}
}
public bool SelectStatementCall(System.Guid id)
{
using(SQLServer Sql = new SQLServer(this.m_connstring))
{
//create parameters
}
}
In my case, I had copied a service from one server to another without performing a proper deployment from Visual Studio. Long story.
Anyway, I had setup all of the appropriate NTFS permissions and whatnot, but it still couldn't load the main DLL for the service.
I fixed it by renaming the corresponding service.pdb file to something else.
For example here's my bin folder:
\bin\
service.dll
service.dll.config
service.pdb
I renamed service.pdb to zzservice.pdb, and then the service.dll loaded fine.
You can use a jQuery plugin called Array Utilities to get an array of unique items. It can be done like this:
var distinctArray = $.distinct([1, 2, 2, 3])
distinctArray = [1,2,3]
Working fine...
window.onload = function() {
var input = document.getElementById("myinputbox").focus();
}
Possible that public/private config is incorrect. please follow the steps to do it. execute command anywhere in window
ssh-keygen -o -f ~/.ssh/id_rsa
now go to the c://users/xyz/.ssh/ and open the id_rsa key (path can vary) now go to the gitlab and userprofile> setting>ssh keys and add your key here. now try clone
I had the same problem. i was using windows8 with 64 bit OS. I just changed the path to Program Files(*86) and then it started work. I put this line in eclipse.ini file like,
-vm
C:\Program Files (x86)\Java\jre7\bin\javaw.exe
System.Type type = typeof(int);
Example:
public class ExampleClass
{
public int sampleMember;
public void SampleMethod() {}
static void Main()
{
Type t = typeof(ExampleClass);
// Alternatively, you could use
// ExampleClass obj = new ExampleClass();
// Type t = obj.GetType();
Console.WriteLine("Methods:");
System.Reflection.MethodInfo[] methodInfo = t.GetMethods();
foreach (System.Reflection.MethodInfo mInfo in methodInfo)
Console.WriteLine(mInfo.ToString());
Console.WriteLine("Members:");
System.Reflection.MemberInfo[] memberInfo = t.GetMembers();
foreach (System.Reflection.MemberInfo mInfo in memberInfo)
Console.WriteLine(mInfo.ToString());
}
}
/*
Output:
Methods:
Void SampleMethod()
System.String ToString()
Boolean Equals(System.Object)
Int32 GetHashCode()
System.Type GetType()
Members:
Void SampleMethod()
System.String ToString()
Boolean Equals(System.Object)
Int32 GetHashCode()
System.Type GetType()
Void .ctor()
Int32 sampleMember
*/
class GetTypeTest
{
static void Main()
{
int radius = 3;
Console.WriteLine("Area = {0}", radius * radius * Math.PI);
Console.WriteLine("The type is {0}",
(radius * radius * Math.PI).GetType()
);
}
}
/*
Output:
Area = 28.2743338823081
The type is System.Double
*/
You can do this in your code:
final ListView lv = (ListView) convertView.findViewById(R.id.list_view);
for (int i = 0; i < lv.getChildCount(); i++) {
((TextView)lv.getChildAt(i)).setTextColor(getResources().getColor(R.color.black));
}
$("#sample_id").css({ 'width' : '', 'height' : '' });
I chose to strip these characters out of the string by doing this -
ini_set('mbstring.substitute_character', "none");
$text= mb_convert_encoding($text, 'UTF-8', 'UTF-8');
A quick workaround is using window.addEventListener
instead of document.addEventListener
.
i think token must include all the needed information encoded inside it, which makes authentication by validating the token and decoding the info https://www.oauth.com/oauth2-servers/access-tokens/self-encoded-access-tokens/
Best way to do this is to use a function:
html
<div ng-repeat="product in products | filter: myFilter">
javascript
$scope.myFilter = function (item) {
return item === 'red' || item === 'blue';
};
Alternatively, you can use ngHide or ngShow to dynamically show and hide elements based on a certain criteria.
This line:
<input type="password" name="PasswordInput"/>
should have an id attribute, like so:
<input type="password" name="PasswordInput" id="PasswordInput"/>
Look back to formal logic and algebra. An expression like
A & B & (D | E)
may be negated in a couple of ways:
The obvious way:
!( A & B & ( D | E ) )
The above can also be restated, you just need to remember some properties of logical expressions:
!( A & B )
is the equivalent of (!A | !B)
.!( A | B )
is the equivalent of (!A & !B)
.!( !A )
is the equivalent of (A).Distribute the NOT (!) across the entire expression to which it applies, inverting operators and eliminating double negatives as you go along:
!A | !B | ( !D & !E )
So, in general, any where clause may be negated according to the above rules. The negation of this
select *
from foo
where test-1
and test-2
and ( test-3
OR test-4
)
is
select *
from foo
where NOT( test-1
and test-2
and ( test-3
OR test-4
)
)
or
select *
from foo
where not test-1
OR not test-2
OR ( not test-3
and not test-4
)
Which is better? That's a very context-sensitive question. Only you can decide that.
Be aware, though, that the use of NOT can affect what the optimizer can or can't do. You might get a less than optimal query plan.
Performance wise both can do equally the same, so the question becomes which saves more development time?
Bash relies on calling other commands, and piping them for creating new ones. This has the advantage that you can quickly create new programs just with the code borrowed from other people, no matter what programming language they used.
This also has the side effect of resisting change in sub-commands pretty well, as the interface between them is just plain text.
Additionally Bash is very permissive on how you can write on it. This means it will work well for a wider variety of context, but it also relies on the programmer having the intention of coding in a clean safe manner. Otherwise Bash won't stop you from building a mess.
Python is more structured on style, so a messy programmer won't be as messy. It will also work on operating systems outside Linux, making it instantly more appropriate if you need that kind of portability.
But it isn't as simple for calling other commands. So if your operating system is Unix most likely you will find that developing on Bash is the fastest way to develop.
When to use Bash:
When to use Python:
AFAIK you can't do an if else
in batch like you can in other languages, it has to be nested if
's.
Using nested if
's your batch would look like
IF %F%==1 IF %C%==1(
::copying the file c to d
copy "%sourceFile%" "%destinationFile%"
) ELSE (
IF %F%==1 IF %C%==0(
::moving the file c to d
move "%sourceFile%" "%destinationFile%"
) ELSE (
IF %F%==0 IF %C%==1(
::copying a directory c from d, /s: bos olanlar hariç, /e:bos olanlar dahil
xcopy "%sourceCopyDirectory%" "%destinationCopyDirectory%" /s/e
) ELSE (
IF %F%==0 IF %C%==0(
::moving a directory
xcopy /E "%sourceMoveDirectory%" "%destinationMoveDirectory%"
rd /s /q "%sourceMoveDirectory%"
)
)
)
)
or as James suggested, chain your if
's, however I think the proper syntax is
IF %F%==1 IF %C%==1(
::copying the file c to d
copy "%sourceFile%" "%destinationFile%"
)
The other solutions seem to stray from the blessed path and I found that my scenario was covered in the Typescript documentation which I've paraphrased below:
interface AppPackageCheck<T> {
new (packageExists: boolean): T
checkIfPackageExists(): boolean;
}
class WebApp {
public static checkIfPackageExists(): boolean {
return false;
}
constructor(public packageExists: boolean) {}
}
class BackendApp {
constructor(public packageExists: boolean) {}
}
function createApp<T>(type: AppPackageCheck<T>): T {
const packageExists = type.checkIfPackageExists();
return new type(packageExists)
}
let web = createApp(WebApp);
// compiler failure here, missing checkIfPackageExists
let backend = createApp(BackendApp);
This is a much simpler example for people only looking for removable usb drives.
using System.IO;
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.DriveType == DriveType.Removable)
{
Console.WriteLine(string.Format("({0}) {1}", drive.Name.Replace("\\",""), drive.VolumeLabel));
}
}
What about nonconforming base64 encoded headers? "SOMETHINGAPP-PARAMS:sdfSD45fdg45/aS"
Length restrictions hm. Can't you make your POST handling distinguish between the meanings? If you want simple parameters like sorting, I don't see why this would be a problem. I guess it's certainty you're worried about.
If you are on windows, what i suppose you need to do set the PATH like this:
SET PATH=%M2%
furthermore i assume you need to set your path to something like C:...\apache-maven-3.0.3\ cause this is the default folder for the windows archive. On the other i assume you need to add the path of maven to your and not set it to only maven so you setting should look like this:
SET PATH=%PATH%;%M2%
If you got this error trying to add a component to Visual Studio,- Microsoft.VisualStudio.TemplateWizardInterface
- (after trying to install weird development tools)
consider this solution(courtesy of larocha (thanks, whoever you are)):
Microsoft.VisualStudio.TemplateWizardInterfac
e" <dependentAssembly>
<!-- assemblyIdentity name="Microsoft.VisualStudio.TemplateWizardInterface" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" / -->
<bindingRedirect oldVersion="0.0.0.0-8.9.9.9" newVersion="9.0.0.0" />
</dependentAssembly>
source: http://webclientguidance.codeplex.com/workitem/15444
While reading from the file, your are not terminating your loop. So its read all the values and correctly throws EOFException on the next iteration of the read at line below:
price = in.readDouble();
If you read the documentation, it says:
Throws:
EOFException - if this input stream reaches the end before reading eight bytes.
IOException - the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
Put a proper termination condition in your while loop to resolve the issue e.g. below:
while(in.available() > 0) <--- if there are still bytes to read
Though a bit late, there is :/
which is the dedicated notation to specify a commit (or revision) based on the commit message, just prefix the search string with :/
, e.g.:
git show :/keyword(s)
Here <keywords>
can be a single word, or a complex regex pattern consisting of whitespaces, so please make sure to quote/escape when necessary, e.g.:
git log -1 -p ":/a few words"
Alternatively, a start point can be specified, to find the closest commit reachable from a specific point, e.g.:
git show 'HEAD^{/fix nasty bug}'
See: git revisions manual.
I feel like the simplest solution is sans javascript and simply putting the link in each cell (provided you don't have massive gullies between your cells or really think border lines). Have your css:
.tableClass td a{
display: block;
}
and then add a link per cell:
<table class="tableClass">
<tr>
<td><a href="#link">Link name</a></td>
<td><a href="#link">Link description</a></td>
<td><a href="#link">Link somthing else</a></td>
</tr>
</table>
boring but clean.
//c code for count the occurence of each character in a string.
void main()
{
int i,j; int c[26],count=0; char a[]="shahid";
clrscr();
for(i=0;i<26;i++)
{
count=0;
for(j=0;j<strlen(a);j++)
{
if(a[j]==97+i)
{
count++;
}
}
c[i]=count;
}
for(i=0;i<26;i++)
{
j=97+i;
if(c[i]!=0) { printf("%c of %d times\n",j,c[i]);
}
}
getch();
}
In Matlab I did something similar using the delaunay
function on the x
, y
coords only (not the z
), then plotting with trimesh
or trisurf
, using z
as the height.
SciPy has the Delaunay class, which is based on the same underlying QHull library that the Matlab's delaunay
function is, so you should get identical results.
From there, it should be a few lines of code to convert this Plotting 3D Polygons in python-matplotlib example into what you wish to achieve, as Delaunay
gives you the specification of each triangular polygon.
First, the error you're getting is due to where you're using the COUNT
function -- you can't use an aggregate (or group) function in the WHERE
clause.
Second, instead of using a subquery, simply join the table to itself:
SELECT a.pid
FROM Catalog as a LEFT JOIN Catalog as b USING( pid )
WHERE a.sid != b.sid
GROUP BY a.pid
Which I believe should return only rows where at least two rows exist with the same pid
but there is are at least 2 sid
s. To make sure you get back only one row per pid
I've applied a grouping clause.
Based on the answer of @AlokThakur (thanks!):
def run_system_command(command):
return_value = os.system(command)
# Calculate the return value code
return_value = int(bin(return_value).replace("0b", "").rjust(16, '0')[:8], 2)
if return_value != 0:
raise RuntimeError(f'The system command\n{command}\nexited with return code {return_value}')
Okay: weird syntax!
var el: HTMLElement = document.getElementById('content');
fixes the problem. I wonder why the example didn't do this in the first place?
complete code:
class Greeter {
element: HTMLElement;
span: HTMLElement;
timerToken: number;
constructor (element: HTMLElement) {
this.element = element;
this.element.innerText += "The time is: ";
this.span = document.createElement('span');
this.element.appendChild(this.span);
this.span.innerText = new Date().toUTCString();
}
start() {
this.timerToken = setInterval(() => this.span.innerText = new Date().toUTCString(), 500);
}
stop() {
clearTimeout(this.timerToken);
}
}
window.onload = () => {
var el: HTMLElement = document.getElementById('content');
var greeter = new Greeter(el);
greeter.start();
};
If you are trying to call getClass()
from Static method or static block the you can do the following way.
You can call getClass()
on the Properties
object you are loading into.
public static Properties pathProperties = null;
static {
pathProperties = new Properties();
String pathPropertiesFile = "/file.xml;
InputStream paths = pathProperties.getClass().getResourceAsStream(pathPropertiesFile);
}
Answering 10 years old question to help the newcomers.
We can use this package for that javascript-time-ago
// Load locale-specific relative date/time formatting rules.
import en from 'javascript-time-ago/locale/en'
// Add locale-specific relative date/time formatting rules.
TimeAgo.addLocale(en)
// Create relative date/time formatter.
const timeAgo = new TimeAgo('en-US')
timeAgo.format(new Date())
// "just now"
timeAgo.format(Date.now() - 60 * 1000)
// "a minute ago"
timeAgo.format(Date.now() - 2 * 60 * 60 * 1000)
// "2 hours ago"
timeAgo.format(Date.now() - 24 * 60 * 60 * 1000)
// "a day ago"
Well, you have multiple ways to do this: -if you don't have any data on your table, just drop it and create it again.
Dropping the existing field and creating it again like this
ALTER TABLE test DROP PRIMARY KEY, DROP test_id, ADD test_id int AUTO_INCREMENT NOT NULL FIRST, ADD PRIMARY KEY (test_id);
Or just modify it
ALTER TABLE test MODIFY test_id INT AUTO_INCREMENT NOT NULL, ADD PRIMARY KEY (test_id);
I had the same problem for a GitHub repository. My account was missing SSH Key. The process is
Then, you can clone the repository with submodules (git clone --recursive YOUR-GIT-REPO-URL
)
or
Run git submodule init
and git submodule update
to fetch submodules in already cloned repository.
The Java 8 streaming api offers an elegant alternative:
public static void main(String[] args) {
double avg = Arrays.stream(new int[]{1,3,2,5,8}).average().getAsDouble();
System.out.println("avg: " + avg);
}
You need to get 2 folders back from your css file.
Try:
background-image: url("../../images/image.png");
HTML div
elements, unlike SVG circle
primitives, are always rectangular.
You could use round corners (i.e. CSS border-radius
) to make it look round. On square elements, a value of 50% naturally forms a circle. Use this, or even a SVG inside your HTML:
document.body.innerHTML+='<i></i>'.repeat(4);
_x000D_
i{border-radius:50%;display:inline-block;background:#F48024;}
svg {fill:#F48024;width:60px;height:60px;}
i:nth-of-type(1n){width:30px;height:30px;}
i:nth-of-type(2n){width:60px;height:60px;}
_x000D_
<svg viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg">
<circle cx="60" cy="60" r="60"/>
</svg>
_x000D_
When you use Apache with mod_php apache is enforced in prefork
mode, and not worker
. As, even if php5 is known to support multi-thread, it is also known that some php5 libraries are not behaving very well in multithreaded environments (so you would have a locale call on one thread altering locale on other php threads, for example).
So, if php is not running in cgi way like with php-fpm you have mod_php inside apache and apache in prefork mode. On your tests you have simply commented the prefork settings and increased the worker settings, what you now have is default values for prefork settings and some altered values for the shared ones :
StartServers 20
MinSpareServers 5
MaxSpareServers 10
MaxClients 1024
MaxRequestsPerChild 0
This means you ask apache to start with 20 process, but you tell it that, if there is more than 10 process doing nothing it should reduce this number of children, to stay between 5 and 10 process available. The increase/decrease speed of apache is 1 per minute. So soon you will fall back to the classical situation where you have a fairly low number of free available apache processes (average 2). The average is low because usually you have something like 5 available process, but as soon as the traffic grows they're all used, so there's no process available as apache is very slow in creating new forks. This is certainly increased by the fact your PHP requests seems to be quite long, they do not finish early and the apache forks are not released soon enough to treat another request.
See on the last graphic the small amount of green before the red peak? If you could graph this on a 1 minute basis instead of 5 minutes you would see that this green amount was not big enough to take the incoming traffic without any error message.
Now you set 1024
MaxClients
. I guess the cacti graph are not taken after this configuration modification, because with such modification, when no more process are available, apache would continue to fork new children, with a limit of 1024 busy children. Take something like 20MB of RAM per child (or maybe you have a big memory_limit in PHP and allows something like 64MB or 256MB and theses PHP requests are really using more RAM), maybe a DB server... your server is now slowing down because you have only 768MB of RAM. Maybe when apache is trying to initiate the first 20 children you already reach the available RAM limit.
So. a classical way of handling that is to check the amount of memory used by an apache fork (make some top commands while it is running), then find how many parallel request you can handle with this amount of RAM (that mean parallel apache children in prefork mode). Let's say it's 12, for example. Put this number in apache mpm settings this way:
<IfModule prefork.c>
StartServers 12
MinSpareServers 12
MaxSpareServers 12
MaxClients 12
MaxRequestsPerChild 300
</IfModule>
That means you do not move the number of fork while traffic increase or decrease, because you always want to use all the RAM and be ready for traffic peaks. The 300
means you recyclate each fork after 300 requests, it's better than 0, it means you will not have potential memory leaks issues. MaxClients is set to 12 25 or 50 which is more than 12 to handle the (removed this strange sentende, I can't remember why I said that, if more than 12 requests are incoming the next one will be pushed in the Backlog queue, but you should set MaxClient to your targeted number of processes).ListenBacklog
queue, which can enqueue some requests, you may take a bigger queue, but you would get some timeouts maybe
And yes, that means you cannot handle more than 12 parallel requests.
If you want to handle more requests:
If your problem is really traffic peaks, solutions could be available with caches, like a proxy-cache server. If the problem is a random slowness in PHP then... it's an application problem, do you do some HTTP query to another site from PHP, for example?
And finally, as stated by @Jan Vlcinsky you could try nginx, where php will only be available as php-fpm. If you cannot buy RAM and must handle a big traffic that's definitively desserve a test.
Update: About internal dummy connections (if it's your problem, but maybe not).
Check this link and this previous answer. This is 'normal', but if you do not have a simple virtualhost theses requests are maybe hitting your main heavy application, generating slow http queries and preventing regular users to acces your apache processes. They are generated on graceful reload or children managment.
If you do not have a simple basic "It works" default Virtualhost prevent theses requests on your application by some rewrites:
RewriteCond %{HTTP_USER_AGENT} ^.*internal\ dummy\ connection.*$ [NC]
RewriteRule .* - [F,L]
Update:
Having only one Virtualhost does not protect you from internal dummy connections, it is worst, you are sure now that theses connections are made on your unique Virtualhost. So you should really avoid side effects on your application by using the rewrite rules.
Reading your cacti graphics, it seems your apache is not in prefork mode bug in worker mode. Run httpd -l
or apache2 -l
on debian, and check if you have worker.c or prefork.c. If you are in worker mode you may encounter some PHP problems in your application, but you should check the worker settings, here is an example:
<IfModule worker.c>
StartServers 3
MaxClients 500
MinSpareThreads 75
MaxSpareThreads 250
ThreadsPerChild 25
MaxRequestsPerChild 300
</IfModule>
You start 3 processes, each containing 25 threads (so 3*25=75 parallel requests available by default), you allow 75 threads doing nothing, as soon as one thread is used a new process is forked, adding 25 more threads. And when you have more than 250 threads doing nothing (10 processes) some process are killed. You must adjust theses settings with your memory. Here you allow 500 parallel process (that's 20 process of 25 threads). Your usage is maybe more:
<IfModule worker.c>
StartServers 2
MaxClients 250
MinSpareThreads 50
MaxSpareThreads 150
ThreadsPerChild 25
MaxRequestsPerChild 300
</IfModule>
The information you want can be found by running
mysql --help
or
mysqld --help --verbose
I tried this command on my machine:
mysql --help | grep "Default options" -A 1
And it printed out:
Default options are read from the following files in the given order:
/etc/my.cnf /usr/local/etc/my.cnf ~/.my.cnf
See if that works for you.
You go File->Settings->Gradle Look at the "Offline work" inbox, if it's checked u uncheck and try to sync again I have the same problem and i try this , the problem resolved. Good luck !
if(!string.IsNullOrEmpty(Request.QueryString["id"]))
{
//querystring contains id
}
I try dismis progress on method onPageFinished(), but not good too much, it has time delay to render webview.
try with onPageCommitVisible() better:
val progressBar = ProgressDialog(context)
progressBar.setCancelable(false)
progressBar.show()
val url = "your url here"
web_container.settings.javaScriptEnabled = true
web_container.loadUrl(url)
web_container.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
view.loadUrl(url)
progressBar.show()
return true
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
}
override fun onPageCommitVisible(view: WebView?, url: String?) {
super.onPageCommitVisible(view, url)
progressBar.dismiss()
}
}
web_container.setOnKeyListener(View.OnKeyListener { _, keyCode, event ->
if (keyCode == KEYCODE_BACK && event.action == MotionEvent.ACTION_UP
&& web_container.canGoBack()) {
web_container.goBack()
return@OnKeyListener true
}
return@OnKeyListener false
})
Such as
VERSION=1.0.0
deploy.sh
INPUTFILE=docker-compose.yml
RESULT_NAME=docker-compose.product.yml
NAME=test
prepare() {
local inFile=$(pwd)/$INPUTFILE
local outFile=$(pwd)/$RESULT_NAME
cp $inFile $outFile
while read -r line; do
OLD_IFS="$IFS"
IFS="="
pair=($line)
IFS="$OLD_IFS"
sed -i -e "s/\${${pair[0]}}/${pair[1]}/g" $outFile
done <.env
}
deploy() {
docker stack deploy -c $outFile $NAME
}
prepare
deploy
If you have copied & Pasted files from an old backup folder to new then its simple.
Just copy the old ibdata1
into your new one. You can find it from \xampp\mysql\data
I was getting this error because the project I was working on was developed on php 5.6 and after install, the project was unable to run on php7.1.
Just for anyone that uses Vagrant with ubuntu/nginx, in the nginx directory(/etc/nginx/), there is a directory named "sites-available" which contains a file named like the url configured for the vagrant maschine. In my case was homestead.app. Within this file there is a line that says something like
fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
There you can change the php version to the desired for that particular site.
Googled this but wasnt really able to find a simple answer that said where to look and what to change.
Hope that this helps anyone. Thanks.
I struggled with this myself, and tried Tomik's answer. However, this didn't made the layout to full available width on start, only when you add something to the view.
You'll need to set the LayoutParams.FILL_PARENT
when adding the view:
//I'm using actionbarsherlock, but it's the same.
LayoutParams layout = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
getSupportActionBar().setCustomView(overlay, layout);
This way it completely fills the available space. (You may need to use Tomik's solution too).
Paul Irish has a way to do this that covers most of the common problems. See his bullet-proof @font-face article:
The final variant, which stops unnecessary data from being downloaded by IE, and works in IE8, Firefox, Opera, Safari, and Chrome looks like this:
@font-face {
font-family: 'Graublau Web';
src: url('GraublauWeb.eot');
src: local('Graublau Web Regular'), local('Graublau Web'),
url("GraublauWeb.woff") format("woff"),
url("GraublauWeb.otf") format("opentype"),
url("GraublauWeb.svg#grablau") format("svg");
}
He also links to a generator that will translate the fonts into all the formats you need.
As others have already specified, this will only work in the latest generation of browsers. Your best bet is to use this in conjunction with something like Cufon, and only load Cufon if the browser doesn't support @font-face
.
>>> import random
>>> random.randrange(5,60,5)
should work in any Python >= 2.
There are after and before methods for Timestamp
which will do the trick
These steps will do it:
git reset --hard HEAD
git clean -f -x -d -n
then without -n
This will take care of all local changes. Now the commits...
git status
and note the line such as:
Your branch is ahead of 'xxxx' by N commits.
Take a note of number 'N' now:
git reset --hard HEAD~N
git pull
and finally:
git status
should show nothing to add/commit. All clean.
However, a fresh clone can do the same (but is much slow).
===Updated===
As my git knowledge slightly improved over the the time, I have come up with yet another simpler way to do the same. Here is how (#with explanation). While in your working branch:
git fetch # This updates 'remote' portion of local repo.
git reset --hard origin/<your-working-branch>
# this will sync your local copy with remote content, discarding any committed
# or uncommitted changes.
Although your local commits and changes will disappear from sight after this, it is possible to recover committed changes, if necessary.
$suborder['payment_date'] = Carbon::parse($item['created_at'])->format('M d Y');
The easiest way I found:
<Setter Property="Focusable" Value="false"/>
The "adjustment" in adjusted R-squared is related to the number of variables and the number of observations.
If you keep adding variables (predictors) to your model, R-squared will improve - that is, the predictors will appear to explain the variance - but some of that improvement may be due to chance alone. So adjusted R-squared tries to correct for this, by taking into account the ratio (N-1)/(N-k-1) where N = number of observations and k = number of variables (predictors).
It's probably not a concern in your case, since you have a single variate.
Some references:
A cleaner way to do this:
class Book {
public Title: string;
public Price: number;
public Description: string;
constructor(public BookId: number, public Author: string){}
}
Then
var bks: Book[] = [
new Book(1, "vamsee")
];
In order to use base_url()
, you must first have the URL Helper loaded. This can be done either in application/config/autoload.php
(on or around line 67):
$autoload['helper'] = array('url');
Or, manually:
$this->load->helper('url');
Once it's loaded, be sure to keep in mind that base_url()
doesn't implicitly print or echo out anything, rather it returns the value to be printed:
echo base_url();
Remember also that the value returned is the site's base url as provided in the config file. CodeIgniter will accomodate an empty value in the config file as well:
If this (base_url) is not set then CodeIgniter will guess the protocol, domain and path to your installation.
application/config/config.php, line 13
This should work for you. Infact the one which you are thinking will also work:-
.......
DECLARE @returnvalue INT
EXEC @returnvalue = SP_One
.....
downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?
You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.
http://www.microsoft.com/en-us/download/details.aspx?id=1695
Its unbelievable after so many answers, but I did it little differently in the end. I don't like primary key to be nullable, I want to have it as first argument and also want to insert without defining it and also it should not be var.
@Entity(tableName = "employments")
data class Employment(
@PrimaryKey(autoGenerate = true) val id: Long,
@ColumnInfo(name = "code") val code: String,
@ColumnInfo(name = "title") val name: String
){
constructor(code: String, name: String) : this(0, code, name)
}
- Here its more about the coding style
than being the functionality....
- The 1st option is very clear, but then the 2nd one is quite elegant... no offense, its just my view..
As mentioned above:
The GOPATH environment variable specifies the location of your workspace.
For Windows, this worked for me (in Ms-dos window):
set GOPATH=D:\my_folder_for_go_code\
This creates a GOPATH variable that Ms-dos recognizes when used as follows:
cd %GOPATH%
You forgot to use Comic Sans as a font, that's why its erroring.
This should do the trick:
pw_bytes.decode("utf-8")
I am not sure if this is the correct solution but I have achieved this by redefining .marquee class just after animation CSS.
Check below:
<style>
#marquee-wrapper{
width:700px;
display:block;
border:1px solid red;
}
div.marquee{
width:100px;
height:100px;
background:red;
position:relative;
animation:myfirst 5s;
-moz-animation:myfirst 5s; /* Firefox */
}
@-moz-keyframes myfirst /* Firefox */{
0% {background:red; left:0px; top:0px;}
100% {background:red; left:100%; top:0px}
}
div.marquee{
left:700px; top:0px
}
</style>
<!-- HTMl COde -->
<p><b>Note:</b> This example does not work in Internet Explorer and Opera.</p>
<div id="marquee-wrapper">
<div class="marquee"></div>
nope, none of this will work. What you need is this!!!
Try this:
if (screen.width <= 960) {
alert('Less than 960');
} else if (screen.width >960) {
alert('More than 960');
}
Also, you can copy an item from the finder using command-C, jump into the Terminal (e.g. using Spotlight or QuickSilver) type 'cd ' and simply paste with command-v
As mentioned earlier, you'll create the add and delete commands. You can use svn move on both your working copy or the repository url. If you use your working copy, the changes won't be committed - you'll need to commit in a separate operation.
If you svn move a URL, you'll need to supply a --message, and the changes will be reflected in the repository immediately.
Or check this out this will help align all the elements at once.
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/showdescriptioncontenttitle"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:layout_gravity="center"
android:gravity="center_horizontal"
>
<TextView
android:id="@+id/showdescriptiontitle"
android:text="Title"
android:textSize="35dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
I had the same problem. When I run a php file, the web browser showed me the php code instead of execute it. I had tried many times: uninstall/reinstall the wampserver64, working around the PHP/Apache settings/modules, etc. After 2 days: I realised that when I tried to run the php file within the notepad++ by pressing the default combination "ctrl + alt + shift + R" for chrome. It was trying to execute my php file like: "file///C:/wamp64/www/bla/bla.." in my chrome's address bar. That was my problem. I made the changes according to page Configuring Notepad++ to run php on localhost?. My problem was solved. But after 2 days..
You can try:
$ git fetch --all
$ git reset --hard origin/master
$ git pull
I am not writing anything same here. Just a changelog note from PHP manual.
Changelog for continue
Version Description
7.0.0 - continue outside of a loop or switch control structure is now detected at compile-time instead of run-time as before, and triggers an E_COMPILE_ERROR.
5.4.0 continue 0; is no longer valid. In previous versions it was interpreted the same as continue 1;.
5.4.0 Removed the ability to pass in variables (e.g., $num = 2; continue $num;) as the numerical argument.
Changelog for break
Version Description
7.0.0 break outside of a loop or switch control structure is now detected at compile-time instead of run-time as before, and triggers an E_COMPILE_ERROR.
5.4.0 break 0; is no longer valid. In previous versions it was interpreted the same as break 1;.
5.4.0 Removed the ability to pass in variables (e.g., $num = 2; break $num;) as the numerical argument.
To make a FULL jQuery plugin as .outerHTML
, add the following script to any js file and include after jQuery in your header:
update New version has better control as well as a more jQuery Selector friendly service! :)
;(function($) {
$.extend({
outerHTML: function() {
var $ele = arguments[0],
args = Array.prototype.slice.call(arguments, 1)
if ($ele && !($ele instanceof jQuery) && (typeof $ele == 'string' || $ele instanceof HTMLCollection || $ele instanceof Array)) $ele = $($ele);
if ($ele.length) {
if ($ele.length == 1) return $ele[0].outerHTML;
else return $.map($("div"), function(ele,i) { return ele.outerHTML; });
}
throw new Error("Invalid Selector");
}
})
$.fn.extend({
outerHTML: function() {
var args = [this];
if (arguments.length) for (x in arguments) args.push(arguments[x]);
return $.outerHTML.apply($, args);
}
});
})(jQuery);
This will allow you to not only get the outerHTML of one element, but even get an Array return of multiple elements at once! and can be used in both jQuery standard styles as such:
$.outerHTML($("#eleID")); // will return outerHTML of that element and is
// same as
$("#eleID").outerHTML();
// or
$.outerHTML("#eleID");
// or
$.outerHTML(document.getElementById("eleID"));
For multiple elements
$("#firstEle, .someElesByClassname, tag").outerHTML();
console.log('$.outerHTML($("#eleID"))'+"\t", $.outerHTML($("#eleID"))); _x000D_
console.log('$("#eleID").outerHTML()'+"\t\t", $("#eleID").outerHTML());_x000D_
console.log('$("#firstEle, .someElesByClassname, tag").outerHTML()'+"\t", $("#firstEle, .someElesByClassname, tag").outerHTML());_x000D_
_x000D_
var checkThisOut = $("div").outerHTML();_x000D_
console.log('var checkThisOut = $("div").outerHTML();'+"\t\t", checkThisOut);_x000D_
$.each(checkThisOut, function(i, str){ $("div").eq(i).text("My outerHTML Was: " + str); });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script src="https://rawgit.com/JDMcKinstry/ce699e82c7e07d02bae82e642fb4275f/raw/deabd0663adf0d12f389ddc03786468af4033ad2/jQuery.outerHTML.js"></script>_x000D_
<div id="eleID">This will</div>_x000D_
<div id="firstEle">be Replaced</div>_x000D_
<div class="someElesByClassname">At RunTime</div>_x000D_
<h3><tag>Open Console to see results</tag></h3>
_x000D_
You didn't bind all your bindings here
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM comments WHERE articleid = :art
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );
You've declared a binding called :numRows but you never actually bind anything to it.
UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion
Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.
In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)
Better to find cells from gridview instead of static/fix index so it will not generate any problem whenever you will add/remove any columns on gridview.
ASPX:
<asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound" >
<Columns>
<asp:BoundField HeaderText="Date" DataField="CreatedDate" />
</Columns>
</asp:GridView>
CS:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
if (string.Compare(e.Row.Cells[i].Text, "Date", true) == 0)
{
e.Row.Cells[i].Text = "Created Date";
}
}
}
}
Step 1: Install the dependencies
sudo apt-get install build-dep python-psycopg2
Step 2: Run this command in your virtualenv
pip install psycopg2
Ref: Fernando Munoz
Building off of @gnovice's answer, you can actually create filled plots with shading only in the area between the two curves. Just use fill
in conjunction with fliplr
.
Example:
x=0:0.01:2*pi; %#initialize x array
y1=sin(x); %#create first curve
y2=sin(x)+.5; %#create second curve
X=[x,fliplr(x)]; %#create continuous x value array for plotting
Y=[y1,fliplr(y2)]; %#create y values for out and then back
fill(X,Y,'b'); %#plot filled area
By flipping the x array and concatenating it with the original, you're going out, down, back, and then up to close both arrays in a complete, many-many-many-sided polygon.
In the context of Drupal, the difference will depend whether clean URLs are on or not.
With them off, $_SERVER['REQUEST_URI']
will have the full path of the page as called w/ /index.php
, while $_GET["q"]
will just have what is assigned to q
.
With them on, they will be nearly identical w/o other arguments, but $_GET["q"]
will be missing the leading /
. Take a look towards the end of the default .htaccess to see what is going on. They will also differ if additional arguments are passed into the page, eg when a pager is active.
Yes, it's OK - it's just like using it in an if
statement. Of course, you can't use a break
to break out of a loop from inside a switch.
At the end of each switch case, just add the break
-statement to resolve this problem
switch (manu)
{
case manufacturers.Nokia:
_phanefact = new NokiaFactory();
break;
case manufacturers.Samsung:
_phanefact = new SamsungFactory();
break;
}