Tweaking MB's answer for windows, will get rid of the console window:
start javaw -jar squirrel-sql.jar
Using document.body.innerHTML = '';
does work! Just saying, if using HTML
(DOM
or on function
) you can usedocument.writeln('');
but only onClick
or onDoubleClick
:)
Note: The following method will work on windows.
An alternative method (if it is ok to run a single version of PHP at a time) is to define multiple Apache services, each of which will use a different PHP version.
First of all use conditions in the Apache configuration file:
<ifdefine php54>
SetEnv PHPRC C:/apache/php54/
ScriptAlias /php/ "C:/apache/php54/"
AddType application/x-httpd-php .php
Action application/x-httpd-php "/php/php-cgi.exe"
</ifdefine>
<ifdefine php55>
SetEnv PHPRC C:/apache/php55/
ScriptAlias /php/ "C:/apache/php55/"
AddType application/x-httpd-php .php
Action application/x-httpd-php "/php/php-cgi.exe"
</ifdefine>
Now using the httpd.exe create two separate services from command line (elevated to administrator):
httpd.exe -k install -n Apache224_php54 -D php54
httpd.exe -k install -n Apache224_php55 -D php55
Now you can start one of the above services at a time (should shutdown one before starting the other).
If you have previously installed Apache as service you can remove that using below command (replace the service name with the one you have used):
apache -k uninstall -n Apache224
One further note is that I personally use a "notification area icon program" called "Seobiseu" to start and stop services as needed. I have added the two above services to it.
You can use the lower
function:
Guide.where("lower(title)='attack'")
As a comment: Work on your question. The title isn't terribly informative, and you drop a big chunk of code at the end that is irrelevant to your question.
If you are willing to use your own custom output format, you would be able to get the desired behaviour with RDD as well.
Have a look at the following classes: FileOutputFormat, FileOutputCommitter
In file output format you have a method named checkOutputSpecs, which is checking whether the output directory exists. In FileOutputCommitter you have the commitJob which is usually transferring data from the temporary directory to its final place.
I wasn't able to verify it yet (would do it, as soon as I have few free minutes) but theoretically: If I extend FileOutputFormat and override checkOutputSpecs to a method that doesn't throw exception on directory already exists, and adjust the commitJob method of my custom output committer to perform which ever logic that I want (e.g. Override some of the files, append others) than I may be able to achieve the desired behaviour with RDDs as well.
The output format is passed to: saveAsNewAPIHadoopFile (which is the method saveAsTextFile called as well to actually save the files). And the Output committer is configured at the application level.
Here's how I addressed this (using a MEAN derivative)
My variables:
{
NODE_ENV : development,
...
ui_varables {
var1: one,
var2: two
}
}
First I had to make sure that the necessary config variables were being passed. MEAN uses the node nconf package, and by default is set up to limit which variables get passed from the environment. I had to remedy that:
config/config.js:
original:
nconf.argv()
.env(['PORT', 'NODE_ENV', 'FORCE_DB_SYNC'] ) // Load only these environment variables
.defaults({
store: {
NODE_ENV: 'development'
}
});
after modifications:
nconf.argv()
.env('__') // Load ALL environment variables
// double-underscore replaces : as a way to denote hierarchy
.defaults({
store: {
NODE_ENV: 'development'
}
});
Now I can set my variables like this:
export ui_varables__var1=first-value
export ui_varables__var2=second-value
Note: I reset the "heirarchy indicator" to "__" (double underscore) because its default was ":", which makes variables more difficult to set from bash. See another post on this thread.
Now the jade part: Next the values need to be rendered, so that javascript can pick them up on the client side. A straightforward way to write these values to the index file. Because this is a one-page app (angular), this page is always loaded first. I think ideally this should be a javascript include file (just to keep things clean), but this is good for a demo.
app/controllers/index.js:
'use strict';
var config = require('../../config/config');
exports.render = function(req, res) {
res.render('index', {
user: req.user ? JSON.stringify(req.user) : "null",
//new lines follow:
config_defaults : {
ui_defaults: JSON.stringify(config.configwriter_ui).replace(/<\//g, '<\\/') //NOTE: the replace is xss prevention
}
});
};
app/views/index.jade:
extends layouts/default
block content
section(ui-view)
script(type="text/javascript").
window.user = !{user};
//new line here
defaults = !{config_defaults.ui_defaults};
In my rendered html, this gives me a nice little script:
<script type="text/javascript">
window.user = null;
defaults = {"var1":"first-value","var2:"second-value"};
</script>
From this point it's easy for angular to utilize the code.
To get the names of current directory we can use getcwd()
or dirname(__FILE__)
but getcwd()
and dirname(__FILE__)
are not synonymous. They do exactly what their names are. If your code is running by referring a class in another file which exists in some other directory then these both methods will return different results.
For example if I am calling a class, from where these two functions are invoked and the class exists in some /controller/goodclass.php
from /index.php
then getcwd()
will return '/
and dirname(__FILE__)
will return /controller
.
if you want the queries to be logged to mongodb log file, you have to set both the log level and the profiling, like for example:
db.setLogLevel(1)
db.setProfilingLevel(2)
(see https://docs.mongodb.com/manual/reference/method/db.setLogLevel)
Setting only the profiling would not have the queries logged to file, so you can only get it from
db.system.profile.find().pretty()
I've been studying this problem quite a bit lately. Based on that my conclusion is that nowadays this is the best approach:
from collections.abc import Iterable # drop `.abc` with Python 2.7 or lower
def iterable(obj):
return isinstance(obj, Iterable)
The above has been recommended already earlier, but the general consensus has been that using iter()
would be better:
def iterable(obj):
try:
iter(obj)
except Exception:
return False
else:
return True
We've used iter()
in our code as well for this purpose, but I've lately started to get more and more annoyed by objects which only have __getitem__
being considered iterable. There are valid reasons to have __getitem__
in a non-iterable object and with them the above code doesn't work well. As a real life example we can use Faker. The above code reports it being iterable but actually trying to iterate it causes an AttributeError
(tested with Faker 4.0.2):
>>> from faker import Faker
>>> fake = Faker()
>>> iter(fake) # No exception, must be iterable
<iterator object at 0x7f1c71db58d0>
>>> list(fake) # Ooops
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/.../site-packages/faker/proxy.py", line 59, in __getitem__
return self._factory_map[locale.replace('-', '_')]
AttributeError: 'int' object has no attribute 'replace'
If we'd use insinstance()
, we wouldn't accidentally consider Faker instances (or any other objects having only __getitem__
) to be iterable:
>>> from collections.abc import Iterable
>>> from faker import Faker
>>> isinstance(Faker(), Iterable)
False
Earlier answers commented that using iter()
is safer as the old way to implement iteration in Python was based on __getitem__
and the isinstance()
approach wouldn't detect that. This may have been true with old Python versions, but based on my pretty exhaustive testing isinstance()
works great nowadays. The only case where isinstance()
didn't work but iter()
did was with UserDict
when using Python 2. If that's relevant, it's possible to use isinstance(item, (Iterable, UserDict))
to get that covered.
There are times that using OPTION(RECOMPILE)
makes sense. In my experience the only time this is a viable option is when you are using dynamic SQL. Before you explore whether this makes sense in your situation I would recommend rebuilding your statistics. This can be done by running the following:
EXEC sp_updatestats
And then recreating your execution plan. This will ensure that when your execution plan is created it will be using the latest information.
Adding OPTION(RECOMPILE)
rebuilds the execution plan every time that your query executes. I have never heard that described as creates a new lookup strategy
but maybe we are just using different terms for the same thing.
When a stored procedure is created (I suspect you are calling ad-hoc sql from .NET but if you are using a parameterized query then this ends up being a stored proc call) SQL Server attempts to determine the most effective execution plan for this query based on the data in your database and the parameters passed in (parameter sniffing), and then caches this plan. This means that if you create the query where there are 10 records in your database and then execute it when there are 100,000,000 records the cached execution plan may no longer be the most effective.
In summary - I don't see any reason that OPTION(RECOMPILE)
would be a benefit here. I suspect you just need to update your statistics and your execution plan. Rebuilding statistics can be an essential part of DBA work depending on your situation. If you are still having problems after updating your stats, I would suggest posting both execution plans.
And to answer your question - yes, I would say it is highly unusual for your best option to be recompiling the execution plan every time you execute the query.
I know this is old post but JsonConvert actually has a different method so it would be
var product = new { Name = "", Price = 0 };
var jsonResponse = JsonConvert.DeserializeAnonymousType(json, product);
As in this forum post by Gonzalo Medina, a third way may be:
\documentclass{article}
\usepackage{caption}
\DeclareCaptionType{equ}[][]
%\captionsetup[equ]{labelformat=empty}
\begin{document}
Some text
\begin{equ}[!ht]
\begin{equation}
a=b+c
\end{equation}
\caption{Caption of the equation}
\end{equ}
Some other text
\end{document}
More details of the commands used from package caption
: here.
A screenshot of the output of the above code:
Try not to go
MAMP > conf > [your PHP version] > php.ini
but
MAMP > bin > php > [your PHP version] > conf > php.ini
and change it there, it worked for me...
Destructive seems simplest, especially if we can assume the input is sorted:
/* destructively finds the intersection of
* two arrays in a simple fashion.
*
* PARAMS
* a - first array, must already be sorted
* b - second array, must already be sorted
*
* NOTES
* State of input arrays is undefined when
* the function returns. They should be
* (prolly) be dumped.
*
* Should have O(n) operations, where n is
* n = MIN(a.length, b.length)
*/
function intersection_destructive(a, b)
{
var result = [];
while( a.length > 0 && b.length > 0 )
{
if (a[0] < b[0] ){ a.shift(); }
else if (a[0] > b[0] ){ b.shift(); }
else /* they're equal */
{
result.push(a.shift());
b.shift();
}
}
return result;
}
Non-destructive has to be a hair more complicated, since we’ve got to track indices:
/* finds the intersection of
* two arrays in a simple fashion.
*
* PARAMS
* a - first array, must already be sorted
* b - second array, must already be sorted
*
* NOTES
*
* Should have O(n) operations, where n is
* n = MIN(a.length(), b.length())
*/
function intersect_safe(a, b)
{
var ai=0, bi=0;
var result = [];
while( ai < a.length && bi < b.length )
{
if (a[ai] < b[bi] ){ ai++; }
else if (a[ai] > b[bi] ){ bi++; }
else /* they're equal */
{
result.push(a[ai]);
ai++;
bi++;
}
}
return result;
}
Quite an old article on mssqlcity attempts to explain the types of locks:
Shared locks are used for operations that do not change or update data, such as a SELECT statement.
Update locks are used when SQL Server intends to modify a page, and later promotes the update page lock to an exclusive page lock before actually making the changes.
Exclusive locks are used for the data modification operations, such as UPDATE, INSERT, or DELETE.
What it doesn't discuss are Intent (which basically is a modifier for these lock types). Intent (Shared/Exclusive) locks are locks held at a higher level than the real lock. So, for instance, if your transaction has an X lock on a row, it will also have an IX lock at the table level (which stops other transactions from attempting to obtain an incompatible lock at a higher level on the table (e.g. a schema modification lock) until your transaction completes or rolls back).
The concept of "sharing" a lock is quite straightforward - multiple transactions can have a Shared lock for the same resource, whereas only a single transaction may have an Exclusive lock, and an Exclusive lock precludes any transaction from obtaining or holding a Shared lock.
Building off of @Karl Rosaen
parser = argparse.ArgumentParser()
optional = parser._action_groups.pop() # Edited this line
required = parser.add_argument_group('required arguments')
# remove this line: optional = parser...
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')
parser._action_groups.append(optional) # added this line
return parser.parse_args()
and this outputs:
usage: main.py [-h] [--required_arg REQUIRED_ARG]
[--optional_arg OPTIONAL_ARG]
required arguments:
--required_arg REQUIRED_ARG
optional arguments:
-h, --help show this help message and exit
--optional_arg OPTIONAL_ARG
The solution to the issue when i had this earlier today was that there was an additional set of tags bolted on the end of my Web.config. Once removed the functionality returned.
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: { dynamic: '=dynamic'},
link: function postLink(scope, element, attrs) {
scope.$watch( 'attrs.dynamic' , function(html){
element.html(scope.dynamic);
$compile(element.contents())(scope);
});
}
};
});
Try this element.html(scope.dynamic); than element.html(attr.dynamic);
then you should override onHandleIntent()
like this
Override
protected void onHandleIntent(@Nullable Intent intent) {
startForeground(FOREGROUND_ID,getNotification()); //<-- Makes Foreground
// Do something
stopForeground(true); // <-- Makes it again a normal Service
}
simple. Here is the getNotification()
Method
public Notification getNotification()
{
Intent intent = new Intent(this, SecondActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);
NotificationCompat.Builder foregroundNotification = new NotificationCompat.Builder(this);
foregroundNotification.setOngoing(true);
foregroundNotification.setContentTitle("MY Foreground Notification")
.setContentText("This is the first foreground notification Peace")
.setSmallIcon(android.R.drawable.ic_btn_speak_now)
.setContentIntent(pendingIntent);
return foregroundNotification.build();
}
This happens
A foreground service,
makes sure that user is actively aware of that something is going on in the background by providing the notification.
(most importantly) is not killed by System when it runs low on memory
You can use the following flags --single-branch
&& --depth
to download the specific branch and to limit the amount of history which will be downloaded.
You will clone the repo from a certain point in time and only for the given branch
git clone -b <branch> --single-branch <url> --depth <number of commits>
--[no-]single-branch
Clone only the history leading to the tip of a single branch, either specified by the
--branch
option or the primary branch remote’sHEAD
points at.Further fetches into the resulting repository will only update the
remote-tracking
branch for the branch this option was used for the initial cloning. If the HEAD at the remote did not point at any branch when--single-branch
clone was made, no remote-tracking branch is created.
--depth
Create a shallow clone with a history truncated to the specified number of commits
Ipaper::geom_boxplot2 is just what you want.
# devtools::install_github('kongdd/Ipaper')
library(Ipaper)
library(ggplot2)
p <- ggplot(mpg, aes(class, hwy))
p + geom_boxplot2(width = 0.8, width.errorbar = 0.5)
or use this syntax:
$("#mainTable").css("width", "100px");
$("#mainTable").css("height", "200px");
Use a pattern along these lines:
function getValue(file) {
return lookupValue(file);
}
getValue('myFile.txt').then(function(res) {
// do whatever with res here
});
(although this is a bit redundant, I'm sure your actual code is more complicated)
Well, my mini wrapper library would do the job as well.
>>> import pyexcel as pe
>>> data = pe.load('all16.csv', name_columns_by_row=0)
>>> min(data.column[1])
Meanwhile, if you know what header column index one is, for example "Column 1", you can do this instead:
>>> min(data.column["Column 1"])
You can use HTML5 autofocus
for this. You don't need jQuery or other JavaScript.
<input type="text" name="some_field" autofocus>
Note this will not work on IE9 and lower.
It does support input/output parameters (including RETURN
value) if you use DynamicParameters
, but in this case the simpler option is simply:
var id = connection.QuerySingle<int>( @"
INSERT INTO [MyTable] ([Stuff]) VALUES (@Stuff);
SELECT CAST(SCOPE_IDENTITY() as int)", new { Stuff = mystuff});
Note that on more recent versions of SQL Server you can use the OUTPUT
clause:
var id = connection.QuerySingle<int>( @"
INSERT INTO [MyTable] ([Stuff])
OUTPUT INSERTED.Id
VALUES (@Stuff);", new { Stuff = mystuff});
The easiest way is to use the null coalescing operator: ??
bool? x = ...;
if (x ?? true) {
}
The ??
with nullable values works by examining the provided nullable expression. If the nullable expression has a value the it's value will be used else it will use the expression on the right of ??
select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='<Table Name>'
You can get details like column datatype and size by this query
Answer:
^((?!hede).)*$
Explanation:
^
the beginning of the string,
(
group and capture to \1 (0 or more times (matching the most amount possible)),
(?!
look ahead to see if there is not,
hede
your string,
)
end of look-ahead,
.
any character except \n,
)*
end of \1 (Note: because you are using a quantifier on this capture, only the LAST repetition of the captured pattern will be stored in \1)
$
before an optional \n, and the end of the string
Yes browsers clear all ref. for a window. So you have to search a ClassName of something on the main window or use cookies as Javascript homemade ref.
I have a radio on my project page. And then you turn on for the radio it´s starts in a popup window and i controlling the main window links on the main page and show status of playing and in FF it´s easy but in MSIE not so Easy at all. But it can be done.
Try this...
I am in Windows 7 with Code::Blocks
while (true)
{
char input;
input = getch();
switch(input)
{
case -32: //This value is returned by all arrow key. So, we don't want to do something.
break;
case 72:
printf("up");
break;
case 75:
printf("left");
break;
case 77:
printf("right");
break;
case 80:
printf("down");
break;
default:
printf("INVALID INPUT!");
break;
}
}
var arr = [1,2,2,3,4,5,5,5,6,7,7,8,9,10,10];
function squash(arr){
var tmp = [];
for(var i = 0; i < arr.length; i++){
if(tmp.indexOf(arr[i]) == -1){
tmp.push(arr[i]);
}
}
return tmp;
}
console.log(squash(arr));
Working Example http://jsfiddle.net/7Utn7/
You can add the model error on any property of your model, I suggest if there is nothing related to create a new property.
As an exemple we check if the email is already in use in DB and add the error to the Email property in the action so when I return the view, they know that there's an error and how to show it up by using
<%: Html.ValidationSummary(true)%>
<%: Html.ValidationMessageFor(model => model.Email) %>
and
ModelState.AddModelError("Email", Resources.EmailInUse);
It's depends on if your computer support WMI
. My computer can't run this WMI demo too.
But I successfully get the CPU temperature via Open Hardware Monitor. Add the Openhardwaremonitor reference in Visual Studio. It's easier. Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenHardwareMonitor.Hardware;
namespace Get_CPU_Temp5
{
class Program
{
public class UpdateVisitor : IVisitor
{
public void VisitComputer(IComputer computer)
{
computer.Traverse(this);
}
public void VisitHardware(IHardware hardware)
{
hardware.Update();
foreach (IHardware subHardware in hardware.SubHardware) subHardware.Accept(this);
}
public void VisitSensor(ISensor sensor) { }
public void VisitParameter(IParameter parameter) { }
}
static void GetSystemInfo()
{
UpdateVisitor updateVisitor = new UpdateVisitor();
Computer computer = new Computer();
computer.Open();
computer.CPUEnabled = true;
computer.Accept(updateVisitor);
for (int i = 0; i < computer.Hardware.Length; i++)
{
if (computer.Hardware[i].HardwareType == HardwareType.CPU)
{
for (int j = 0; j < computer.Hardware[i].Sensors.Length; j++)
{
if (computer.Hardware[i].Sensors[j].SensorType == SensorType.Temperature)
Console.WriteLine(computer.Hardware[i].Sensors[j].Name + ":" + computer.Hardware[i].Sensors[j].Value.ToString() + "\r");
}
}
}
computer.Close();
}
static void Main(string[] args)
{
while (true)
{
GetSystemInfo();
}
}
}
}
You need to run this demo as administrator.
You can see the tutorial here: http://www.lattepanda.com/topic-f11t3004.html
You use separator when you are building a file path. So in unix the separator is /
. So if you wanted to build the unix path /var/temp
you would do it like this:
String path = File.separator + "var"+ File.separator + "temp"
You use the pathSeparator
when you are dealing with a list of files like in a classpath. For example, if your app took a list of jars as argument the standard way to format that list on unix is: /path/to/jar1.jar:/path/to/jar2.jar:/path/to/jar3.jar
So given a list of files you would do something like this:
String listOfFiles = ...
String[] filePaths = listOfFiles.split(File.pathSeparator);
I picked node-sass implementer for libsass because it is based on node.js.
$ npm install -g node-sass
installs node-sass globally -g
.This will hopefully install all you need, if not read libsass at the bottom.
General format:
$ node-sass [options] <input.scss> [output.css]
$ cat <input.scss> | node-sass > output.css
Examples:
$ node-sass my-styles.scss my-styles.css
compiles a single file manually.$ node-sass my-sass-folder/ -o my-css-folder/
compiles all the files in a folder manually.$ node-sass -w sass/ -o css/
compiles all the files in a folder automatically whenever the source file(s) are modified. -w
adds a watch for changes to the file(s).More usefull options like 'compression' @ here. Command line is good for a quick solution, however, you can use task runners like Grunt.js or Gulp.js to automate the build process.
You can also add the above examples to npm scripts. To properly use npm scripts as an alternative to gulp read this comprehensive article @ css-tricks.com especially read about grouping tasks.
package.json
file in your project directory running $ npm init
will create one. Use it with -y
to skip the questions. "sass": "node-sass -w sass/ -o css/"
to scripts
in package.json
file. It should look something like this:"scripts": {
"test" : "bla bla bla",
"sass": "node-sass -w sass/ -o css/"
}
$ npm run sass
will compile your files.$ npm install -g gulp
installs Gulp globally.package.json
file in your project directory running $ npm init
will create one. Use it with -y
to skip the questions.$ npm install --save-dev gulp
installs Gulp locally. --save-dev
adds gulp
to devDependencies
in package.json
.$ npm install gulp-sass --save-dev
installs gulp-sass locally.gulpfile.js
file in your project root folder with this content:'use strict';
var gulp = require('gulp');
A basic example to transpile
Add this code to your gulpfile.js:
var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('sass', function () {
gulp.src('./sass/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'));
});
$ gulp sass
runs the above task which compiles .scss file(s) in the sass
folder and generates .css file(s) in the css
folder.
To make life easier, let's add a watch so we don't have to compile it manually. Add this code to your gulpfile.js
:
gulp.task('sass:watch', function () {
gulp.watch('./sass/**/*.scss', ['sass']);
});
All is set now! Just run the watch task:
$ gulp sass:watch
As the name of node-sass implies, you can write your own node.js scripts for transpiling. If you are curious, check out node-sass project page.
Libsass is a library that needs to be built by an implementer such as sassC or in our case node-sass. Node-sass contains a built version of libsass which it uses by default. If the build file doesn't work on your machine, it tries to build libsass for your machine. This process requires Python 2.7.x (3.x doesn't work as of today). In addition:
LibSass requires GCC 4.6+ or Clang/LLVM. If your OS is older, this version may not compile. On Windows, you need MinGW with GCC 4.6+ or VS 2013 Update 4+. It is also possible to build LibSass with Clang/LLVM on Windows.
Use npm-run
.
From the readme:
Any executable available to an npm lifecycle script is available to npm-run
.
$ npm install mocha # mocha installed in ./node_modules
$ npm-run mocha test/* # uses locally installed mocha executable
$ npm install -g npm-run
In addition to the already excellent answers, also consider this function to retrieve both the number of dimensions and their bounds, which is similar to John's answer, but works and looks a little differently:
Function sizeOfArray(arr As Variant) As String
Dim str As String
Dim numDim As Integer
numDim = NumberOfArrayDimensions(arr)
str = "Array"
For i = 1 To numDim
str = str & "(" & LBound(arr, i) & " To " & UBound(arr, i)
If Not i = numDim Then
str = str & ", "
Else
str = str & ")"
End If
Next i
sizeOfArray = str
End Function
Private Function NumberOfArrayDimensions(arr As Variant) As Integer
' By Chip Pearson
' http://www.cpearson.com/excel/vbaarrays.htm
Dim Ndx As Integer
Dim Res As Integer
On Error Resume Next
' Loop, increasing the dimension index Ndx, until an error occurs.
' An error will occur when Ndx exceeds the number of dimension
' in the array. Return Ndx - 1.
Do
Ndx = Ndx + 1
Res = UBound(arr, Ndx)
Loop Until Err.Number <> 0
NumberOfArrayDimensions = Ndx - 1
End Function
Example usage:
Sub arrSizeTester()
Dim arr(1 To 2, 3 To 22, 2 To 9, 12 To 18) As Variant
Debug.Print sizeOfArray(arr())
End Sub
And its output:
Array(1 To 2, 3 To 22, 2 To 9, 12 To 18)
You are floating the children which means they "float" in front of the container. In order to take the correct height, you must "clear" the float
The div style="clear: both" clears the floating an gives the correct height to the container. see http://css.maxdesign.com.au/floatutorial/clear.htm for more info on floats.
eg.
<div class="c">
<div class="l">
</div>
<div class="m">
World
</div>
<div style="clear: both" />
</div>
Bootstrap comes with many pre-build classes and one of them is class="text-left"
. Please call this class whenever needed. :-)
When you use @SpringBootApplication annotation in for example package
com.company.config
it will automatically make component scan like this:
@ComponentScan("com.company.config")
So it will NOT scan packages like com.company.controller etc.. Thats why you have to declare your @SpringBootApplication in package one level prior to your normal packages like this: com.company OR use scanBasePackages property, like this:
@SpringBootApplication(scanBasePackages = { "com.company" })
OR componentScan:
@SpringBootApplication
@ComponentScan("com.company")
Try this:
TO_DATE('2011-07-28T23:54:14Z', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')
oltp- mostly used for business transaction.used to collect business data.In sql we use insert,update and delete command for retrieving small source of data.like wise they are highly normalised.... OLTP Mostly used for maintaining the data integrity.
olap- mostly use for reporting,data mining and business analytic purpose. for the large or bulk data.deliberately it is de-normalised. it stores Historical data..
CREATE DATE USING MONTH YEAR IN SQL::
DECLARE @FromMonth int=NULL,
@ToMonth int=NULL,
@FromYear int=NULL,
@ToYear int=NULL
/**Region For Create Date**/
DECLARE @FromDate DATE=NULL
DECLARE @ToDate DATE=NULL
SET @FromDate=DateAdd(day,0, DateAdd(month, @FromMonth - 1,DateAdd(Year, @FromYear-1900, 0)))
SET @ToDate=DateAdd(day,-1, DateAdd(month, @ToMonth - 0,DateAdd(Year, @ToYear-1900, 0)))
/**Region For Create Date**/
This is what worked for me. I am not sure why the syntax is different, But it was extremely frustrating trying every combination of activate, inactive, deactivated, disabled, etc. In lower case upper case in quotes out of quotes in brackets out of brackets etc. Well, here's the winning combination for me, for some reason.. different than everyone else?
import tkinter
class App(object):
def __init__(self):
self.tree = None
self._setup_widgets()
def _setup_widgets(self):
butts = tkinter.Button(text = "add line", state="disabled")
butts.grid()
def main():
root = tkinter.Tk()
app = App()
root.mainloop()
if __name__ == "__main__":
main()
Your curl gets timed out. Probably the url you are trying that requires more that 30 seconds.
If you are running the script through browser, then set the set_time_limit
to zero for infinite seconds.
set_time_limit(0);
Increase the curl's operation time limit using this option CURLOPT_TIMEOUT
curl_setopt($ch, CURLOPT_TIMEOUT,500); // 500 seconds
It can also happen for infinite redirection from the server. To halt this try to run the script with follow location disabled.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
I have experienced a great example of reproducing such a problem. Maybe my experience will help someone one day.
Check that your @Embedded Id of container has no possible collisions.
When Hibernate instantiates collection wrapper, it searches for already instantiated collection by CollectionKey in internal Map.
For Entity with @Embedded id, CollectionKey wraps EmbeddedComponentType and uses @Embedded Id properties for equality checks and hashCode calculation.
So if you have two entities with equal @Embedded Ids, Hibernate will instantiate and put new collection by the first key and will find same collection for the second key. So two entities with same @Embedded Id will be populated with same collection.
Suppose you have Account entity which has lazy set of loans. And Account has @Embedded Id consists of several parts(columns).
@Entity
@Table(schema = "SOME", name = "ACCOUNT")
public class Account {
@OneToMany(fetch = FetchType.LAZY, mappedBy = "account")
private Set<Loan> loans;
@Embedded
private AccountId accountId;
...
}
@Embeddable
public class AccountId {
@Column(name = "X")
private Long x;
@Column(name = "BRANCH")
private String branchId;
@Column(name = "Z")
private String z;
...
}
Then suppose that Account has additional property mapped by @Embedded Id but has relation to other entity Branch.
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "BRANCH")
@MapsId("accountId.branchId")
@NotFound(action = NotFoundAction.IGNORE)//Look at this!
private Branch branch;
It could happen that you have no FK for Account to Brunch relation id DB so Account.BRANCH column can have any value not presented in Branch table.
According to @NotFound(action = NotFoundAction.IGNORE)
if value is not present in related table, Hibernate will load null value for the property.
If X and Y columns of two Accounts are same(which is fine), but BRANCH is different and not presented in Branch table, hibernate will load null for both and Embedded Ids will be equal.
So two CollectionKey objects will be equal and will have same hashCode for different Accounts.
result = {CollectionKey@34809} "CollectionKey[Account.loans#Account@43deab74]"
role = "Account.loans"
key = {Account@26451}
keyType = {EmbeddedComponentType@21355}
factory = {SessionFactoryImpl@21356}
hashCode = 1187125168
entityMode = {EntityMode@17415} "pojo"
result = {CollectionKey@35653} "CollectionKey[Account.loans#Account@33470aa]"
role = "Account.loans"
key = {Account@35225}
keyType = {EmbeddedComponentType@21355}
factory = {SessionFactoryImpl@21356}
hashCode = 1187125168
entityMode = {EntityMode@17415} "pojo"
Because of this, Hibernate will load same PesistentSet for two entities.
Warning
If you run PowerShell from a cmd.exe window created by Powershell, the 2nd instance no longer waits for jobs to complete.
cmd> PowerShell
PS> Start-Process cmd.exe -Wait
Now from the new cmd window, run PowerShell again and within it start a 2nd cmd window: cmd2> PowerShell
PS> Start-Process cmd.exe -Wait
PS>
The 2nd instance of PowerShell no longer honors the -Wait request and ALL background process/jobs return 'Completed' status even thou they are still running !
I discovered this when my C# Explorer program is used to open a cmd.exe window and PS is run from that window, it also ignores the -Wait request. It appears that any PowerShell which is a 'win32 job' of cmd.exe fails to honor the wait request.
I ran into this with PowerShell version 3.0 on windows 7/x64
string myMessage="helloworld";
int len;
int slength = (int)myMessage.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, myMessage.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, myMessage.c_str(), slength, buf, len);
std::wstring r(buf);
std::wstring stemp = r.C_str();
LPCWSTR result = stemp.c_str();
The reason is your result
assigned to the returning Task
which represents continuation of your method, and you have a different Task in your method which is running, if you directly assign Task like this you will get your expected results:
var task = Task.Run(() =>
{
for (int i = 10; i < 432543543; i++)
{
// just for a long job
double d3 = Math.Sqrt((Math.Pow(i, 5) - Math.Pow(i, 2)) / Math.Sin(i * 8));
}
return "Foo Completed.";
});
while (task.Status != TaskStatus.RanToCompletion)
{
Console.WriteLine("Thread ID: {0}, Status: {1}", Thread.CurrentThread.ManagedThreadId,task.Status);
}
Console.WriteLine("Result: {0}", task.Result);
Console.WriteLine("Finished.");
Console.ReadKey(true);
The output
:
Consider this for better explanation: You have a Foo
method,let's say it Task A, and you have a Task
in it,let's say it Task B, Now the running task, is Task B, your Task A awaiting for Task B result.And you assing your result variable to your returning Task
which is Task A, because Task B doesn't return a Task, it returns a string
. Consider this:
If you define your result like this:
Task result = Foo(5);
You won't get any error.But if you define it like this:
string result = Foo(5);
You will get:
Cannot implicitly convert type 'System.Threading.Tasks.Task' to 'string'
But if you add an await
keyword:
string result = await Foo(5);
Again you won't get any error.Because it will wait the result (string) and assign it to your result variable.So for the last thing consider this, if you add two task into your Foo Method:
private static async Task<string> Foo(int seconds)
{
await Task.Run(() =>
{
for (int i = 0; i < seconds; i++)
{
Console.WriteLine("Thread ID: {0}, second {1}.", Thread.CurrentThread.ManagedThreadId, i);
Task.Delay(TimeSpan.FromSeconds(1)).Wait();
}
// in here don't return anything
});
return await Task.Run(() =>
{
for (int i = 0; i < seconds; i++)
{
Console.WriteLine("Thread ID: {0}, second {1}.", Thread.CurrentThread.ManagedThreadId, i);
Task.Delay(TimeSpan.FromSeconds(1)).Wait();
}
return "Foo Completed.";
});
}
And if you run the application, you will get the same results.(WaitingForActivation) Because now, your Task A is waiting those two tasks.
My experience in Visual Studio 2010 is that there are two changes needed so as to not need DLL's. From the project property page (right click on the project name in the Solution Explorer window):
Under Configuration Properties --> General, change the "Use of MFC" field to "Use MFC in a Static Library".
Under Configuration Properties --> C/C++ --> Code Generation, change the "Runtime Library" field to "Multi-Threaded (/MT)"
Not sure why both were needed. I used this to remove a dependency on glut32.dll.
Added later: When making these changes to the configurations, you should make them to "All Configurations" --- you can select this at the top of the Properties window. If you make the change to just the Debug configuration, it won't apply to the Release configuration, and vice-versa.
This can also happen if CMAKE_FIND_ROOT_PATH
is set as different from BOOST_ROOT
.
I faced the same issue that in spite of setting BOOST_ROOT
, I was getting the error.
But for cross compiling for ARM I was using Toolchain-android.cmake in which I had (for some reason):
set(BOOST_ROOT "/home/.../boost")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --sysroot=${SYSROOT}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --sysroot=${SYSROOT} -I${SYSROOT}/include/libcxx")
set(CMAKE_CXX_LINK_FLAGS "${CMAKE_CXX_LINK_FLAGS}")
set(CMAKE_FIND_ROOT_PATH "${SYSROOT}")
CMAKE_FIND_ROOT_PATH
seems to be overriding BOOST_ROOT
which was causing the issue.
Using the following will return a single 0 when input is all 0.
string s = "0000000"
s = int.Parse(s).ToString();
Here is my working code
function emptyTextAreaCheck(textarea, submitButtonClass) {
if(!submitButtonClass)
submitButtonClass = ".transSubmit";
if($(textarea).val() == '') {
$(submitButtonClass).addClass('disabled_button');
$(submitButtonClass).removeClass('transSubmit');
}
$(textarea).live('focus keydown keyup', function(){
if($(this).val().length == 0) {
$(submitButtonClass).addClass('disabled_button');
$(submitButtonClass).removeClass('transSubmit');
} else {
$('.disabled_button').addClass('transSubmit').css({
'cursor':'pointer'
}).removeClass('disabled_button');
}
});
}
Another method that can be used to copy tables from the source database to the destination one is the SQL Server Export and Import wizard, which is available in SQL Server Management Studio.
You have the choice to export from the source database or import from the destination one in order to transfer the data.
This method is a quick way to copy tables from the source database to the destination one, if you arrange to copy tables having no concern with the tables’ relationships and orders.
When using this method, the tables’ indexes and keys will not be transferred. If you are interested in copying it, you need to generate scripts for these database objects.
If these are Foreign Keys, connecting these tables together, you need to export the data in the correct order, otherwise the export wizard will fail.
Feel free to read more about this method, as well as about some more methods (including generate scripts, SELECT INTO and third party tools) in this article: https://www.sqlshack.com/how-to-copy-tables-from-one-database-to-another-in-sql-server/
We will consider first List type is String and want to convert it to Integer type of List.
List<String> origList = new ArrayList<>(); // assume populated
Add values in the original List.
origList.add("1");
origList.add("2");
origList.add("3");
origList.add("4");
origList.add("8");
Create target List of Integer Type
List<Integer> targetLambdaList = new ArrayList<Integer>();
targetLambdaList=origList.stream().map(Integer::valueOf).collect(Collectors.toList());
Print List values using forEach:
targetLambdaList.forEach(System.out::println);
Here are two examples of how to generate graphs in separate windows (frames), and, an example of how to generate graphs and save them into separate graphics files.
Okay, first the on-screen example. Notice that we use a separate instance of plt.figure(), for each graph, with plt.plot(). At the end, we have to call plt.show() to put it all on the screen.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace( 0,10 )
for n in range(3):
y = np.sin( x+n )
plt.figure()
plt.plot( x, y )
plt.show()
Another way to do this, is to use plt.show(block=False) inside the loop:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace( 0,10 )
for n in range(3):
y = np.sin( x+n )
plt.figure()
plt.plot( x, y )
plt.show( block=False )
Now, let's generate the graphs and instead, write them each to a file. Here we replace plt.show(), with plt.savefig( filename ). The difference from the previous example is that we don't have to account for ''blocking'' at each graph. Note also, that we number the file names. Here we use %03d so that we can conveniently have them in number order afterwards.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace( 0,10 )
for n in range(3):
y = np.sin( x+n )
plt.figure()
plt.plot( x, y )
plt.savefig('myfilename%03d.png'%(n))
The expression between the <%= %> is evaluated before the c:if tag is evaluated. So, supposing that |request.isUserInRole| returns |true|, your example would be evaluated to this first:
<c:if test="true">
<li>user</li>
</c:if>
and then the c:if tag would be executed.
The way you are using await/async is poor at best, and it makes it hard to follow. You are mixing await
with Task'1.Result
, which is just confusing. However, it looks like you are looking at a final task result, rather than the contents.
I've rewritten your function and function call, which should fix your issue:
async Task<string> GetResponseString(string text)
{
var httpClient = new HttpClient();
var parameters = new Dictionary<string, string>();
parameters["text"] = text;
var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
var contents = await response.Content.ReadAsStringAsync();
return contents;
}
And your final function call:
Task<string> result = GetResponseString(text);
var finalResult = result.Result;
Or even better:
var finalResult = await GetResponseString(text);
Added v4.8 support to the script:
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse |
Get-ItemProperty -name Version,Release -EA 0 |
Where { $_.PSChildName -match '^(?![SW])\p{L}'} |
Select PSChildName, Version, Release, @{
name="Product"
expression={
switch -regex ($_.Release) {
"378389" { [Version]"4.5" }
"378675|378758" { [Version]"4.5.1" }
"379893" { [Version]"4.5.2" }
"393295|393297" { [Version]"4.6" }
"394254|394271" { [Version]"4.6.1" }
"394802|394806" { [Version]"4.6.2" }
"460798|460805" { [Version]"4.7" }
"461308|461310" { [Version]"4.7.1" }
"461808|461814" { [Version]"4.7.2" }
"528040|528049" { [Version]"4.8" }
{$_ -gt 528049} { [Version]"Undocumented version (> 4.8), please update script" }
}
}
}
From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.
Usage looks like this:
using System.Linq;
// ...
public void My()
{
var myArray = new[] { "abc", "123", "zyx" };
List<string> myList = myArray.ToList();
}
PS. There's also ToArray()
method that works in other way.
if you have zsh installed you can also update ~/.zprofile
with
if [[ -z "$LC_ALL" ]]; then
export LC_ALL='en_US.UTF-8'
fi
and check the output using the locale
cmd as show above
? locale
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL="en_US.UTF-8"
For anyone finding this question while using Nightwatch.js (1.3.4), there's an acceptInsecureCerts: true
setting in the config file:
firefox: {_x000D_
desiredCapabilities: {_x000D_
browserName: 'firefox',_x000D_
alwaysMatch: {_x000D_
// Enable this if you encounter unexpected SSL certificate errors in Firefox_x000D_
acceptInsecureCerts: true,_x000D_
'moz:firefoxOptions': {_x000D_
args: [_x000D_
// '-headless',_x000D_
// '-verbose'_x000D_
],_x000D_
}_x000D_
}_x000D_
}_x000D_
},
_x000D_
As posted by 'Dan' in a similar thread, there is a possible fix if you're not using a sprite:
How do I make background-size work in IE?
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale')";
However, this scales the entire image to fit in the allocated area. So if your using a sprite, this may cause issues.
Caution
The filter has a flaw, any links inside the allocated area are no longer clickable.
Can't tell you how many times this has caught. me.
Guid myGuid = Guid.NewGuid();
Remove all special character don't give space write in single line
trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9 ]/', ' ',
urldecode(html_entity_decode(strip_tags($string))))));
I had this problem while working with Pycharm and with a database that was originally given to me by another user.
So, this is how I solve it in my case:
You change default value in MySQL configuration file (option connect_timeout in mysqld section) -
[mysqld]
connect_timeout=100
If this file is not accessible for you, then you can set this value using this statement -
SET GLOBAL connect_timeout=100;
I recognize that this is tagged for oauth 2.0 and NOT OIDC, however there is frequently a conflation between the 2 standards since both standards can use JWTs and the aud
claim. And one (OIDC) is basically an extension of the other (OAUTH 2.0). (I stumbled across this question looking for OIDC myself.)
For OAuth 2.0 Access tokens, existing answers pretty well cover it. Additionally here is one relevant section from OAuth 2.0 Framework (RFC 6749)
For public clients using implicit flows, this specification does not provide any method for the client to determine what client an access token was issued to.
...
Authenticating resource owners to clients is out of scope for this specification. Any specification that uses the authorization process as a form of delegated end-user authentication to the client (e.g., third-party sign-in service) MUST NOT use the implicit flow without additional security mechanisms that would enable the client to determine if the access token was issued for its use (e.g., audience- restricting the access token).
OIDC has ID Tokens in addition to Access tokens. The OIDC spec is explicit on the use of the aud
claim in ID Tokens. (openid-connect-core-1.0)
aud
REQUIRED. Audience(s) that this ID Token is intended for. It MUST contain the OAuth 2.0 client_id of the Relying Party as an audience value. It MAY also contain identifiers for other audiences. In the general case, the aud value is an array of case sensitive strings. In the common special case when there is one audience, the aud value MAY be a single case sensitive string.
furthermore OIDC specifies the azp
claim that is used in conjunction with aud
when aud
has more than one value.
azp
OPTIONAL. Authorized party - the party to which the ID Token was issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. This Claim is only needed when the ID Token has a single audience value and that audience is different than the authorized party. It MAY be included even when the authorized party is the same as the sole audience. The azp value is a case sensitive string containing a StringOrURI value.
try this:
declare @i tinyint = 0,
@count tinyint,
@id int,
@name varchar(max)
select @count = count(*) from table
while (@i < @count)
begin
select @id = id, @name = name from table
order by nr asc offset @i rows fetch next 1 rows only
exec stored_proc @varName = @id, @otherVarName = 'test', @varForName = @name
set @i = @i + 1
end
Inci framework you can do download like so:
function clubDownload($clubname)
{
$this->load->library("excel");
$object = new PHPExcel();
$object->setActiveSheetIndex(0);
$this->load->model('Members_student_model');
$query = $this->db->query("SELECT * FROM student WHERE $clubname!='' order by id desc");
$resultdatanew=$query->result_array();
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 1;
$object->getActiveSheet()->getStyle("A1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("B1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("C1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("D1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("E1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("F1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("G1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("H1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("I1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$headerStyle = array(
'fill' => array(
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb'=>'CCE5FF'),
),
'font' => array(
'bold' => true,
)
);
$object->getActiveSheet()->getStyle('A1:'.'I1')->applyFromArray($headerStyle);
$table_columns = array("id", "studentid", "passport", "lastname", "firstname","university","commencing",$clubname,"added_date");
$column = 0;
foreach($table_columns as $field)
{
$object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);
$column++;
}
$excel_row = 2;
foreach($resultdatanew as $row)
{
$id=$row['id'];
$studentid=$row['studentid'];
$passport=$row['passport'];
$lastname=$row['last_name'];
$firstname=$row['first_name'];
$passport=$row['university'];
$commencing=$row['commencing'];
$email_id=$row['email_id'];
$added_date=$row['added_date'];
$object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row,$id);
$object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row, $studentid);
$object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row, $passport);
$object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row, $lastname);
$object->getActiveSheet()->setCellValueByColumnAndRow(4, $excel_row, $firstname);
$object->getActiveSheet()->setCellValueByColumnAndRow(5, $excel_row, $passport);
$object->getActiveSheet()->setCellValueByColumnAndRow(6, $excel_row, $commencing);
$object->getActiveSheet()->setCellValueByColumnAndRow(7, $excel_row, $email_id);
$object->getActiveSheet()->setCellValueByColumnAndRow(8, $excel_row, $added_date);
$excel_row++;
}
$object_writer = PHPExcel_IOFactory::createWriter($object, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="club' .$clubname.'-'.date('Y-m-d') . '.xls');
$object_writer->save('php://output');
Use a comparison function:
bool compareByLength(const data &a, const data &b)
{
return a.word.size() < b.word.size();
}
and then use std::sort
in the header #include <algorithm>
:
std::sort(info.begin(), info.end(), compareByLength);
In ES2015 a.k.a ES6 version of JavaScript, a new datatype called Map
is introduced.
let map = new Map([["key1", "value1"], ["key2", "value2"]]);
map.get("key1"); // => value1
check this reference for more info.
The way I solved this was using flexbox. By using flexbox to layout the contents of your container div, you can have flexbox automatically distribute free space to an item above the one you want to have "stick to the bottom".
For example, say this is your container div with some other block elements inside it, and that the blue box (third one down) is a paragraph and the purple box (last one) is the one you want to have "stick to the bottom".
By setting this layout up with flexbox, you can set flex-grow: 1;
on just the paragraph (blue box) and, if it is the only thing with flex-grow: 1;
, it will be allocated ALL of the remaining space, pushing the element(s) after it to the bottom of the container like this:
(apologies for the terrible, quick-and-dirty graphics)
Default is:
Username: root
Password: [null]
The Password is set to 'password' in some versions.
It is easy to create a self-signed certificate, import it, and bind it to your website.
1.) Create a self-signed certificate:
Run the following 4 commands, one at a time, from an elevated Command Prompt:
cd C:\Program Files (x86)\Windows Kits\8.1\bin\x64
makecert -r -n "CN=localhost" -b 01/01/2000 -e 01/01/2099 -eku 1.3.6.1.5.5.7.3.3 -sv localhost.pvk localhost.cer
cert2spc localhost.cer localhost.spc
pvk2pfx -pvk localhost.pvk -spc localhost.spc -pfx localhost.pfx
2.) Import certificate to Trusted Root Certification Authorities store:
start --> run --> mmc.exe --> Certificates plugin --> "Trusted Root Certification Authorities" --> Certificates
Right-click Certificates --> All Tasks --> Import Find your "localhost" Certificate at C:\Program Files (x86)\Windows Kits\8.1\bin\x64\
3.) Bind certificate to website:
start --> (IIS) Manager --> Click on your Server --> Click on Sites --> Click on your top level site --> Bindings
Add or edit a binding for https and select the SSL certificate called "localhost".
4.) Import Certificate to Chrome:
Chrome Settings --> Manage Certificates --> Import .pfx certificate from C:\certificates\ folder
Test Certificate by opening Chrome and navigating to https://localhost/
Just a simple line of code in the head section can refresh the page
<meta http-equiv="refresh" content="30">
although its not a javascript function, its the simplest way to accomplish the above task hopefully.
You could use the CSS calc
parameter to calculate the height dynamically like so:
.dynamic-height {_x000D_
color: #000;_x000D_
font-size: 12px;_x000D_
margin-top: calc(100% - 10px);_x000D_
text-align: left;_x000D_
}
_x000D_
<div class='dynamic-height'>_x000D_
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>_x000D_
</div>
_x000D_
Logically speaking,we're actually talking about the same thing. But I think a simple metaphor would be helpful to solve this dilemma.
If the metaphors can be called various connection point we can equate them to plug points on a wall. In this case we can consider parameters and arguments as follows;
Parameters are the sockets of the plug-point which may take various different shapes. But only certain types of plugs fit them.
Arguments will be the actual plugs that would be plugged into the plug points/sockets to activate certain equipments.
I got few links sometime back while reading on ExtJS full framework in itself is JSON.
http://www.thomasfrank.se/xml_to_json.html
http://camel.apache.org/xmljson.html
online XML to JSON converter : http://jsontoxml.utilities-online.info/
UPDATE BTW, To get JSON as added in question, HTML need to have type & content tags in it too like this or you need to use some xslt transformation to add these elements while doing JSON conversion
<?xml version="1.0" encoding="UTF-8" ?>
<type>div</type>
<content>
<type>span</type>
<content>Text2</content>
</content>
<content>Text2</content>
You can't use IF like that. You can do what you want with AND and OR:
SELECT t.first_name,
t.last_name,
t.employid,
t.status
FROM employeetable t
WHERE ((status_flag = STATUS_ACTIVE AND t.status = 'A')
OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
OR (source_flag = SOURCE_USER AND t.business_unit = 'users'))
AND t.first_name LIKE firstname
AND t.last_name LIKE lastname
AND t.employid LIKE employeeid;
The FAB is colored based on your colorAccent
.
<style name="AppTheme" parent="Base.Theme.AppCompat.Light">
<item name="colorAccent">@color/accent</item>
</style>
Ok maybe this one should solve your problem. Note that each time you make a change you call the change() method that releases the wait.
Integer any = new Integer(0);
public synchronized boolean waitTillChange() {
any.wait();
return true;
}
public synchronized void change() {
any.notify();
}
Probably the closest you can do is
static bool IntegerFunction<T>(T value) where T: struct
Not sure if you could do the following
static bool IntegerFunction<T>(T value) where T: struct, IComparable
, IFormattable, IConvertible, IComparable<T>, IEquatable<T>
For something so specific, why not just have overloads for each type, the list is so short and it would possibly have less memory footprint.
Java now has a pretty good built-in date library, java.time bundled with Java 8.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Foo {
public static void main(String[] args) {
DateTimeFormatter format =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
LocalDateTime now = LocalDateTime.now();
LocalDateTime then = now.minusDays(7);
System.out.println(String.format(
"Now: %s\nThen: %s",
now.format(format),
then.format(format)
));
/*
Example output:
Now: 2014-05-09T14:51:48Z
Then: 2014-05-02T14:51:48Z
*/
}
}
If you do not mind using numpy (import numpy as np
):
np.partition(numbers, -2)[-2]
gives you the 2nd largest element of the list with a guaranteed worst-case O(n) running time.
The partition(a, kth)
methods returns an array where the k
th element is the same it would be in a sorted array, all elements before are smaller, and all behind are larger.
What do you want to do with the attribute? Is it an html attribute or something of your own?
Most of the time you can simply address it as a property: want to set a title on an element? element.title = "foo"
will do it.
For your own custom JS attributes the DOM is naturally extensible (aka expando=true), the simple upshot of which is that you can do element.myCustomFlag = foo
and subsequently read it without issue.
NOTE : AsyncTask was deprecated in API level 30.
https://developer.android.com/reference/android/os/AsyncTask
This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask
:
class RetrieveFeedTask extends AsyncTask<String, Void, RSSFeed> {
private Exception exception;
protected RSSFeed doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlreader = parser.getXMLReader();
RssHandler theRSSHandler = new RssHandler();
xmlreader.setContentHandler(theRSSHandler);
InputSource is = new InputSource(url.openStream());
xmlreader.parse(is);
return theRSSHandler.getFeed();
} catch (Exception e) {
this.exception = e;
return null;
} finally {
is.close();
}
}
protected void onPostExecute(RSSFeed feed) {
// TODO: check this.exception
// TODO: do something with the feed
}
}
How to execute the task:
In MainActivity.java
file you can add this line within your oncreate()
method
new RetrieveFeedTask().execute(urlToRssFeed);
Don't forget to add this to AndroidManifest.xml
file:
<uses-permission android:name="android.permission.INTERNET"/>
window.open
will open a new browser with the specified URL.
window.location.href
will open the URL in the window in which the code is called.
Note also that window.open()
is a function on the window object itself whereas window.location
is an object that exposes a variety of other methods and properties.
If you know the position of the date object in the string (for example in a log file), you can use .split()[index] to extract the date without fully knowing the format.
For example:
>>> string = 'monkey 2010-07-10 love banana'
>>> date = string.split()[1]
>>> date
'2010-07-10'
HTML Form Element Validation
Run Function
<script>
$("#validationForm").validation({
button: "#btnGonder",
onSubmit: function () {
alert("Submit Process");
},
onCompleted: function () {
alert("onCompleted");
},
onError: function () {
alert("Error Process");
}
});
</script>
Go to example and download https://github.com/naimserin/Validation.
#temp is materalized and CTE is not.
CTE is just syntax so in theory it is just a subquery. It is executed. #temp is materialized. So an expensive CTE in a join that is execute many times may be better in a #temp. On the other side if it is an easy evaluation that is not executed but a few times then not worth the overhead of #temp.
The are some people on SO that don't like table variable but I like them as the are materialized and faster to create than #temp. There are times when the query optimizer does better with a #temp compared to a table variable.
The ability to create a PK on a #temp or table variable gives the query optimizer more information than a CTE (as you cannot declare a PK on a CTE).
In order to execute multiple programs, I also needed a profiles
section:
<profiles>
<profile>
<id>traverse</id>
<activation>
<property>
<name>traverse</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<argument>org.dhappy.test.NeoTraverse</argument>
</arguments>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
This is then executable as:
mvn exec:exec -Ptraverse
An abstract data type, sometimes abbreviated ADT, is a logical description of how we view the data and the operations that are allowed without regard to how they will be implemented. This means that we are concerned only with what the data is representing and not with how it will eventually be constructed.
If you are running your application just on localhost and it is not yet live, I believe it is very difficult to send mail using this.
Once you put your application online, I believe that this problem should be automatically solved. By the way,ini_set() helps you to change the values in php.ini during run time.
This is the same question as Failed to connect to mailserver at "localhost" port 25
also check this php mail function not working
UPDATE: This is no longer valid for newer Keras versions. Please use argmax()
as in the answer from Emilia Apostolova.
The functional API models have just the predict()
function which for classification would return the class probabilities. You can then select the most probable classes using the probas_to_classes()
utility function. Example:
y_proba = model.predict(x)
y_classes = keras.np_utils.probas_to_classes(y_proba)
This is equivalent to model.predict_classes(x)
on the Sequential model.
The reason for this is that the functional API support more general class of tasks where predict_classes()
would not make sense.
I'm in the process of setting up a CI build server on a Linux box for a legacy system started in 2000. There is a section that generates a PDF that contains non-UTF8 characters. We are in the final steps of a release, so I cannot replace the characters giving me grief, yet for Dilbertesque reasons, I cannot wait a week to solve this issue after the release. Fortunately, the "javac" command in Ant has an "encoding" parameter.
<javac destdir="${classes.dir}" classpathref="production-classpath" debug="on"
includeantruntime="false" source="${java.level}" target="${java.level}"
encoding="iso-8859-1">
<src path="${production.dir}" />
</javac>
This is a much easier way to do it within Hive's SQL:
set hive.execution.engine=tez;
set hive.merge.tezfiles=true;
set hive.exec.compress.output=false;
INSERT OVERWRITE DIRECTORY '/tmp/job/'
ROW FORMAT DELIMITED
FIELDS TERMINATED by ','
NULL DEFINED AS ''
STORED AS TEXTFILE
SELECT * from table;
If the author has a GitHub account, just click the author's username from anywhere in the commit history, and the commits you can see will be filtered down to those by that author:
You can also click the 'n commits' link below their name on the repo's "contributors" page:
Alternatively, you can directly append ?author=<theusername>
or ?author=<emailaddress>
to the URL. For example, https://github.com/jquery/jquery/commits/master?author=dmethvin or https://github.com/jquery/jquery/commits/[email protected] both give me:
For authors without a GitHub account, only filtering by email address will work, and you will need to manually add ?author=<emailaddress>
to the URL - the author's name will not be clickable from the commits list.
You can also get the list of commits by a particular author from the command line using
git log --author=[your git name]
Example:
git log --author=Prem
UPDATE:
The HTML was requested so I've pasted it below.
<div ui-grid="gridOptions" class="my-grid"></div>
ORIGINAL:
We were able to adequately solve this problem by using responsive CSS (@media
) that sets the height and width based on screen real estate. Something like (and clearly you can add more based on your needs):
@media (min-width: 1024px) {
.my-grid {
width: 772px;
}
}
@media (min-width: 1280px) {
.my-grid {
width: 972px;
}
}
@media (min-height: 768px) {
.my-grid {
height: 480px;
}
}
@media (min-height: 900px) {
.my-grid {
height: 615px;
}
}
The best part about this solution is that we need no resize event handling to monitor for grid size changes. It just works.
Simple way founded here with pydotplus (graphviz must be installed):
from IPython.display import Image
from sklearn import tree
import pydotplus # installing pyparsing maybe needed
...
dot_data = tree.export_graphviz(best_model, out_file=None, feature_names = X.columns)
graph = pydotplus.graph_from_dot_data(dot_data)
Image(graph.create_png())
In laravel eloquent, has default exists() method, refer followed example.
if(User::where('id', $user_id )->exists()){
// your code...
}
For Linux, you can use this:
import gi
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk
s = Gdk.Screen.get_default()
screen_width = s.get_width()
screen_height = s.get_height()
print(screen_width)
print(screen_height)
add this code to your project
public static class Extension {
public static string TextAfter(this string value ,string search) {
return value.Substring(value.IndexOf(search) + search.Length);
}
}
then use
"code : string text ".TextAfter(":")
The declaration of x
is inside foo
but the x=5
initialization takes place outside of foo
!
What we need to understand here is that
static int x = 5;
is not the same as
static int x;
x = 5;
Other answers have used the important words here, scope and lifetime, and pointed out that the scope of x
is from the point of its declaration in the function foo
to the end of the function foo
. For example I checked by moving the declaration to the end of the function, and that makes x
undeclared at the x++;
statement.
So the static int x
(scope) part of the statement actually applies where you read it, somewhere INSIDE the function and only from there onwards, not above it inside the function.
However the x = 5
(lifetime) part of the statement is initialization of the variable and happening OUTSIDE of the function as part of the program loading. Variable x
is born with a value of 5
when the program loads.
I read this in one of the comments: "Also, this doesn't address the really confusing part, which is the fact that the initializer is skipped on subsequent calls." It is skipped on all calls. Initialization of the variable is outside of the function code proper.
The value of 5 is theoretically set regardless of whether or not foo is called at all, although a compiler might optimize the function away if you don't call it anywhere. The value of 5 should be in the variable before foo is ever called.
Inside of foo
, the statement static int x = 5;
is unlikely to be generating any code at all.
I found the address x
uses when I put a function foo
into a program of mine, and then (correctly) guessed that the same location would be used if I ran the program again. The partial screen capture below shows that x
has the value 5
even before the first call to foo
.
This is hard to answer without more detail about the network architecture. Some things to investigate are:
This is a convention that programmer usually use to identify different file names for include files. So that if the other developers is working on their code, he can easily identify why this file is there and what is purpose of this file by just seeing the name of the file.
Remove this line from your code:
console.info(JSON.parse(scatterSeries));
INSERT INTO #TempTable (ID, Date, Name)
SELECT id, date, name
FROM physical_table
Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)
Do it the other way around:
$a = "1,435";
$b = str_replace( ',', '', $a );
if( is_numeric( $b ) ) {
$a = $b;
}
The easiest would be:
$var = intval(preg_replace('/[^\d.]/', '', $var));
or if you need float:
$var = floatval(preg_replace('/[^\d.]/', '', $var));
Another approach is to use timestamp values:
end_time.timestamp() - start_time.timestamp()
Your other option is to initialize j
:
j = [None] * len(i)
This worked for me
sudo apt install openjdk-8-jre-headless
Instead of using string interpolation you could simply format the DateTime using the ToString("u")
method and concatenate that with the rest of the string:
$startTime = Get-Date
Write-Host "The script was started " + $startTime.ToString("u")
AFAIK, there is nothing built in for searching all columns. You can use Find
only against the primary key. Select
needs specified columns. You can perhaps use LINQ, but ultimately this just does the same looping. Perhaps just unroll it yourself? It'll be readable, at least.
You can serialize simple data to check for equality:
data1 = {firstName: 'John', lastName: 'Smith'};
data2 = {firstName: 'Jane', lastName: 'Smith'};
JSON.stringify(data1) === JSON.stringify(data2)
This will give you something like
'{firstName:"John",lastName:"Smith"}' === '{firstName:"Jane",lastName:"Smith"}'
As a function...
function compare(a, b) {
return JSON.stringify(a) === JSON.stringify(b);
}
compare(data1, data2);
If you're using chai like you say, check out http://chaijs.com/api/bdd/#equal-section
If you just want to check keys...
function compareKeys(a, b) {
var aKeys = Object.keys(a).sort();
var bKeys = Object.keys(b).sort();
return JSON.stringify(aKeys) === JSON.stringify(bKeys);
}
should do it.
Hey i got the solution recently... Just copy the "ROOT" folder FROM C:\Program Files\ Apache Software Foundation\ Tomcat 7.0\ webapps \ TO your_Workspace\ .metadata\ .plugins\ org.eclipse.wst.server.core\ tmp0 \wtpwebapps\ and over write it when asked..
This is needed because eclipse forgets to copy that root folder to its workspace.. Just right click on Apache tomcat 7.0 in servers tab and observe that in location will be workspace metadata by default example:"location:[workspace metadata]". Therefore it will find the root folder which has the welcome page in it and the 404 page not found error will be displayed. Thankyou ..
You can use the @RequestHeader
annotation with HttpHeaders
method parameter to gain access to all request headers:
@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers) {
// Use headers to get the information about all the request headers
long contentLength = headers.getContentLength();
// ...
StreamSource source = new StreamSource(new StringReader(body));
YourObject obj = (YourObject) jaxb2Mashaller.unmarshal(source);
// ...
}
One observation: (though this can be thought of side effect)
boolean being a primitive can either say yes or no.
Boolean is an object (it can refer to either yes or no or 'don't know' i.e. null)
Actually, valueOf
uses parseInt
internally. The difference is parseInt
returns an int
primitive while valueOf
returns an Integer
object. Consider from the Integer.class source:
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s, 10);
}
public static Integer valueOf(String s, int radix) throws NumberFormatException {
return Integer.valueOf(parseInt(s, radix));
}
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
As for parsing with a comma, I'm not familiar with one. I would sanitize them.
int million = Integer.parseInt("1,000,000".replace(",", ""));
Use
Model.created_at.strftime("%FT%T")
where,
%F - The ISO 8601 date format (%Y-%m-%d)
%T - 24-hour time (%H:%M:%S)
Following are some of the frequently used useful list of Date
and Time
formats that you could specify in strftime
method:
Date (Year, Month, Day):
%Y - Year with century (can be negative, 4 digits at least)
-0001, 0000, 1995, 2009, 14292, etc.
%C - year / 100 (round down. 20 in 2009)
%y - year % 100 (00..99)
%m - Month of the year, zero-padded (01..12)
%_m blank-padded ( 1..12)
%-m no-padded (1..12)
%B - The full month name (``January'')
%^B uppercased (``JANUARY'')
%b - The abbreviated month name (``Jan'')
%^b uppercased (``JAN'')
%h - Equivalent to %b
%d - Day of the month, zero-padded (01..31)
%-d no-padded (1..31)
%e - Day of the month, blank-padded ( 1..31)
%j - Day of the year (001..366)
Time (Hour, Minute, Second, Subsecond):
%H - Hour of the day, 24-hour clock, zero-padded (00..23)
%k - Hour of the day, 24-hour clock, blank-padded ( 0..23)
%I - Hour of the day, 12-hour clock, zero-padded (01..12)
%l - Hour of the day, 12-hour clock, blank-padded ( 1..12)
%P - Meridian indicator, lowercase (``am'' or ``pm'')
%p - Meridian indicator, uppercase (``AM'' or ``PM'')
%M - Minute of the hour (00..59)
%S - Second of the minute (00..59)
%L - Millisecond of the second (000..999)
%N - Fractional seconds digits, default is 9 digits (nanosecond)
%3N millisecond (3 digits)
%6N microsecond (6 digits)
%9N nanosecond (9 digits)
%12N picosecond (12 digits)
For the complete list of formats for strftime
method please visit APIDock
This happens when your table structure and model class no longer in sync. You need to update the table structure according to the model class or vice versa -- this is when your data is important and must not be deleted. If your data structure has changed and the data isn't important to you, you can use the DropCreateDatabaseIfModelChanges
feature (formerly known as 'RecreateDatabaseIfModelChanges
' feature) by adding the following code in your Global.asax.cs:
Database.SetInitializer<MyDbContext>(new DropCreateDatabaseIfModelChanges<MyDbContext>());
Run your application again.
As the name implies, this will drop your database and recreate according to your latest model class (or classes) -- provided you believe the table structure definitions in your model classes are the most current and latest; otherwise change the property definitions of your model classes instead.
Open Android Studio then go to gradle.properties file and change the last line to
org.gradle.jvmargs=-Xmx1024m.
And then press try again
You can't compare against text
with the =
operator, but instead must used one of the comparison functions listed here. Also note the large warning box at the top of the page, it's important.
Basically, flush() cleans out your RAM buffer, its real power is that it lets you continue to write to it afterwards - but it shouldn't be thought of as the best/safest write to file feature. It's flushing your RAM for more data to come, that is all. If you want to ensure data gets written to file safely then use close() instead.
Basic Availability: The database appears to work most of the time.
Soft State: Stores don’t have to be write-consistent or mutually consistent all the time.
Eventual consistency: Data should always be consistent, with regards how any number of changes are performed.
In fact, this is a retro-gradation of Python3 as compared to Python2. Certainly, Python2 which uses range() and xrange() is more convenient than Python3 which uses list(range()) and range() respectively. The reason is because the original designer of Python3 is not very experienced, they only considered the use of the range function by many beginners to iterate over a large number of elements where it is both memory and CPU inefficient; but they neglected the use of the range function to produce a number list. Now, it is too late for them to change back already.
If I was to be the designer of Python3, I will:
That should be optimal.
This is not due to input
tags not having any content per-se, but that their content is outside the scope of CSS.
input
elements are a special type called replaced elements
, these do not support :pseudo
selectors like :before
and :after
.
In CSS, a replaced element is an element whose representation is outside the scope of CSS. These are kind of external objects whose representation is independent of the CSS. Typical replaced elements are
<img>
,<object>
,<video>
or form elements like<textarea>
and<input>
. Some elements, like<audio>
or<canvas>
are replaced elements only in specific cases. Objects inserted using the CSS content properties are anonymous replaced elements.
Note that this is even referred to in the spec:
This specification does not fully define the interaction of
:before
and:after
with replaced elements (such as IMG in HTML).
And more explicitly:
Replaced elements do not have
::before
and::after
pseudo-elements
Concatenation of a string and integer is simple: just use
abhishek+str(2)
I think this is an straight forward answer:
public static IEnumerable<string> Split(this string str, int chunkSize)
{
if(string.IsNullOrEmpty(str) || chunkSize<1)
throw new ArgumentException("String can not be null or empty and chunk size should be greater than zero.");
var chunkCount = str.Length / chunkSize + (str.Length % chunkSize != 0 ? 1 : 0);
for (var i = 0; i < chunkCount; i++)
{
var startIndex = i * chunkSize;
if (startIndex + chunkSize >= str.Length)
yield return str.Substring(startIndex);
else
yield return str.Substring(startIndex, chunkSize);
}
}
And it covers edge cases.
JAXB is an ideal solution. But you do not necessarily need xsd and xjc for that. More often than not you don't have an xsd but you know what your xml is. Simply analyze your xml, e.g.,
<customer id="100">
<age>29</age>
<name>mkyong</name>
</customer>
Create necessary model class(es):
@XmlRootElement
public class Customer {
String name;
int age;
int id;
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
@XmlAttribute
public void setId(int id) {
this.id = id;
}
}
Try to unmarshal:
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(new File("C:\\file.xml"));
Check results, fix bugs!
You can use date(t_stamp)
to get only the date part from a timestamp.
You can check the date() function in the docs
DATE(expr)
Extracts the date part of the date or datetime expression expr.
mysql> SELECT DATE('2003-12-31 01:02:03'); -> '2003-12-31'
NOTE: This changed in Jenkins 1.597, Please see here for more info regarding the migration
You should be able to view all the global environment variables that are available during the build by navigating to https://<your-jenkins>/env-vars.html
.
Replace https://<your-jenkins>/
with the URL you use to get to Jenkins webpage (for example, it could be http://localhost:8080/env-vars.html
).
One of the environment variables is :
BUILD_ID
The current build id, such as "2005-08-22_23-59-59" (YYYY-MM-DD_hh-mm-ss)
If you use jenkins editable email notification, you should be able to use ${ENV, var="BUILD_ID"}
in the subject line of your email.
$(info your_text)
: Information. This doesn't stop the execution.
$(warning your_text)
: Warning. This shows the text as a warning.
$(error your_text)
: Fatal Error. This will stop the execution.
If you don't care about the order of the array, then you may want to get the difference between arr1
and arr2
by id
using differenceBy() and then simply use concat() to append all the updated objects.
var result = _(arr1).differenceBy(arr2, 'id').concat(arr2).value();
var arr1 = [{_x000D_
id: '124',_x000D_
name: 'qqq'_x000D_
}, {_x000D_
id: '589',_x000D_
name: 'www'_x000D_
}, {_x000D_
id: '45',_x000D_
name: 'eee'_x000D_
}, {_x000D_
id: '567',_x000D_
name: 'rrr'_x000D_
}]_x000D_
_x000D_
var arr2 = [{_x000D_
id: '124',_x000D_
name: 'ttt'_x000D_
}, {_x000D_
id: '45',_x000D_
name: 'yyy'_x000D_
}];_x000D_
_x000D_
var result = _(arr1).differenceBy(arr2, 'id').concat(arr2).value();_x000D_
_x000D_
console.log(result);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.js"></script>
_x000D_
You can use a node.js extension to provide bindings for your C++ code. Here is one tutorial that covers that:
http://syskall.com/how-to-write-your-own-native-nodejs-extension
Try this, Its work for me, get data between test word.
$str = "Xdata test HD01 test 1data";
$result = explode('test',$str);
print_r($result);
echo $result[1];
I've just created a little example showing how to implement commands in convention over configuration style. However it requires Reflection.Emit() to be available. The supporting code may seem a little weird but once written it can be used many times.
Teaser:
public class SampleViewModel: BaseViewModelStub
{
public string Name { get; set; }
[UiCommand]
public void HelloWorld()
{
MessageBox.Show("Hello World!");
}
[UiCommand]
public void Print()
{
MessageBox.Show(String.Concat("Hello, ", Name, "!"), "SampleViewModel");
}
public bool CanPrint()
{
return !String.IsNullOrEmpty(Name);
}
}
}
UPDATE: now there seem to exist some libraries like http://www.codeproject.com/Articles/101881/Executing-Command-Logic-in-a-View-Model that solve the problem of ICommand boilerplate code.
Let me share a basic Logcat analysis for when you meet a Force Close (when the app stops working).
DOCS
The basic tool from Android to collect/analyze logs is the logcat.
HERE is the Android's page about logcat
If you use android Studio, you can also check this LINK.
Capturing
Basically, you can MANUALLY capture logcat with the following command (or just check AndroidMonitor window in AndroidStudio):
adb logcat
There's a lot of parameters you can add to the command which helps you to filter and display the message that you want... This is personal... I always use the command below to get the message timestamp:
adb logcat -v time
You can redirect the output to a file and analyze it in a Text Editor.
Analyzing
If you app is Crashing, you'll get something like:
07-09 08:29:13.474 21144-21144/com.example.khan.abc D/AndroidRuntime: Shutting down VM
07-09 08:29:13.475 21144-21144/com.example.khan.abc E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.khan.abc, PID: 21144
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.FragmentActivity.onBackPressed()' on a null object reference
at com.example.khan.abc.AudioFragment$1.onClick(AudioFragment.java:125)
at android.view.View.performClick(View.java:4848)
at android.view.View$PerformClick.run(View.java:20262)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5631)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
07-09 08:29:15.195 21144-21144/com.example.khan.abc I/Process: Sending signal. PID: 21144 SIG: 9
This part of the log shows you a lot of information:
07-09 08:29:13.475
It is important to check when the issue happened... You may find several errors in a log... you must be sure that you are checking the proper messages :)
com.example.khan.abc
This way, you know which app crashed (to be sure that you are checking the logs about your message)
java.lang.NullPointerException
A NULL Pointer Exception error
Attempt to invoke virtual method 'void android.support.v4.app.FragmentActivity.onBackPressed()' on a null object reference
You tried to call method onBackPressed()
from a FragmentActivity
object. However, that object was null
when you did it.
Stack Trace: Stack Trace shows you the method invocation order... Sometimes, the error happens in the calling method (and not in the called method).
at com.example.khan.abc.AudioFragment$1.onClick(AudioFragment.java:125)
Error happened in file com.example.khan.abc.AudioFragment.java
, inside onClick()
method at line: 125
(stacktrace shows the line that error happened)
It was called by:
at android.view.View.performClick(View.java:4848)
Which was called by:
at android.view.View$PerformClick.run(View.java:20262)
which was called by:
at android.os.Handler.handleCallback(Handler.java:815)
etc....
Overview
This was just an overview... Not all logs are simple but the error gives specific problem and verbose shows up all problem ... It is just to share the idea and provide entry-level information to you...
I hope I could help you someway... Regards
I had the same error and i did followed article found on google solves my issue. You have not concluded your merge
The Typedef is a Keyword in C and C++. It is used to create new names for basic data types (char, int, float, double, struct & enum).
typedef enum {
kCircle,
kRectangle,
kOblateSpheroid
} ShapeType;
Here it creates enumerated data type ShapeType & we can write new names for enum type ShapeType as given below
ShapeType shape1;
ShapeType shape2;
ShapeType shape3;
You can try this:
const data = {
name : "Test",
value: 12
}
if("name" in data){
//Found
}
else {
//Not found
}
cURL > 7.18.0 has an option --data-urlencode
which solves this problem. Using this, I can simply send a POST request as
curl -d name=john --data-urlencode passwd=@31&3*J https://www.mysite.com
You can pass any number of arguments to the function that apply
is calling through either unnamed arguments, passed as a tuple to the args
parameter, or through other keyword arguments internally captured as a dictionary by the kwds
parameter.
For instance, let's build a function that returns True for values between 3 and 6, and False otherwise.
s = pd.Series(np.random.randint(0,10, 10))
s
0 5
1 3
2 1
3 1
4 6
5 0
6 3
7 4
8 9
9 6
dtype: int64
s.apply(lambda x: x >= 3 and x <= 6)
0 True
1 True
2 False
3 False
4 True
5 False
6 True
7 True
8 False
9 True
dtype: bool
This anonymous function isn't very flexible. Let's create a normal function with two arguments to control the min and max values we want in our Series.
def between(x, low, high):
return x >= low and x =< high
We can replicate the output of the first function by passing unnamed arguments to args
:
s.apply(between, args=(3,6))
Or we can use the named arguments
s.apply(between, low=3, high=6)
Or even a combination of both
s.apply(between, args=(3,), high=6)
app.use is Application level middleware
Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
you can use to check all requests, for example, you want to check token/access token you need to write a middleware by using app.use to check the token in the request.
This example shows a middleware function with no mount path. The function is executed every time the app receives a request.
var app = express()
app.use(function (req, res, next) {
console.log('Time:', Date.now())
next()
})
reference from https://expressjs.com/en/guide/using-middleware.html
Yes,
You can download Xcode with/without Paid (Premium) Apple Developer Account from below links.
Xcode 11
Xcode 11.3
- (Command Line Tool (Xcode 11.3) - for macOS 10.14)Xcode 11.2.1
- (Command Line Tool (Xcode 11.2 beta 2) - for macOS 10.14)Xcode 10
Xcode 10.2.1
- (Command Line Tool (Xcode 10.2.1) - for macOS 10.14)Xcode 10.2
- (Command Line Tool (Xcode 10.2) - for macOS 10.14)Xcode 10.1
- (Command Line Tool (Xcode 10.1) - for macOS 10.14)
- (Command Line Tool (Xcode 10.1) - for macOS 10.13)Xcode 10
- (Command Line Tool (Xcode 10) - for macOS 10.14)
- (Command Line Tool (Xcode 10) - for macOS 10.13)
For non-premium account/apple id: (Download Xcode 10 without Paid (Premium) Apple Developer Account from below link)
Look at here: How to install & set command line tool
See here for older versions of Xcode (Which may need to authenticate your apple account):
the right ways
const getUser = user => {return { name: user.name, age: user.age };};
const user = { name: "xgqfrms", age: 21 };
console.log(getUser(user));
// {name: "xgqfrms", age: 21}
const getUser = user => ({ name: user.name, age: user.age });
const user = { name: "xgqfrms", age: 21 };
console.log(getUser(user));
// {name: "xgqfrms", age: 21}
https://github.com/lydiahallie/javascript-questions/issues/220
https://mariusschulz.com/blog/returning-object-literals-from-arrow-functions-in-javascript
File.WriteAllText("path", String.Empty);
or
File.CreateText("path").Close();
The other answers all contain significant omissions.
The is
operator does not check if the runtime type of the operand is exactly the given type; rather, it checks to see if the runtime type is compatible with the given type:
class Animal {}
class Tiger : Animal {}
...
object x = new Tiger();
bool b1 = x is Tiger; // true
bool b2 = x is Animal; // true also! Every tiger is an animal.
But checking for type identity with reflection checks for identity, not for compatibility
bool b5 = x.GetType() == typeof(Tiger); // true
bool b6 = x.GetType() == typeof(Animal); // false! even though x is an animal
or with the type variable
bool b7 = t == typeof(Tiger); // true
bool b8 = t == typeof(Animal); // false! even though x is an
If that's not what you want, then you probably want IsAssignableFrom:
bool b9 = typeof(Tiger).IsAssignableFrom(x.GetType()); // true
bool b10 = typeof(Animal).IsAssignableFrom(x.GetType()); // true! A variable of type Animal may be assigned a Tiger.
or with the type variable
bool b11 = t.IsAssignableFrom(x.GetType()); // true
bool b12 = t.IsAssignableFrom(x.GetType()); // true! A
Check: key = undef !!!
You got also the warn message:
Each child in a list should have a unique "key" prop.
if your code is complete right, but if on
<MyComponent key={someValue} />
someValue is undefined!!! Please check this first. You can save hours.
@Someone Somewhere I used this to clear focus:
editText.clearFocus();
and it helps
If you are using vagrant ensure that the file is on the server and then use the path to the file. e.g if the file is stored in the public folder you will have
sql> source /var/www/public/xxx.sql
Where xxx is the name of the file
Make sure you've set your target API (different from the target SDK) in the Project Properties (not the manifest) to be at least 4.0/API 14.
You can't put a CLOB in the WHERE clause. From the documentation:
Large objects (LOBs) are not supported in comparison conditions. However, you can use PL/SQL programs for comparisons on CLOB data.
If your values are always less than 4k, you can use:
UPDATE IMS_TEST
SET TEST_Category = 'just testing'
WHERE to_char(TEST_SCRIPT) = 'something'
AND ID = '10000239';
It is strange to search by a CLOB anyways.. could you not just search by the ID column?
Here is the actual way I'm doing for more than 6 months. I use a folder named node_modules as my root folder in the project, in this way it will always look for that folder from everywhere I call an absolute require:
This is more useful when you are nested into folders and it's a lot less work to change a file location if is set in absolute way. I only use 2 the relative require in my whole app.
It is similar to x = (x >> 1)
.
(operand1)(operator)=(operand2) implies(=>) (operand1)=(operand1)(operator)(operand2)
It shifts the binary value of x by one to the right.
E.g.
int x=3; // binary form (011)
x = x >> 1; // zero shifted in from the left, 1 shifted out to the right:
// x=1, binary form (001)
public enum MyEvents
{
Event1
}
public class CustomEventArgs : EventArgs
{
public MyEvents MyEvents { get; set; }
}
private EventHandler<CustomEventArgs> onTrigger;
public event EventHandler<CustomEventArgs> Trigger
{
add
{
onTrigger += value;
}
remove
{
onTrigger -= value;
}
}
protected void OnTrigger(CustomEventArgs e)
{
if (onTrigger != null)
{
onTrigger(this, e);
}
}
Beware that Popen.communicate(input=s)
may give you trouble ifs
is too big, because apparently the parent process will buffer it before forking the child subprocess, meaning it needs "twice as much" used memory at that point (at least according to the "under the hood" explanation and linked documentation found here). In my particular case,s
was a generator that was first fully expanded and only then written tostdin
so the parent process was huge right before the child was spawned,
and no memory was left to fork it:
File "/opt/local/stow/python-2.7.2/lib/python2.7/subprocess.py", line 1130, in _execute_child
self.pid = os.fork()
OSError: [Errno 12] Cannot allocate memory
Use widget as PasswordInput
from django import forms
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
There's no difference between these two things. Think about it.
Let's take a simpler definition, "A positive number is even if it is zero or that number minus two is even." Does this say 8 is even if 6 is even? Or does this say 8 is even if 6, 4, 2, and 0 are even?
There's no difference. If it says 8 is even if 6 is even, it also says 6 is even if 4 is even. And thus it also says 4 is even if 2 is even. And thus it says 2 is even if 0 is even. So if it says 8 is even if 6 is even, it (indirectly) says 8 is even if 6, 4, 2, and 0 are even.
It's the same thing here. Any indirect sub-tree can be found by a chain of direct sub-trees. So even if it only applies directly to direct sub-trees, it still applies indirectly to all sub-trees (and thus all nodes).
Both of the examples immediately above didn't work for me. Opening a recordset on the table and adding a record does work to add the record, except:
myLong = CLng(rs!AutoNumberField)
returns Null if put between rs.AddNew and rs.Update. If put after rs.Update, it does return something, but it's always wrong, and always the same incorrect value. Looking at the table directly after adding the new record shows an autonumber field value different than the one returned by the above statement.
myLong = DLookup("AutoNumberField","TableName","SomeCriteria")
will work properly, as long as it's done after rs.Update, and there are any other fields which can uniquely identify the record.
Jelly Bean adds support for this with the ActivityOptions.makeCustomAnimation() method. Of course, since it's only on Jelly Bean, it's pretty much worthless for practical purposes.
There are some open source alternatives:
Declare a Class(Type) to hold the elements you want to join. In the below example declare JoinElement
public class **JoinElement**
{
public int? Id { get; set; }
public string Name { get; set; }
}
results = from course in courseQueryable.AsQueryable()
join agency in agencyQueryable.AsQueryable()
on new **JoinElement**() { Id = course.CourseAgencyId, Name = course.CourseDeveloper }
equals new **JoinElement**() { Id = agency.CourseAgencyId, Name = "D" } into temp1
Step 1) See what Objects exist with the name:
select * from all_objects where object_name = upper('&object_name');
It could be that a Synonym exists but no Table?
Step 2) If that's not the problem, investigate the Synonym:
select * from all_synonyms where synonym_name = upper('&synonym_name');
It could be that an underlying Table or View to that Synonym is missing?
Because you are using ARC you must be using iOS 4.0 or later. This means you could use blocks. If instead of remembering the selector to perform you instead took a block, ARC would be able to better track what is actually going on and you wouldn't have to run the risk of accidentally introducing a memory leak.
Because when you use a return
statement inside an each
loop, a "non-false" value will act as a continue
, whereas false
will act as a break
. You will need to return false
from the each
function. Something like this:
function findXX(word) {
var toReturn;
$.each(someArray, function(i) {
$('body').append('-> '+i+'<br />');
if(someArray[i] == word) {
toReturn = someArray[i];
return false;
}
});
return toReturn;
}
From the docs:
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
I have followed the below steps in Macbook.
Assuming you want an actual SQL Server MERGE
statement:
MERGE INTO dbo.energydata WITH (HOLDLOCK) AS target
USING dbo.temp_energydata AS source
ON target.webmeterID = source.webmeterID
AND target.DateTime = source.DateTime
WHEN MATCHED THEN
UPDATE SET target.kWh = source.kWh
WHEN NOT MATCHED BY TARGET THEN
INSERT (webmeterID, DateTime, kWh)
VALUES (source.webmeterID, source.DateTime, source.kWh);
If you also want to delete records in the target that aren't in the source:
MERGE INTO dbo.energydata WITH (HOLDLOCK) AS target
USING dbo.temp_energydata AS source
ON target.webmeterID = source.webmeterID
AND target.DateTime = source.DateTime
WHEN MATCHED THEN
UPDATE SET target.kWh = source.kWh
WHEN NOT MATCHED BY TARGET THEN
INSERT (webmeterID, DateTime, kWh)
VALUES (source.webmeterID, source.DateTime, source.kWh)
WHEN NOT MATCHED BY SOURCE THEN
DELETE;
Because this has become a bit more popular, I feel like I should expand this answer a bit with some caveats to be aware of.
First, there are several blogs which report concurrency issues with the MERGE
statement in older versions of SQL Server. I do not know if this issue has ever been addressed in later editions. Either way, this can largely be worked around by specifying the HOLDLOCK
or SERIALIZABLE
lock hint:
MERGE INTO dbo.energydata WITH (HOLDLOCK) AS target
[...]
You can also accomplish the same thing with more restrictive transaction isolation levels.
There are several other known issues with MERGE
. (Note that since Microsoft nuked Connect and didn't link issues in the old system to issues in the new system, these older issues are hard to track down. Thanks, Microsoft!) From what I can tell, most of them are not common problems or can be worked around with the same locking hints as above, but I haven't tested them.
As it is, even though I've never had any problems with the MERGE
statement myself, I always use the WITH (HOLDLOCK)
hint now, and I prefer to use the statement only in the most straightforward of cases.
May be i am too late to the party but this will parse/escape single quote (don't want to get into a battle on parse vs escape)..
JSON.parse("\"'\"")
Above example is technically incorrect. Per latest jQuery, use the prop()
method should be used for things like disabled. See their API page.
To disable all form elements inside 'target', use the :input selector which matches all input, textarea, select and button elements.
$("#target :input").prop("disabled", true);
If you only want the elements, use this.
$("#target input").prop("disabled", true);
*args and **kwargs are special-magic features of Python. Think of a function that could have an unknown number of arguments. For example, for whatever reasons, you want to have function that sums an unknown number of numbers (and you don't want to use the built-in sum function). So you write this function:
def sumFunction(*args):
result = 0
for x in args:
result += x
return result
and use it like: sumFunction(3,4,6,3,6,8,9).
**kwargs has a diffrent function. With **kwargs you can give arbitrary keyword arguments to a function and you can access them as a dictonary.
def someFunction(**kwargs):
if 'text' in kwargs:
print kwargs['text']
Calling someFunction(text="foo") will print foo.
I believe this is a more easy approach:
public class HibernateProxyTypeAdapter implements JsonSerializer<HibernateProxy>{
public JsonElement serialize(HibernateProxy object_,
Type type_,
JsonSerializationContext context_) {
return new GsonBuilder().create().toJsonTree(initializeAndUnproxy(object_)).getAsJsonObject();
// that will convert enum object to its ordinal value and convert it to json element
}
public static <T> T initializeAndUnproxy(T entity) {
if (entity == null) {
throw new
NullPointerException("Entity passed for initialization is null");
}
Hibernate.initialize(entity);
if (entity instanceof HibernateProxy) {
entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer()
.getImplementation();
}
return entity;
}
}
And then you will be able to call it like this:
Gson gson = new GsonBuilder()
.registerTypeHierarchyAdapter(HibernateProxy.class, new HibernateProxyTypeAdapter())
.create();
This way all the hibernate objects will be converted automatically.
I found it. Perl has multi-line comments:
#!/usr/bin/perl
use strict;
use warnings;
=for comment
Example of multiline comment.
Example of multiline comment.
=cut
print "Multi Line Comment Example \n";
Just keep going with your code - you're on the right track:
//call SQL helper class to get initial data
DataTable dt = sql.ExecuteDataTable("sp_MyProc");
dt.Columns.Add("NewColumn", typeof(System.Int32));
foreach(DataRow row in dt.Rows)
{
//need to set value to NewColumn column
row["NewColumn"] = 0; // or set it to some other value
}
// possibly save your Dataset here, after setting all the new values
You only need a single line of code to set the border around every cell in the range:
Range("A1:F20").Borders.LineStyle = xlContinuous
It's also easy to apply multiple effects to the border around each cell.
For example:
Sub RedOutlineCells()
Dim rng As Range
Set rng = Range("A1:F20")
With rng.Borders
.LineStyle = xlContinuous
.Color = vbRed
.Weight = xlThin
End With
End Sub
try this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<body>
<a href="#name">click me</a>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
<div name="name" id="name">here</div>
</body>
</html>
For the benefit of anyone searching for similar, see worksheet .UsedRange
,
e.g. ? ActiveSheet.UsedRange.Rows.Count
and loops such as
For Each loopRow in Sheets(1).UsedRange.Rows: Print loopRow.Row: Next
If I understand your questions correctly, all you need to do is add the .Where(m => m.r.u.UserId == 1):
var UserInRole = db.UserProfiles.
Join(db.UsersInRoles, u => u.UserId, uir => uir.UserId,
(u, uir) => new { u, uir }).
Join(db.Roles, r => r.uir.RoleId, ro => ro.RoleId, (r, ro) => new { r, ro })
.Where(m => m.r.u.UserId == 1)
.Select (m => new AddUserToRole
{
UserName = m.r.u.UserName,
RoleName = m.ro.RoleName
});
Hope that helps.
Using direct conditions (like ==, !=, !condition) will have a slight performance improvement over the .equals(condition) as in one case you are calling the method from an object whereas direct comparisons are performed directly.
Use CSS3
.container {
-webkit-column-count: 2;
-moz-column-count: 2;
column-count: 2;
-webkit-column-gap: 20px;
-moz-column-gap: 20px;
column-gap: 20px;
}
Browser Support
-webkit-
)-moz-
)-webkit-
)-webkit-
)Update
As of jQuery 3.0, the new syntax is just .on:
see this answer here and the code:
$('iframe').on('load', function() {
// do stuff
});
SHORT ANSWER
Like others have said - you should always quote the variables to prevent strange behaviour. So use echo "$foo" in instead of just echo $foo.
LONG ANSWER
I do think this example warrants further explanation because there is more going on than it might seem on the face of it.
I can see where your confusion comes in because after you ran your first example you probably thought to yourself that the shell is obviously doing:
So from your first example:
me$ FOO="BAR * BAR"
me$ echo $FOO
After parameter expansion is equivalent to:
me$ echo BAR * BAR
And after filename expansion is equivalent to:
me$ echo BAR file1 file2 file3 file4 BAR
And if you just type echo BAR * BAR
into the command line you will see that they are equivalent.
So you probably thought to yourself "if I escape the *, I can prevent the filename expansion"
So from your second example:
me$ FOO="BAR \* BAR"
me$ echo $FOO
After parameter expansion should be equivalent to:
me$ echo BAR \* BAR
And after filename expansion should be equivalent to:
me$ echo BAR \* BAR
And if you try typing "echo BAR \* BAR" directly into the command line it will indeed print "BAR * BAR" because the filename expansion is prevented by the escape.
So why did using $foo not work?
It's because there is a third expansion that takes place - Quote Removal. From the bash manual quote removal is:
After the preceding expansions, all unquoted occurrences of the characters ‘\’, ‘'’, and ‘"’ that did not result from one of the above expansions are removed.
So what happens is when you type the command directly into the command line, the escape character is not the result of a previous expansion so BASH removes it before sending it to the echo command, but in the 2nd example, the "\*" was the result of a previous Parameter expansion, so it is NOT removed. As a result, echo receives "\*" and that's what it prints.
Note the difference between the first example - "*" is not included in the characters that will be removed by Quote Removal.
I hope this makes sense. In the end the conclusion in the same - just use quotes. I just thought I'd explain why escaping, which logically should work if only Parameter and Filename expansion are at play, didn't work.
For a full explanation of BASH expansions, refer to:
http://www.gnu.org/software/bash/manual/bashref.html#Shell-Expansions
Have a look at the documentation. You made the following mistakes.
Firstly, ps.executeQuery()
doesn't have any parameters. Instead you passed the SQL query into it.
Secondly, regarding the prepared statement, you have to use the ?
symbol if want to pass any parameters. And later bind it using
setXXX(index, value)
Here xxx stands for the data type.
date = new DateTime(date.year, date.month, date.day, HH, MM, SS);
Run the below commands as admin to install NuGet
using Powershell:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Install-PackageProvider -Name NuGet
Conditions apply because you can use where condition for sub-select statements. You can perform complicated inserts using sub-selects.
For example:
INSERT INTO suppliers
(supplier_id, supplier_name)
SELECT account_no, name
FROM customers
WHERE city = 'Newark';
By placing a "select" in the insert statement, you can perform multiples inserts quickly.
With this type of insert, you may wish to check for the number of rows being inserted. You can determine the number of rows that will be inserted by running the following SQL statement before performing the insert.
SELECT count(*)
FROM customers
WHERE city = 'Newark';
You can make sure that you do not insert duplicate information by using the EXISTS condition.
For example, if you had a table named clients with a primary key of client_id, you could use the following statement:
INSERT INTO clients
(client_id, client_name, client_type)
SELECT supplier_id, supplier_name, 'advertising'
FROM suppliers
WHERE not exists (select * from clients
where clients.client_id = suppliers.supplier_id);
This statement inserts multiple records with a subselect.
If you wanted to insert a single record, you could use the following statement:
INSERT INTO clients
(client_id, client_name, client_type)
SELECT 10345, 'IBM', 'advertising'
FROM dual
WHERE not exists (select * from clients
where clients.client_id = 10345);
The use of the dual table allows you to enter your values in a select statement, even though the values are not currently stored in a table.
See also How to insert with where clause
<?php
ini_set("SMTP", "aspmx.l.google.com");
ini_set("sendmail_from", "[email protected]");
$message = "The mail message was sent with the following mail setting:\r\nSMTP = aspmx.l.google.com\r\nsmtp_port = 25\r\nsendmail_from = [email protected]";
$headers = "From: [email protected]";
mail("[email protected]", "Testing", $message, $headers);
echo "Check your email now....<BR/>";
?>
or, for more details, read on.
to avoid the problem with CDROM: sudo nano /etc/apt/sources.list
find your cdrom and comment it with #
save the changes: "cntrl + o", than exit the file: "cntrl + x"
and try to install again
You have an incredible number of choices to achieve delegates in C++. Here are the ones that came to my mind.
Option 1 : functors:
A function object may be created by implementing operator()
struct Functor
{
// Normal class/struct members
int operator()(double d) // Arbitrary return types and parameter list
{
return (int) d + 1;
}
};
// Use:
Functor f;
int i = f(3.14);
Option 2: lambda expressions (C++11 only)
// Syntax is roughly: [capture](parameter list) -> return type {block}
// Some shortcuts exist
auto func = [](int i) -> double { return 2*i/1.15; };
double d = func(1);
Option 3: function pointers
int f(double d) { ... }
typedef int (*MyFuncT) (double d);
MyFuncT fp = &f;
int a = fp(3.14);
Option 4: pointer to member functions (fastest solution)
See Fast C++ Delegate (on The Code Project).
struct DelegateList
{
int f1(double d) { }
int f2(double d) { }
};
typedef int (DelegateList::* DelegateType)(double d);
DelegateType d = &DelegateList::f1;
DelegateList list;
int a = (list.*d)(3.14);
Option 5: std::function
(or boost::function
if your standard library doesn't support it). It is slower, but it is the most flexible.
#include <functional>
std::function<int(double)> f = [can be set to about anything in this answer]
// Usually more useful as a parameter to another functions
Option 6: binding (using std::bind)
Allows setting some parameters in advance, convenient to call a member function for instance.
struct MyClass
{
int DoStuff(double d); // actually a DoStuff(MyClass* this, double d)
};
std::function<int(double d)> f = std::bind(&MyClass::DoStuff, this, std::placeholders::_1);
// auto f = std::bind(...); in C++11
Option 7: templates
Accept anything as long as it matches the argument list.
template <class FunctionT>
int DoSomething(FunctionT func)
{
return func(3.14);
}
Alex's answer shows you a solution for standard normal distribution (mean = 0, standard deviation = 1). If you have normal distribution with mean
and std
(which is sqr(var)
) and you want to calculate:
from scipy.stats import norm
# cdf(x < val)
print norm.cdf(val, m, s)
# cdf(x > val)
print 1 - norm.cdf(val, m, s)
# cdf(v1 < x < v2)
print norm.cdf(v2, m, s) - norm.cdf(v1, m, s)
Read more about cdf here and scipy implementation of normal distribution with many formulas here.
//Sets the row color depending on the value in the "Status" column.
function setRowColors() {
var range = SpreadsheetApp.getActiveSheet().getDataRange();
var statusColumnOffset = getStatusColumnOffset();
for (var i = range.getRow(); i < range.getLastRow(); i++) {
rowRange = range.offset(i, 0, 1);
status = rowRange.offset(0, statusColumnOffset).getValue();
if (status == 'Completed') {
rowRange.setBackgroundColor("#99CC99");
} else if (status == 'In Progress') {
rowRange.setBackgroundColor("#FFDD88");
} else if (status == 'Not Started') {
rowRange.setBackgroundColor("#CC6666");
}
}
}
//Returns the offset value of the column titled "Status"
//(eg, if the 7th column is labeled "Status", this function returns 6)
function getStatusColumnOffset() {
lastColumn = SpreadsheetApp.getActiveSheet().getLastColumn();
var range = SpreadsheetApp.getActiveSheet().getRange(1,1,1,lastColumn);
for (var i = 0; i < range.getLastColumn(); i++) {
if (range.offset(0, i, 1, 1).getValue() == "Status") {
return i;
}
}
}
For large datasets, it is memory efficient to read only selected rows via the skiprows
parameter.
Example
pred = lambda x: x not in [1, 3]
pd.read_csv("data.csv", skiprows=pred, index_col=0, names=...)
This will now return a DataFrame from a file that skips all rows except 1 and 3.
Details
From the docs:
skiprows
: list-like or integer or callable, defaultNone
...
If callable, the callable function will be evaluated against the row indices, returning True if the row should be skipped and False otherwise. An example of a valid callable argument would be
lambda x: x in [0, 2]
This feature works in version pandas 0.20.0+. See also the corresponding issue and a related post.
This is how you can create a simple observable for static data.
let observable = Observable.create(observer => {
setTimeout(() => {
let users = [
{username:"balwant.padwal",city:"pune"},
{username:"test",city:"mumbai"}]
observer.next(users); // This method same as resolve() method from Angular 1
console.log("am done");
observer.complete();//to show we are done with our processing
// observer.error(new Error("error message"));
}, 2000);
})
to subscribe to it is very easy
observable.subscribe((data)=>{
console.log(data); // users array display
});
I hope this answer is helpful. We can use HTTP call instead static data.
I've worked around the inability to put a border on the select in IE7 (IE8 in compatibility mode)
By giving it a border as wel as a padding, it looks like something....
Not everything, but it's start...
You can use input text with "list" attribute, which refers to the datalist of values.
<input type="text" name="city" list="cityname">_x000D_
<datalist id="cityname">_x000D_
<option value="Boston">_x000D_
<option value="Cambridge">_x000D_
</datalist>
_x000D_
This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist
The simplest solution I found for simply limiting the string length was {{ modal.title | slice:0:20 }}
, and then borrowing from @Govan above you can use {{ modal.title.length > 20 ? '...' : ''}}
to add the suspension points if the string is longer than 20, so the final result is simply:
{{ modal.title | slice:0:20 }}{{ modal.title.length > 20 ? '...' : ''}}
https://angular.io/docs/ts/latest/api/common/index/SlicePipe-pipe.html