My answer is based on all the expert comments above, but below is the following code that anyone can use to make sure on each postback and on each asynchronous postback the JavaScript code will still be executed.
In my case, I had a user control within a page. Just paste the below code in your user control.
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
if (args.get_error() == undefined) {
UPDATEPANELFUNCTION();
}
}
function UPDATEPANELFUNCTION() {
jQuery(document).ready(function ($) {
/* Insert all your jQuery events and function calls */
});
}
UPDATEPANELFUNCTION();
</script>
The Network pending state on time, means your request is in progressing state. As soon as it responds the time will be updated with total elapsed time.
This picture shows the network call is in processing state(Pending)
This picture shows the time taken in processing by network call.
To quote the help page (try ?integer
), bolded portion mine:
Integer vectors exist so that data can be passed to C or Fortran code which expects them, and so that (small) integer data can be represented exactly and compactly.
Note that current implementations of R use 32-bit integers for integer vectors, so the range of representable integers is restricted to about +/-2*10^9: doubles can hold much larger integers exactly.
Like the help page says, R's integer
s are signed 32-bit numbers so can hold between -2147483648 and +2147483647 and take up 4 bytes.
R's numeric
is identical to an 64-bit double
conforming to the IEEE 754 standard. R has no single precision data type. (source: help pages of numeric
and double
). A double can store all integers between -2^53 and 2^53 exactly without losing precision.
We can see the data type sizes, including the overhead of a vector (source):
> object.size(1:1000)
4040 bytes
> object.size(as.numeric(1:1000))
8040 bytes
Using Visual Studio 2005 or 2008 when you create a project for an executable, on the properties windows inside the "Application" panel there is a check box named “Make single instance application” that you can activate to convert the application on a single instance application.
Here is a capture of the window I'm talking of: This is a Visual Studio 2008 windows application project.
I wrote this and placed it in a test/utils
module in my project. For cases when its not a class, just plan ol' dict, this will traverse both objects and ensure
Its big... its not sexy... but oh boi does it work!
def assertObjectsEqual(obj_a, obj_b):
def _assert(a, b):
if a == b:
return
raise AssertionError(f'{a} !== {b} inside assertObjectsEqual')
def _check(a, b):
if a is None or b is None:
_assert(a, b)
for k,v in a.items():
if isinstance(v, dict):
assertObjectsEqual(v, b[k])
else:
_assert(v, b[k])
# Asserting both directions is more work
# but it ensures no dangling values on
# on either object
_check(obj_a, obj_b)
_check(obj_b, obj_a)
You can clean it up a little by removing the _assert
and just using plain ol' assert
but then the message you get when it fails is very unhelpful.
Now only I came across this situation and found some more interesting features around GROUP_CONCAT
. I hope these details will make you feel interesting.
simple GROUP_CONCAT
SELECT GROUP_CONCAT(TaskName)
FROM Tasks;
Result:
+------------------------------------------------------------------+
| GROUP_CONCAT(TaskName) |
+------------------------------------------------------------------+
| Do garden,Feed cats,Paint roof,Take dog for walk,Relax,Feed cats |
+------------------------------------------------------------------+
GROUP_CONCAT with DISTINCT
SELECT GROUP_CONCAT(TaskName)
FROM Tasks;
Result:
+------------------------------------------------------------------+
| GROUP_CONCAT(TaskName) |
+------------------------------------------------------------------+
| Do garden,Feed cats,Paint roof,Take dog for walk,Relax,Feed cats |
+------------------------------------------------------------------+
GROUP_CONCAT with DISTINCT and ORDER BY
SELECT GROUP_CONCAT(DISTINCT TaskName ORDER BY TaskName DESC)
FROM Tasks;
Result:
+--------------------------------------------------------+
| GROUP_CONCAT(DISTINCT TaskName ORDER BY TaskName DESC) |
+--------------------------------------------------------+
| Take dog for walk,Relax,Paint roof,Feed cats,Do garden |
+--------------------------------------------------------+
GROUP_CONCAT with DISTINCT and SEPARATOR
SELECT GROUP_CONCAT(DISTINCT TaskName SEPARATOR ' + ')
FROM Tasks;
Result:
+----------------------------------------------------------------+
| GROUP_CONCAT(DISTINCT TaskName SEPARATOR ' + ') |
+----------------------------------------------------------------+
| Do garden + Feed cats + Paint roof + Relax + Take dog for walk |
+----------------------------------------------------------------+
GROUP_CONCAT and Combining Columns
SELECT GROUP_CONCAT(TaskId, ') ', TaskName SEPARATOR ' ')
FROM Tasks;
Result:
+------------------------------------------------------------------------------------+
| GROUP_CONCAT(TaskId, ') ', TaskName SEPARATOR ' ') |
+------------------------------------------------------------------------------------+
| 1) Do garden 2) Feed cats 3) Paint roof 4) Take dog for walk 5) Relax 6) Feed cats |
+------------------------------------------------------------------------------------+
GROUP_CONCAT and Grouped Results
Assume that the following are the results before using GROUP_CONCAT
+------------------------+--------------------------+
| ArtistName | AlbumName |
+------------------------+--------------------------+
| Iron Maiden | Powerslave |
| AC/DC | Powerage |
| Jim Reeves | Singing Down the Lane |
| Devin Townsend | Ziltoid the Omniscient |
| Devin Townsend | Casualties of Cool |
| Devin Townsend | Epicloud |
| Iron Maiden | Somewhere in Time |
| Iron Maiden | Piece of Mind |
| Iron Maiden | Killers |
| Iron Maiden | No Prayer for the Dying |
| The Script | No Sound Without Silence |
| Buddy Rich | Big Swing Face |
| Michael Learns to Rock | Blue Night |
| Michael Learns to Rock | Eternity |
| Michael Learns to Rock | Scandinavia |
| Tom Jones | Long Lost Suitcase |
| Tom Jones | Praise and Blame |
| Tom Jones | Along Came Jones |
| Allan Holdsworth | All Night Wrong |
| Allan Holdsworth | The Sixteen Men of Tain |
+------------------------+--------------------------+
USE Music;
SELECT ar.ArtistName,
GROUP_CONCAT(al.AlbumName)
FROM Artists ar
INNER JOIN Albums al
ON ar.ArtistId = al.ArtistId
GROUP BY ArtistName;
Result:
+------------------------+----------------------------------------------------------------------------+
| ArtistName | GROUP_CONCAT(al.AlbumName) |
+------------------------+----------------------------------------------------------------------------+
| AC/DC | Powerage |
| Allan Holdsworth | All Night Wrong,The Sixteen Men of Tain |
| Buddy Rich | Big Swing Face |
| Devin Townsend | Epicloud,Ziltoid the Omniscient,Casualties of Cool |
| Iron Maiden | Somewhere in Time,Piece of Mind,Powerslave,Killers,No Prayer for the Dying |
| Jim Reeves | Singing Down the Lane |
| Michael Learns to Rock | Eternity,Scandinavia,Blue Night |
| The Script | No Sound Without Silence |
| Tom Jones | Long Lost Suitcase,Praise and Blame,Along Came Jones |
+------------------------+----------------------------------------------------------------------------+
[]
is to select columns.When the indexing operator is passed a string or integer, it attempts to find a column with that particular name and return it as a Series.
So, in the question above: df[2]
searches for a column name matching the integer value 2
. This column does not exist and a KeyError
is raised.
Strangely, when given a slice, the DataFrame indexing operator selects rows and can do so by integer location or by index label.
df[2:3]
This will slice beginning from the row with integer location 2 up to 3, exclusive of the last element. So, just a single row. The following selects rows beginning at integer location 6 up to but not including 20 by every third row.
df[6:20:3]
You can also use slices consisting of string labels if your DataFrame index has strings in it. For more details, see this solution on .iloc vs .loc.
I almost never use this slice notation with the indexing operator as its not explicit and hardly ever used. When slicing by rows, stick with .loc/.iloc
.
Works for all browsers and all versions:
JS
jQuery(document).ready(function () {
var widthOfSelect = $("#first").width();
widthOfSelect = widthOfSelect - 13;
//alert(widthOfSelect);
jQuery('#first').wrap("<div id='sss' style='width: "+widthOfSelect+"px; overflow: hidden; border-right: #000 1px solid;' width=20></div>");
});
HTML
<select class="first" id="first">
<option>option1</option>
<option>option2</option>
<option>option3</option>
</select>
I made this useful table with all the cases:
blank?
, present?
are provided by Rails.
No such thing. the input type=date
will pick up whatever your system default is and show that in the GUI but will always store the value in ISO format (yyyy-mm-dd). Beside be aware that not all browsers support this so it's not a good idea to depend on this input type yet.
If this is a corporate issue, force all the computer to use local regional format (dd-mm-yyyy) and your UI will show it in this format (see wufoo link before after changing your regional settings, you need to reopen the browser).
See: http://www.wufoo.com/html5/types/4-date.html for example
See: http://caniuse.com/#feat=input-datetime for browser supports
See: https://www.w3.org/TR/2011/WD-html-markup-20110525/input.date.html for spec. <- no format attr.
Your best bet is still to use JavaScript based component that will allow you to customize this to whatever you wish.
to merely set typeface of app to normal
, sans
, serif
or monospace
(not to a custom font!), you can do this.
define a theme and set the android:typeface
attribute to the typeface you want to use in styles.xml
:
<resources>
<!-- custom normal activity theme -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<!-- other elements -->
<item name="android:typeface">monospace</item>
</style>
</resources>
apply the theme to the whole app in the AndroidManifest.xml
file:
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
<application
android:theme="@style/AppTheme" >
</application>
</manifest>
Search for copyLinesDownAction
or copyLinesUpAction
in your keyboard shortcuts
Usually, it is SHIFT+ALT+?
Adding to this. If you use both INSERT IGNORE
and ON DUPLICATE KEY UPDATE
in the same statement, the update will still happen if the insert finds a duplicate key. In other words, the update takes precedence over the ignore. However, if the ON DUPLICATE KEY UPDATE
clause itself causes a duplicate key error, that error will be ignored.
This can happen if you have more than one unique key, or if your update attempts to violate a foreign key constraint.
CREATE TABLE test
(id BIGINT (20) UNSIGNED AUTO_INCREMENT,
str VARCHAR(20),
PRIMARY KEY(id),
UNIQUE(str));
INSERT INTO test (str) VALUES('A'),('B');
/* duplicate key error caused not by the insert,
but by the update: */
INSERT INTO test (str) VALUES('B')
ON DUPLICATE KEY UPDATE str='A';
/* duplicate key error is suppressed */
INSERT IGNORE INTO test (str) VALUES('B')
ON DUPLICATE KEY UPDATE str='A';
There are a few options
Using the host : guest
format you can do any of the following:
volumes:
# Just specify a path and let the Engine create a volume
- /var/lib/mysql
# Specify an absolute path mapping
- /opt/data:/var/lib/mysql
# Path on the host, relative to the Compose file
- ./cache:/tmp/cache
# User-relative path
- ~/configs:/etc/configs/:ro
# Named volume
- datavolume:/var/lib/mysql
As of docker-compose v3.2 you can use long syntax which allows the configuration of additional fields that can be expressed in the short form such as mount type
(volume, bind or tmpfs) and read_only
.
version: "3.2"
services:
web:
image: nginx:alpine
ports:
- "80:80"
volumes:
- type: volume
source: mydata
target: /data
volume:
nocopy: true
- type: bind
source: ./static
target: /opt/app/static
networks:
webnet:
volumes:
mydata:
Check out https://docs.docker.com/compose/compose-file/#long-syntax-3 for more info.
You made the error, for the second call, to set the size of source to the size of the target.
Anyway i bet that you want the same aspect ratio for the scaled image, so you need to compute it :
var hRatio = canvas.width / img.width ;
var vRatio = canvas.height / img.height ;
var ratio = Math.min ( hRatio, vRatio );
ctx.drawImage(img, 0,0, img.width, img.height, 0,0,img.width*ratio, img.height*ratio);
i also suppose you want to center the image, so the code would be :
function drawImageScaled(img, ctx) {
var canvas = ctx.canvas ;
var hRatio = canvas.width / img.width ;
var vRatio = canvas.height / img.height ;
var ratio = Math.min ( hRatio, vRatio );
var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
var centerShift_y = ( canvas.height - img.height*ratio ) / 2;
ctx.clearRect(0,0,canvas.width, canvas.height);
ctx.drawImage(img, 0,0, img.width, img.height,
centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);
}
you can see it in a jsbin here : http://jsbin.com/funewofu/1/edit?js,output
I had the same problem and the only solution I found was putting everything that used the FB statement inside the init script, I also used async loading, so the callback function is after everything that needs FB. I have a common page dinamycally loaded with php so many parts need different facebook functions controlled by php if statements which is making everything a bit messy, but is working!. if I try taking any FB declaration out of the loading script, then firefox shows the "FB is not defined" message. Hope it helps in anything.
For C, at least, per C11 6.7.5:
A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that:
for an object, causes storage to be reserved for that object;
for a function, includes the function body;
for an enumeration constant, is the (only) declaration of the identifier;
for a typedef name, is the first (or only) declaration of the identifier.
Per C11 6.7.9.8-10:
An initializer specifies the initial value stored in an object ... if an object that has automatic storage is not initialized explicitly, its value is indeterminate.
So, broadly speaking, a declaration introduces an identifier and provides information about it. For a variable, a definition is a declaration which allocates storage for that variable.
Initialization is the specification of the initial value to be stored in an object, which is not necessarily the same as the first time you explicitly assign a value to it. A variable has a value when you define it, whether or not you explicitly give it a value. If you don't explicitly give it a value, and the variable has automatic storage, it will have an initial value, but that value will be indeterminate. If it has static storage, it will be initialized implicitly depending on the type (e.g. pointer types get initialized to null pointers, arithmetic types get initialized to zero, and so on).
So, if you define an automatic variable without specifying an initial value for it, such as:
int myfunc(void) {
int myvar;
...
You are defining it (and therefore also declaring it, since definitions are declarations), but not initializing it. Therefore, definition does not equal declaration plus initialization.
$date_string = "2012-10-18";
echo "Weeknummer: " . date("W", strtotime($date_string));
If you are trying to debug your virtual host configuration, you may find the Apache -S command line switch useful. That is, type the following command:
httpd -S
This command will dump out a description of how Apache parsed the configuration file. Careful examination of the IP addresses and server names may help uncover configuration mistakes. (See the docs for the httpd program for other command line options).
DONE.
Example whatever.h
#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif
Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once
but it is not guaranteed to be supported on every compiler.
Example whatever.c
#include "whatever.h"
int f(int a) { return a + 1; }
And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.
Like this:
sample.c
#include "whatever.h"
int main(int argc, char **argv)
{
printf("%d\n", f(2)); /* prints 3 */
return 0;
}
To compile it (if you use GCC):
$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o
To link the files to create an executable file:
$ gcc sample.o whatever.o -o sample
You can test sample:
$ ./sample
3
$
use the command prompt, as suggested. I figured out why explorer is so slow a while ago, it gives you an estimate of how long it will take to delete the files/folders. To do this, it has to scan the number of items and the size. This takes ages, hence the ridiculous wait with large folders.
Also, explorer will stop if there is a particular problem with a file,
There is indeed such a tool, Comeau's C++ compiler. . It will generate C code which you can't manually maintain, but that's no problem. You'll maintain the C++ code, and just convert to C on the fly.
In Swift 5 and Xcode 10.2
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: {
//Set status bar background colour
let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView
statusBar?.backgroundColor = UIColor.red
//Set navigation bar subView background colour
for view in controller.navigationController?.navigationBar.subviews ?? [] {
view.tintColor = UIColor.white
view.backgroundColor = UIColor.red
}
})
Here i fixed status bar background colour and navigation bar background colour. If you don't want navigation bar colour comment it.
Here is a solution I came up with for myself. This is ready to run as a command prompt project. You need to clean some stuff if not. Hope this helps. It accepts several input formats like: 1.234.567,89 1,234,567.89 etc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Linq;
namespace ConvertStringDecimal
{
class Program
{
static void Main(string[] args)
{
while(true)
{
// reads input number from keyboard
string input = Console.ReadLine();
double result = 0;
// remove empty spaces
input = input.Replace(" ", "");
// checks if the string is empty
if (string.IsNullOrEmpty(input) == false)
{
// check if input has , and . for thousands separator and decimal place
if (input.Contains(",") && input.Contains("."))
{
// find the decimal separator, might be , or .
int decimalpos = input.LastIndexOf(',') > input.LastIndexOf('.') ? input.LastIndexOf(',') : input.LastIndexOf('.');
// uses | as a temporary decimal separator
input = input.Substring(0, decimalpos) + "|" + input.Substring(decimalpos + 1);
// formats the output removing the , and . and replacing the temporary | with .
input = input.Replace(".", "").Replace(",", "").Replace("|", ".");
}
// replaces , with .
if (input.Contains(","))
{
input = input.Replace(',', '.');
}
// checks if the input number has thousands separator and no decimal places
if(input.Count(item => item == '.') > 1)
{
input = input.Replace(".", "");
}
// tries to convert input to double
if (double.TryParse(input, out result) == true)
{
result = Double.Parse(input, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, CultureInfo.InvariantCulture);
}
}
// outputs the result
Console.WriteLine(result.ToString());
Console.WriteLine("----------------");
}
}
}
}
Another issue could be with your dev-dependencies. Please check if they have been installed properly (check if they are availabe in the node_modules folder)
If not then a quick fix would be:
npm i --only=dev
Or check how your npm settings are regarding prod:
npm config get production
In case they are set to true - change them to false:
npm config set -g production false
and setup a new angular project.
Found that hint here: https://github.com/angular/angular-cli/issues/10661 (ken107 and lichunbin814)
Hope that helps.
...\Program Files\Microsoft SQL Server\MSSQL 1.0\MSSQL\Backup
Above all answers are right but there is another method also which is very handy.
Pre-condition: Your project is Maven project Or converts it to Maven project.
RightclickOnProject > Configuration > Convert in to Maven Project
1. Select any jar for which you want to download sources or javadocs.
2. RightClick > Maven > Download javadoc or Download javasources
In case you know the password of that user, or you would like to guess it, do the following:
connect user/password
If this command connects successufully, you will see the message "connected", otherwise you'd see an error message. If you are then successufull logging, that means that you know the password. In that case, just do:
alter user NAME_OF_THE_USER identified by OLD_PASSWORD;
and this will reset the password to the same password as before and also reset the account_status for that user.
What you want is the outer HTML, not the inner HTML :
$('<some element/>')[0].outerHTML;
This SQL Server User Defined Function resolves the problem efficiently.No recursion, no complex loops. It takes a very short time to generate.
ALTER FUNCTION [GA].[udf_GenerateCalendar]
(
@StartDate DATE -- StartDate
, @EndDate DATE -- EndDate
)
RETURNS @Results TABLE
(
Date DATE
)
AS
/**********************************************************
Purpose: Generate a sequence of dates based on StartDate and EndDate
***********************************************************/
BEGIN
DECLARE @counter INTEGER = 1
DECLARE @days table(
day INTEGER NOT NULL
)
DECLARE @months table(
month INTEGER NOT NULL
)
DECLARE @years table(
year INTEGER NOT NULL
)
DECLARE @calendar table(
Date DATE NOT NULL
)
-- Populate generic days
SET @counter = 1
WHILE @counter <= 31
BEGIN
INSERT INTO @days
SELECT @counter dia
SELECT @counter = @counter + 1
END
-- Populate generic months
SET @counter = 1
WHILE @counter <= 12
BEGIN
INSERT INTO @months
SELECT @counter month
SELECT @counter = @counter + 1
END
-- Populate generic years
SET @counter = YEAR(@StartDate)
WHILE @counter <= YEAR(@EndDate)
BEGIN
INSERT INTO @years
SELECT @counter year
SELECT @counter = @counter + 1
END
INSERT @calendar (Date)
SELECT Date
FROM (
SELECT
CONVERT(Date, [Date], 102) AS Date
FROM (
SELECT
CAST(
y.year * 10000
+ m.month * 100
+ d.day
AS VARCHAR(8)) AS Date
FROM @days d, @months m, @years y
WHERE
ISDATE(CAST(
y.year * 10000
+ m.month * 100
+ d.day
AS VARCHAR(8))
) = 1
) A
) A
INSERT @Results (Date)
SELECT Date
FROM @calendar
WHERE Date BETWEEN @StartDate AND @EndDate
RETURN
/*
DECLARE @StartDate DATE = '2015-08-01'
DECLARE @EndDate DATE = '2015-08-31'
select * from [GA].[udf_GenerateCalendar](@StartDate, @EndDate)
*/
END
There are some issue with above written Regex.
This works perfectly.
^[a-zA-Z\d\-_.,\s]+$
Only allowed special characters are included here and can be extended after comma.
h1 {_x000D_
border: dashed 2px blue;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
border-radius: 100px;_x000D_
text-align: center;_x000D_
line-height: 60px;_x000D_
_x000D_
}
_x000D_
<h1> <br>hello world</h1>
_x000D_
There is an function, but it's extra: http://docs.jquery.com/Cookbook/wait
This little snippet allows you to wait:
$.fn.wait = function(time, type) {
time = time || 1000;
type = type || "fx";
return this.queue(type, function() {
var self = this;
setTimeout(function() {
$(self).dequeue();
}, time);
});
};
You will see the same error if you are trying to install an apk that was built using
compileSdkVersion "android-L"
Even for devices running the final version of Android 5.0. Simply change this to
compileSdkVersion 21
500 Internal Error
Windows Hosting Error
Godaddy Hosting issue
I have been facing the same issue, but now my issue has been resolved. Always use in this hosting this it works.
I will also recommend you all to do whatever changes you are looking to make in your web.config file. Please do it one by one and test the same on the live domain so that you can find the exact problem or the features that your hosting provider does not allow you to use.
<?xml version="1.0"?>
<configuration>
<system.web>
<trust level="Medium"/>
<compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
<httpRuntime targetFramework="4.5" />
<sessionState mode="InProc" cookieless="false" timeout="90" />
<authentication mode="Forms">
<forms loginUrl="default.aspx"
defaultUrl="default.aspx"
protection="All"
cookieless="UseCookies"
slidingExpiration="false"
timeout="30"
name="aeon.corpusjuris.in" />
</authentication>
<customErrors
mode="Off"
defaultRedirect="errorpage.aspx">
<error statusCode="403" redirect="errorpage.aspx"/>
<error statusCode="404" redirect="errorpage.aspx"/>
</customErrors>
<!-- <httpModules>
<add name="HTTPCaching" type="HTTPCaching"/>
</httpModules>
-->
</system.web>
<runtime>
<performanceScenario value="HighDensityWebHosting" />
</runtime>
<system.webServer>
<!-- <modules runAllManagedModulesForAllRequests="true">
<add name="HTTPCaching" type="HTTPCaching"/>
</modules>
-->
<defaultDocument>
<files>
<clear />
<add value="default.aspx" />
</files>
</defaultDocument>
<httpErrors errorMode="Detailed" />
<asp scriptErrorSentToBrowser="true"/>
<staticContent>
<clientCache cacheControlCustom="public"
cacheControlMaxAge="60:00:00"
cacheControlMode="UseMaxAge" />
</staticContent>
</system.webServer>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="90000000">
</jsonSerialization>
</webServices>
</scripting>
</system.web.extensions>
</configuration>
Simple and Easy , just add following
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
just change the default folder for your R libraries in a directory with no Administrator rights, e.g.
.libPaths("C:/R/libs")
On a system with both Python 2 and 3 installed and with pip2
-installed Pillow failing to provide Image
, it is possible to install PIL for Python 2 in a way that will solve ImportError: No module named Image
:
easy_install-2.7 --user PIL
or
sudo easy_install-2.7 PIL
Sometimes I need to extract several command line parameters, but not all of them and not from the first one. Let's assume the following call:
Test.bat uno dos tres cuatro cinco seis siete
Of course, the extension ".bat" is not needed at least you have test.exe in same folder. What we want is to get the output "tres cuatro cinco" (no matter if one line or three). The goal is that only I need three parameters and starting in the third one. In order to have a simple example the action for each one is just "echo", but you can think in some other more complex action over the selected parameters.
I've produced some examples, (options) in order you can see which one you consider better for you. Unfortunately, there is not a nice (or I don't know about) way based on a for loop over the range like "for %%i in (%3, 1, %5)".
@echo off
setlocal EnableDelayedExpansion
echo Option 1: one by one (same line)
echo %3, %4, %5
echo.
echo Option 2: Loop For one by one
for %%a in (%3, %4, %5) do echo %%a
echo.
echo Option 3: Loop For with check of limits
set i=0
for %%a in (%*) do (
set /A i=i+1
If !i! GTR 2 if !i! LSS 6 echo %%a
)
echo.
echo Option 4: Loop For with auxiliary list
for /l %%i in (3,1,5) do (
set a=%%i
set b=echo %%
set b=!b!!a!
call !b!
)
echo.
echo Option 5: Assigning to an array of elements previously
set e[0]=%0
set i=0
for %%a in (%*) do (
set /A i=i+1
set e[!i!]=%%a
)
for /l %%i in (3,1,5) do (
echo !e[%%i]!
)
echo.
echo Option 6: using shift and goto loop. It doesn't work with for loop
set i=2
:loop6
set /A i=i+1
echo %3
shift
If %i% LSS 5 goto :loop6
Probably you can find more options or combine several ones. Enjoy them.
As a beginner I would suggest you go through http://www.mkyong.com/android/android-custom-dialog-example/
I'll rundown what it basically does
Dialog
dialog.show()
method.if you need the batch file to schedule the backup, the SQL management tools have scheduled tasks built in...
The best way is to use an And
clause in your While
statement
Dim count as Integer
count =0
While True And count <= 10
count=count+1
Debug.Print(count)
Wend
The primary role of the @Named annotation is to define a bean for the purpose of resolving EL statements within the application, usually through JSF EL resolvers. Injection can be performed using names but this was not how injection in CDI was meant to work since CDI gives us a much richer way to express injection points and the beans to be injected into them.
All you have to do is read the code on getbootstrap.com:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
_x000D_
<nav class="navbar navbar-inverse navbar-static-top" role="navigation">_x000D_
<div class="container">_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">_x000D_
<span class="sr-only">Toggle navigation</span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
</div>_x000D_
_x000D_
<!-- Collect the nav links, forms, and other content for toggling -->_x000D_
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
<ul class="nav navbar-nav">_x000D_
<li><a href="index.php">Home</a></li>_x000D_
<li><a href="about.php">About</a></li>_x000D_
<li><a href="#portfolio">Portfolio</a></li>_x000D_
<li><a href="#">Blog</a></li>_x000D_
<li><a href="contact.php">Contact</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
</nav>
_x000D_
Removing leading and trailing blanks might be achieved through the trim() function from the gdata package as well:
require(gdata)
example(trim)
Usage example:
> trim(" Remove leading and trailing blanks ")
[1] "Remove leading and trailing blanks"
I'd prefer to add the answer as comment to user56's, but I am yet unable so writing as an independent answer.
I would suggest using inline CSS styling.
<table border="1" style="padding-right: 10px;">
<tr>
<td>Content</td>
</tr>
</table>
or
<table border="1">
<tr style="padding-right: 10px;">
<td>Content</td>
</tr>
</table>
or
<table border="1">
<tr>
<td style="padding-right: 10px;">Content</td>
</tr>
</table>
I don't quite follow what you need, but this is what I would do, assuming I understand you needs.
View this picture to see how you can change the bundle identifier
Explanation:
As you can see in the picture, the name of my App is PracticeApp. And my bundle identifier is: com.hello500.PracticeApp
In this case, You can change hello500 to change the bundle identifier of the app.
This info is current as of today, August 10, 2016. Here are the exact steps I took to fix this using methods posted above. I did not see anyone post: export PATH=$PATH:$HOME/anaconda/bin
(you need to add export to the beginning of the line).
Here it is, step-by-step:
For anyone running into the same problem while using oh-my-zsh, you need to do the following:
-Open your .zshrc
in your terminal. I am using iTerm 2
and have Sublime Text 3
as my default text editor:
subl ~/.zshrc
-Once the file opens in your text editor, scroll to the very bottom and add:
export PATH=$PATH:$HOME/anaconda/bin
-Save the file, then close it.
-Close your terminal, then relaunch it.
-Once back in your terminal, type:
conda --v
You should then see the version of conda
installed printed on your screen.
If you're using zsh, then after doing that, your terminal may show you zsh: command not found: rvm-prompt
.
The solution is:
alias rvm-prompt=$HOME/.rvm/bin/rvm-prompt
within .zshrc
file.source .zshrc
.Then the zsh: command not found: rvm-prompt
will disappear.
when i write import StringIO it says there is no such module.
From What’s New In Python 3.0:
The
StringIO
andcStringIO
modules are gone. Instead, import theio
module and useio.StringIO
orio.BytesIO
for text and data respectively.
.
A possibly useful method of fixing some Python 2 code to also work in Python 3 (caveat emptor):
try:
from StringIO import StringIO ## for Python 2
except ImportError:
from io import StringIO ## for Python 3
Note: This example may be tangential to the main issue of the question and is included only as something to consider when generically addressing the missing
StringIO
module. For a more direct solution the messageTypeError: Can't convert 'bytes' object to str implicitly
, see this answer.
Modulo "7" without "%" operator
int a = x % 7;
int a = (x + x / 7) & 7;
Well, as most of the answers pointed out, you can include the jQuery file locally as well as use Google's CDN/Microsoft CDN servers. On choosing Google vs. Microsoft CDN go Google_CDN vs. Microsoft_CDN depending on your requirement.
Generally for intranet applications include jQuery file locally and never use the CDN method since for intranet, the LAN is 10x times faster than Internet. For Internet and public facing applications use a hybrid approach as suggested by cowgod elsewhere. Also don't forget to use the nice tool JS_Compressor to compress the extra JavaScript code you add to your jQuery library. It makes JavaScript really fast.
In case you get a compiler error for __attribute__((noinline))
, you can just try:
noinline int func(int arg)
{
....
}
Simple: [boolean](get-variable "Varname" -ErrorAction SilentlyContinue)
Example of each kind listed in the question:
import java.util.*;
public class ListIterationExample {
public static void main(String []args){
List<Integer> numbers = new ArrayList<Integer>();
// populates list with initial values
for (Integer i : Arrays.asList(0,1,2,3,4,5,6,7))
numbers.add(i);
printList(numbers); // 0,1,2,3,4,5,6,7
// replaces each element with twice its value
for (int index=0; index < numbers.size(); index++) {
numbers.set(index, numbers.get(index)*2);
}
printList(numbers); // 0,2,4,6,8,10,12,14
// does nothing because list is not being changed
for (Integer number : numbers) {
number++; // number = new Integer(number+1);
}
printList(numbers); // 0,2,4,6,8,10,12,14
// same as above -- just different syntax
for (Iterator<Integer> iter = numbers.iterator(); iter.hasNext(); ) {
Integer number = iter.next();
number++;
}
printList(numbers); // 0,2,4,6,8,10,12,14
// ListIterator<?> provides an "add" method to insert elements
// between the current element and the cursor
for (ListIterator<Integer> iter = numbers.listIterator(); iter.hasNext(); ) {
Integer number = iter.next();
iter.add(number+1); // insert a number right before this
}
printList(numbers); // 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
// Iterator<?> provides a "remove" method to delete elements
// between the current element and the cursor
for (Iterator<Integer> iter = numbers.iterator(); iter.hasNext(); ) {
Integer number = iter.next();
if (number % 2 == 0) // if number is even
iter.remove(); // remove it from the collection
}
printList(numbers); // 1,3,5,7,9,11,13,15
// ListIterator<?> provides a "set" method to replace elements
for (ListIterator<Integer> iter = numbers.listIterator(); iter.hasNext(); ) {
Integer number = iter.next();
iter.set(number/2); // divide each element by 2
}
printList(numbers); // 0,1,2,3,4,5,6,7
}
public static void printList(List<Integer> numbers) {
StringBuilder sb = new StringBuilder();
for (Integer number : numbers) {
sb.append(number);
sb.append(",");
}
sb.deleteCharAt(sb.length()-1); // remove trailing comma
System.out.println(sb.toString());
}
}
The Google Finance Gadget API has been officially deprecated since October 2012, but as of April 2014, it's still active:
http://www.google.com/finance/info?q=NASDAQ:GOOG
http://www.google.com/finance/info?q=CURRENCY:GBPUSD
http://finance.google.com/finance/info?client=ig&q=AAPL,YHOO
You can also get charts: https://www.google.com/finance/getchart?q=YELP
Note that if your application is for public consumption, using the Google Finance API is against Google's terms of service.
Check google-finance-get-stock-quote-realtime for the complete code in python
show alert box with use variable with message
<script>
$(document).ready(function() {
var total = 30 ;
alert("your total is :"+ total +"rs");
});
</script>
If you're open to using jQuery:
<script type="text/javascript">
function fncsave()
{
$('#<%= savebtn.ClientID %>').click();
}
</script>
Also, if you are using .NET 4 or better you can make the ClientIDMode == static
and simplify the code:
<script type="text/javascript">
function fncsave()
{
$("#savebtn").click();
}
</script>
Reference: MSDN Article for Control.ClientIDMode
int a = 10;
To get the address of a, you do: &a
(address of a
) which returns an int*
(pointer to int)
int *p = &a;
Then you store the address of a in p
which is of type int*
.
Finally, if you do &p
you get the address of p
which is of type int**
, i.e. pointer to pointer to int:
int** p_ptr = &p;
just seen your edit:
to print out the pointer's address, you either need to convert it:
printf("address of pointer is: 0x%0X\n", (unsigned)&p);
printf("address of pointer to pointer is: 0x%0X\n", (unsigned)&p_ptr);
or if your printf supports it, use the %p
:
printf("address of pointer is: %p\n", p);
printf("address of pointer to pointer is: %p\n", p_ptr);
My host is Windows10 my VM guest is ubuntu build by vagrant. This worked for me:
vagrant plugin install vagrant-winnfsd
Create a path where you want to copy the file and then use:
docker run -d -v hostpath:dockerimag
Add the below lines in .gitignore and place the file inside ur project folder
/target/
/.classpath
/*.project
/.settings
/*.springBeans
To set the data in kotlin
val offerIds = ArrayList<Offer>()
offerIds.add(Offer(1))
retrunIntent.putExtra(C.OFFER_IDS, offerIds)
To get the data
val offerIds = data.getSerializableExtra(C.OFFER_IDS) as ArrayList<Offer>?
Now access the arraylist
Generally speaking, no. Views are primarily used for convenience and security, and won't (by themselves) produce any speed benefit.
That said, SQL Server 2000 and above do have a feature called Indexed Views that can greatly improve performance, with a few caveats:
COUNT
, MIN
, MAX
, or TOP
.This article describes additional benefits and limitations of indexed views:
You Can…
- The view definition can reference one or more tables in the same database.
- Once the unique clustered index is created, additional nonclustered indexes can be created against the view.
- You can update the data in the underlying tables – including inserts, updates, deletes, and even truncates.
You Can’t…
- The view definition can’t reference other views, or tables in other databases.
- It can’t contain COUNT, MIN, MAX, TOP, outer joins, or a few other keywords or elements.
- You can’t modify the underlying tables and columns. The view is created with the WITH SCHEMABINDING option.
- You can’t always predict what the query optimizer will do. If you’re using Enterprise Edition, it will automatically consider the unique clustered index as an option for a query – but if it finds a “better” index, that will be used. You could force the optimizer to use the index through the WITH NOEXPAND hint – but be cautious when using any hint.
break
and continue
breaks the readability for the reader, although it's often useful.
Not as much as "goto" concept, but almost.
Besides, if you take some new languages like Scala (inspired by Java and functional programming languages like Ocaml), you will notice that break
and continue
simply disappeared.
Especially in functional programming, this style of code is avoided:
Why scala doesn't support break and continue?
To sum up: break
and continue
are widely used in Java for an imperative style, but for any coders that used to practice functional programming, it might be.. weird.
Finally it works for me.
private VideoView videoView;
videoView = (VideoView) findViewById(R.id.videoView);
Uri video = Uri.parse("http://www.servername.com/projects/projectname/videos/1361439400.mp4");
videoView.setVideoURI(video);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
videoView.start();
}
});
Hope this would help others.
2018 Solution, still other answers are valid but you dont need to use any dependency:
First you have to create a new migration:
php artisan make:migration change_appointment_time_column_type
Then in that migration file up()
, try:
Schema::table('appointments', function ($table) {
$table->string('time')->change();
});
If you donot change the size default will be varchar(191)
but If you want to change size of the field:
Schema::table('appointments', function ($table) {
$table->string('time', 40)->change();
});
Then migrate the file by:
php artisan migrate
Ok well this might work for you, a function that takes a path and returns an array of file names in the folder. You could use an if statement to get just the excel files when looping through the array.
Function listfiles(ByVal sPath As String)
Dim vaArray As Variant
Dim i As Integer
Dim oFile As Object
Dim oFSO As Object
Dim oFolder As Object
Dim oFiles As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(sPath)
Set oFiles = oFolder.Files
If oFiles.Count = 0 Then Exit Function
ReDim vaArray(1 To oFiles.Count)
i = 1
For Each oFile In oFiles
vaArray(i) = oFile.Name
i = i + 1
Next
listfiles = vaArray
End Function
It would be nice if we could just access the files in the files object by index number but that seems to be broken in VBA for whatever reason (bug?).
On Windows, you can find it under.
%USERPROFILE%\AppData\Roaming\Subversion\auth\svn.simple
(same as below)
%APPDATA%\Roaming\Subversion\auth\svn.simple
There may be multiple files under this directory, depending upon the repos you are contributing to. You can assume this as one file for each svn server. You can open the file with any text editor and make sure you are going to delete the correct file.
Give the parent a style of overflow: hidden
. If it is overlapping sibling elements, you will have to put it inside of a container with a fixed height/width and give that a style of overflow: hidden
.
this should be close!
public static void OpenWithDefaultProgram(string path)
{
Process fileopener = new Process();
fileopener.StartInfo.FileName = "explorer";
fileopener.StartInfo.Arguments = "\"" + path + "\"";
fileopener.Start();
}
You should override the inspect
method of your object to return the desired hash, or just implement a similar method without overriding the default object behaviour.
If you want to get fancier, you can iterate over an object's instance variables with object.instance_variables
Here's an example of how you'd use filter
within your AngularJS JavaScript (rather than in an HTML element).
In this example, we have an array of Country records, each containing a name and a 3-character ISO code.
We want to write a function which will search through this list for a record which matches a specific 3-character code.
Here's how we'd do it without using filter
:
$scope.FindCountryByCode = function (CountryCode) {
// Search through an array of Country records for one containing a particular 3-character country-code.
// Returns either a record, or NULL, if the country couldn't be found.
for (var i = 0; i < $scope.CountryList.length; i++) {
if ($scope.CountryList[i].IsoAlpha3 == CountryCode) {
return $scope.CountryList[i];
};
};
return null;
};
Yup, nothing wrong with that.
But here's how the same function would look, using filter
:
$scope.FindCountryByCode = function (CountryCode) {
// Search through an array of Country records for one containing a particular 3-character country-code.
// Returns either a record, or NULL, if the country couldn't be found.
var matches = $scope.CountryList.filter(function (el) { return el.IsoAlpha3 == CountryCode; })
// If 'filter' didn't find any matching records, its result will be an array of 0 records.
if (matches.length == 0)
return null;
// Otherwise, it should've found just one matching record
return matches[0];
};
Much neater.
Remember that filter
returns an array as a result (a list of matching records), so in this example, we'll either want to return 1 record, or NULL.
Hope this helps.
Add the sheet name infront of the cell, e.g.:
=COUNTIFS(stock!A:A,"M",stock!C:C,"Yes")
Assumes the sheet name is "stock"
As what Ray said, you can stop it by modifying content-header like -
$http.defaults.headers.post["Content-Type"] = "text/plain";
For Example -
angular.module('myApp').factory('User', ['$resource','$http',
function($resource,$http){
$http.defaults.headers.post["Content-Type"] = "text/plain";
return $resource(API_ENGINE_URL+'user/:userId', {}, {
query: {method:'GET', params:{userId:'users'}, isArray:true},
getLoggedIn:{method:'GET'}
});
}]);
Or directly to a call -
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': 'text/plain'
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
This will not send any pre-flight option request.
NOTE: Request should not have any custom header parameter, If request header contains any custom header then browser will make pre-flight request, you cant avoid it.
I know it's an old question. But it keeps showing in google first position and all it says it's "install node.js". For a newbie this is not obvious, so all you have to do is go to the node.js website and search for the command for your linux distribution version or any other operating system. Here is the link: https://nodejs.org/en/download/package-manager/
In this page you have to choose your operating system and you'll find your command. Then you just log into your console as a root (using putty for instance) and execute that command.
After that, you log as normal user and go again inside your laravel application folder and run again npm install command, and it should work. Hope it helps.
Another approach through flipping array to get direct value.
Snippet
$array = [ 'Name1' => 'John', 'Name2' => 'Jane', 'Name3' => 'Jonny' ];
$val = array_rand(array_flip($array));
array_rand
return key not value. So, we're flipping value as key.
Note: PHP key alway be an unique key, so when array is flipped, duplicate value as a key will be overwritten.
If i understand you correctly, (i probably don't)
'SELECT @RowCount = COUNT(*)
FROM dbo.Comm_Services
WHERE CompanyId = ' + CAST(@CompanyId AS CHAR) + '
AND ' + @condition
I have just tested the following pipeline and it works
parallel firstBranch: {
stage ('Starting Test')
{
build job: 'test1', parameters: [string(name: 'Environment', value: "$env.Environment")]
}
}, secondBranch: {
stage ('Starting Test2')
{
build job: 'test2', parameters: [string(name: 'Environment', value: "$env.Environment")]
}
}
This Job named 'trigger-test' accepts one parameter named 'Environment'
Job 'test1' and 'test2' are simple jobs:
Example for 'test1'
On execution, I am able to see both stages running in the same time
You can easily add a second legend by adding the line:
ax2.legend(loc=0)
You'll get this:
But if you want all labels on one legend then you should do something like this:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')
time = np.arange(10)
temp = np.random.random(10)*30
Swdown = np.random.random(10)*100-10
Rn = np.random.random(10)*100-10
fig = plt.figure()
ax = fig.add_subplot(111)
lns1 = ax.plot(time, Swdown, '-', label = 'Swdown')
lns2 = ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
lns3 = ax2.plot(time, temp, '-r', label = 'temp')
# added these three lines
lns = lns1+lns2+lns3
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc=0)
ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()
Which will give you this:
INSTALLED_APPS = [
'rest_framework',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#apps
'apps.endpoints',
]
maybe forgot the comma "," or while pasting packing name it might have extra whitespace "packagename "check for that
ES7
class member syntax:ES7
has a solution for 'junking' your constructor function. Here is an example:
class Car {_x000D_
_x000D_
wheels = 4;_x000D_
weight = 100;_x000D_
_x000D_
}_x000D_
_x000D_
const car = new Car();_x000D_
console.log(car.wheels, car.weight);
_x000D_
The above example would look the following in ES6
:
class Car {_x000D_
_x000D_
constructor() {_x000D_
this.wheels = 4;_x000D_
this.weight = 100;_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
const car = new Car();_x000D_
console.log(car.wheels, car.weight);
_x000D_
Be aware when using this that this syntax might not be supported by all browsers and might have to be transpiled an earlier version of JS.
function generateCar(wheels, weight) {_x000D_
_x000D_
class Car {_x000D_
_x000D_
constructor() {}_x000D_
_x000D_
wheels = wheels;_x000D_
weight = weight;_x000D_
_x000D_
}_x000D_
_x000D_
return new Car();_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
const car1 = generateCar(4, 50);_x000D_
const car2 = generateCar(6, 100);_x000D_
_x000D_
console.log(car1.wheels, car1.weight);_x000D_
console.log(car2.wheels, car2.weight);
_x000D_
In order to assign a variable safely you have to use the SET-SELECT statement:
SET @PrimaryContactKey = (SELECT c.PrimaryCntctKey
FROM tarcustomer c, tarinvoice i
WHERE i.custkey = c.custkey
AND i.invckey = @tmp_key)
Make sure you have both a starting and an ending parenthesis!
The reason the SET-SELECT version is the safest way to set a variable is twofold.
1. The SELECT returns several posts
What happens if the following select results in several posts?
SELECT @PrimaryContactKey = c.PrimaryCntctKey
FROM tarcustomer c, tarinvoice i
WHERE i.custkey = c.custkey
AND i.invckey = @tmp_key
@PrimaryContactKey
will be assigned the value from the last post in the result.
In fact @PrimaryContactKey
will be assigned one value per post in the result, so it will consequently contain the value of the last post the SELECT-command was processing.
Which post is "last" is determined by any clustered indexes or, if no clustered index is used or the primary key is clustered, the "last" post will be the most recently added post. This behavior could, in a worst case scenario, be altered every time the indexing of the table is changed.
With a SET-SELECT statement your variable will be set to null
.
2. The SELECT returns no posts
What happens, when using the second version of the code, if your select does not return a result at all?
In a contrary to what you may believe the value of the variable will not be null - it will retain it's previous value!
This is because, as stated above, SQL will assign a value to the variable once per post - meaning it won't do anything with the variable if the result contains no posts. So, the variable will still have the value it had before you ran the statement.
With the SET-SELECT statement the value will be null
.
Select element (or group of elements) having class "abc", not having class "xyz":
$('.abc:not(".xyz")')
When selecting regular CSS you can use .abc:not(.xyz)
.
A Map is a collection of Key + Value pairs, which is visualized like this:
{[fooKey=fooValue],barKey=barValue],[quxKey=quxValue]}
The Map interface allows a few options for accessing this collection: The Key set [fooKey, barKey,quxKey]
, the Value set [fooValue, barValue, quxValue]
and finally entry Set [fooKey=fooValue],barKey=barValue],[quxKey=quxValue]
.
Entry set is simply a convenience to iterate over the key value pairs in the map, the Map.Entry is the representation of each key value pair. An equivalent way to do your last loop would be:
for (String buttonKey: listbouton.keySet()) {
this.add(listbouton.get(buttonKey)) ;
}
or
for (JButton button: listbouton.values()) {
this.add(button) ;
}
You can group your dependencies within a different project with packaging pom
as described by Sonatypes Best Practices:
<project>
<modelVersion>4.0.0</modelVersion>
<artifactId>base-dependencies</artifactId>
<groupId>es.uniovi.innova</groupId>
<version>1.0.0</version>
<packaging>pom</packaging>
<dependencies>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
</project>
and reference them from your parent-pom (watch the dependency <type>pom</type>
):
<project>
<modelVersion>4.0.0</modelVersion>
<artifactId>base</artifactId>
<groupId>es.uniovi.innova</groupId>
<version>1.0.0</version>
<packaging>pom</packaging>
<dependencies>
<dependency>
<artifactId>base-dependencies</artifactId>
<groupId>es.uniovi.innova</groupId>
<version>1.0.0</version>
<type>pom</type>
</dependency>
</dependencies>
</project>
Your child-project inherits this parent-pom as before. But now, the mail dependency can be excluded in the child-project within the dependencyManagement
block:
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>jruby</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<artifactId>base</artifactId>
<groupId>es.uniovi.innova</groupId>
<version>1.0.0</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<artifactId>base-dependencies</artifactId>
<groupId>es.uniovi.innova</groupId>
<version>1.0.0</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</dependencyManagement>
</project>
Yes! Here is how you set it up.
Create a Remote run configuration:
The configuration above provides three read-only fields. These are options that tell the JVM to open up port 5005 for remote debugging when running your application. Add the appropriate one to the JVM options of the application you are debugging. One way you might do this would be like so:
export JAVA_OPTS="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"
But it depends on how your run your application. If you're not sure which of the three applies to you, start with the first and go down the list until you find the one that works.
You can change suspend=n
to suspend=y
to force your application to wait until you connect with IntelliJ before it starts up. This is helpful if the breakpoint you want to hit occurs on application startup.
Start your application as you would normally, then in IntelliJ select the new configuration and hit 'Debug'.
IntelliJ will connect to the JVM and initiate remote debugging.
You can now debug the application by adding breakpoints to your code where desired. The output of the application will still appear wherever it did before, but your breakpoints will hit in IntelliJ.
In my case setting width to all divs helped:
.page-content div {
width: auto !important;
max-width: 99%;
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class CopyFiles {
private File targetFolder;
private int noOfFiles;
public void copyDirectory(File sourceLocation, String destLocation)
throws IOException {
targetFolder = new File(destLocation);
if (sourceLocation.isDirectory()) {
if (!targetFolder.exists()) {
targetFolder.mkdir();
}
String[] children = sourceLocation.list();
for (int i = 0; i < children.length; i++) {
copyDirectory(new File(sourceLocation, children[i]),
destLocation);
}
} else {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetFolder + "\\"+ sourceLocation.getName(), true);
System.out.println("Destination Path ::"+targetFolder + "\\"+ sourceLocation.getName());
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
noOfFiles++;
}
}
public static void main(String[] args) throws IOException {
File srcFolder = new File("C:\\sourceLocation\\");
String destFolder = new String("C:\\targetLocation\\");
CopyFiles cf = new CopyFiles();
cf.copyDirectory(srcFolder, destFolder);
System.out.println("No Of Files got Retrieved from Source ::"+cf.noOfFiles);
System.out.println("Successfully Retrieved");
}
}
You have to go through the collection from the last item to the first. this code is in vb
for i as integer= list.items.count-1 to 0 step -1
....
list.items.removeat(i)
next
Not with CSS directly, you could set CSS properties via JavaScript based on the internal contents but in the end you would still need to be operating in the definitions of CSS.
Add this to html:
<svg id="mySVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"/>
Try this function and adapt for you program:
var svgNS = "http://www.w3.org/2000/svg";
function createCircle()
{
var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle. for rectangle use "rectangle"
myCircle.setAttributeNS(null,"id","mycircle");
myCircle.setAttributeNS(null,"cx",100);
myCircle.setAttributeNS(null,"cy",100);
myCircle.setAttributeNS(null,"r",50);
myCircle.setAttributeNS(null,"fill","black");
myCircle.setAttributeNS(null,"stroke","none");
document.getElementById("mySVG").appendChild(myCircle);
}
Similar to startService(Intent), but with an implicit promise that the Service will call startForeground(int, android.app.Notification) once it begins running. The service is given an amount of time comparable to the ANR interval to do this, otherwise the system will automatically stop the service and declare the app ANR.
Unlike the ordinary startService(Intent), this method can be used at any time, regardless of whether the app hosting the service is in a foreground state.
make sure you call the Service.startForeground(int, android.app.Notification)
on the onCreate() so you ensure it will be called..if you have any condition that may prevent you from doing that, then you'd better off using the normal Context.startService(Intent)
and call the Service.startForeground(int, android.app.Notification)
yourself.
It seems that the Context.startForegroundService()
adds a watchdog to make sure you called the Service.startForeground(int, android.app.Notification)
before it was destroyed...
Two possible options (there might be more of course):
You can use the crypto/rand
package that supports reading random byte arrays (from /dev/urandom) and is geared towards cryptographic random generation. see http://golang.org/pkg/crypto/rand/#example_Read . It might be slower than normal pseudo-random number generation though.
Take a random number and hash it using md5 or something like this.
Swift 5
func isValidEmailAddress(emailAddressString: String) -> Bool {
var returnValue = true
let emailRegEx = "[A-Z0-9a-z.-_]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,3}"
do {
let regex = try NSRegularExpression(pattern: emailRegEx)
let nsString = emailAddressString as NSString
let results = regex.matches(in: emailAddressString, range: NSRange(location: 0, length: nsString.length))
if results.count == 0
{
returnValue = false
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
returnValue = false
}
return returnValue
}
Then:
let validEmail = isValidEmailAddress(emailAddressString: "[email protected]")
print(validEmail)
The order of execution of ng-click and ng-model is different with angular 1.2 vs 1.6
You must test, with 1.2 and 1.6,
for example, with angular 1.2, ng-click get execute before ng-model, with angular 1.6, ng-model maybe get excute before ng-click.
so you get 'true checked' / 'false uncheck' value maybe not you expect
Sorting is just a sort(), reindexing seems a bit silly but if it is needed this will do it. Though not in-place. Use array_walk() if you will do this in a bunch of places, just use a for-key-value loop if this is a one-time operation.
<?php
function reindex(&$item, $key, &$reindexedarr) {
$reindexedarr[$key+1] = $item;
}
$arr = Array (2 => 'c', 1 => 'b', 0 => 'a');
sort($arr);
$newarr = Array();
array_walk($arr, reindex, &$newarr);
$arr = $newarr;
print_r($arr); // Array ( [1] => a [2] => b [3] => c )
?>
Works perfect:
internal static int GetDifferenceInYears(DateTime startDate)
{
int finalResult = 0;
const int DaysInYear = 365;
DateTime endDate = DateTime.Now;
TimeSpan timeSpan = endDate - startDate;
if (timeSpan.TotalDays > 365)
{
finalResult = (int)Math.Round((timeSpan.TotalDays / DaysInYear), MidpointRounding.ToEven);
}
return finalResult;
}
Adding export PATH="/Users/<username>/anaconda/bin:$PATH"
(or export PATH="/Users/<username>/anaconda3/bin:$PATH"
if you have anaconda 3)
to my ~/.bash_profile file, fixed this issue for me.
Assuming t1 is the folder with files in it, and t2 is the empty directory. What you want is something like this:
sudo cp -R t1/* t2/
Bear in mind, for the first example, t1 and t2 have to be the full paths, or relative paths (based on where you are). If you want, you can navigate to the empty folder (t2) and do this:
sudo cp -R t1/* ./
Or you can navigate to the folder with files (t1) and do this:
sudo cp -R ./* t2/
Note: The * sign (or wildcard) stands for all files and folders. The -R flag means recursively (everything inside everything).
I read this post Why String is Immutable or Final in Java and suppose that following may be the most important reason:
String is Immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client's action would affect all another client.
Here's a drop-in example that expands on Andreas Köberle's solution. It uses jQuery for the event handler and the document ready event, but those could be switched to plain JS:
(function(document, $) {
$(function() {
$(document).on('click', '[disable-on-click], .disable-on-click', function() {
var disableText = this.getAttribute("data-disable-text") || 'Processing...';
if(this.form) {
this.form.submit();
}
this.disabled = true;
if(this.tagName === 'BUTTON') {
this.innerHTML = disableText;
} else if(this.tagName === 'INPUT') {
this.value = disableText;
}
});
});
})(document, jQuery);
It can then be used in HTML like this:
<button disable-on-click data-disable-text="Saving...">Click Me</button>
<button class="disable-on-click">Click Me</button>
<input type="submit" disable-on-click value="Click Me" />
This question is full of misunderstandings. First lets understand the question fully. The asker wants to get the same result as for when running the MS SQL Server function DATEDIFF ( datepart , startdate , enddate )
where datepart
takes dd
, mm
, or yy
.
This function is defined by:
This function returns the count (as a signed integer value) of the specified datepart boundaries crossed between the specified startdate and enddate.
That means how many day boundaries, month boundaries, or year boundaries, are crossed. Not how many days, months, or years it is between them. That's why datediff(yy, '2010-04-01', '2012-03-05')
is 2, and not 1. There is less than 2 years between those dates, meaning only 1 whole year has passed, but 2 year boundaries have crossed, from 2010 to 2011, and from 2011 to 2012.
The following are my best attempt at replicating the logic correctly.
-- datediff(dd`, '2010-04-01', '2012-03-05') = 704 // 704 changes of day in this interval
select ('2012-03-05'::date - '2010-04-01'::date );
-- 704 changes of day
-- datediff(mm, '2010-04-01', '2012-03-05') = 23 // 23 changes of month
select (date_part('year', '2012-03-05'::date) - date_part('year', '2010-04-01'::date)) * 12 + date_part('month', '2012-03-05'::date) - date_part('month', '2010-04-01'::date)
-- 23 changes of month
-- datediff(yy, '2010-04-01', '2012-03-05') = 2 // 2 changes of year
select date_part('year', '2012-03-05'::date) - date_part('year', '2010-04-01'::date);
-- 2 changes of year
On windows and Netbeans you can set the relative path as:
new FileReader("src\\PACKAGE_NAME\\FILENAME");
On Linux and Netbeans you can set the relative path as:
new FileReader("src/PACKAGE_NAME/FILENAME");
If you have your code inside Source Packages
I do not know if it is the same for eclipse or other IDE
Yep, that would be the enumerate
function! Or more to the point, you need to do:
list(enumerate([3,7,19]))
[(0, 3), (1, 7), (2, 19)]
At, i think Angular 8:
ActivatedRoute.params
has been replaced by ActivatedRoute.paramMap
ActivatedRoute.queryParams
has been replaced by ActivatedRoute.queryParamMap
npm prune [[<@scope>/]<pkg>...] [--production] [--dry-run] [--json]
This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.
Extraneous packages are packages that are not listed on the parent package's dependencies list.
If the --production flag is specified or the NODE_ENV environment variable is set to production, this command will remove the packages specified in your devDependencies. Setting --no-production will negate NODE_ENV being set to production.
If the --dry-run flag is used then no changes will actually be made.
If the --json flag is used then the changes npm prune made (or would have made with --dry-run) are printed as a JSON object.
In normal operation with package-locks enabled, extraneous modules are pruned automatically when modules are installed and you'll only need this command with the --production flag.
If you've disabled package-locks then extraneous modules will not be removed and it's up to you to run npm prune from time-to-time to remove them.
npm dedupe
npm ddp
Searches the local package tree and attempts to simplify the overall structure by moving dependencies further up the tree, where they can be more effectively shared by multiple dependent packages.
For example, consider this dependency graph:
a
+-- b <-- depends on [email protected]
| `-- [email protected]
`-- d <-- depends on c@~1.0.9
`-- [email protected]
In this case, npm-dedupe will transform the tree to:
a
+-- b
+-- d
`-- [email protected]
Because of the hierarchical nature of node's module lookup, b and d will both get their dependency met by the single c package at the root level of the tree.
The deduplication algorithm walks the tree, moving each dependency as far up in the tree as possible, even if duplicates are not found. This will result in both a flat and deduplicated tree.
You should iterate over the keys and get the values using square brackets.
See: How do I enumerate the properties of a javascript object?
EDIT: Obviously, this makes the question a duplicate.
One way to get this error is to forget to use the 'new' keyword when instantiating your Date in javascript like this:
> d = Date();
'Tue Mar 15 2016 20:05:53 GMT-0400 (EDT)'
> typeof(d);
'string'
> d.getFullYear();
TypeError: undefined is not a function
Had you used the 'new' keyword, it would have looked like this:
> el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:08:58 GMT-0400 (EDT)
> typeof(d);
'object'
> d.getFullYear(0);
2016
Another way to get that error is to accidentally re-instantiate a variable in javascript between when you set it and when you use it, like this:
el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:12:13 GMT-0400 (EDT)
> d.getFullYear();
2016
> d = 57 + 23;
80
> d.getFullYear();
TypeError: undefined is not a function
Try this:
$("div[class]").filter(function() {
var classNames = this.className.split(/\s+/);
for (var i=0; i<classNames.length; ++i) {
if (classNames[i].substr(0, 6) === "apple-") {
return true;
}
}
return false;
})
INSERT INTO wp_bp_activity
(
user_id,
component,
`type`,
`action`,
content,
primary_link,
item_id,
secondary_item_id,
date_recorded,
hide_sitewide,
mptt_left,
mptt_right
)
VALUES(
1,'activity','activity_update','<a title="admin" href="http://brandnewmusicreleases.com/social-network/members/admin/">admin</a> posted an update','<a title="242925_1" href="http://brandnewmusicreleases.com/social-network/wp-content/uploads/242925_1.jpg" class="buddyboss-pics-picture-link">242925_1</a>','http://brandnewmusicreleases.com/social-network/members/admin/',' ',' ','2012-06-22 12:39:07',0,0,0
)
Well, why this exists in general is probably different than why it exists in your example.
It all started half a century ago with repurposing hardcopy communication terminals as computer user interfaces. In the initial Unix and C era that was the ASR-33 Teletype.
This device was slow (10 cps) and noisy and ugly and its view of the ASCII character set ended at 0x5f, so it had (look closely at the pic) none of the keys:
{ | } ~
The trigraphs were defined to fix a specific problem. The idea was that C programs could use the ASCII subset found on the ASR-33 and in other environments missing the high ASCII values.
Your example is actually two of
??!
, each meaning|
, so the result is||
.
However, people writing C code almost by definition had modern equipment,1 so my guess is: someone showing off or amusing themself, leaving a kind of Easter egg in the code for you to find.
It sure worked, it led to a wildly popular SO question.
ASR-33 Teletype
In fact, it is very easy.
composer update
will do all this for you, but it will also update the other packages.
To remove a package without updating the others, specifiy that package in the command, for instance:
composer update monolog/monolog
will remove the monolog/monolog
package.
Nevertheless, there may remain some empty folders or files that cannot be removed automatically, and that have to be removed manually.
Note : Use it if calculating / adding days from current date.
Be aware: this answer has issues (see comments)
var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);
It should be like
var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));
This object provides a sensible implementation of equals(), returning true if equals() is true on each of the contained objects.
An open source GUI tool is available at keystore-explorer.org
KeyStore Explorer
KeyStore Explorer is an open source GUI replacement for the Java command-line utilities keytool and jarsigner. KeyStore Explorer presents their functionality, and more, via an intuitive graphical user interface.
Following screens will help (they are from the official site)
Default screen that you get by running the command:
shantha@shantha:~$./Downloads/kse-521/kse.sh
And go to Examine
and Examine a URL
option and then give the web URL that you want to import.
The result window will be like below if you give google site link.
This is one of Use case and rest is up-to the user(all credits go to the keystore-explorer.org)
According to my test result, I'd like to vote the regular_express one provided by karim79. (I don't have enough reputation to vote it now!)
The solution from zombat uses too many function calls, I even simplify the codes. I'm using PHP 5.4 to run both solutions for 100,000 times, and here's the result:
$str = 'Hello abc, have a nice day abc! abc!';
$pos = strpos($str, 'abc');
$str = substr_replace($str, '123', $pos, 3);
==> 1.85 sec
$str = 'Hello abc, have a nice day abc! abc!';
$str = preg_replace('/abc/', '123', $str, 1);
==> 1.35 sec
As you can see. The performance of preg_replace is not so bad as many people think. So I'd suggest the classy solution if your regular express is not complicated.
I wrote my own, it's short, super simple, and you can copy it if you like: http://www.dmurph.com/2011/01/java-uri-encoder/
I tried @PhilNicholas 's code and got the same problem of @its_me said in the comments that search bar show up on the next line of navbar, and I found that form
need to be added an attribute width
.
<form role="search" style="width: 15em; margin: 0.3em 2em;">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search">
<div class="input-group-btn">
<button type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-search"></span>
</button>
</div>
</div>
</form>
Parameters starting with -
or --
are usually considered optional. All other parameters are positional parameters and as such required by design (like positional function arguments). It is possible to require optional arguments, but this is a bit against their design. Since they are still part of the non-positional arguments, they will still be listed under the confusing header “optional arguments” even if they are required. The missing square brackets in the usage part however show that they are indeed required.
See also the documentation:
In general, the argparse module assumes that flags like -f and --bar indicate optional arguments, which can always be omitted at the command line.
Note: Required options are generally considered bad form because users expect options to be optional, and thus they should be avoided when possible.
That being said, the headers “positional arguments” and “optional arguments” in the help are generated by two argument groups in which the arguments are automatically separated into. Now, you could “hack into it” and change the name of the optional ones, but a far more elegant solution would be to create another group for “required named arguments” (or whatever you want to call them):
parser = argparse.ArgumentParser(description='Foo')
parser.add_argument('-o', '--output', help='Output file name', default='stdout')
requiredNamed = parser.add_argument_group('required named arguments')
requiredNamed.add_argument('-i', '--input', help='Input file name', required=True)
parser.parse_args(['-h'])
usage: [-h] [-o OUTPUT] -i INPUT
Foo
optional arguments:
-h, --help show this help message and exit
-o OUTPUT, --output OUTPUT
Output file name
required named arguments:
-i INPUT, --input INPUT
Input file name
https://github.com/cognitom/paper-css seems to solve all my needs.
Front-end printing solution - previewable and live-reloadable!
The problem with 500 errors (with CodeIgniter), with different apache settings, it displays 500 error when there's an error with PHP configuration.
Here's how it can trigger 500 error with CodeIgniter:
Please check your apache error logs, there should be some interesting information in there.
This function convert wildcard to regexp and make test (it supports .
and *
wildcharts)
function wildTest(wildcard, str) {
let w = wildcard.replace(/[.+^${}()|[\]\\]/g, '\\$&'); // regexp escape
const re = new RegExp(`^${w.replace(/\*/g,'.*').replace(/\?/g,'.')}$`,'i');
return re.test(str); // remove last 'i' above to have case sensitive
}
function wildTest(wildcard, str) {_x000D_
let w = wildcard.replace(/[.+^${}()|[\]\\]/g, '\\$&'); // regexp escape _x000D_
const re = new RegExp(`^${w.replace(/\*/g,'.*').replace(/\?/g,'.')}$`,'i');_x000D_
return re.test(str); // remove last 'i' above to have case sensitive_x000D_
}_x000D_
_x000D_
_x000D_
// Example usage_x000D_
_x000D_
let arr = ["birdBlue", "birdRed", "pig1z", "pig2z", "elephantBlua" ];_x000D_
_x000D_
let resultA = arr.filter( x => wildTest('biRd*', x) );_x000D_
let resultB = arr.filter( x => wildTest('p?g?z', x) );_x000D_
let resultC = arr.filter( x => wildTest('*Blu?', x) );_x000D_
_x000D_
console.log('biRd*',resultA);_x000D_
console.log('p?g?z',resultB);_x000D_
console.log('*Blu?',resultC);
_x000D_
Height is easily implemented by recursion, take the maximum of the height of the subtrees plus one.
The "balance factor of R" refers to the right subtree of the tree which is out of balance, I suppose.
In my case this worked (Mac, Excel 2011, both Cyrillic and Latin characters with Czech diacritics):
Yes, EnterpriseDT's edtFTPj is stable (first released in 2000), has all the features you might need, and is open source as well.
It's used in a bunch of open source projects (as well as in many commercial projects), and is acknowledged to be one of the fastest client libraries around.
As another poster noted, if you do wish to upgrade to SFTP and/or FTPS, it is a simple upgrade path with very few code changes required.
Creating Custom Action for WIX written in managed code (C#) without Votive
I use the following function extensively. As pointed out above, using other methods can sometimes give inaccurate results due to used range updates, gaps in the data, or different columns having different row counts.
Example of use:
lastRow=FindRange("Sheet1","A1:A1000")
would return the last occupied row number of the entire range. You can specify any range you want from single columns to random rows, eg FindRange("Sheet1","A100:A150")
Public Function FindRange(inSheet As String, inRange As String) As Long
Set fr = ThisWorkbook.Sheets(inSheet).Range(inRange).find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
If Not fr Is Nothing Then FindRange = fr.row Else FindRange = 0
End Function
"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur. (From other SO answer)
So you can't do anything about it, it is the issue of the server.
But you could use try .. except
block to handle that exception:
from socket import error as SocketError
import errno
try:
response = urllib2.urlopen(request).read()
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise # Not error we are looking for
pass # Handle error here.
First step would be making the function object, then applying it. If you want a matrix object that has the same number of rows, you can predefine it and use the object[] form as illustrated (otherwise the returned value will be simplified to a vector):
bvnormdens <- function(x=c(0,0),mu=c(0,0), sigma=c(1,1), rho=0){
exp(-1/(2*(1-rho^2))*(x[1]^2/sigma[1]^2+
x[2]^2/sigma[2]^2-
2*rho*x[1]*x[2]/(sigma[1]*sigma[2]))) *
1/(2*pi*sigma[1]*sigma[2]*sqrt(1-rho^2))
}
out=rbind(c(1,2),c(3,4),c(5,6));
bvout<-matrix(NA, ncol=1, nrow=3)
bvout[] <-apply(out, 1, bvnormdens)
bvout
[,1]
[1,] 1.306423e-02
[2,] 5.931153e-07
[3,] 9.033134e-15
If you wanted to use other than your default parameters then the call should include named arguments after the function:
bvout[] <-apply(out, 1, FUN=bvnormdens, mu=c(-1,1), rho=0.6)
apply() can also be used on higher dimensional arrays and the MARGIN argument can be a vector as well as a single integer.
This error can also occur when you load all google play services apis when you only using afew.
As stated by google:"In versions of Google Play services prior to 6.5, you had to compile the entire package of APIs into your app. In some cases, doing so made it more difficult to keep the number of methods in your app (including framework APIs, library methods, and your own code) under the 65,536 limit.
From version 6.5, you can instead selectively compile Google Play service APIs into your app."
For example when your app needs play-services-maps ,play-services-location .You need to add only the two apis in your build.gradle file at app level as show below:
compile 'com.google.android.gms:play-services-maps:10.2.1'
compile 'com.google.android.gms:play-services-location:10.2.1'
Instead of:
compile 'com.google.android.gms:play-services:10.2.1'
For full documentation and list of google play services apis click here
UPD. The answer and demo are updated to align with latest Angular.
You can subscribe to entire form changes due to the fact that FormGroup representing a form provides valueChanges
property which is an Observerable instance:
this.form.valueChanges.subscribe(data => console.log('Form changes', data));
In this case you would need to construct form manually using FormBuilder. Something like this:
export class App {
constructor(private formBuilder: FormBuilder) {
this.form = formBuilder.group({
firstName: 'Thomas',
lastName: 'Mann'
})
this.form.valueChanges.subscribe(data => {
console.log('Form changes', data)
this.output = data
})
}
}
Check out valueChanges
in action in this demo: http://plnkr.co/edit/xOz5xaQyMlRzSrgtt7Wn?p=preview
AutoResetEvent maintains a boolean variable in memory. If the boolean variable is false then it blocks the thread and if the boolean variable is true it unblocks the thread.
When we instantiate an AutoResetEvent object, we pass the default value of boolean value in the constructor. Below is the syntax of instantiate an AutoResetEvent object.
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
WaitOne method
This method blocks the current thread and wait for the signal by other thread. WaitOne method puts the current thread into a Sleep thread state. WaitOne method returns true if it receives the signal else returns false.
autoResetEvent.WaitOne();
Second overload of WaitOne method wait for the specified number of seconds. If it does not get any signal thread continues its work.
static void ThreadMethod()
{
while(!autoResetEvent.WaitOne(TimeSpan.FromSeconds(2)))
{
Console.WriteLine("Continue");
Thread.Sleep(TimeSpan.FromSeconds(1));
}
Console.WriteLine("Thread got signal");
}
We called WaitOne method by passing the 2 seconds as arguments. In the while loop, it wait for the signal for 2 seconds then it continues its work. When the thread got the signal WaitOne returns true and exits the loop and print the "Thread got signal".
Set method
AutoResetEvent Set method sent the signal to the waiting thread to proceed its work. Below is the syntax of calling Set method.
autoResetEvent.Set();
ManualResetEvent maintains a boolean variable in memory. When the boolean variable is false then it blocks all threads and when the boolean variable is true it unblocks all threads.
When we instantiate a ManualResetEvent, we initialize it with default boolean value.
ManualResetEvent manualResetEvent = new ManualResetEvent(false);
In the above code, we initialize the ManualResetEvent with false value, that means all the threads which calls the WaitOne method will block until some thread calls the Set() method.
If we initialize ManualResetEvent with true value, all the threads which calls the WaitOne method will not block and free to proceed further.
WaitOne Method
This method blocks the current thread and wait for the signal by other thread. It returns true if its receives a signal else returns false.
Below is the syntax of calling WaitOne method.
manualResetEvent.WaitOne();
In the second overload of WaitOne method, we can specify the time interval till the current thread wait for the signal. If within time internal, it does not receives a signal it returns false and goes into the next line of method.
Below is the syntax of calling WaitOne method with time interval.
bool isSignalled = manualResetEvent.WaitOne(TimeSpan.FromSeconds(5));
We have specify 5 seconds into the WaitOne method. If the manualResetEvent object does not receives a signal between 5 seconds, it set the isSignalled variable to false.
Set Method
This method is used for sending the signal to all waiting threads. Set() Method set the ManualResetEvent object boolean variable to true. All the waiting threads are unblocked and proceed further.
Below is the syntax of calling Set() method.
manualResetEvent.Set();
Reset Method
Once we call the Set() method on the ManualResetEvent object, its boolean remains true. To reset the value we can use Reset() method. Reset method change the boolean value to false.
Below is the syntax of calling Reset method.
manualResetEvent.Reset();
We must immediately call Reset method after calling Set method if we want to send signal to threads multiple times.
Use event delegation by assigning the onclick
to the <ol>
. Then pass the event
object as the argument, and using that, grab the text from the clicked element.
function addText(event) {_x000D_
var targ = event.target || event.srcElement;_x000D_
document.getElementById("alltext").value += targ.textContent || targ.innerText;_x000D_
}
_x000D_
<textarea id="alltext"></textarea>_x000D_
_x000D_
<ol onclick="addText(event)">_x000D_
<li>Hello</li>_x000D_
<li>World</li>_x000D_
<li>Earthlings</li>_x000D_
</ol>
_x000D_
Note that this method of passing the event
object works in older IE as well as W3 compliant systems.
As others have mentioned, you can use document.title = 'My new title'
and React Helmet to update the page title. Both of these solutions will still render the initial 'React App' title before scripts are loaded.
If you are using create-react-app
the initial document title is set in the <title>
tag /public/index.html
file.
You can edit this directly or use a placeholder which will be filled from environmental variables:
/.env
:
REACT_APP_SITE_TITLE='My Title!'
SOME_OTHER_VARS=...
If for some reason I wanted a different title in my development environment -
/.env.development
:
REACT_APP_SITE_TITLE='**DEVELOPMENT** My TITLE! **DEVELOPMENT**'
SOME_OTHER_VARS=...
/public/index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
...
<title>%REACT_APP_SITE_TITLE%</title>
...
</head>
<body>
...
</body>
</html>
This approach also means that I can read the site title environmental variable from my application using the global process.env
object, which is nice:
console.log(process.env.REACT_APP_SITE_TITLE_URL);
// My Title!
_method
hidden field workaround
The following simple technique is used by a few web frameworks:
add a hidden _method
parameter to any form that is not GET or POST:
<input type="hidden" name="_method" value="PUT">
This can be done automatically in frameworks through the HTML creation helper method.
fix the actual form method to POST (<form method="post"
)
processes _method
on the server and do exactly as if that method had been sent instead of the actual POST
You can achieve this in:
form_tag
@method("PATCH")
Rationale / history of why it is not possible in pure HTML: https://softwareengineering.stackexchange.com/questions/114156/why-there-are-no-put-and-delete-methods-in-html-forms
nvarchar(max)
is what you want to be using. The biggest advantage is that you can use all the T-SQL string functions on this data type. This is not possible with ntext
. I'm not aware of any real disadvantages.
If you happen to be an iOS developer
:
Check how many simulators that you have downloaded as they take up a lot of space:
Go to: ~/Library/Developer/Xcode/iOS DeviceSupport
Also delete old archived apps:
Go to: ~/Library/Developer/Xcode/Archives
I cleared 100GB doing this.
I have the problem because I updated Java version.
The following steps work for me:
- Run
\Tomcat\bin\tomcat7w.exe
- Confirm "Startup" tab -> "Mode" choose "jvm"
- "Java" tab -> update "Java Virtual Machine" path to new version path
- Restart Tomcat
Done.
1st Step : Move to the Directory where your service is present
Command : cd c:\xxx\yyy\service
2nd Step : Enter the below command
Command : C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe service.exe \u
Here service.exe is your service exe and \u will uninstall the service. you'll see "The uninstall has completed" message.
If you wanna install a service, Remove \u in the above command which will install your service
Documentation for parseDouble()
says "Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.", so they should be identical.
You can stop a macro by pressing ctrl + break but if you don't have the break key you could use this autohotkey (open source) code:
+ESC:: SendInput {CtrlBreak} return
Pressing shift + Escape will be like pressing ctrl + break and thus will stop your macro.
All the glory to this page
Just for the record in modern times,
1 - Just have updated Xcode on your machine as you normally do
2 - Open terminal and
$ xcode-select --install
it will perform a short install of a minute or two.
3 - Launch Xcode. "New" "Project" ... you have to choose "Command line tool"
Note - confusingly this is under the "macOS" tab.
Select "C" language on the next screen...
4- You'll be asked to save the project somewhere on your desktop. The name you give the project here is just the name of the folder that will hold the project. It does not have any importance in the actual software.
5 - You're golden! You can now enjoy c with Mac and Xcode.
Generally this problem occurs when you are modifying the keys very oftenly. Based on the server it might take some time to update the new key that you have generated and pasted in the server. So after generating the key and pasting in the server, wait for 3 to 4 hours and then try. The problem should be solved. It happened with me.
I prefer using PHPMailer script to send emails from localhost as it lets me use my Gmail account as SMTP. You can find the PHPMailer from http://phpmailer.worxware.com/ . Help regarding how to use gmail as SMTP or any other SMTP can be found at http://www.mittalpatel.co.in/php_send_mail_from_localhost_using_gmail_smtp . Hope this helps!
I would (and have) used IDA Pro to decompile executables. It creates semi-complete code, you can decompile to assembly or C.
If you have a copy of the debug symbols around, load those into IDA before decompiling and it will be able to name many of the functions, parameters, etc.
I've found using cmd works well as an alternative, especially when you need to pipe the output from the called application (espeically when it doesn't have built in logging, unlike msbuild)
cmd /C "$msbuild $args" >> $outputfile
You could just use underscore library.
Install it:
npm install underscore --save
npm install @types/underscore --save-dev
Import it
import _ = require('underscore');
Use it
var x = _.filter(
[{ "id": 1 }, { "id": -2 }, { "id": 3 }],
myObj => myObj.id < 0)
);
I was also disappointed by the lack of type a function can throw, but I get it now thanks to @rickster and I'll summarize it like this: let's say we could specify the type a function throws, we would have something like this:
enum MyError: ErrorType { case ErrorA, ErrorB }
func myFunctionThatThrows() throws MyError { ...throw .ErrorA...throw .ErrorB... }
do {
try myFunctionThatThrows()
}
case .ErrorA { ... }
case .ErrorB { ... }
The problem is that even if we don't change anything in myFunctionThatThrows, if we just add an error case to MyError:
enum MyError: ErrorType { case ErrorA, ErrorB, ErrorC }
we are screwed because our do/try/catch is no longer exhaustive, as well as any other place where we called functions that throw MyError
Basename wild cards were introduced in Java 6; i.e. "foo/*" means all ".jar" files in the "foo" directory.
In earlier versions of Java that do not support wildcard classpaths, I have resorted to using a shell wrapper script to assemble a Classpath by 'globbing' a pattern and mangling the results to insert ':' characters at the appropriate points. This would be hard to do in a BAT file ...
As mentioned earlier, you can use the grid system to layout your inputs and labels anyway that you want. The trick is to remember that you can use rows within your columns to break them into twelfths as well.
The example below is one possible way to accomplish your goal and will put the two text boxes near Label3 on the same line when the screen is small or larger.
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->_x000D_
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->_x000D_
<!--[if lt IE 9]>_x000D_
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>_x000D_
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>_x000D_
<![endif]-->_x000D_
</head>_x000D_
<body>_x000D_
<div class="row">_x000D_
<div class="col-xs-6 form-group">_x000D_
<label>Label1</label>_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
<div class="col-xs-6 form-group">_x000D_
<label>Label2</label>_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
<div class="col-xs-6">_x000D_
<div class="row">_x000D_
<label class="col-xs-12">Label3</label>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-xs-12 col-sm-6">_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
<div class="col-xs-12 col-sm-6">_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-xs-6 form-group">_x000D_
<label>Label4</label>_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>_x000D_
</body>_x000D_
</html>
_x000D_
Add this parameter to JAVA_OPTS
or to the command line in Maven:
-Dhttps.protocols=TLSv1.2
These are the two options I managed to build, not having the luxury of working with var
type, nor with additional variables on the line:
string f = "aS.".Substring(0, "aS.".IndexOf("S"));
Console.WriteLine(f);
string s = "aS.".Split("S".ToCharArray(),StringSplitOptions.RemoveEmptyEntries)[0];
Console.WriteLine(s);
This is what it gets:
I also had the same issue. Tried most of the things found on this and other forums.
Finally was successful after doing a little own RnD.
I went into IIS Settings and then into my website permission options added my Organizations Domain User Group.
Now as all my domain user have been granted the access to that website i did not encounter that issue.
Hope this helps
var val = yyy.First().Value;
return yyy.All(x=>x.Value == val) ? val : otherValue;
Cleanest way I can think of. You can make it a one-liner by inlining val, but First() would be evaluated n times, doubling execution time.
To incorporate the "empty set" behavior specified in the comments, you simply add one more line before the two above:
if(yyy == null || !yyy.Any()) return otherValue;
#!/bin/bash
cat > FILE.txt <<EOF
info code info
info code info
info code info
EOF
Does it have to be gray? You could just set the opacity of the image lower (to dull it). Alternatively, you could create a <div>
overlay and set that to be gray (change the alpha to get the effect).
html:
<div id="wrapper">
<img id="myImage" src="something.jpg" />
</div>
css:
#myImage {
opacity: 0.4;
filter: alpha(opacity=40); /* msie */
}
/* or */
#wrapper {
opacity: 0.4;
filter: alpha(opacity=40); /* msie */
background-color: #000;
}
Editing RobG's solution and using JavaScript's Date().
function msToTime(ms) {
function addZ(n) {
return (n<10? '0':'') + n;
}
var dt = new Date(ms);
var hrs = dt.getHours();
var mins = dt.getMinutes();
var secs = dt.getSeconds();
var millis = dt.getMilliseconds();
var tm = addZ(hrs) + ':' + addZ(mins) + ':' + addZ(secs) + "." + millis;
return tm;
}
The option to save the .orig file can be disabled by configuring KDiff3
Try this
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
btn.setBackgroundResource(R.drawable.icon);
}
});
This will only give you marginal protection. If the attacker can run arbitrary code in your application they can get at the passwords in exactly the same way your application can. You could still get some protection from some SQL injection attacks and misplaced db backups if you store a secret key in a file and use that to encrypt on the way to the db and decrypt on the way out. But you should use bindparams to completely avoid the issue of SQL injection.
If decide to encrypt, you should use some high level crypto library for this, or you will get it wrong. You'll have to get the key-setup, message padding and integrity checks correct, or all your encryption effort is of little use. GPGME is a good choice for one example. Mcrypt is too low level and you will probably get it wrong.
I like @Eduardo's answer and I liked the accepted answer. I like to get back a boolean from something like this, so I wrote it up for you guys.
CREATE FUNCTION dbo.DatabaseExists(@dbname nvarchar(128))
RETURNS bit
AS
BEGIN
declare @result bit = 0
SELECT @result = CAST(
CASE WHEN db_id(@dbname) is not null THEN 1
ELSE 0
END
AS BIT)
return @result
END
GO
Now you can use it like this:
select [dbo].[DatabaseExists]('master') --returns 1
select [dbo].[DatabaseExists]('slave') --returns 0
I think that the best approach is to assign the onclick handler unobtrusively.
Something like this:
window.onload = function(){
var myLink = document.getElementsById('myLinkId');
myLink.onclick = function(){
parse('#', false, '<a href="xyz');
return false;
}
}
//...
<a href="#" id="myLink">Test</a>
The WebClient class should be more than capable of handling the functionality you describe, for example:
System.Net.WebClient wc = new System.Net.WebClient();
byte[] raw = wc.DownloadData("http://www.yoursite.com/resource/file.htm");
string webData = System.Text.Encoding.UTF8.GetString(raw);
or (further to suggestion from Fredrick in comments)
System.Net.WebClient wc = new System.Net.WebClient();
string webData = wc.DownloadString("http://www.yoursite.com/resource/file.htm");
When you say it took 30 seconds, can you expand on that a little more? There are many reasons as to why that could have happened. Slow servers, internet connections, dodgy implementation etc etc.
You could go a level lower and implement something like this:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://www.yoursite.com/resource/file.htm");
using (StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream(), Encoding.UTF8))
{
streamWriter.Write(requestData);
}
string responseData = string.Empty;
HttpWebResponse httpResponse = (HttpWebResponse)webRequest.GetResponse();
using (StreamReader responseReader = new StreamReader(httpResponse.GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
}
However, at the end of the day the WebClient class wraps up this functionality for you. So I would suggest that you use WebClient and investigate the causes of the 30 second delay.
Increasing Java Heap unfairly eats deficit mobile resurces. Sometimes it is sufficient to just wait for garbage collector and then resume your operations after heap space is reduced. Use this static method then.
Just noticed that I had named my file ' index.html'
instead for 'index.html'
with a leading space. That was why it could not find it.
try this:
echo ${array[@]} | awk 'BEGIN{RS=" ";} {print $1}' | sort
Output will be:
3 5 a b c f
Problem solved.
If you're running using uwsgi look at the python auto reload option:
uwsgi --py-autoreload 1
Example uwsgi-dev-example.ini:
[uwsgi]
socket = 127.0.0.1:5000
master = true
virtualenv = /Users/xxxx/.virtualenvs/sites_env
chdir = /Users/xxx/site_root
module = site_module:register_debug_server()
callable = app
uid = myuser
chmod-socket = 660
log-date = true
workers = 1
py-autoreload = 1
site_root/__init__.py
def register_debug_server():
from werkzeug.debug import DebuggedApplication
app = Flask(__name__)
app.debug = True
app = DebuggedApplication(app, evalex=True)
return app
Then run:
uwsgi --ini uwsgi-dev-example.ini
Note: This example also enables the debugger.
I went this route to mimic production as close as possible with my nginx setup. Simply running the flask app with it's built in web server behind nginx it would result in a bad gateway error.
You have an extra double quote at the end, which is adding it back to the end of the string (after removing both quotes from the string).
Input:
set widget="a very useful item"
set widget
set widget=%widget:"=%
set widget
Output:
widget="a very useful item"
widget=a very useful item
Note: To replace Double Quotes " with Single Quotes ' do the following:
set widget=%widget:"='%
Note: To replace the word "World" (not case sensitive) with BobB do the following:
set widget="Hello World!"
set widget=%widget:world=BobB%
set widget
Output:
widget="Hello BobB!"
As far as your initial question goes (save the following code to a batch file .cmd or .bat and run):
@ECHO OFF
ECHO %0
SET BathFileAndPath=%~0
ECHO %BathFileAndPath%
ECHO "%BathFileAndPath%"
ECHO %~0
ECHO %0
PAUSE
Output:
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
Press any key to continue . . .
%0
is the Script Name and Path.
%1
is the first command line argument, and so on.
In addition to Michael Sorens' answer:
Start-Process PowerShell {[void][System.Console]::ReadKey($true)} -Wait -NoNewWindow
You can try this one.
var hours = 24; // Reset when storage is more than 24hours
var now = Date.now();
var setupTime = localStorage.getItem('setupTime');
if (setupTime == null) {
localStorage.setItem('setupTime', now)
} else if (now - setupTime > hours*60*60*1000) {
localStorage.clear()
localStorage.setItem('setupTime', now);
}
You'll have to include/require the class anyway, otherwise PHP won't know about the namespace.
You don't necessary have to do it in the same file though. You can do it in a bootstrap file for example. (or use an autoloader, but that's not the topic actually)
For those experiencing this error on CI/CD, adding the line below worked for me on my GitHub Actions CI/CD workflow right after running pip install pyflakes diff-cover
:
git fetch origin master:refs/remotes/origin/master
This is a snippet of the solution from the diff-cover github repo:
Solution: diff-cover matches source files in the coverage XML report with source files in the git diff. For this reason, it's important that the relative paths to the files match. If you are using coverage.py to generate the coverage XML report, then make sure you run diff-cover from the same working directory.
I got the solution on the links below. It is a documented diff-cover
error.
https://diff-cover.readthedocs.io/en/latest//README.html https://github.com/Bachmann1234/diff_cover/blob/master/README.rst
Hope this helps :-).
I don't see any problem, unless you are not managing them using a connection pool.
If you use connection pool, these connections are re-used instead of initiating new connections. so basically, leaving open connections and re-use them it is less problematic than re-creating them each time.
Consider Strapdown.
Strapdown is Javascript-based solution that renders the markdown content in the browser, which makes it great for offline-viewing. From their own description:
Strapdown.js makes it embarrassingly simple to create elegant Markdown documents. No server-side compilation required.
So rename your .md
markdown file to .html
, and surround it with:
<xmp theme="united" style="display:none;">
# Markdown content here
…
</xmp>
<script src="http://strapdownjs.com/v/0.2/strapdown.js"></script>
and opening in any browser will show rendered HTML. Added bonus: you can easily change the theme.
Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..
FROM TABLE A
The other way is
FROM (SELECT col as name1, col2 as name2 FROM ...) B
Notice that the select clause and the parentheses around it are a table, a virtual table.
So, using your second code example (I am guessing at the columns you are hoping to retrieve here):
SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
Notice that your real table attribute
is the first table in this join, and that this virtual table I've called b
is the second table.
This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.
SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
SELECT count(*) AS langcount, at.attribute
FROM attributeTranslation at
GROUP BY at.attribute
) c ON (a.id = c.attribute)
See how that goes? You've generated a virtual table c
containing two columns, joined it to the other two, used one of the columns for the ON
clause, and returned the other as a column in your result set.
The only thing I see is that it's supposed to be since Midnight Jan 1, 1970 UTC
TimeSpan span= DateTime.Now.Subtract(new DateTime(1970,1,1,0,0,0, DateTimeKind.Utc));
return span.TotalSeconds;
another option ... needs remoting ...
(invoke-command -ComputerName mymachine -ScriptBlock {Get-ItemProperty HKLM:\SOFTWARE\VanDyke\VShell\License -Name Version }).version
Posting new answer since Angular behavior has changed. Checking equality with undefined now works in angular expressions, at least as of 1.5, as the following code works:
ng-if="foo !== undefined"
When this ng-if evaluates to true, deleting the percentages property off the appropriate scope and calling $digest removes the element from the document, as you would expect.
if you have number of columns in your database table more than number of columns in your csv you can proceed like this:
LOAD DATA LOCAL INFILE 'pathOfFile.csv'
INTO TABLE youTable
CHARACTER SET latin1 FIELDS TERMINATED BY ';' #you can use ',' if you have comma separated
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\r\n'
(yourcolumn,yourcolumn2,yourcolumn3,yourcolumn4,...);
Here's an updated answer for Angular 4 & 5. TransformRequest and angular.identity were dropped. I've also included the ability to combine files with JSON data in one request.
Angular 5 Solution:
import {HttpClient} from '@angular/common/http';
uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
// Note that setting a content-type header
// for mutlipart forms breaks some built in
// request parsers like multer in express.
const options = {} as any; // Set any options you like
const formData = new FormData();
// Append files to the virtual form.
for (const file of files) {
formData.append(file.name, file)
}
// Optional, append other kev:val rest data to the form.
Object.keys(restObj).forEach(key => {
formData.append(key, restObj[key]);
});
// Send it.
return this.httpClient.post(uploadUrl, formData, options)
.toPromise()
.catch((e) => {
// handle me
});
}
Angular 4 Solution:
// Note that these imports below are deprecated in Angular 5
import {Http, RequestOptions} from '@angular/http';
uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
// Note that setting a content-type header
// for mutlipart forms breaks some built in
// request parsers like multer in express.
const options = new RequestOptions();
const formData = new FormData();
// Append files to the virtual form.
for (const file of files) {
formData.append(file.name, file)
}
// Optional, append other kev:val rest data to the form.
Object.keys(restObj).forEach(key => {
formData.append(key, restObj[key]);
});
// Send it.
return this.http.post(uploadUrl, formData, options)
.toPromise()
.catch((e) => {
// handle me
});
}
It's method syntax (which I find easier to read) but this might do it
Updated post comment
Use .FirstOrDefault()
instead of .First()
With regard to the dates average, you may have to drop that ordering for the moment as I am unable to get to an IDE at the moment
var groupByReference = context.Measurements
.GroupBy(m => m.Reference)
.Select(g => new {Creation = g.FirstOrDefault().CreationTime,
// Avg = g.Average(m => m.CreationTime.Ticks),
Items = g })
.OrderBy(x => x.Creation)
// .ThenBy(x => x.Avg)
.Take(numOfEntries)
.ToList();
You can pass new value like this
setExampleState({...exampleState, masterField2: {
fieldOne: "c",
fieldTwo: {
fieldTwoOne: "d",
fieldTwoTwo: "e"
}
},
}})
You are mixing razor and aspx syntax,if your view engine is razor just do this:
<button class="btn btn-info" type="button" id="addressSearch"
onclick="location.href='@Url.Action("List", "Search")'">
Sorry the problem is me! the was out of sync but this was because I have the HTML text the wrong way around. On the first click I want the div to fade out and the text to say "Show Text".
Will check more thoroughly next time before I ask!
My code is now:
$(function() {
$("#show-background").toggle(function (){
$("#content-area").animate({opacity: '0'}, 'slow')
$("#show-background").text("Show Text")
.stop();
}, function(){
$("#content-area").animate({opacity: '1'}, 'slow')
$("#show-background").text("Show Background")
.stop();
});
});
Thanks again for the help!
Stop using jQuery just for the sake of it! This is so simple with JavaScript only.
document.querySelector('#the-link').setAttribute('href', 'http://google.com');
The command
echo this ^& that
works as expected, outputing
this & that
The command
echo this ^& that > tmp
also works, writing the string to file "tmp". However, before a pipe
echo this ^& that | clip
the ^ is interpreted completely differently. It tries to write the output of the two commands "echo this" and "that" to the pipe. The echo will work then "that" will give an error. Saying
echo this ^& echo that | clip
will put the strings "this" and "that" on the clipboard.
Without the ^:
echo this & echo that | clip
the first echo will write to the console and only the second echo's output will be piped to clip (similarly for "> tmp" redirection). So, when output is being redirected, the ^ does not quote the & but instead causes it to be applied before the redirection rather than after.
To pipe an &, you have to quote it twice
echo this ^^^& that | clip
If you put the string in a variable
set m=this ^& that
then
set m
will output
m=this & that
but the obvious
echo %m%
fails because, after Windows substitutes the variable, resulting in
echo this & that
it parses this as a new command and tries to execute "that".
In a batch file, you can use delayed expansion:
setlocal enableDelayedExpansion
echo !m!
To output to a pipe, we have to replace all &s in the variable value with ^&, which we can do with the %VAR:FROM=TO% syntax:
echo !m:^&=^^^&! | clip
On the command line, "cmd /v" enables delayed expansion:
cmd /v /c echo !m!
This works even when writing to a pipe
cmd /v /c echo !m! | clip
Simple.
Here's my standard implementation. I like the labels to be self-descriptive.
Public Sub DoSomething()
On Error GoTo Catch ' Try
' normal code here
Exit Sub
Catch:
'error code: you can get the specific error by checking Err.Number
End Sub
Or, with a Finally
block:
Public Sub DoSomething()
On Error GoTo Catch ' Try
' normal code here
GoTo Finally
Catch:
'error code
Finally:
'cleanup code
End Sub
In my case the same Model was used in many pages for re-usability purposes. So what i did was i have created a custom attribute which checks for exclusions
public class ValidateAttribute : ActionFilterAttribute
{
public string Exclude { get; set; }
public string Base { get; set; }
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!string.IsNullOrWhiteSpace(this.Exclude))
{
string[] excludes = this.Exclude.Split(',');
foreach (var exclude in excludes)
{
actionContext.ModelState.Remove(Base + "." + exclude);
}
}
if (actionContext.ModelState.IsValid == false)
{
var mediaType = new MediaTypeHeaderValue("application/json");
var error = actionContext.ModelState;
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, error.Keys, mediaType);
}
}
}
and in your controller
[Validate(Base= "person",Exclude ="Age,Name")]
public async Task<IHttpActionResult> Save(User person)
{
//do something
}
Say the Model is
public class User
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Range(18,99)]
public string Age { get; set; }
[MaxLength(250)]
public string Address { get; set; }
}
Just /
refers to the root of your website from the public html folder. DOCUMENT_ROOT
refers to the local path to the folder on the server that contains your website.
For example, I have EasyPHP setup on a machine...
$_SERVER["DOCUMENT_ROOT"]
gives me file:///C:/Program%20Files%20(x86)/EasyPHP-5.3.9/www
but any file I link to with just /
will be relative to my www
folder.
If you want to give the absolute path to a file on your server (from the server's root) you can use DOCUMENT_ROOT
. if you want to give the absolute path to a file from your website's root, use just /
.
I have a similar problem and as I'm newbie, here are some facts for somebody to comment:
I'm sending form data to Google sheet this way (scriptURL is https://script.google.com/macros/s/AKfy..., showSuccess() is showing a simple image):
fetch(scriptURL, {method: 'POST', body: new FormData(form)})
.then(response => showSuccess())
.catch(error => alert('Error! ' + error.message))
Executed in Edge my HTML doesn't show error and Network tab reports this 3 requests: Executed in Chrome my HTML (index.htm) shows Failed to fetch error and Network tab reports this 2 requests: The value in the second column is blocked:other and there is also an error in Console tab:
GET https://script.googleusercontent.com/macros/echo?user_content_key=D-ABF... net::ERR_BLOCKED_BY_CLIENT
In order to suspend installed Chrome extensions, I executed my code in an Incognito window and there is no error message and Network tab reports this 2 requests:
My guess is that something (extension?) prevents Chrome to read the request's answer (the GET request is blocked).
View Data
==============
@model IEnumerable<DemoApp.Models.BankInfo>
<p>
<b>Search Results</b>
</p>
@if (!Model.Any())
{
<tr>
<td colspan="4" style="text-align:center">
No Bank(s) found
</td>
</tr>
}
else
{
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Address)
</th>
<th>
@Html.DisplayNameFor(model => model.Postcode)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.DisplayFor(modelItem => item.Postcode)
</td>
<td>
<input type="button" class="btn btn-default bankdetails" value="Select" data-id="@item.Id" />
</td>
</tr>
}
</table>
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnSearch").off("click.search").on("click.search", function () {
if ($("#SearchBy").val() != '') {
$.ajax({
url: '/home/searchByName',
data: { 'name': $("#SearchBy").val() },
dataType: 'html',
success: function (data) {
$('#dvBanks').html(data);
}
});
}
else {
alert('Please enter Bank Name');
}
});
}
});
public ActionResult SearchByName(string name)
{
var banks = GetBanksInfo();
var filteredBanks = banks.Where(x => x.Name.ToLower().Contains(name.ToLower())).ToList();
return PartialView("_banks", filteredBanks);
}
/// <summary>
/// Get List of Banks Basically it should get from Database
/// </summary>
/// <returns></returns>
private List<BankInfo> GetBanksInfo()
{
return new List<BankInfo>
{
new BankInfo {Id = 1, Name = "Bank of America", Address = "1438 Potomoc Avenue, Pittsburge", Postcode = "PA 15220" },
new BankInfo {Id = 2, Name = "Bank of America", Address = "643 River Hwy, Mooresville", Postcode = "NC 28117" },
new BankInfo {Id = 3, Name = "Bank of Barroda", Address = "643 Hyderabad", Postcode = "500061" },
new BankInfo {Id = 4, Name = "State Bank of India", Address = "AsRao Nagar", Postcode = "500061" },
new BankInfo {Id = 5, Name = "ICICI", Address = "AsRao Nagar", Postcode = "500061" }
};
}
The keyword you're looking for is super
. See this guide, for instance.
That's happening, because switch
statement is a statement
, but here javascript expects an expression.
Although, it's not recommended to use switch statement in a render
method, you can use self-invoking function to achieve this:
render() {
// Don't forget to return a value in a switch statement
return (
<div>
{(() => {
switch(...) {}
})()}
</div>
);
}
I was in the same trouble. For my case, that was a conflict between /etc/zabbix/zabbix_agentd.conf and zabbix_server.conf parameters. I adjusted
"DBHost=localhost",
"DBName=zabbix",
"DBUser=zabbix",
"DBPassword=******",
"DebugLevel=3"
"ListenPort".
If you run the default installation, you should keep ListenPort=10051 for the server and 10050 for the agent.
Cheers!
Sure you can.
You can use case x ... y for the range
Example:
#include <iostream.h>
#include <stdio.h>
int main()
{
int Answer;
cout << "How many cars do you have?";
cin >> Answer;
switch (Answer)
{
case 1 ... 4:
cout << "You need more cars. ";
break;
case 5 ... 8:
cout << "Now you need a house. ";
break;
default:
cout << "What are you? A peace-loving hippie freak? ";
}
cout << "\nPress ENTER to continue... " << endl;
getchar();
return 0;
}
Make sure you have "-std=c++0x" flag enabled within your compiler
For me it worked after removing the target
folder
I know that it could be done with a FOR but I wanted to know if there's another way
There is another way. You can also do it with map and itemgetter:
>>> from operator import itemgetter
>>> map(itemgetter(1), elements)
This still performs a loop internally though and it is slightly slower than the list comprehension:
setup = 'elements = [(1,1,1) for _ in range(100000)];from operator import itemgetter'
method1 = '[x[1] for x in elements]'
method2 = 'map(itemgetter(1), elements)'
import timeit
t = timeit.Timer(method1, setup)
print('Method 1: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup)
print('Method 2: ' + str(t.timeit(100)))
Results:
Method 1: 1.25699996948 Method 2: 1.46600008011
If you need to iterate over a list then using a for
is fine.
You were on the right track with response.getOutputStream()
, but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:
@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
// convert JSON to Employee
Employee emp = convertSomehow(json);
// generate the file
PdfUtil.showHelp(emp);
// retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
byte[] contents = (...);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
// Here you have to set the actual filename of your pdf
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
return response;
}
Notes:
showHelp
is not a good ideabyte[]
: example hereshowHelp()
to avoid overwriting the file if two users send a request at the same time