You can declare SqlConnection
and SqlCommand
instances at global level so that you can use it through out the class. Connection string is in Web.Config
.
SqlConnection sqlConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlConnector"].ConnectionString);
SqlCommand sqlcomm = new SqlCommand();
Now you can use the below method to pass values to Stored Procedure and get the DataSet
.
public DataSet GetDataSet(string paramValue)
{
sqlcomm.Connection = sqlConn;
using (sqlConn)
{
try
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
// This will be your input parameter and its value
sqlcomm.Parameters.AddWithValue("@ParameterName", paramValue);
// You can retrieve values of `output` variables
var returnParam = new SqlParameter
{
ParameterName = "@Error",
Direction = ParameterDirection.Output,
Size = 1000
};
sqlcomm.Parameters.Add(returnParam);
// Name of stored procedure
sqlcomm.CommandText = "StoredProcedureName";
da.SelectCommand = sqlcomm;
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds);
}
}
catch (SQLException ex)
{
Console.WriteLine("SQL Error: " + ex.Message);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
return new DataSet();
}
The following is the sample of connection string in config file
<connectionStrings>
<add name="SqlConnector"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=YourDatabaseName;User id=YourUserName;Password=YourPassword"
providerName="System.Data.SqlClient" />
</connectionStrings>
In your code where you run the stored procedure you should have something like this:
SqlCommand c = new SqlCommand(...)
//...
Add such a line of code:
c.CommandTimeout = 0;
This will wait as much time as needed for the operation to complete.
For some strange reason the SelectElement
for webdriver (version 2.25.1.0) does not properly work with the firefoxdriver (Firefox 15). Sometimes it may not select an option from a dropdownlist. It does, however, seem to work with the chromedriver... This is a link to the chromedriver... just drop it in the bin dir.
The concatenation operator '&' is allowed on the right side of the signal assignment operator '<=', only
Also:
func getTime() -> (hour: Int, minute: Int,second: Int) {
let hour = 1
let minute = 2
let second = 3
return ( hour, minute, second)
}
Then it's invoked as:
let time = getTime()
print("hour: \(time.hour), minute: \(time.minute), second: \(time.second)")
This is the standard way how to use it in the book The Swift Programming Language written by Apple.
or just like:
let time = getTime()
print("hour: \(time.0), minute: \(time.1), second: \(time.2)")
it's the same but less clearly.
i came here for the same problem, i couldn't find anywhere in my code where a certain user was making the action. apparently it was from a trigger that was using a user which was long deleted (db was restored from an older version) so in case you are puzzled as i were, take a look at your db events/triggers/routines. hope this will help someone.
An alternative is to use the maven shade plugin to build an uber-jar
.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version> Your Version Here </version>
<configuration>
<!-- put your configurations here -->
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
If you want to remove all pending tasks and also the active and reserved ones to completely stop Celery, this is what worked for me:
from proj.celery import app
from celery.task.control import inspect, revoke
# remove pending tasks
app.control.purge()
# remove active tasks
i = inspect()
jobs = i.active()
for hostname in jobs:
tasks = jobs[hostname]
for task in tasks:
revoke(task['id'], terminate=True)
# remove reserved tasks
jobs = i.reserved()
for hostname in jobs:
tasks = jobs[hostname]
for task in tasks:
revoke(task['id'], terminate=True)
Below are two methods that are superior to looping. Both handle a "no-find" case.
VLOOKUP
with error-handling if the variable doesn't exist (INDEX/MATCH
may be a better route than VLOOKUP
, ie if your two columns A and B were in reverse order, or were far apart)VBAs FIND
method (matching a whole string in column A given I use the xlWhole
argument)
Sub Method1()
Dim strSearch As String
Dim strOut As String
Dim bFailed As Boolean
strSearch = "trees"
On Error Resume Next
strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
If Err.Number <> 0 Then bFailed = True
On Error GoTo 0
If Not bFailed Then
MsgBox "corresponding value is " & vbNewLine & strOut
Else
MsgBox strSearch & " not found"
End If
End Sub
Sub Method2()
Dim rng1 As Range
Dim strSearch As String
strSearch = "trees"
Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
If Not rng1 Is Nothing Then
MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
Else
MsgBox strSearch & " not found"
End If
End Sub
1 += 2
is a syntax error (left-side must be a variable).
x += y
is shorthand for x = x + y
.
Update in 2020. Here is another way if you prefer.
IdentityResult res = new IdentityResult();
var _role = new IdentityRole();
_role.Name = role.RoleName;
res = await _roleManager.CreateAsync(_role);
if (!res.Succeeded)
{
foreach (IdentityError er in res.Errors)
{
ModelState.AddModelError(string.Empty, er.Description);
}
ViewBag.UserMessage = "Error Adding Role";
return View();
}
else
{
ViewBag.UserMessage = "Role Added";
return View();
}
Why you dont use document.getElementById("myId").reset();
? this is the simple and pretty
I found a solution that is more efficient than currently accepted answer, because current answer forces all list elements to be refreshed. My solution will refresh only one element (that was touched) by calling adapters getView and recycling current view which adds even more efficiency.
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Edit object data that is represented in Viewat at list's "position"
view = mAdapter.getView(position, view, parent);
}
});
I stumbled over this thread searching for answer to similar case. Basically all answers are found, but it's still hard to extract the essentials from them.
Assume a class Foo probably derived from some other class(es) with probably more classes derived from it.
Then accessing
this.method()
this.property
Foo.method()
Foo.property
this.constructor.method()
this.constructor.property
this.method()
this.property
Foo.method()
Foo.property
Foo.prototype.method.call( this )
Object.getOwnPropertyDescriptor( Foo.prototype,"property" ).get.call(this);
Keep in mind that using
this
isn't working this way when using arrow functions or invoking methods/getters explicitly bound to custom value.
this
is referring to current instance.super
is basically referring to same instance, but somewhat addressing methods and getters written in context of some class current one is extending (by using the prototype of Foo's prototype).this.constructor
.this
is available to refer to the definition of current class directly.super
is not referring to some instance either, but to static methods and getters written in context of some class current one is extending.Try this code:
class A {_x000D_
constructor( input ) {_x000D_
this.loose = this.constructor.getResult( input );_x000D_
this.tight = A.getResult( input );_x000D_
console.log( this.scaledProperty, Object.getOwnPropertyDescriptor( A.prototype, "scaledProperty" ).get.call( this ) );_x000D_
}_x000D_
_x000D_
get scaledProperty() {_x000D_
return parseInt( this.loose ) * 100;_x000D_
}_x000D_
_x000D_
static getResult( input ) {_x000D_
return input * this.scale;_x000D_
}_x000D_
_x000D_
static get scale() {_x000D_
return 2;_x000D_
}_x000D_
}_x000D_
_x000D_
class B extends A {_x000D_
constructor( input ) {_x000D_
super( input );_x000D_
this.tight = B.getResult( input ) + " (of B)";_x000D_
}_x000D_
_x000D_
get scaledProperty() {_x000D_
return parseInt( this.loose ) * 10000;_x000D_
}_x000D_
_x000D_
static get scale() {_x000D_
return 4;_x000D_
}_x000D_
}_x000D_
_x000D_
class C extends B {_x000D_
constructor( input ) {_x000D_
super( input );_x000D_
}_x000D_
_x000D_
static get scale() {_x000D_
return 5;_x000D_
}_x000D_
}_x000D_
_x000D_
class D extends C {_x000D_
constructor( input ) {_x000D_
super( input );_x000D_
}_x000D_
_x000D_
static getResult( input ) {_x000D_
return super.getResult( input ) + " (overridden)";_x000D_
}_x000D_
_x000D_
static get scale() {_x000D_
return 10;_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
let instanceA = new A( 4 );_x000D_
console.log( "A.loose", instanceA.loose );_x000D_
console.log( "A.tight", instanceA.tight );_x000D_
_x000D_
let instanceB = new B( 4 );_x000D_
console.log( "B.loose", instanceB.loose );_x000D_
console.log( "B.tight", instanceB.tight );_x000D_
_x000D_
let instanceC = new C( 4 );_x000D_
console.log( "C.loose", instanceC.loose );_x000D_
console.log( "C.tight", instanceC.tight );_x000D_
_x000D_
let instanceD = new D( 4 );_x000D_
console.log( "D.loose", instanceD.loose );_x000D_
console.log( "D.tight", instanceD.tight );
_x000D_
I think keySet() may be well to find the keys mapping to the value, and have a better coding style than entrySet().
Ex:
Suppose you have a HashMap map, ArrayList res, a value you want to find all the key mapping to , then store keys to the res.
You can write code below:
for (int key : map.keySet()) {
if (map.get(key) == value) {
res.add(key);
}
}
rather than use entrySet() below:
for (Map.Entry s : map.entrySet()) {
if ((int)s.getValue() == value) {
res.add((int)s.getKey());
}
}
Hope it helps :)
Here is a bash script inspired by abarnert's answer which will unpack a package named MyPackage.pkg
into a subfolder named MyPackage_pkg
and then open the folder in Finder.
#!/usr/bin/env bash
filename="$*"
dirname="${filename/\./_}"
pkgutil --expand "$filename" "$dirname"
cd "$dirname"
tar xvf Payload
open .
Usage:
pkg-upack.sh MyPackage.pkg
Warning: This will not work in all cases, and will fail with certain files, e.g. the PKGs inside the OSX system installer. If you want to peek inside the pkg file and see what's inside, you can try SuspiciousPackage (free app), and if you need more options such as selectively unpacking specific files, then have a look at Pacifist (nagware).
This hack works for Internet Explorer 6 and later, Google Chrome, Firefox, and Opera:
table {
border-collapse: separate;
border-spacing: 10px; /* cellspacing */
*border-collapse: expression('separate', cellSpacing = '10px');
}
table td, table th {
padding: 10px; /* cellpadding */
}
The *
declaration is for Internet Explorer 6 and 7, and other browsers will properly ignore it.
expression('separate', cellSpacing = '10px')
returns 'separate'
, but both statements are run, as in JavaScript you can pass more arguments than expected and all of them will be evaluated.
I feel I need to clarify one very important thing, for others (like my co-worker) who came across this thread and got the wrong information.
The answer given ("Try decimal(9,2) or decimal(10,2) or whatever.") is correct, but the reason ("increase the number of digits before the decimal") is wrong.
decimal(p,s) and numeric(p,s) both specify a Precision and a Scale. The "precision" is not the number of digits to the left of the decimal, but instead is the total precision of the number.
For example: decimal(2,1) covers 0.0 to 9.9, because the precision is 2 digits (00 to 99) and the scale is 1. decimal(4,1) covers 000.0 to 999.9 decimal(4,2) covers 00.00 to 99.99 decimal(4,3) covers 0.000 to 9.999
This can also happen if you have the wrong python27.dll file (in case of Windows), to solve this just re-install (or extract) python with the exact corresponding dll version. I had a similar experience.
You could do it if template is a react component.
Template.js
var React = require('react');
var Template = React.createClass({
render: function(){
return (<div>Mi HTML</div>);
}
});
module.exports = Template;
MainComponent.js
var React = require('react');
var ReactDOM = require('react-dom');
var injectTapEventPlugin = require("react-tap-event-plugin");
var Template = require('./Template');
//Needed for React Developer Tools
window.React = React;
//Needed for onTouchTap
//Can go away when react 1.0 release
//Check this repo:
//https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin();
var MainComponent = React.createClass({
render: function() {
return(
<Template/>
);
}
});
// Render the main app react component into the app div.
// For more details see: https://facebook.github.io/react/docs/top-level-api.html#react.render
ReactDOM.render(
<MainComponent />,
document.getElementById('app')
);
And if you are using Material-UI, for compatibility use Material-UI Components, no normal inputs.
using java you can do this:
Using the Scanner:
Scanner reader = new Scanner(System.in);
String line = reader.nextLine();
// now you can use some converter to change the String value to the value you need.
// for example Long.parseLong(line) or Integer.parseInt(line) or other type cast
Using the BufferedReader:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
// now you can use some converter to change the String value to the value you need.
// for example Long.parseLong(line) or Integer.parseInt(line) or other type cast
In the two cases you need to pass you Default input, in my case System.in
You might looking for the placeholder
attribute which will display a grey text in the input field while empty.
From Mozilla Developer Network:
A hint to the user of what can be entered in the control . The placeholder text must not contain carriage returns or line-feeds. This attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored.
However as it's a fairly 'new' tag (from the HTML5 specification afaik) you might want to to browser testing to make sure your target audience is fine with this solution.
(If not tell tell them to upgrade browser 'cause this tag works like a charm ;o) )
And finally a mini-fiddle to see it directly in action: http://jsfiddle.net/LnU9t/
Edit: Here is a plain jQuery solution which will also clear the input field if an escape keystroke is detected: http://jsfiddle.net/3GLwE/
AngularJS provides a simple and concise way to associate routes with controllers and templates using a $routeProvider
object. While recently updating an application to the latest release (1.2 RC1 at the current time) I realized that $routeProvider
isn’t available in the standard angular.js script any longer.
After reading through the change log I realized that routing is now a separate module (a great move I think) as well as animation and a few others. As a result, standard module definitions and config code like the following won’t work any longer if you’re moving to the 1.2 (or future) release:
var app = angular.module('customersApp', []);
app.config(function ($routeProvider) {
$routeProvider.when('/', {
controller: 'customersController',
templateUrl: '/app/views/customers.html'
});
});
How do you fix it?
Simply add angular-route.js in addition to angular.js to your page (grab a version of angular-route.js here – keep in mind it’s currently a release candidate version which will be updated) and change the module definition to look like the following:
var app = angular.module('customersApp', ['ngRoute']);
If you’re using animations you’ll need angular-animation.js and also need to reference the appropriate module:
var app = angular.module('customersApp', ['ngRoute', 'ngAnimate']);
Your Code can be as follows:
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/controllerone', {
controller: 'friendDetails',
templateUrl: 'controller3.html'
}, {
controller: 'friendsName',
templateUrl: 'controller3.html'
}
)
.when('/controllerTwo', {
controller: 'simpleControoller',
templateUrl: 'views.html'
})
.when('/controllerThree', {
controller: 'simpleControoller',
templateUrl: 'view2.html'
})
.otherwise({
redirectTo: '/'
});
});
$('.reset').on('click',function(){
$('#upload input, #upload select').each(
function(index){
var input = $(this);
if(input.attr('type')=='text'){
document.getElementById(input.attr('id')).value = null;
}else if(input.attr('type')=='checkbox'){
document.getElementById(input.attr('id')).checked = false;
}else if(input.attr('type')=='radio'){
document.getElementById(input.attr('id')).checked = false;
}else{
document.getElementById(input.attr('id')).value = '';
//alert('Type: ' + input.attr('type') + ' -Name: ' + input.attr('name') + ' -Value: ' + input.val());
}
}
);
});
Most of the solutions provided here use alternative repetition paths i.e. (A|B)*.
You may encounter stack overflows on large inputs since some pattern compiler implements this using recursion.
Java for instance: http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6337993
Something like this:
"(?:[^"\\]*(?:\\.)?)*"
, or the one provided by Guy Bedford will reduce the amount of parsing steps avoiding most stack overflows.
Some cases just worked when I used Math.log10:
public static double log2(int n)
{
return (Math.log10(n) / Math.log10(2));
}
It really all comes down to how you want to handle output that the command might return and whether you want your PHP script to wait for the callee program to finish or not.
exec
executes a command and passes output to the caller (or returns it in an optional variable).
passthru
is similar to the exec()
function in that it executes a command . This function should be used in place of exec()
or system()
when the output from the Unix command is binary data which needs to be passed directly back to the browser.
system
executes an external program and displays the output, but only the last line.
If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru()
function.
Based on answers from Hogan and Zero Trick Pony. I think this should be both fast and flexible enough to handle well most use cases:
var hash = '####################################################################'
function build_string(length) {
if (length == 0) {
return ''
} else if (hash.length <= length) {
return hash.substring(0, length)
} else {
var result = hash
const half_length = length / 2
while (result.length <= half_length) {
result += result
}
return result + result.substring(0, length - result.length)
}
}
I made a script to solve this which is here. You don't need any extra software for this.
Installation:
brew install akashaggarwal7/tools/tsay
Usage:
sleep 5; tsay
Feel free to contribute!
I found that when within a Miniconda3 environment I had to run:
conda deactivate
Neither deactivate
nor source deactivate
worked for me.
The problem is in your pubspec.yaml
, here you need to delete the last comma.
uses-material-design: true,
As for me none of the solutions worked well, only using:
-webkit-mask-image: -webkit-radial-gradient(circle, white, black);
on the wrapper element did the job.
Here the example: http://jsfiddle.net/gpawlik/qWdf6/74/
Just add this in you styles.xml. The colorPrimary is for the action bar and the colorPrimaryDark is for the status bar.
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:colorPrimary">@color/primary</item>
<item name="android:colorPrimaryDark">@color/primary_dark</item>
</style>
This picture from developer android explains more about color pallete. You can read more on this link.
Option Explicit
Const ConnectionStrngAccessPW As String = _"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\BARON\Desktop\Test_DB-PW.accdb;
Jet OLEDB:Database Password=123pass;"
Const ConnectionStrngAccess As String = _"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\BARON\Desktop\Test_DB.accdb;
Persist Security Info=False;"
'C:\Users\BARON\Desktop\Test.accdb
Sub ModifyingExistingDataOnAccessDB()
Dim TableConn As ADODB.Connection
Dim TableData As ADODB.Recordset
Set TableConn = New ADODB.Connection
Set TableData = New ADODB.Recordset
TableConn.ConnectionString = ConnectionStrngAccess
TableConn.Open
On Error GoTo CloseConnection
With TableData
.ActiveConnection = TableConn
'.Source = "SELECT Emp_Age FROM Roster WHERE Emp_Age > 40;"
.Source = "Roster"
.LockType = adLockOptimistic
.CursorType = adOpenForwardOnly
.Open
On Error GoTo CloseRecordset
Do Until .EOF
If .Fields("Emp_Age").Value > 40 Then
.Fields("Emp_Age").Value = 40
.Update
End If
.MoveNext
Loop
.MoveFirst
MsgBox "Update Complete"
End With
CloseRecordset:
TableData.CancelUpdate
TableData.Close
CloseConnection:
TableConn.Close
Set TableConn = Nothing
Set TableData = Nothing
End Sub
Sub AddingDataToAccessDB()
Dim TableConn As ADODB.Connection
Dim TableData As ADODB.Recordset
Dim r As Range
Set TableConn = New ADODB.Connection
Set TableData = New ADODB.Recordset
TableConn.ConnectionString = ConnectionStrngAccess
TableConn.Open
On Error GoTo CloseConnection
With TableData
.ActiveConnection = TableConn
.Source = "Roster"
.LockType = adLockOptimistic
.CursorType = adOpenForwardOnly
.Open
On Error GoTo CloseRecordset
Sheet3.Activate
For Each r In Range("B3", Range("B3").End(xlDown))
MsgBox "Adding " & r.Offset(0, 1)
.AddNew
.Fields("Emp_ID").Value = r.Offset(0, 0).Value
.Fields("Emp_Name").Value = r.Offset(0, 1).Value
.Fields("Emp_DOB").Value = r.Offset(0, 2).Value
.Fields("Emp_SOD").Value = r.Offset(0, 3).Value
.Fields("Emp_EOD").Value = r.Offset(0, 4).Value
.Fields("Emp_Age").Value = r.Offset(0, 5).Value
.Fields("Emp_Gender").Value = r.Offset(0, 6).Value
.Update
Next r
MsgBox "Update Complete"
End With
CloseRecordset:
TableData.Close
CloseConnection:
TableConn.Close
Set TableConn = Nothing
Set TableData = Nothing
End Sub
You can have only one default export which you declare like:
export default App;
or
export default class App extends React.Component {...
and later do import App from './App'
If you want to export something more you can use named exports which you declare without default
keyword like:
export {
About,
Contact,
}
or:
export About;
export Contact;
or:
export const About = class About extends React.Component {....
export const Contact = () => (<div> ... </div>);
and later you import them like:
import App, { About, Contact } from './App';
EDIT:
There is a mistake in the tutorial as it is not possible to make 3 default exports in the same main.js
file. Other than that why export anything if it is no used outside the file?. Correct main.js
:
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute } from 'react-router'
class App extends React.Component {
...
}
class Home extends React.Component {
...
}
class About extends React.Component {
...
}
class Contact extends React.Component {
...
}
ReactDOM.render((
<Router history = {browserHistory}>
<Route path = "/" component = {App}>
<IndexRoute component = {Home} />
<Route path = "home" component = {Home} />
<Route path = "about" component = {About} />
<Route path = "contact" component = {Contact} />
</Route>
</Router>
), document.getElementById('app'))
EDIT2:
another thing is that this tutorial is based on react-router-V3 which has different api than v4.
The shortcut didn't work for me in Visual Studio 2015, also it was not in the edit menu.
Download and install the Productivity Power Tools for VS2015 and than you can find these options in the edit > advanced menu.
Laravel 5 compatible and generic way:
I just had the same problem and solved it in a generic way. If you create an item it uses the default rules, if you update an item it will check your rules for :unique
and insert an exclude automatically (if needed).
Create a BaseModel
class and let all your models inherit from it:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class BaseModel extends Model {
/**
* The validation rules for this model
*
* @var array
*/
protected static $rules = [];
/**
* Return model validation rules
*
* @return array
*/
public static function getRules() {
return static::$rules;
}
/**
* Return model validation rules for an update
* Add exception to :unique validations where necessary
* That means: enforce unique if a unique field changed.
* But relax unique if a unique field did not change
*
* @return array;
*/
public function getUpdateRules() {
$updateRules = [];
foreach(self::getRules() as $field => $rule) {
$newRule = [];
// Split rule up into parts
$ruleParts = explode('|',$rule);
// Check each part for unique
foreach($ruleParts as $part) {
if(strpos($part,'unique:') === 0) {
// Check if field was unchanged
if ( ! $this->isDirty($field)) {
// Field did not change, make exception for this model
$part = $part . ',' . $field . ',' . $this->getAttribute($field) . ',' . $field;
}
}
// All other go directly back to the newRule Array
$newRule[] = $part;
}
// Add newRule to updateRules
$updateRules[$field] = join('|', $newRule);
}
return $updateRules;
}
}
You now define your rules in your model like you are used to:
protected static $rules = [
'name' => 'required|alpha|unique:roles',
'displayName' => 'required|alpha_dash',
'permissions' => 'array',
];
And validate them in your Controller. If the model does not validate, it will automatically redirect back to the form with the corresponding validation errors. If no validation errors occurred it will continue to execute the code after it.
public function postCreate(Request $request)
{
// Validate
$this->validate($request, Role::getRules());
// Validation successful -> create role
Role::create($request->all());
return redirect()->route('admin.role.index');
}
public function postEdit(Request $request, Role $role)
{
// Validate
$this->validate($request, $role->getUpdateRules());
// Validation successful -> update role
$role->update($request->input());
return redirect()->route('admin.role.index');
}
That's it! :) Note that on creation we call Role::getRules()
and on edit we call $role->getUpdateRules()
.
I can give you an example which results with the same problem, but it may not give you an answer to your question. (Additionally, in this example, I'm using my Maven 3 knowledge, which may not apply for Maven 2.)
In a multi-module maven project (contains modules A
and B
, where B
depends on A
), you can add also a test dependency on A
from B
.
This dependency may look as follows:
<dependency>
<groupId>com.foo</groupId>
<artifactId>A</artifactId>
<type>test-jar</type> <!-- I'm not sure if there is such a thing in Maven 2, but there is definitely a way to achieve such dependency in Maven 2. -->
<scope>test</scope>
</dependency>
(for more information refer to https://maven.apache.org/guides/mini/guide-attached-tests.html)
Note that the project A
produces secondary artifact with a classifier tests
where the test classes and test resources are located.
If you build your project with -Dmaven.test.skip=true
, you will get a dependency resolution error as long as the test artifact wasn't found in your local repo or external repositories. The reason is that the tests classes were neither compiled nor the tests
artifact was produced.
However, if you run your build with -DskipTests
your tests
artifact will be produced (though the tests won't run) and the dependency will be resolved.
You can instantiate an object from matplotlib.pyplot.axes
and call the set_ylim()
on it. It would be something like this:
import matplotlib.pyplot as plt
axes = plt.axes()
axes.set_ylim([0, 1])
Try this:
$('#Datepicker').change(function(){
var $bef = $('#Datepicker').val();
var $today = new Date();
var $before = new Date($bef);
var $befores = $before.getFullYear();
var $todays = $today.getFullYear();
var $bmonth = $before.getMonth();
var $tmonth = $today.getMonth();
var $bday = $before.getDate();
var $tday = $today.getDate();
if ($bmonth>$tmonth)
{$('#age').val($todays-$befores);}
if ($bmonth==$tmonth)
{
if ($tday > $bday) {$('#age').val($todays-$befores-1);}
else if ($tday <= $bday) {$('#age').val($todays-$befores);}
}
else if ($bmonth<$tmonth)
{ $('#age').val($todays-$befores-1);}
})
As a helper method (without Linq):
public static List<T> Distinct<T>(this List<T> list)
{
return (new HashSet<T>(list)).ToList();
}
I have seen in unidirectional @ManytoOne, delete don't work as expected. When parent is deleted, ideally child should also be deleted, but only parent is deleted and child is NOT deleted and is left as orphan
Technology used are Spring Boot/Spring Data JPA/Hibernate
Sprint Boot : 2.1.2.RELEASE
Spring Data JPA/Hibernate is used to delete row .eg
parentRepository.delete(parent)
ParentRepository extends standard CRUD repository as shown below
ParentRepository extends CrudRepository<T, ID>
Following are my entity class
@Entity(name = “child”)
public class Child {
@Id
@GeneratedValue
private long id;
@ManyToOne( fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = “parent_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
private Parent parent;
}
@Entity(name = “parent”)
public class Parent {
@Id
@GeneratedValue
private long id;
@Column(nullable = false, length = 50)
private String firstName;
}
Please make sur that res.getInt(1) is not null. If it can be null, use Integer count = null; and not int count =0;
Integer count = null;
if (rs! = null) (
while (rs.next ()) (
count = rs.getInt (1);
)
)
Quicker - no. More effective - yes, if you will use the StringBuilder
class. With your implementation each operation generates a copy of a string which under circumstances may impair performance. Strings are immutable objects so each operation just returns a modified copy.
If you expect this method to be actively called on multiple Strings
of significant length, it might be better to "migrate" its implementation onto the StringBuilder
class. With it any modification is performed directly on that instance, so you spare unnecessary copy operations.
public static class StringExtention
{
public static string clean(this string s)
{
StringBuilder sb = new StringBuilder (s);
sb.Replace("&", "and");
sb.Replace(",", "");
sb.Replace(" ", " ");
sb.Replace(" ", "-");
sb.Replace("'", "");
sb.Replace(".", "");
sb.Replace("eacute;", "é");
return sb.ToString().ToLower();
}
}
There are many variations possible for this problem. Here is a regular expression similar to an answer I previously placed on SO.
^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$
It would match the following examples and much more:
18005551234
1 800 555 1234
+1 800 555-1234
+86 800 555 1234
1-800-555-1234
1 (800) 555-1234
(800)555-1234
(800) 555-1234
(800)5551234
800-555-1234
800.555.1234
800 555 1234x5678
8005551234 x5678
1 800 555-1234
1----800----555-1234
Regardless of the way the phone number is entered, the capture groups can be used to breakdown the phone number so you can process it in your code.
Here is a breakdown of the expression if you're interested:
^\s* #Line start, match any whitespaces at the beginning if any.
(?:\+?(\d{1,3}))? #GROUP 1: The country code. Optional.
[-. (]* #Allow certain non numeric characters that may appear between the Country Code and the Area Code.
(\d{3}) #GROUP 2: The Area Code. Required.
[-. )]* #Allow certain non numeric characters that may appear between the Area Code and the Exchange number.
(\d{3}) #GROUP 3: The Exchange number. Required.
[-. ]* #Allow certain non numeric characters that may appear between the Exchange number and the Subscriber number.
(\d{4}) #Group 4: The Subscriber Number. Required.
(?: *x(\d+))? #Group 5: The Extension number. Optional.
\s*$ #Match any ending whitespaces if any and the end of string.
To make the Area Code optional, just add a question mark after the (\d{3}) for the area code.
You can deserialize directly to a list by using the TypeReference
wrapper. An example method:
public static <T> T fromJSON(final TypeReference<T> type,
final String jsonPacket) {
T data = null;
try {
data = new ObjectMapper().readValue(jsonPacket, type);
} catch (Exception e) {
// Handle the problem
}
return data;
}
And is used thus:
final String json = "";
Set<POJO> properties = fromJSON(new TypeReference<Set<POJO>>() {}, json);
Because growthRates is a sequence (you're even iterating it!) and you multiply it by (1 + 0.01), which is obviously a float (1.01). I guess you mean for growthRate in growthRates: ... * growthrate
?
The answer by @Mobilpadde is nice. But this is my solution with regex using preg_replace which might be faster according to my tests.
echo preg_replace('/<br\s?\/?>/i', "\r\n", "testing<br/><br /><BR><br>");
function function_one() {
preg_replace('/<br\s?\/?>/i', "\r\n", "testing<br/><br /><BR><br>");
}
function function_two() {
str_ireplace(['<br />','<br>','<br/>'], "\r\n", "testing<br/><br /><BR><br>");
}
function benchmark() {
$count = 10000000;
$before = microtime(true);
for ($i=0 ; $i<$count; $i++) {
function_one();
}
$after = microtime(true);
echo ($after-$before)/$i . " sec/function one\n";
$before = microtime(true);
for ($i=0 ; $i<$count; $i++) {
function_two();
}
$after = microtime(true);
echo ($after-$before)/$i . " sec/function two\n";
}
benchmark();
Results:
1.1471637010574E-6 sec/function one (preg_replace)
1.6027762889862E-6 sec/function two (str_ireplace)
Like others have mentioned, I think of roles as containers for more granular permissions.
Although I found the Hierarchy Role implementation to be lacking fine control of these granular permission.
So I created a library to manage the relationships and inject the permissions as granted authorities in the security context.
I may have a set of permissions in the app, something like CREATE, READ, UPDATE, DELETE, that are then associated with the user's Role.
Or more specific permissions like READ_POST, READ_PUBLISHED_POST, CREATE_POST, PUBLISH_POST
These permissions are relatively static, but the relationship of roles to them may be dynamic.
Example -
@Autowired
RolePermissionsRepository repository;
public void setup(){
String roleName = "ROLE_ADMIN";
List<String> permissions = new ArrayList<String>();
permissions.add("CREATE");
permissions.add("READ");
permissions.add("UPDATE");
permissions.add("DELETE");
repository.save(new RolePermissions(roleName, permissions));
}
You may create APIs to manage the relationship of these permissions to a role.
I don't want to copy/paste another answer, so here's the link to a more complete explanation on SO.
https://stackoverflow.com/a/60251931/1308685
To re-use my implementation, I created a repo. Please feel free to contribute!
https://github.com/savantly-net/spring-role-permissions
TRUNCATE is fast, DELETE is slow.
Although, TRUNCATE has no accountability.
There is no trigger to perform code when the app is deleted from the device. Access to the keychain is dependant on the provisioning profile that is used to sign the application. Therefore no other applications would be able to access this information in the keychain.
It does not help with you aim to remove the password in the keychain when the user deletes application from the device but it should give you some comfort that the password is not accessible (only from a re-install of the original application).
You can give a try to django-import-export. It has nice admin integration, changes preview, can create, update, delete objects.
Replace(@"\""", "")
You have to use double-doublequotes to escape double-quotes within a verbatim string.
Are you mixing C and C++? One issue that can occur is that the declarations in the .h
file for a .c
file need to be surrounded by:
#if defined(__cplusplus)
extern "C" { // Make sure we have C-declarations in C++ programs
#endif
and:
#if defined(__cplusplus)
}
#endif
Note: if unable / unwilling to modify the .h
file(s) in question, you can surround their inclusion with extern "C"
:
extern "C" {
#include <abc.h>
} //extern
From ?read.table
: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.
So, perhaps your data file isn't clean. Being more specific will help the data import:
d = read.table("foobar.txt",
sep="\t",
col.names=c("id", "name"),
fill=FALSE,
strip.white=TRUE)
will specify exact columns and fill=FALSE
will force a two column data frame.
Please check my working code.
function sendMail()
{
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => '[email protected]', // change it to yours
'smtp_pass' => 'xxx', // change it to yours
'mailtype' => 'html',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
$message = '';
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('[email protected]'); // change it to yours
$this->email->to('[email protected]');// change it to yours
$this->email->subject('Resume from JobsBuddy for your Job posting');
$this->email->message($message);
if($this->email->send())
{
echo 'Email sent.';
}
else
{
show_error($this->email->print_debugger());
}
}
Teradata table or view stores NULL as "?" and SQL considers it as a character or string. This is the main reason for the error "The value violated the integrity constraints for the column." when data is ported from Teradata source to SQL destination. Solution 1: Allow the destination table to hold NULL Solution 2: Convert the '?' character to be stored as some value in the destination table.
I'm on Windows 10 and I saved my key with Windows1252 encoding and it worked for me. On another StackOverflow question some people were fixing this with UTF-8 with BOM.
In other words, it may be the file encoding.
In case if you are using WPF application using PRISM framework then configuration should exist in your start up project (i.e. in the project where your bootstrapper resides.)
In short just remove it from the class library and put into a start up project.
Acording to your first code snipet seems ok, but I've got similar behavior caused by bad programing. Have you checked the "options" variable is not null before the put call?
I'm using Struts2 (2.3.3) webapp and use a HashMap for displaying results. When is executed (in a class initialized by an Action class) :
if(value != null) pdfMap.put("date",value.toString());
else pdfMap.put("date","");
Got this error:
Struts Problem Report
Struts has detected an unhandled exception:
Messages:
File: aoc/psisclient/samples/PDFValidation.java
Line number: 155
Stacktraces
java.lang.NullPointerException
aoc.psisclient.samples.PDFValidation.getRevisionsDetail(PDFValidation.java:155)
aoc.action.signature.PDFUpload.execute(PDFUpload.java:66)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
...
Seems the NullPointerException points to the put method (Line number 155), but the problem was that de Map hasn't been initialized before. It compiled ok since the variable is out of the method that set the value.
2017:
Simple way, adding time color to the message, you don't need to change your code, use keep your console.log('msg') or console.err('error')
var clc = require("cli-color");
var mapping = {
log: clc.blue,
warn: clc.yellow,
error: clc.red
};
["log", "warn", "error"].forEach(function(method) {
var oldMethod = console[method].bind(console);
console[method] = function() {
oldMethod.apply(
console,
[mapping[method](new Date().toISOString())]
.concat(arguments)
);
};
});
For MySQL > 5.1.11 or MariaDB
SET GLOBAL log_output = 'TABLE';
SET GLOBAL general_log = 'ON';
mysql.general_log
If you want to output to a log file:
SET GLOBAL log_output = "FILE";
SET GLOBAL general_log_file = "/path/to/your/logfile.log"
SET GLOBAL general_log = 'ON';
As mentioned by jeffmjack in comments, these settings will be forgetting before next session unless you edit the configuration files (e.g. edit /etc/mysql/my.cnf
, then restart to apply changes).
Now, if you'd like you can tail -f /var/log/mysql/mysql.log
This technique is usually used for multiple axis in a figure. In this context it is often required to have a colorbar that corresponds in size with the result from imshow. This can be achieved easily with the axes grid tool kit:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots()
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)
im = ax.imshow(data, cmap='bone')
fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()
To create an option that needs no value, set the action
[docs] of it to 'store_const'
, 'store_true'
or 'store_false'
.
Example:
parser.add_argument('-s', '--simulate', action='store_true')
None of above worked for me. Using Android Studio 3.5 Beta 4. I even selected "do not save, forget passwords after restart" in file>settings>appearance & behavior>System settings>password
So What I did.
VCS>git>remotes
If you want the font you chose to be applied and not the one in bootstrap without modifying the original bootstrap files you can rearrange the tags in your HTML documents so your CSS files that applies the font called after the bootstrap one. In this way since the browser reads the documents line after line first it will read the bootstrap files and apply it roles then it will read your file and override the roles in the bootstrap and replace it with the ones in your file.
Yes, that is possible. The challenge, however, is to do their layout properly. The easiest way to do it would be to have an AbsoluteLayout and then put the two images where you want them to be. You don't need to do anything special for the transparent png except having it added later to the layout.
If using Django, you can use the timezone.localtime
method:
from django.utils import timezone
date
# datetime.datetime(2014, 8, 1, 20, 15, 0, 513000, tzinfo=<UTC>)
timezone.localtime(date)
# datetime.datetime(2014, 8, 1, 16, 15, 0, 513000, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>)
The headers are entirely encrypted. The only information going over the network 'in the clear' is related to the SSL setup and D/H key exchange. This exchange is carefully designed not to yield any useful information to eavesdroppers, and once it has taken place, all data is encrypted.
I think your date data should look like 2013-08-14.
<?php
$yrdata= strtotime('2013-08-14');
echo date('M-Y', $yrdata);
?>
// Output is Aug-2013
It's optional.
The port may be specified so cookies can be port specific. It's not necessary, the web server / application must care of this.
Source: German Wikipedia article, RFC2109, Chapter 4.3.1
I've been struggling with this problem in one form or another for AGES, thank you, Thank You, THANK YOU.... :)
I just wanted to point out that you can get a generalizable solution from what Bob Lee's done by just extending View and overriding onMeasure. That way you can use this with any drawable you want, and it won't break if there's no image:
public class CardImageView extends View {
public CardImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public CardImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CardImageView(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable bg = getBackground();
if (bg != null) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = width * bg.getIntrinsicHeight() / bg.getIntrinsicWidth();
setMeasuredDimension(width,height);
}
else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
I used the property
display: table;
and
display: table-cell;
to achieve the same.Link to fiddle below shows 3 tables wrapped in divs and these divs are further wrapped in a parent div
<div id='content'>
<div id='div-1'><!-- COntains table --></div>
<div id='div-2'><!-- contains two more divs that require to be arranged one below other --></div>
</div>
Here is the jsfiddle: http://jsfiddle.net/vikikamath/QU6WP/1/ I thought this might be helpful to someone looking to set divs in same line without using display-inline
I resolved it.
the correct mode is :
set global sql_mode="NO_BACKSLASH_ESCAPES,STRICT_TRANS_TABLE,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
First you need to download the particular jar from Oracle site (ojdbc.jar version 11.2.0.3)
if you download it to C:\filefolder
go to that directory in cmd prompt and provide the below command.It will install the dependency.Then you can build your project.
mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dpackaging=jar -Dversion=11.2.0.4.0 -Dfile=ojdbc6.jar -DgeneratePom=true
You should store your images, css and JS files in a public
directory. To create a link to any of them, use asset()
helper:
{{ asset('img/myimage.png') }}
https://laravel.com/docs/5.1/helpers#method-asset
As alternative, you could use amazing Laravel Collective package for building forms and HTML elements, so your code will look like this:
{{ HTML::image('img/myimage.png', 'a picture') }}
You are missing a PDO driver.
First install the driver
For ubuntu: For mysql database.
sudo apt-get install php5.6-mysql/php7.2-mysql
You also can search for other database systems.
You also can search for the driver:
sudo apt-cache search drivername
Then Run the cmd php artisan migrate
this should do:
//Main Class
public class SomeClass {
//Sub-Class
public static class AnotherClass {
public enum MyEnum {
VALUE_A, VALUE_B
}
public MyEnum myEnum;
}
public void someMethod() {
AnotherClass.MyEnum enumExample = AnotherClass.MyEnum.VALUE_A; //...
switch (enumExample) {
case VALUE_A: { //<-- error on this line
//..
break;
}
}
}
}
I think the Vim documentation should've explained the meaning behind the naming of these commands. Just telling you what they do doesn't help you remember the names.
map
is the "root" of all recursive mapping commands. The root form applies to "normal", "visual+select", and "operator-pending" modes. (I'm using the term "root" as in linguistics.)
noremap
is the "root" of all non-recursive mapping commands. The root form applies to the same modes as map
. (Think of the nore
prefix to mean "non-recursive".)
(Note that there are also the !
modes like map!
that apply to insert & command-line.)
See below for what "recursive" means in this context.
Prepending a mode letter like n
modify the modes the mapping works in. It can choose a subset of the list of applicable modes (e.g. only "visual"), or choose other modes that map
wouldn't apply to (e.g. "insert").
Use help map-modes
will show you a few tables that explain how to control which modes the mapping applies to.
Mode letters:
n
: normal onlyv
: visual and selecto
: operator-pendingx
: visual onlys
: select onlyi
: insertc
: command-linel
: insert, command-line, regexp-search (and others. Collectively called "Lang-Arg" pseudo-mode)"Recursive" means that the mapping is expanded to a result, then the result is expanded to another result, and so on.
The expansion stops when one of these is true:
At that point, Vim's default "meaning" of the final result is applied/executed.
"Non-recursive" means the mapping is only expanded once, and that result is applied/executed.
Example:
nmap K H
nnoremap H G
nnoremap G gg
The above causes K
to expand to H
, then H
to expand to G
and stop. It stops because of the nnoremap
, which expands and stops immediately. The meaning of G
will be executed (i.e. "jump to last line"). At most one non-recursive mapping will ever be applied in an expansion chain (it would be the last expansion to happen).
The mapping of G
to gg
only applies if you press G
, but not if you press K
. This mapping doesn't affect pressing K
regardless of whether G
was mapped recursively or not, since it's line 2 that causes the expansion of K
to stop, so line 3 wouldn't be used.
define() is part of the AMD spec of js
See:
Edit: Also see Claudio's answer below. Likely the more relevant explanation.
var defaultSettings = {
ajaxsettings: {},
uisettings: {}
};
Take a look at this site: http://www.json.org/
Also, you can try calling JSON.stringify() on one of your objects from the browser to see the json format. You'd have to do this in the console or a test page.
In my experience window.requestAnimationFrame
wasn't enough to ensure that the DOM had been fully rendered / reflow-complete from componentDidMount
. I have code running that accesses the DOM immediately after a componentDidMount
call and using solely window.requestAnimationFrame
would result in the element being present in the DOM; however, updates to the element's dimensions aren't reflected yet since a reflow hasn't yet occurred.
The only truly reliable way for this to work was to wrap my method in a setTimeout
and a window.requestAnimationFrame
to ensure React's current call stack gets cleared before registering for the next frame's render.
function onNextFrame(callback) {
setTimeout(function () {
requestAnimationFrame(callback)
})
}
If I had to speculate on why this is occurring / necessary I could see React batching DOM updates and not actually applying the changes to the DOM until after the current stack is complete.
Ultimately, if you're using DOM measurements in the code you're firing after the React callbacks you'll probably want to use this method.
Here is the code for you`r class . but this also contains lot of refactoring. Please add a for each rather than for. cheers :)
static int isLeft(ArrayList<String> left, ArrayList<String> right)
{
int f = 0;
for (int i = 0; i < left.size(); i++) {
for (int j = 0; j < right.size(); j++)
{
if (left.get(i).charAt(0) == right.get(j).charAt(0)) {
System.out.println("Grammar is left recursive");
f = 1;
}
}
}
return f;
}
public static void main(String[] args) {
// TODO code application logic here
ArrayList<String> left = new ArrayList<String>();
ArrayList<String> right = new ArrayList<String>();
Scanner sc = new Scanner(System.in);
System.out.println("enter no of prod");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.println("enter left prod");
String leftText = sc.next();
left.add(leftText);
System.out.println("enter right prod");
String rightText = sc.next();
right.add(rightText);
}
System.out.println("the productions are");
for (int i = 0; i < n; i++) {
System.out.println(left.get(i) + "->" + right.get(i));
}
int flag;
flag = isLeft(left, right);
if (flag == 1) {
System.out.println("Removing left recursion");
} else {
System.out.println("No left recursion");
}
}
I found that the hostname was not visible to other containers when using docker run
. This turns out to be a known issue (perhaps more a known feature), with part of the discussion being:
We should probably add a warning to the docs about using hostname. I think it is rarely useful.
The correct way of assigning a hostname - in terms of container networking - is to define an alias like so:
services:
some-service:
networks:
some-network:
aliases:
- alias1
- alias2
Unfortunately this still doesn't work with docker run
. The workaround is to assign the container a name:
docker-compose run --name alias1 some-service
And alias1
can then be pinged from the other containers.
UPDATE: As @grilix points out, you should use docker-compose run --use-aliases
to make the defined aliases available.
Delaying GCD call using asyncAfter in swift
let delayQueue = DispatchQueue(label: "com.theappmaker.in", qos: .userInitiated)
let additionalTime: DispatchTimeInterval = .seconds(2)
We can delay as **microseconds,milliseconds,nanoseconds
delayQueue.asyncAfter(deadline: .now() + 0.60) {
print(Date())
}
delayQueue.asyncAfter(deadline: .now() + additionalTime) {
print(Date())
}
I just recompiled curl with configure options pointing to the openssl 1.0.2g library folder and include folder, and I still get this message. When I do ldd on curl, it does not show that it uses either libcrypt.so
or libssl.so
, so I assume this must mean that even though the make
and make install
succeeded without errors, nevertheless curl does not have HTTPS support? Configure and make was as follows:
./configure --prefix=/local/scratch/PACKAGES/local --with-ssl=/local/scratch/PACKAGES/local/openssl/openssl-1.0.2g --includedir=/local/scratch/PACKAGES/local/include/openssl/openssl-1.0.2g
make
make test
make install
I should mention that libssl.so.1
is in /local/scratch/PACKAGES/local/lib
. It is unclear whether the --with-ssl
option should point there or to the directory where the openssl install placed the openssl.cnf file. I chose the latter. But if it were supposed to be the former, the make should have failed with an error that it couldn't find the library.
In my case only after I added gcm.jar
to lib folder, it started to work.
It was here: C:\adt-bundle-windows-x86_64-20131030\sdk\extras\google\gcm\gcm-client\dist
So the google-play-services.jar
didn't work...
This might work. This Code dynamically appends the <script>
tag to the head
of the html file on button clicked.
const url = 'http://iknow.com/this/does/not/work/either/file.js';
export class MyAppComponent {
loadAPI: Promise<any>;
public buttonClicked() {
this.loadAPI = new Promise((resolve) => {
console.log('resolving promise...');
this.loadScript();
});
}
public loadScript() {
console.log('preparing to load...')
let node = document.createElement('script');
node.src = url;
node.type = 'text/javascript';
node.async = true;
node.charset = 'utf-8';
document.getElementsByTagName('head')[0].appendChild(node);
}
}
First of all, be sure that you have downloaded it or not. Open up your terminal application, and enter $ gcc
if you have not installed it you will get an alert. You can verify that you have installed it by
$ xcode-select -p
/Library/Developer/CommandLineTools
And to be sure then enter $ gcc --version
You can read more about the process here: Xcode command line tools for Mavericks
This will not work in your situation. You can only specify the constraint that it has an empty constructor:
public static string GetAllItems<T>(...) where T: new()
What you could do is use property injection by defining this interface:
public interface ITakesAListItem
{
ListItem Item { set; }
}
Then you could alter your method to be this:
public static string GetAllItems<T>(...) where T : ITakesAListItem, new()
{
...
List<T> tabListItems = new List<T>();
foreach (ListItem listItem in listCollection)
{
tabListItems.Add(new T() { Item = listItem });
}
...
}
The other alternative is the Func
method described by JaredPar.
change the data type to another one which uses less memory works. For me, I change the data type to numpy.uint8:
data['label'] = data['label'].astype(np.uint8)
First, you should define "doesn't work".
Second, I assume that your table field 'content' is varchar/text, so you need to enclose it in quotes. content = '{$content}'
And last but not least: use echo mysql_error()
directly after a query to debug.
Another working example:
var zlib = require('zlib');
var tar = require('tar');
var ftp = require('ftp');
var files = [];
var conn = new ftp();
conn.on('connect', function(e)
{
conn.auth(function(e)
{
if (e)
{
throw e;
}
conn.get('/tz/tzdata-latest.tar.gz', function(e, stream)
{
stream.on('success', function()
{
conn.end();
console.log("Processing files ...");
for (var name in files)
{
var file = files[name];
console.log("filename: " + name);
console.log(file);
}
console.log("OK")
});
stream.on('error', function(e)
{
console.log('ERROR during get(): ' + e);
conn.end();
});
console.log("Reading ...");
stream
.pipe(zlib.createGunzip())
.pipe(tar.Parse())
.on("entry", function (e)
{
var filename = e.props["path"];
console.log("filename:" + filename);
if( files[filename] == null )
{
files[filename] = "";
}
e.on("data", function (c)
{
files[filename] += c.toString();
})
});
});
});
})
.connect(21, "ftp.iana.org");
Surround the string with <html></html>
and break the lines with <br/>
.
JLabel l = new JLabel("<html>Hello World!<br/>blahblahblah</html>", SwingConstants.CENTER);
If you just want to know the number, rather than get it in a query then you can use:
SHOW CREATE TABLE tablename;
You should see the auto_increment at the bottom
Popen expect a list of strings for non-shell calls and a string for shell calls.
Call subprocess.Popen with shell=True:
process = subprocess.Popen(command, stdout=tempFile, shell=True)
Hopefully this solves your issue.
This issue is listed here: https://bugs.python.org/issue17023
There's no built-in JavaScript function to do this, but you can write your own fairly easily:
function pad(n) {
return (n < 10) ? ("0" + n) : n;
}
Meanwhile there is a native JS function that does that. See String#padStart
console.log(String(5).padStart(2, '0'));
_x000D_
Visual Studio, when starting up, will (for some reason) attempt to access the URL:
/debugattach.aspx
If you have a rewrite rule that redirects (or otherwise catches), say, .aspx
files, somewhere else then you will get this error. The solution is to add this section to the beginning of your web.config
's <system.webServer>/<rewrite>/<rules>
section:
<rule name="Ignore Default.aspx" enabled="true" stopProcessing="true">
<match url="^debugattach\.aspx" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
<action type="None" />
</rule>
This will make sure to catch this one particular request, do nothing, and, most importantly, stop execution so none of your other rules will get run. This is a robust solution, so feel free to keep this in your config file for production.
You can create a .htaccess file for the folder, wich should have denied access with
Deny from all
or you can redirect to a custom 404 page
Redirect /includes/ 404.html
Using the getBytes
method, giving it the appropriate Charset
(or Charset
name).
Example:
String s = "Hello, there.";
byte[] b = s.getBytes(StandardCharsets.US_ASCII);
(Before Java 7: byte[] b = s.getBytes("US-ASCII");
)
I actually prefer to use the html button form element and make it runat=server. The button element can hold other elements inside it. You can even add formatting inside it with span's or strong's. Here is an example:
<button id="BtnSave" runat="server"><img src="Images/save.png" />Save</button>
If you are using SolrSharp, it does not support negative queries.
You need to change QueryParameter.cs (Create a new parameter)
private bool _negativeQuery = false;
public QueryParameter(string field, string value, ParameterJoin parameterJoin = ParameterJoin.AND, bool negativeQuery = false)
{
this._field = field;
this._value = value.Trim();
this._parameterJoin = parameterJoin;
this._negativeQuery = negativeQuery;
}
public bool NegativeQuery
{
get { return _negativeQuery; }
set { _negativeQuery = value; }
}
And in QueryParameterCollection.cs class, the ToString() override, looks if the Negative parameter is true
arQ[x] = (qp.NegativeQuery ? "-(" : "(") + qp.ToString() + ")" + (qp.Boost != 1 ? "^" + qp.Boost.ToString() : "");
When you call the parameter creator, if it's a negative value. Simple change the propertie
List<QueryParameter> QueryParameters = new List<QueryParameter>();
QueryParameters.Add(new QueryParameter("PartnerList", "[* TO *]", ParameterJoin.AND, true));
I tried it by recursively appending each script
Note If your scripts are dependent one after other, then position will need to be in sync.
Major Dependency should be in last in array so that initial scripts can use it
const scripts = ['https://www.gstatic.com/firebasejs/6.2.0/firebase-storage.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-firestore.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-app.js']_x000D_
let count = 0_x000D_
_x000D_
_x000D_
const recursivelyAddScript = (script, cb) => {_x000D_
const el = document.createElement('script')_x000D_
el.src = script_x000D_
if(count < scripts.length) {_x000D_
count ++_x000D_
el.onload = recursivelyAddScript(scripts[count])_x000D_
document.body.appendChild(el)_x000D_
} else {_x000D_
console.log('All script loaded')_x000D_
return_x000D_
}_x000D_
}_x000D_
_x000D_
recursivelyAddScript(scripts[count])
_x000D_
Sometimes depending on how the configuration is set, the long form and the short form of the property tag can also make the difference.
e.g. if you have it like:
<property name="hibernate.hbm2ddl.auto" value="create"/>
try changing it to:
<property name="hibernate.hbm2ddl.auto">create</property>
Private Sub CommandButton1_Click()
Dim Z As Long
Dim Cellidx As Range
Dim NextRow As Long
Dim Rng As Range
Dim SrcWks As Worksheet
Dim DataWks As Worksheet
Z = 1
Set SrcWks = Worksheets("Sheet1")
Set DataWks = Worksheets("Sheet2")
Set Rng = EntryWks.Range("B6:ad6")
NextRow = DataWks.UsedRange.Rows.Count
NextRow = IIf(NextRow = 1, 1, NextRow + 1)
For Each RA In Rng.Areas
For Each Cellidx In RA
Z = Z + 1
DataWks.Cells(NextRow, Z) = Cellidx
Next Cellidx
Next RA
End Sub
Alternatively
Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10")
This is a CopynPaste - Method
Sub CopyDataToPlan()
Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean
On Error GoTo Err_Execute
'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value
Sheets("Plan").Select
'Start at column B
LColumn = 2
LFound = False
While LFound = False
'Encountered blank cell in row 2, terminate search
If Len(Cells(2, LColumn)) = 0 Then
MsgBox "No matching date was found."
Exit Sub
'Found match in row 2
ElseIf Cells(2, LColumn) = LDate Then
'Select values to copy from "Rolling Plan" sheet
Sheets("Rolling Plan").Select
Range("B5:H6").Select
Selection.Copy
'Paste onto "Plan" sheet
Sheets("Plan").Select
Cells(3, LColumn).Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
LFound = True
MsgBox "The data has been successfully copied."
'Continue searching
Else
LColumn = LColumn + 1
End If
Wend
Exit Sub
Err_Execute:
MsgBox "An error occurred."
End Sub
And there might be some methods doing that in Excel.
yo can try this code
@using (Html.BeginForm("SignUp", "Account", FormMethod.Post)){<fieldset>
<legend>Sign Up</legend>
<table>
<tr>
<td>
@Html.Label("User Name")
</td>
<td>
@Html.TextBoxFor(account => account.Username)
</td>
</tr>
<tr>
<td>
@Html.Label("Email")
</td>
<td>
@Html.TextBoxFor(account => account.Email)
</td>
</tr>
<tr>
<td>
@Html.Label("Password")
</td>
<td>
@Html.TextBoxFor(account => account.Password)
</td>
</tr>
<tr>
<td>
@Html.Label("Confirm Password")
</td>
<td>
@Html.Password("txtPassword")
</td>
</tr>
<tr>
<td>
<input type="submit" name="btnSubmit" value="Sign Up" />
</td>
</tr>
</table>
</fieldset>}
You can do it on Internet explorer with OCX component and on chrome browser using a chrome extension chrome document in any case need additional settings on the client system!
Important part of chrome extension source:
var port = chrome.runtime.connectNative("your.app.id");
port.onMessage.addListener(onNativeMessage);
port.onDisconnect.addListener(onDisconnected);
port.postMessage("send some data to STDIO");
permission file:
{
"name": "your.app.id",
"description": "Name of your extension",
"path": "myapp.exe",
"type": "stdio",
"allowed_origins": [
"chrome-extension://IDOFYOUREXTENSION_lokldaeplkmh/"
]
}
and windows registry settings:
HKEY_CURRENT_USER\Software\Google\Chrome\NativeMessagingHosts\your.app.id
REG_EXPAND_SZ : c:\permissionsettings.json
Realizing this answered long ago, but wanted to post different approach not presented...
Use ng-init
to tally your total. This way, you do not have to iterate in the HTML and iterate in the controller. In this scenario, I think this is a cleaner/simpler solution. (If the tallying logic was more complex, I definitely would recommend moving the logic to the controller or service as appropriate.)
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr ng-repeat="product in cart.products">
<td>{{product.name}}</td>
<td>{{product.quantity}}</td>
<td ng-init="itemTotal = product.price * product.quantity; controller.Total = controller.Total + itemTotal">{{itemTotal}} €</td>
</tr>
<tr>
<td></td>
<td>Total :</td>
<td>{{ controller.Total }}</td> // Here is the total value of my cart
</tr>
Of course, in your controller, simply define/initialize your Total
field:
// random controller snippet
function yourController($scope..., blah) {
var vm = this;
vm.Total = 0;
}
SELECT
ing columns from a tableCOUNT
, SUM
, MAX
/MIN
DISTINCT
, GROUP BY
, HAVING
JOIN
s, ANSI-89 and ANSI-92 syntaxUNION
vs UNION ALL
NULL
handling: COALESCE
& Native NULL handlingIN
, EXISTS
, and inline viewsWITH
syntax: Subquery Factoring/CTECOMMIT
, ROLLBACK
, Error HandlingThis thread provides the code necessary: http://bytes.com/forum/thread251367.html
but here's the relevant code:
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential, Pack=1)]
internal struct TokPriv1Luid
{
public int Count;
public long Luid;
public int Attr;
}
[DllImport("kernel32.dll", ExactSpelling=true) ]
internal static extern IntPtr GetCurrentProcess();
[DllImport("advapi32.dll", ExactSpelling=true, SetLastError=true) ]
internal static extern bool OpenProcessToken( IntPtr h, int acc, ref IntPtr
phtok );
[DllImport("advapi32.dll", SetLastError=true) ]
internal static extern bool LookupPrivilegeValue( string host, string name,
ref long pluid );
[DllImport("advapi32.dll", ExactSpelling=true, SetLastError=true) ]
internal static extern bool AdjustTokenPrivileges( IntPtr htok, bool disall,
ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen );
[DllImport("user32.dll", ExactSpelling=true, SetLastError=true) ]
internal static extern bool ExitWindowsEx( int flg, int rea );
internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
internal const int TOKEN_QUERY = 0x00000008;
internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
internal const int EWX_LOGOFF = 0x00000000;
internal const int EWX_SHUTDOWN = 0x00000001;
internal const int EWX_REBOOT = 0x00000002;
internal const int EWX_FORCE = 0x00000004;
internal const int EWX_POWEROFF = 0x00000008;
internal const int EWX_FORCEIFHUNG = 0x00000010;
private void DoExitWin( int flg )
{
bool ok;
TokPriv1Luid tp;
IntPtr hproc = GetCurrentProcess();
IntPtr htok = IntPtr.Zero;
ok = OpenProcessToken( hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok );
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_ENABLED;
ok = LookupPrivilegeValue( null, SE_SHUTDOWN_NAME, ref tp.Luid );
ok = AdjustTokenPrivileges( htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero );
ok = ExitWindowsEx( flg, 0 );
}
Usage:
DoExitWin( EWX_SHUTDOWN );
or
DoExitWin( EWX_REBOOT );
Instead of WorksheetFunction.Vlookup
, you can use Application.Vlookup
. If you set a Variant
equal to this it returns Error 2042 if no match is found. You can then test the variant - cellNum
in this case - with IsError
:
Sub test()
Dim ws As Worksheet: Set ws = Sheets("2012")
Dim rngLook As Range: Set rngLook = ws.Range("A:M")
Dim currName As String
Dim cellNum As Variant
'within a loop
currName = "Example"
cellNum = Application.VLookup(currName, rngLook, 13, False)
If IsError(cellNum) Then
MsgBox "no match"
Else
MsgBox cellNum
End If
End Sub
The Application
versions of the VLOOKUP
and MATCH
functions allow you to test for errors without raising the error. If you use the WorksheetFunction
version, you need convoluted error handling that re-routes your code to an error handler, returns to the next statement to evaluate, etc. With the Application
functions, you can avoid that mess.
The above could be further simplified using the IIF
function. This method is not always appropriate (e.g., if you have to do more/different procedure based on the If/Then
) but in the case of this where you are simply trying to determinie what prompt to display in the MsgBox, it should work:
cellNum = Application.VLookup(currName, rngLook, 13, False)
MsgBox IIF(IsError(cellNum),"no match", cellNum)
Consider those methods instead of On Error ...
statements. They are both easier to read and maintain -- few things are more confusing than trying to follow a bunch of GoTo
and Resume
statements.
I ran into this and eventually figured out it was because I was trying to use NSNumber
as dictionary keys, and property lists only allow strings as keys. The documentation for setObject:forKey:
doesn't mention this limitation, but the About Property Lists page that it links to does:
By convention, each Cocoa and Core Foundation object listed in Table 2-1 is called a property-list object. Conceptually, you can think of “property list” as being an abstract superclass of all these classes. If you receive a property list object from some method or function, you know that it must be an instance of one of these types, but a priori you may not know which type. If a property-list object is a container (that is, an array or dictionary), all objects contained within it must also be property-list objects. If an array or dictionary contains objects that are not property-list objects, then you cannot save and restore the hierarchy of data using the various property-list methods and functions. And although NSDictionary and CFDictionary objects allow their keys to be objects of any type, if the keys are not string objects, the collections are not property-list objects.
(Emphasis mine)
A Collection
does not have an ordering, so wanting to sort it does not make sense. You can sort List
instances and arrays, and the methods to do that are Collections.sort()
and Arrays.sort()
This is basically the same solution as @andy-wilkinson provided, but as of Spring Boot 1.0 the customize(...) method has a ConfigurableEmbeddedServletContainer parameter.
Another thing that is worth mentioning is that Tomcat only compresses content types of text/html
, text/xml
and text/plain
by default. Below is an example that supports compression of application/json
as well:
@Bean
public EmbeddedServletContainerCustomizer servletContainerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer servletContainer) {
((TomcatEmbeddedServletContainerFactory) servletContainer).addConnectorCustomizers(
new TomcatConnectorCustomizer() {
@Override
public void customize(Connector connector) {
AbstractHttp11Protocol httpProtocol = (AbstractHttp11Protocol) connector.getProtocolHandler();
httpProtocol.setCompression("on");
httpProtocol.setCompressionMinSize(256);
String mimeTypes = httpProtocol.getCompressableMimeTypes();
String mimeTypesWithJson = mimeTypes + "," + MediaType.APPLICATION_JSON_VALUE;
httpProtocol.setCompressableMimeTypes(mimeTypesWithJson);
}
}
);
}
};
}
Based on the @AndrewCox 's answer with some minor improvements:
from http.client import HTTPSConnection
from base64 import b64encode
client = HTTPSConnection("www.google.com")
user = "user_name"
password = "password"
headers = {
"Authorization": "Basic {}".format(
b64encode(bytes(f"{user}:{password}", "utf-8")).decode("ascii")
)
}
client.request('GET', '/', headers=headers)
res = client.getresponse()
data = res.read()
Note, you should set encoding if you use bytes
function instead of b""
.
From the ECMAScript specification, Section 11.9.3 The Abstract Equality Comparison Algorithm:
The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:
- If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
Thus, in, if (1 == true)
, true
gets coerced to a Number
, i.e. Number(true)
, which results in the value of 1
, yielding the final if (1 == 1)
which is true
.
if (0 == false)
is the exact same logic, since Number(false) == 0
.
This doesn't happen when you use the strict equals operator ===
instead:
11.9.6 The Strict Equality Comparison Algorithm
The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:
- If Type(x) is different from Type(y), return false.
(int)99.99999
It will be 99. Casting a double to an int does not round, it'll discard the fraction part.
Memory leak: When there is a memory area in a heap but no variable in the stack pointing to that memory.
char *myarea=(char *)malloc(10);
char *newarea=(char *)malloc(10);
myarea=newarea;
Dangling pointer: When a pointer variable in a stack but no memory in heap.
char *p =NULL;
A dangling pointer trying to dereference without allocating space will result in a segmentation fault.
In fact in the last answer String strAsciiTab = Character.toString((char) iAsciiValue); the essential part is (char)iAsciiValue which is doing the job (Character.toString useless)
Meaning the first answer was correct actually char ch = (char) yourInt;
if in yourint=49 (or 0x31), ch will be '1'
Download whatever configuration script that your browser is using.
the script would have various host:port configuration. based on the domain you want to connect , one of the host:port is selected by the borwser.
in the eclipse network setting you can try to put on of the host ports and see if that works.
worked for me.
the config script looks like,
if (isPlainHostName(host))
return "DIRECT";
else if (dnsDomainIs(host, "<***sample host name *******>"))
return "PROXY ***some ip*****; DIRECT";
else if (dnsDomainIs(host, "address.com")
|| dnsDomainIs(host, "adress2..com")
|| dnsDomainIs(host, "address3.com")
|| dnsDomainIs(host, "address4.com")
return "PROXY <***some proxyhost****>:8080";
you would need to look for the host port in the return statement.
If JSON is dynamic as below
{
"Items": [{
"Name": "Apple",
"Price": 12.3
},
{
"Name": "Grape",
"Price": 3.21
}
],
"Date": "21/11/2010"
}
Then, Once you install NewtonSoft.Json
from NuGet and include it in your project, you can serialize it as
string jsonString = "{\"Items\": [{\"Name\": \"Apple\",\"Price\": 12.3},{\"Name\": \"Grape\",\"Price\": 3.21}],\"Date\": \"21/11/2010\"}";
dynamic DynamicData = JsonConvert.DeserializeObject(jsonString);
Console.WriteLine( DynamicData.Date); // "21/11/2010"
Console.WriteLine(DynamicData.Items.Count); // 2
Console.WriteLine(DynamicData.Items[0].Name); // "Apple"
Source: How to read JSON data in C# (Example using Console app & ASP.NET MVC)?
Try update latest build version, target and compile version and also update dependencies but not works for me
In my case change <meta-items/>
to <meta-data/>
in manifest works for me...
Hope its helpful for someone...
If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.
extension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControl.State) {
let size = CGSize(width: 1, height: 1)
UIGraphicsBeginImageContext(size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(CGRect(origin: CGPoint.zero, size: size))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
setBackgroundImage(colorImage, for: forState)
}
}
Swift 5 , thanks @Maverick
Well there are a few ways to go about this depending on the intended behavior, but this link should give you all the best solutions and not surprisingly is from Dianne Hackborn
http://groups.google.com/group/android-developers/browse_thread/thread/d2a5c203dad6ec42
Essentially you have the following options
FragmentManager.popBackStack(String name,
FragmentManager.POP_BACK_STACK_INCLUSIVE)
.FragmentManager.getBackStackEntryCount()
/getBackStackEntryAt().getId()
to retrieve the ID of the first entry on the back stack, and
FragmentManager.popBackStack(int id,
FragmentManager.POP_BACK_STACK_INCLUSIVE)
.FragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
is supposed to pop the entire back stack... I think the documentation for
that is just wrong. (Actually I guess it just doesn't cover the case where
you pass in POP_BACK_STACK_INCLUSIVE
), Building on this comment I wrote a one-liner to hit the Github Markdown API using curl
and jq
.
Paste this bash function onto the command line or into your ~/.bash_profile
:
mdsee(){
HTMLFILE="$(mktemp -u).html"
cat "$1" | \
jq --slurp --raw-input '{"text": "\(.)", "mode": "markdown"}' | \
curl -s --data @- https://api.github.com/markdown > "$HTMLFILE"
echo $HTMLFILE
open "$HTMLFILE"
}
And then to see the rendered HTML in-browser run:
mdsee readme.md
Replace open "$HTMLFILE"
with lynx "$HTMLFILE"
if you need a pure terminal solution.
Here is the detailed explanation of why "Random.nextInt(n)
is both more efficient and less biased than Math.random() * n
" from the Sun forums post that Gili linked to:
Math.random() uses Random.nextDouble() internally.
Random.nextDouble() uses Random.next() twice to generate a double that has approximately uniformly distributed bits in its mantissa, so it is uniformly distributed in the range 0 to 1-(2^-53).
Random.nextInt(n) uses Random.next() less than twice on average- it uses it once, and if the value obtained is above the highest multiple of n below MAX_INT it tries again, otherwise is returns the value modulo n (this prevents the values above the highest multiple of n below MAX_INT skewing the distribution), so returning a value which is uniformly distributed in the range 0 to n-1.
Prior to scaling by 6, the output of Math.random() is one of 2^53 possible values drawn from a uniform distribution.
Scaling by 6 doesn't alter the number of possible values, and casting to an int then forces these values into one of six 'buckets' (0, 1, 2, 3, 4, 5), each bucket corresponding to ranges encompassing either 1501199875790165 or 1501199875790166 of the possible values (as 6 is not a disvisor of 2^53). This means that for a sufficient number of dice rolls (or a die with a sufficiently large number of sides), the die will show itself to be biased towards the larger buckets.
You will be waiting a very long time rolling dice for this effect to show up.
Math.random() also requires about twice the processing and is subject to synchronization.
When you don't have a PC on hand, you could use Eruda, which is devtools for mobile browsers https://github.com/liriliri/eruda
It is provided as embeddable javascript and also a bookmarklet (pasting bookmarklet in chrome removes the javascript: prefix, so you have to type it yourself)
From SDK:
Cancelling a task
A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true.
After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns.
To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)
So your code is right for dialog listener:
uploadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
myTask.cancel(true);
//finish();
}
});
Now, as I have mentioned earlier from SDK, you have to check whether the task is cancelled or not, for that you have to check isCancelled() inside the onPreExecute() method.
For example:
if (isCancelled())
break;
else
{
// do your work here
}
I don't know of a global setting nither but you can try this:
Full sync has few tasks:
git reset HEAD --hard
git clean -f
git pull origin master
Or else, what I prefer is that, I may create a new branch with the latest from the remote using:
git checkout origin/master -b <new branch name>
origin is my remote repository reference, and master is my considered branch name. These may different from yours.
Sometimes when we do these steps:
alter table my_table drop constraint my_pk;
alter table my_table add constraint my_pk primary key (city_id, buildtime, time);
The last statement fails with
ORA-00955 "name is already used by an existing object"
Oracle usually creates an unique index with the same name my_pk. In such a case you can drop the unique index or rename it based on whether the constraint is still relevant.
You can combine the dropping of primary key constraint and unique index into a single sql statement:
alter table my_table drop constraint my_pk drop index;
check this: ORA-00955 "name is already used by an existing object"
According to Reddit, more options icon and kabob menu are popular names. I prefer the latter as it goes well with hamburger menu.
PHP side code Name of file class.sendCode.php
<?php
class sendCode{
function __construct($dateini,$datefin) {
echo $this->printCode($dateini,$datefin);
}
function printCode($dateini,$datefin){
$code =" alert ('code Coming from AJAX {$this->dateini} and {$this->datefin}');";
//Insert all the code you want to execute,
//only javascript or Jquery code , dont incluce <script> tags
return $code ;
}
}
new sendCode($_POST['dateini'],$_POST['datefin']);
Now from your Html page you must trigger the ajax function to send the data.
.... <script src="http://code.jquery.com/jquery-1.9.1.js"></script> ....
Date begin: <input type="text" id="startdate"><br>
Date end : <input type="text" id="enddate"><br>
<input type="button" value="validate'" onclick="triggerAjax()"/>
Now at our local script.js we will define the ajax
function triggerAjax() {
$.ajax({
type: "POST",
url: 'class.sendCode.php',
dataType: "HTML",
data : {
dateini : $('#startdate').val(),
datefin : $('#enddate').val()},
success: function(data){
$.globalEval(data);
// here is where the magic is made by executing the data that comes from
// the php class. That is our javascript code to be executed
}
});
}
You can do it like that but storing a DataSet object in Session is not very efficient. If you have a web app with lots of users it will clog your server memory really fast.
If you really must do it like that I suggest removing it from the session as soon as you don't need the DataSet.
You need to assign different classes to each table.
Create a class in CSS with the dot '.' operator and write your properties inside each class. For example,
.table1 {
//some properties
}
.table2 {
//Some other properties
}
and use them in your html code.
Just wanted to point out something about the solution said above several times:
git config credential.helper store
You can use any command that requires a password after this. You don't have to push. (you can also pull for instance) After that, you won't need to type in your username / password again.
Even after all these time, it might help someone. This is simple JS solution.
JS
let date = new Date();
let today = date.toISOString().substr(0, 10);
//console.log("Today: ", today);//test
document.getElementById("form-container").innerHTML =
'<input type="date" name="myDate" value="' + today + '" >';//inject field
HTML
<form id="form-container"></form>
Similar solution works in Angular without any additional library to convert date format. For Angular (code is shortened due to common component code):
//so in myComponent.ts
//Import.... @Component...etc...
date: Date = new Date();
today: String; //<- note String
//more const ...
export class MyComponent implements OnInit {
//constructor, etc....
ngOnInit() {
this.today = this.date.toISOString().substr(0, 10);
}
}
//so in component.html
<input type="date" [(ngModel)]="today" />
You can get the parameters you are asking for by typing:
dir /?
For the full list, try:
dir /s /b /a:d
this is how you do it with ActionLIstener
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
public class MyWind extends JFrame{
public MyWind() {
initialize();
}
private void initialize() {
setSize(300, 300);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField field = new JTextField();
field.setSize(200, 50);
field.setText(" ");
JComboBox comboBox = new JComboBox();
comboBox.setEditable(true);
comboBox.addItem("item1");
comboBox.addItem("item2");
//
// Create an ActionListener for the JComboBox component.
//
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//
// Get the source of the component, which is our combo
// box.
//
JComboBox comboBox = (JComboBox) event.getSource();
Object selected = comboBox.getSelectedItem();
if(selected.toString().equals("item1"))
field.setText("30");
else if(selected.toString().equals("item2"))
field.setText("40");
}
});
getContentPane().add(comboBox);
getContentPane().add(field);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyWind().setVisible(true);
}
});
}
}
lintOptions {
checkReleaseBuilds false
abortOnError false
}
The above code can fix the problem by ignoring it, but it may result in crashing the app as well.
The good answer is in the following link:
This function found here, works fine for me
function jsonRemoveUnicodeSequences($struct) {
return preg_replace("/\\\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($struct));
}
To check if a character is lower case, use the islower
method of str
. This simple imperative program prints all the lowercase letters in your string:
for c in s:
if c.islower():
print c
Note that in Python 3 you should use print(c)
instead of print c
.
Possibly ending up with assigning those letters to a different variable.
To do this I would suggest using a list comprehension, though you may not have covered this yet in your course:
>>> s = 'abCd'
>>> lowercase_letters = [c for c in s if c.islower()]
>>> print lowercase_letters
['a', 'b', 'd']
Or to get a string you can use ''.join
with a generator:
>>> lowercase_letters = ''.join(c for c in s if c.islower())
>>> print lowercase_letters
'abd'
You are presumably encountering an exception and the program is exiting because of this (with a traceback). The first thing to do therefore is to catch that exception, before exiting cleanly (maybe with a message, example given).
Try something like this in your main
routine:
import sys, traceback
def main():
try:
do main program stuff here
....
except KeyboardInterrupt:
print "Shutdown requested...exiting"
except Exception:
traceback.print_exc(file=sys.stdout)
sys.exit(0)
if __name__ == "__main__":
main()
Change the memory limit in the php.ini file and restart Apache. After the restart, run the phpinfo(); function from any PHP file for a memory_limit
change confirmation.
memory_limit = -1
Memory limit -1 means there is no memory limit set. It's now at the maximum.
You can either use the first one or try the code below which is equally efficient
sort(&a[0], &a[n], greater<int>());
Google maintains a server infrastructure that grows dynamically with the ever increasing internet demands. This link by google describes the method to remain up to date with their IP address ranges.
When you need the literal IP addresses for Google Apps mail servers, start by using one of the common DNS lookup commands (nslookup, dig, host) to retrieve the SPF records for the domain _spf.google.com, like so:
nslookup -q=TXT _spf.google.com 8.8.8.8
This returns a list of the domains included in Google's SPF record, such as: _netblocks.google.com, _netblocks2.google.com, _netblocks3.google.com
Now look up the DNS records associated with those domains, one at a time, like so:
nslookup -q=TXT _netblocks.google.com 8.8.8.8
nslookup -q=TXT _netblocks2.google.com 8.8.8.8
nslookup -q=TXT _netblocks3.google.com 8.8.8.8
The results of these commands contain the current range of addresses.
You can achieve fall through like c++ by the goto keyword.
EX:
switch(num)
{
case 1:
goto case 3;
case 2:
goto case 3;
case 3:
//do something
break;
case 4:
//do something else
break;
case default:
break;
}
All previous answers are great, and I'd like to plug in one more point.
From generative algorithm models, we can derive any distribution; while we can only obtain the conditional distribution P(Y|X) from the discriminative algorithm models(or we can say they are only useful for discriminating Y’s label), and that's why it is called discriminative model. The discriminative model doesn't assume that the X's are independent given the Y($X_i \perp X_{-i} | Y$) and hence is usually more powerful for calculating that conditional distribution.
A CustomValidator would also work here:
<asp:CustomValidator runat="server"
ID="valDateRange"
ControlToValidate="txtDatecompleted"
onservervalidate="valDateRange_ServerValidate"
ErrorMessage="enter valid date" />
Code-behind:
protected void valDateRange_ServerValidate(object source, ServerValidateEventArgs args)
{
DateTime minDate = DateTime.Parse("1000/12/28");
DateTime maxDate = DateTime.Parse("9999/12/28");
DateTime dt;
args.IsValid = (DateTime.TryParse(args.Value, out dt)
&& dt <= maxDate
&& dt >= minDate);
}
There are several tools all built around Xperf. It's rather complex but very powerful -- see the quick start guide. There are other useful resources on the Windows Performance Analysis page
The language standard simply doesn't allow for it. Labels can only be followed by statements, and declarations do not count as statements in C. The easiest way to get around this is by inserting an empty statement after your label, which relieves you from keeping track of the scope the way you would need to inside a block.
#include <stdio.h>
int main ()
{
printf("Hello ");
goto Cleanup;
Cleanup: ; //This is an empty statement.
char *str = "World\n";
printf("%s\n", str);
}
I am not clear exactly what your situation requires but the following may get you started. The key here is using ThisWorkbook.Path
to get a relative file path:
Sub SaveToRelativePath()
Dim relativePath As String
relativePath = ThisWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name
ActiveWorkbook.SaveAs Filename:=relativePath
End Sub
Look for books by Ted Padova. Over the years, he has written a series of books called The Acrobat PDF {5,6,7,8,9...} Bible. They contain chapter(s) on JavaScript in PDF files. They are not as comprehensive as the reference documentation listed here, but in the books there are some realistic use-cases discussed in context.
There was also a talk on hacking PDF files by a computer scientist, given at a conference in 2010. The link on the talk's announcement-page to the slides is dead, but Google is your friend-. The talk is not exclusively on JavaScript, though. YouTube video - JavaScript starts at 06:00.
You would use the focus
and blur
events of the window:
var interval_id;
$(window).focus(function() {
if (!interval_id)
interval_id = setInterval(hard_work, 1000);
});
$(window).blur(function() {
clearInterval(interval_id);
interval_id = 0;
});
To Answer the Commented Issue of "Double Fire" and stay within jQuery ease of use:
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
// do work
break;
case "focus":
// do work
break;
}
}
$(this).data("prevType", e.type);
})
Click to view Example Code Showing it working (JSFiddle)
The most popular way to manage python packages (if you're not using your system package manager) is to use setuptools and easy_install. It is probably already installed on your system. Use it like this:
easy_install django
easy_install uses the Python Package Index which is an amazing resource for python developers. Have a look around to see what packages are available.
A better option is pip, which is gaining traction, as it attempts to fix a lot of the problems associated with easy_install. Pip uses the same package repository as easy_install, it just works better. Really the only time use need to use easy_install is for this command:
easy_install pip
After that, use:
pip install django
At some point you will probably want to learn a bit about virtualenv. If you do a lot of python development on projects with conflicting package requirements, virtualenv is a godsend. It will allow you to have completely different versions of various packages, and switch between them easily depending your needs.
Regarding which python to use, sticking with Apple's python will give you the least headaches, but If you need a newer version (Leopard is 2.5.1 I believe), I would go with the macports python 2.6.
The existing answers are quite clear. Just in case you do not know why it is called reverse
: It takes an input of a url name and gives the actual url, which is reverse to having a url first and then give it a name.
Minizip does have an example programs to demonstrate its usage - the files are called minizip.c and miniunz.c.
Update: I had a few minutes so I whipped up this quick, bare bones example for you. It's very smelly C, and I wouldn't use it without major improvements. Hopefully it's enough to get you going for now.
// uzip.c - Simple example of using the minizip API.
// Do not use this code as is! It is educational only, and probably
// riddled with errors and leaks!
#include <stdio.h>
#include <string.h>
#include "unzip.h"
#define dir_delimter '/'
#define MAX_FILENAME 512
#define READ_SIZE 8192
int main( int argc, char **argv )
{
if ( argc < 2 )
{
printf( "usage:\n%s {file to unzip}\n", argv[ 0 ] );
return -1;
}
// Open the zip file
unzFile *zipfile = unzOpen( argv[ 1 ] );
if ( zipfile == NULL )
{
printf( "%s: not found\n" );
return -1;
}
// Get info about the zip file
unz_global_info global_info;
if ( unzGetGlobalInfo( zipfile, &global_info ) != UNZ_OK )
{
printf( "could not read file global info\n" );
unzClose( zipfile );
return -1;
}
// Buffer to hold data read from the zip file.
char read_buffer[ READ_SIZE ];
// Loop to extract all files
uLong i;
for ( i = 0; i < global_info.number_entry; ++i )
{
// Get info about current file.
unz_file_info file_info;
char filename[ MAX_FILENAME ];
if ( unzGetCurrentFileInfo(
zipfile,
&file_info,
filename,
MAX_FILENAME,
NULL, 0, NULL, 0 ) != UNZ_OK )
{
printf( "could not read file info\n" );
unzClose( zipfile );
return -1;
}
// Check if this entry is a directory or file.
const size_t filename_length = strlen( filename );
if ( filename[ filename_length-1 ] == dir_delimter )
{
// Entry is a directory, so create it.
printf( "dir:%s\n", filename );
mkdir( filename );
}
else
{
// Entry is a file, so extract it.
printf( "file:%s\n", filename );
if ( unzOpenCurrentFile( zipfile ) != UNZ_OK )
{
printf( "could not open file\n" );
unzClose( zipfile );
return -1;
}
// Open a file to write out the data.
FILE *out = fopen( filename, "wb" );
if ( out == NULL )
{
printf( "could not open destination file\n" );
unzCloseCurrentFile( zipfile );
unzClose( zipfile );
return -1;
}
int error = UNZ_OK;
do
{
error = unzReadCurrentFile( zipfile, read_buffer, READ_SIZE );
if ( error < 0 )
{
printf( "error %d\n", error );
unzCloseCurrentFile( zipfile );
unzClose( zipfile );
return -1;
}
// Write data to file.
if ( error > 0 )
{
fwrite( read_buffer, error, 1, out ); // You should check return of fwrite...
}
} while ( error > 0 );
fclose( out );
}
unzCloseCurrentFile( zipfile );
// Go the the next entry listed in the zip file.
if ( ( i+1 ) < global_info.number_entry )
{
if ( unzGoToNextFile( zipfile ) != UNZ_OK )
{
printf( "cound not read next file\n" );
unzClose( zipfile );
return -1;
}
}
}
unzClose( zipfile );
return 0;
}
I built and tested it with MinGW/MSYS on Windows like this:
contrib/minizip/$ gcc -I../.. -o unzip uzip.c unzip.c ioapi.c ../../libz.a
contrib/minizip/$ ./unzip.exe /j/zlib-125.zip
Not tested but you can try something like this :
Declare @count as int
Set @count=1
Declare @inputFile varchar(max)
Declare @Sample Table
(id int,filepath varchar(max) ,Isexists char(3))
while @count<(select max(id) from yourTable)
BEGIN
Set @inputFile =(Select filepath from yourTable where id=@count)
DECLARE @isExists INT
exec master.dbo.xp_fileexist @inputFile ,
@isExists OUTPUT
insert into @Sample
Select @count,@inputFile ,case @isExists
when 1 then 'Yes'
else 'No'
end as isExists
set @count=@count+1
END
Just use
File.Copy(filepath, "\\\\192.168.1.28\\Files");
A windows fileshare exposed via a UNC path is treated as part of the file system, and has nothing to do with the web.
The credentials used will be that of the ASP.NET worker process, or any impersonation you've enabled. If you can tweak those to get it right, this can be done.
You may run into problems because you are using the IP address instead of the server name (windows trust settings prevent leaving the domain - by using IP you are hiding any domain details). If at all possible, use the server name!
If this is not on the same windows domain, and you are trying to use a different domain account, you will need to specify the username as "[domain_or_machine]\[username]"
If you need to specify explicit credentials, you'll need to look into coding an impersonation solution.
With numpy:
In [128]: list_a = np.array([1, 2, 4, 6])
In [129]: filter = np.array([True, False, True, False])
In [130]: list_a[filter]
Out[130]: array([1, 4])
or see Alex Szatmary's answer if list_a can be a numpy array but not filter
Numpy usually gives you a big speed boost as well
In [133]: list_a = [1, 2, 4, 6]*10000
In [134]: fil = [True, False, True, False]*10000
In [135]: list_a_np = np.array(list_a)
In [136]: fil_np = np.array(fil)
In [139]: %timeit list(itertools.compress(list_a, fil))
1000 loops, best of 3: 625 us per loop
In [140]: %timeit list_a_np[fil_np]
10000 loops, best of 3: 173 us per loop
var defaults = {_x000D_
_x000D_
"background-color": "#000",_x000D_
color: "#fff",_x000D_
weekdays: [_x000D_
{0: 'sun'},_x000D_
{1: 'mon'},_x000D_
{2: 'tue'},_x000D_
{3: 'wed'},_x000D_
{4: 'thu'},_x000D_
{5: 'fri'},_x000D_
{6: 'sat'}_x000D_
]_x000D_
_x000D_
};_x000D_
_x000D_
console.log(defaults.weekdays[3]);
_x000D_
I had all the correct packages and usings, but had to built first before I could get GetOwinContext()
to work.
You're probably just getting a stack overflow here. The array is too big to fit in your program's stack address space.
If you allocate the array on the heap you should be fine, assuming your machine has enough memory.
int* array = new int[1000000];
But remember that this will require you to delete[]
the array. A better solution would be to use std::vector<int>
and resize it to 1000000 elements.
Save it as a .ps1 file and then execute
powershell -file "path\to your\start stop nation service command file.ps1"
I use File -> Switch Workspace -> Other... and type in my new workspace name.
(EDIT: Added the composite screen shot.)
Once in the new workspace, File -> Import... and under General choose "Existing Projects into Workspace. Press the Next button and then Browse for the old projects you would like to import. Check "Copy projects into workspace" to make a copy.
here is my data extension. add this and you can call data.ToString()
import Foundation
extension Data
{
func toString() -> String?
{
return String(data: self, encoding: .utf8)
}
}
I think the confusion is that on my server I had to right click the Task Scheduler Library on left hand side and right click to get the option to enable or disable all tasks history.
Hope this helps
I would advise, it is slightly better practise to use string model references for ForeignKey
relationships if utilising an app based approach to seperation of logical concerns .
So, expanding on Martijn Pieters' answer:
class Person(models.Model):
name = models.CharField(max_length=50)
birthday = models.DateField()
anniversary = models.ForeignKey(
'app_label.Anniversary', on_delete=models.CASCADE)
address = models.ForeignKey(
'app_label.Address', on_delete=models.CASCADE)
class Address(models.Model):
line1 = models.CharField(max_length=150)
line2 = models.CharField(max_length=150)
postalcode = models.CharField(max_length=10)
city = models.CharField(max_length=150)
country = models.CharField(max_length=150)
class Anniversary(models.Model):
date = models.DateField()
Based on what I've read and my experience with Django so far, auto_now_add is buggy. I agree with jthanism --- override the normal save method it's clean and you know what's hapenning. Now, to make it dry, create an abstract model called TimeStamped:
from django.utils import timezone
class TimeStamped(models.Model):
creation_date = models.DateTimeField(editable=False)
last_modified = models.DateTimeField(editable=False)
def save(self, *args, **kwargs):
if not self.creation_date:
self.creation_date = timezone.now()
self.last_modified = timezone.now()
return super(TimeStamped, self).save(*args, **kwargs)
class Meta:
abstract = True
And then, when you want a model that has this time-stampy behavior, just subclass:
MyNewTimeStampyModel(TimeStamped):
field1 = ...
If you want the fields to show up in admin, then just remove the editable=False
option
change your jquery loading setting to onload in jsfiddle . . .it works . . .
No, you can't use a non-standard size or dimension, as it'd wreak havoc on peoples' browsers wherever the icons are displayed. You could make it 12x16 (with four pixels of white/transparent padding on the 12 pixel side) to preserve your aspect ratio, but you can't go bigger (well, you can, but the browser'll shrink it).
Here it is. Pure CSS. You do need one extra 'container' element.
The fiddle
(tinkerbin, actually): http://tinkerbin.com/rQ71nWDT
(Tinkerbin is dead.)
The solution.
Note I'm using an 100% throughout the example. You can use whichever percentage you'd like.
Since height percentages are relative to the height of the parent element, we can't rely on it. We must rely on something else. Luckily padding is relative to the width - whether it's horizontal or vertical padding. In padding-xyz: 100%
, 100% equals 100% of the box's width.
Unfortunately, padding is just that, padding. The content-box's height is 0. No problem!
Stick an absolutely positioned element, give it 100% width, 100% height and use it as your actual content box. The 100% height works because percentage heights on absolutely positioned elements are relative to the padding-box of the box their relatively positioned to.
HTML:
<div id="map_container">
<div id="map">
</div>
</div>
CSS:
#map_container {
position: relative;
width: 100%;
padding-bottom: 100%;
}
#map {
position: absolute;
width: 100%;
height: 100%;
}
Trick about detect scroll up or down in listview, you just call this function on onScroll function in OnScrollListener of ListView.
private int oldFirstVisibleItem = -1;
private protected int oldTop = -1;
// you can change this value (pixel)
private static final int MAX_SCROLL_DIFF = 5;
private void calculateListScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem == oldFirstVisibleItem) {
int top = view.getChildAt(0).getTop();
// range between new top and old top must greater than MAX_SCROLL_DIFF
if (top > oldTop && Math.abs(top - oldTop) > MAX_SCROLL_DIFF) {
// scroll up
} else if (top < oldTop && Math.abs(top - oldTop) > MAX_SCROLL_DIFF) {
// scroll down
}
oldTop = top;
} else {
View child = view.getChildAt(0);
if (child != null) {
oldFirstVisibleItem = firstVisibleItem;
oldTop = child.getTop();
}
}
}
Try just clearing the data (not the entire table including headers):
ACell.ListObject.DataBodyRange.ClearContents
How about this
private Object element[] = new Object[] {};
The JavaScript function:
String.prototype.capitalize = function(){
return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};
To use this function:
capitalizedString = someString.toLowerCase().capitalize();
Also, this would work on multiple words string.
To make sure the converted City name is injected into the database, lowercased and first letter capitalized, then you would need to use JavaScript before you send it over to server side. CSS simply styles, but the actual data would remain pre-styled. Take a look at this jsfiddle example and compare the alert message vs the styled output.
internal static string UnixToDate(int Timestamp, string ConvertFormat)
{
DateTime ConvertedUnixTime = DateTimeOffset.FromUnixTimeSeconds(Timestamp).DateTime;
return ConvertedUnixTime.ToString(ConvertFormat);
}
int Timestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
Usage:
UnixToDate(1607013172, "HH:mm:ss"); // Output 16:32:52
Timestamp; // Output 1607013172
::after
may be used to display the fallback image of an image
See the example below, first 2 img
tags are point to the broken urls. But the second one displays the fallback image instead of the default broken logo from the browser. However, I'm not sure this's any practical, I find it kind of tricky to get it to work right.
img {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
width: 300px;_x000D_
height: 200px;_x000D_
vertical-align: top;_x000D_
}_x000D_
img:not(:first-child)::after {_x000D_
position: absolute;_x000D_
left: 0; top: 0; right: 0; bottom: 0;_x000D_
content: "<" attr(alt) "> NOT FOUND";_x000D_
border: 1px dashed #999;_x000D_
background: url(https://cdn.dribbble.com/users/1012566/screenshots/4187820/topic-2.jpg) center/100%;_x000D_
}
_x000D_
<img src="https://source.unsplash.com/random/100/75" alt="logo">_x000D_
<img src="https://source.unsplash.com/random/100/75" alt="logo">_x000D_
<img src="https://source.unsplash.com/random/100x75" alt="logo">
_x000D_
EXPORT_DATABASE("localhost", "user", "pass", "db_name" );
updated function code at github.
Think of the print statement as causing a side-effect, it makes your function write some text out to the user, but it can't be used by another function.
I'll attempt to explain this better with some examples, and a couple definitions from Wikipedia.
Here is the definition of a function from Wikipedia
A function, in mathematics, associates one quantity, the argument of the function, also known as the input, with another quantity, the value of the function, also known as the output..
Think about that for a second. What does it mean when you say the function has a value?
What it means is that you can actually substitute the value of a function with a normal value! (Assuming the two values are the same type of value)
Why would you want that you ask?
What about other functions that may accept the same type of value as an input?
def square(n):
return n * n
def add_one(n):
return n + 1
print square(12)
# square(12) is the same as writing 144
print add_one(square(12))
print add_one(144)
#These both have the same output
There is a fancy mathematical term for functions that only depend on their inputs to produce their outputs: Referential Transparency. Again, a definition from Wikipedia.
Referential transparency and referential opaqueness are properties of parts of computer programs. An expression is said to be referentially transparent if it can be replaced with its value without changing the behavior of a program
It might be a bit hard to grasp what this means if you're just new to programming, but I think you will get it after some experimentation. In general though, you can do things like print in a function, and you can also have a return statement at the end.
Just remember that when you use return you are basically saying "A call to this function is the same as writing the value that gets returned"
Python will actually insert a return value for you if you decline to put in your own, it's called "None", and it's a special type that simply means nothing, or null.
Let's say for example in one case, if you want to locked cells from range A1 to I50 then below is the code:
Worksheets("Enter your sheet name").Range("A1:I50").Locked = True
ActiveSheet.Protect Password:="Enter your Password"
In another case if you already have a protected sheet then follow below code:
ActiveSheet.Unprotect Password:="Enter your Password"
Worksheets("Enter your sheet name").Range("A1:I50").Locked = True
ActiveSheet.Protect Password:="Enter your Password"
Another way is using set data type.
Some characteristic of Sets: Sets are unordered, can include mixed data types, elements in a set cannot be repeated, are mutable.
Solving your question:
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
sorted(set(df.A))
The answer in List type:
[1, 2, 3, 6, 8]
Try this
SELECT COLUMNS.*
FROM INFORMATION_SCHEMA.COLUMNS COLUMNS,
INFORMATION_SCHEMA.TABLES TABLES
WHERE COLUMNS.TABLE_NAME = TABLES.TABLE_NAME
AND Upper(COLUMNS.COLUMN_NAME) = Upper('column_name')
Route your path, and take the params
, and return:
redirect_to controller: "client", action: "get_name", params: request.query_parameters and return
Bootstrap 4
Use the data-parent=""
attribute on the collapse element (instead of the trigger element)
<div id="accordion">
<div class="card">
<div class="card-header">
<h5>
<button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne">
Collapsible #1 trigger
</button>
</h5>
</div>
<div id="collapseOne" class="collapse show" data-parent="#accordion">
<div class="card-body">
Collapsible #1 element
</div>
</div>
</div>
... (more cards/collapsibles inside #accordion parent)
</div>
Bootstrap 3
See this issue on GitHub: https://github.com/twbs/bootstrap/issues/10966
There is a "bug" that makes the accordion dependent on the .panel
class when using the data-parent
attribute. To workaround it, you can wrap each accordion group in a 'panel' div..
<div class="accordion" id="myAccordion">
<div class="panel">
<button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-1" data-parent="#myAccordion">Question 1?</button>
<div id="collapsible-1" class="collapse">
..
</div>
</div>
<div class="panel">
<button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-2" data-parent="#myAccordion">Question 2?</button>
<div id="collapsible-2" class="collapse">
..
</div>
</div>
<div class="panel">
<button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-3" data-parent="#myAccordion">Question 3?</button>
<div id="collapsible-3" class="collapse">
...
</div>
</div>
</div>
Edit
As mentioned in the comments, each section doesn't have to be a .panel
. However...
.panel
must be a direct child of the element used as data-parent=
data-toggle=
) must be a direct child of the .panel
(http://www.bootply.com/AbiRW7BdD6#)[alternative syntax]
For some people, directional pipe operators are not their taste, but they rather prefer chaining. See some interesting opinions on this topic shared in roslyn issue tracker: dotnet/roslyn#5445.
Based on the case and the context, one of this approach can be considered implicit (or indirect). For example, in this case using pipe against enumerable requires special token $_
(aka PowerShell's "THIS" token
) might appear distasteful to some.
For such fellas, here is a more concise, straight-forward way of doing it with dot chaining:
(gci . -re -fi *.txt).FullName
(<rant> Note that PowerShell's command arguments parser accepts the partial parameter names. So in addition to -recursive
; -recursiv
, -recursi
, -recurs
, -recur
, -recu
, -rec
and -re
are accepted, but unfortunately not -r
.. which is the only correct choice that makes sense with single -
character (if we go by POSIXy UNIXy conventions)! </rant>)
Use String.Format()
or TextWriter.Format()
(depending on how you actually write to the file) and specify the width of a field.
String.Format("{0,20}{1,15}{2,15}", "Sample Title One", "Element One", "Whatever Else");
You can specify the width of a field within interpolated strings as well:
$"{"Sample Title One",20}{"Element One",15}{"Whatever Else",15}"
And just so you know, you can create a string of repeated characters using the appropriate string contructor.
new String(' ', 20); // string of 20 spaces
Yes, your example would work fine.
As for exposing your classes, you can export
a class just like anything else:
class Animal {...}
module.exports = Animal;
Or the shorter:
module.exports = class Animal {
};
Once imported into another module, then you can treat it as if it were defined in that file:
var Animal = require('./Animal');
class Cat extends Animal {
...
}
Try __weak
if you get any warning regarding retain cycle else use __block
Person *strongPerson = [Person new];
__weak Person *weakPerson = person;
Now you can refer weakPerson
object inside block.
If your request is sent by HTTPS you will have an extra server variable named 'HTTPS'
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') { //HTTPS }
If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.
Go to Search > Find in Files
(Ctrl+Shift+F for the keyboard addicted) and enter:
(test1|test2)
*.txt
Follow current doc.
to have the path of the current file to be filled.Regular Expression
The error tells you that there is an error but you don´t catch it. This is how you can catch it:
getAllPosts().then(response => {
console.log(response);
}).catch(e => {
console.log(e);
});
You can also just put a console.log(reponse)
at the beginning of your API callback function, there is definitely an error message from the Graph API in it.
More information: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
Or with async/await:
//some async function
try {
let response = await getAllPosts();
} catch(e) {
console.log(e);
}
success
only fires if the AJAX call is successful, i.e. ultimately returns a HTTP 200 status. error
fires if it fails and complete
when the request finishes, regardless of success.
In jQuery 1.8 on the jqXHR
object (returned by $.ajax
) success
was replaced with done
, error
with fail
and complete
with always
.
However you should still be able to initialise the AJAX request with the old syntax. So these do similar things:
// set success action before making the request
$.ajax({
url: '...',
success: function(){
alert('AJAX successful');
}
});
// set success action just after starting the request
var jqxhr = $.ajax( "..." )
.done(function() { alert("success"); });
This change is for compatibility with jQuery 1.5's deferred object. Deferred (and now Promise
, which has full native browser support in Chrome and FX) allow you to chain asynchronous actions:
$.ajax("parent").
done(function(p) { return $.ajax("child/" + p.id); }).
done(someOtherDeferredFunction).
done(function(c) { alert("success: " + c.name); });
This chain of functions is easier to maintain than a nested pyramid of callbacks you get with success
.
However, please note that done
is now deprecated in favour of the Promise
syntax that uses then
instead:
$.ajax("parent").
then(function(p) { return $.ajax("child/" + p.id); }).
then(someOtherDeferredFunction).
then(function(c) { alert("success: " + c.name); }).
catch(function(err) { alert("error: " + err.message); });
This is worth adopting because async
and await
extend promises improved syntax (and error handling):
try {
var p = await $.ajax("parent");
var x = await $.ajax("child/" + p.id);
var c = await someOtherDeferredFunction(x);
alert("success: " + c.name);
}
catch(err) {
alert("error: " + err.message);
}
You can also simply avoid using numeric IDs as Primary Key. You could use Country codes as primary id if the table holds countries information, or you could use permalinks, if it hold articles for example.
You could also simply use a random, or an MD5 value. All this options have it's own benefits, specially on IT sec. numeric IDs are easy to enumerate.
In angular 4, this worked for me
template.html
<select (change)="filterChanged($event.target.value)">
<option *ngFor="let type of filterTypes" [value]="type.value">{{type.display}}
</option>
</select>
component.ts
export class FilterComponent implements OnInit {
selectedFilter:string;
public filterTypes = [
{ value: 'percentage', display: 'percentage' },
{ value: 'amount', display: 'amount' }
];
constructor() {
this.selectedFilter = 'percentage';
}
filterChanged(selectedValue:string){
console.log('value is ', selectedValue);
}
ngOnInit() {
}
}
The proposed solutions are perfect to download the images and if it is enough for you to save all the files in the directory you are using. But if you want to save all the images in a specified directory without reproducing the entire hierarchical tree of the site, try to add "cut-dirs" to the line proposed by Jon.
wget -r -P /save/location -A jpeg,jpg,bmp,gif,png http://www.boia.de --cut-dirs=1 --cut-dirs=2 --cut-dirs=3
in this case cut-dirs will prevent wget from creating sub-directories until the 3th level of depth in the website hierarchical tree, saving all the files in the directory you specified.You can add more 'cut-dirs' with higher numbers if you are dealing with sites with a deep structure.
Definitely use a service to share data between controllers, here is a working example. $broadcast is not the way to go, you should avoid using the eventing system when there is a more appropriate way. Use a 'service', 'value' or 'constant' (for global constants).
http://plnkr.co/edit/ETWU7d0O8Kaz6qpFP5Hp
Here is an example with an input so you can see the data mirror on the page: http://plnkr.co/edit/DbBp60AgfbmGpgvwtnpU
var testModule = angular.module('testmodule', []);
testModule
.controller('QuestionsStatusController1',
['$rootScope', '$scope', 'myservice',
function ($rootScope, $scope, myservice) {
$scope.myservice = myservice;
}]);
testModule
.controller('QuestionsStatusController2',
['$rootScope', '$scope', 'myservice',
function ($rootScope, $scope, myservice) {
$scope.myservice = myservice;
}]);
testModule
.service('myservice', function() {
this.xxx = "yyy";
});
In addition to the great reply about grokking vi, it should be noted that vim does add some very vi-like features that make using vi commands nicer. The one that comes to mind first are text objects: instead of {!}fmt
to reformat the current paragraph, !apfmt
does the same. It works by first specifying that we want to select a
text object, which is the current paragraph. Similar, to change the current string literal (foo
to bar
for an example), instead of T"ct"bar
(move to just after the previous "
, change until just before the next "
, insert bar), you can say ci"bar
: change inside (innermost) quotes, inserting bar.
Thinking in terms of text objects instead of movement commands is quite nice.