You're calling both wait
and notifyAll
without using a synchronized
block. In both cases the calling thread must own the lock on the monitor you call the method on.
From the docs for notify
(wait
and notifyAll
have similar documentation but refer to notify
for the fullest description):
This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:
- By executing a synchronized instance method of that object.
- By executing the body of a synchronized statement that synchronizes on the object.
- For objects of type Class, by executing a synchronized static method of that class.
Only one thread at a time can own an object's monitor.
Only one thread will be able to actually exit wait
at a time after notifyAll
as they'll all have to acquire the same monitor again - but all will have been notified, so as soon as the first one then exits the synchronized block, the next will acquire the lock etc.
I found the thing so useful that I built an even easier to use wrapper around it (npm, github).
Installing it:
npm install -g qckwinsvc
Installing your service:
qckwinsvc
prompt: Service name: [name for your service]
prompt: Service description: [description for it]
prompt: Node script path: [path of your node script]
Service installed
Uninstalling your service:
qckwinsvc --uninstall
prompt: Service name: [name of your service]
prompt: Node script path: [path of your node script]
Service stopped
Service uninstalled
There may simply not be such a guide. If so, you may not have much luck convincing anybody to write one, because it would be a lot of work.
I would recommend either of two things. The easier one is to follow the guide you have slavishly, which means forgetting about msysgit.
The harder one is to put up a Linux server - perhaps as a guest under Windows using VirtualBox (free) or VMWare or Parallels (pay), and then follow one of the many sets of instructions Google will lead you to. But you will probably find those instructions are insufficient - they usually assume you've already set up an ssh server, for example, so you have to get that info elsewhere. I've done that twice, and can say that unless you're already something of a Linux guru, it will be a struggle.
When entered as the reference of a Named range
, it refers to range on the sheet the named range is used on.
For example, create a named range MyName
refering to =SUM(!B1:!K1)
Place a formula on Sheet1
=MyName
. This will sum Sheet1!B1:K1
Now place the same formula (=MyName
) on Sheet2
. That formula will sum Sheet2!B1:K1
Note: (as pnuts commented) this and the regular SheetName!B1:K1
format are relative, so reference different cells as the =MyName
formula is entered into different cells.
As a number of people have pointed out, disabling the submit button has some negative side effects (at least in Chrome it prevents the name/value of the button pressed from being submitted). My solution was to simply add an attribute to indicate that submit has been requested, and then check for the presence of this attribute on every submit. Because I'm using the submit function, this is only called after all HTML 5 validation is successful. Here is my code:
$("form.myform").submit(function (e) {
// Check if we have submitted before
if ( $("#submit-btn").attr('attempted') == 'true' ) {
//stop submitting the form because we have already clicked submit.
e.preventDefault();
}
else {
$("#submit-btn").attr("attempted", 'true');
}
});
Simply You can use following methods.
using (WebClient client = new WebClient())
{
client.DownloadFile(new Uri(url), @"c:\temp\image35.png");
// OR
client.DownloadFileAsync(new Uri(url), @"c:\temp\image35.png");
}
These methods are almost same as DownloadString(..) and DownloadStringAsync(...). They store the file in Directory rather than in C# string and no need of Format extension in URi
public void SaveImage(string filename, ImageFormat format)
{
WebClient client = new WebClient();
Stream stream = client.OpenRead(imageUrl);
Bitmap bitmap; bitmap = new Bitmap(stream);
if (bitmap != null)
{
bitmap.Save(filename, format);
}
stream.Flush();
stream.Close();
client.Dispose();
}
try
{
SaveImage("--- Any Image Path ---", ImageFormat.Png)
}
catch(ExternalException)
{
// Something is wrong with Format -- Maybe required Format is not
// applicable here
}
catch(ArgumentNullException)
{
// Something wrong with Stream
}
I've gotten this error too.
for (int i=0;i<10;i++) { ..
is not valid in the C89/C90 standard. As OysterD says, you need to do:
int i;
for (i=0;i<10;i++) { ..
Your original code is allowed in C99 and later standards of the C language.
Example for a public system resource:
// this will get id for android.R.drawable.ic_dialog_alert
int id = Resources.getSystem().getIdentifier("ic_dialog_alert", "drawable", "android");
Another way is to refer the documentation for android.R.drawable class.
For the record, if you encounter this error after switching from LocalDB
to SQLEXPRESS
, make sure the database already esists in SQLEXPRESS
. You can verify this in Management Studio.
I had the same problem when using Entity Framework
after switching to SQLEXPRESS from LocalDB
. I had to run Update-Database
command. I was able to successfully connect after that.
A good idea is to set all of the "" (blank cells) to NA before any further analysis.
If you are reading your input from a file, it is a good choice to cast all "" to NAs:
foo <- read.table(file="Your_file.txt", na.strings=c("", "NA"), sep="\t") # if your file is tab delimited
If you have already your table loaded, you can act as follows:
foo[foo==""] <- NA
Then to keep only rows with no NA you may just use na.omit()
:
foo <- na.omit(foo)
Or to keep columns with no NA:
foo <- foo[, colSums(is.na(foo)) == 0]
I found this way of using ajax which helped me as it was better in use as not having complex json syntaxes
//fifth
function GetAjaxDataPromise(url, postData) {
debugger;
var promise = $.post(url, postData, function (promise, status) {
});
return promise;
};
$(function () {
$("#btnGet5").click(function () {
debugger;
var promises = GetAjaxDataPromise('@Url.Action("AjaxMethod", "Home")', { EmpId: $("#txtId").val(), EmpName: $("#txtName").val(), EmpSalary: $("#txtSalary").val() });
promises.done(function (response) {
debugger;
alert("Hello: " + response.EmpName + " Your Employee Id Is: " + response.EmpId + "And Your Salary Is: " + response.EmpSalary);
});
});
});
This method comes with jquery promise the best part was on controller we can received data by using separate parameters or just by using a model class.
[HttpPost]
public JsonResult AjaxMethod(PersonModel personModel)
{
PersonModel person = new PersonModel
{
EmpId = personModel.EmpId,
EmpName = personModel.EmpName,
EmpSalary = personModel.EmpSalary
};
return Json(person);
}
or
[HttpPost]
public JsonResult AjaxMethod(string empId, string empName, string empSalary)
{
PersonModel person = new PersonModel
{
EmpId = empId,
EmpName = empName,
EmpSalary = empSalary
};
return Json(person);
}
It works for both of the cases. SO you must try out this way. Got the reference from Using Ajax With Asp.Net MVC
There are few more ways of using Ajax explained there other than this one which you must try.
I dont know if I quite get what the issue is. You can add an image into the ASP button but it depends how its set up as to whether it fits in properly. putting in a background images to asp buttons regularly gives you a dodgy shaped button or a background image with a text overlay because its missing an image tag. such as the image with "SUBMIT QUERY" over the top of it.
As an easy way of doing it I use a "blankspace.gif" file across my website. its a 1x1 pixel blank gif file and I resize it to replace an image on the website.
as I dont use CSS to replace an image I use CSS Sprites to reduce queries. My website was originally 150kb for the homepage and had about 140-150 requests to load the home page. By creating a sprite I killed off the requests compressed the image size to a fraction of the size and it works perfect and any of the areas you need an image file to size it up properly just use the same blankspace.gif image.
<asp:ImageButton class="signup" ID="btn_newsletter" ImageUrl="~/xx/xx/blankspace.gif" Width="87px" Height="28px" runat="server" /
If you see the above the class loads the background image in the css but this leaves the button with the "submit Query" text over it as it needs an image so replacing it with a preloaded image means you got rid of the request and still have the image in the css.
Done.
Seen from a non-PHP guru perspective, this should do exactly what us desired to:
<style>
[name$='pdf'] { width:100%; height: auto;}
</style>
David Heffernan explained the issue in his answer, and I wrote the improved code. See below.
We can write a useful variadic function to concatenate any number of strings:
#include <stdlib.h> // calloc
#include <stdarg.h> // va_*
#include <string.h> // strlen, strcpy
char* concat(int count, ...)
{
va_list ap;
int i;
// Find required length to store merged string
int len = 1; // room for NULL
va_start(ap, count);
for(i=0 ; i<count ; i++)
len += strlen(va_arg(ap, char*));
va_end(ap);
// Allocate memory to concat strings
char *merged = calloc(sizeof(char),len);
int null_pos = 0;
// Actually concatenate strings
va_start(ap, count);
for(i=0 ; i<count ; i++)
{
char *s = va_arg(ap, char*);
strcpy(merged+null_pos, s);
null_pos += strlen(s);
}
va_end(ap);
return merged;
}
#include <stdio.h> // printf
void println(char *line)
{
printf("%s\n", line);
}
int main(int argc, char* argv[])
{
char *str;
str = concat(0); println(str); free(str);
str = concat(1,"a"); println(str); free(str);
str = concat(2,"a","b"); println(str); free(str);
str = concat(3,"a","b","c"); println(str); free(str);
return 0;
}
Output:
// Empty line
a
ab
abc
Note that you should free up the allocated memory when it becomes unneeded to avoid memory leaks:
char *str = concat(2,"a","b");
println(str);
free(str);
I have a 99% pure SQL method. The idea is to version your schema. You can do this in two ways:
Use the 'user_version' pragma command (PRAGMA user_version
) to store an incremental number for your database schema version.
Store your version number in your own defined table.
In this way, when the software is started, it can check the database schema and, if needed, run your ALTER TABLE
query, then increment the stored version. This is by far better than attempting various updates "blind", especially if your database grows and changes a few times over the years.
You have [ValidateAntiForgeryToken]
attribute before your action. You also should add @Html.AntiForgeryToken()
in your form.
Type "ctor" and press the TAB key twice this will add the default constructor automatically
I am writing specifically for Python newbies in a very simple way, though deep down Python does so many things.
Let’s start with the very basic:
Consider a list,
l = [1,2,3]
Let’s write an equivalent function:
def f():
return [1,2,3]
o/p of print(l): [1,2,3]
&
o/p of print(f()) : [1,2,3]
Let’s make list l iterable: In python list is always iterable that means you can apply iterator whenever you want.
Let’s apply iterator on list:
iter_l = iter(l) # iterator applied explicitly
Let’s make a function iterable, i.e. write an equivalent generator function.
In python as soon as you introduce the keyword yield
; it becomes a generator function and iterator will be applied implicitly.
Note: Every generator is always iterable with implicit iterator applied and here implicit iterator is the crux So the generator function will be:
def f():
yield 1
yield 2
yield 3
iter_f = f() # which is iter(f) as iterator is already applied implicitly
So if you have observed, as soon as you made function f a generator, it is already iter(f)
Now,
l is the list, after applying iterator method "iter" it becomes, iter(l)
f is already iter(f), after applying iterator method "iter" it becomes, iter(iter(f)), which is again iter(f)
It's kinda you are casting int to int(x) which is already int and it will remain int(x).
For example o/p of :
print(type(iter(iter(l))))
is
<class 'list_iterator'>
Never forget this is Python and not C or C++
Hence the conclusion from above explanation is:
list l ~= iter(l)
generator function f == iter(f)
import React from 'react';
import {connect} from 'react-redux';
import Userlist from './Userlist';
class Userdetails extends React.Component{
render(){
return(
<div>
<p>Name : <span>{this.props.user.name}</span></p>
<p>ID : <span>{this.props.user.id}</span></p>
<p>Working : <span>{this.props.user.Working}</span></p>
<p>Age : <span>{this.props.user.age}</span></p>
</div>
);
}
}
function mapStateToProps(state){
return {
user:state.activeUser
}
}
export default connect(mapStateToProps, null)(Userdetails);
I usually just type:
gcm notepad
or
gcm note*
gcm is the default alias for Get-Command.
On my system, gcm note* outputs:
[27] » gcm note*
CommandType Name Definition
----------- ---- ----------
Application notepad.exe C:\WINDOWS\notepad.exe
Application notepad.exe C:\WINDOWS\system32\notepad.exe
Application Notepad2.exe C:\Utils\Notepad2.exe
Application Notepad2.ini C:\Utils\Notepad2.ini
You get the directory and the command that matches what you're looking for.
newid()/order by will work, but will be very expensive for large result sets because it has to generate an id for every row, and then sort them.
TABLESAMPLE() is good from a performance standpoint, but you will get clumping of results (all rows on a page will be returned).
For a better performing true random sample, the best way is to filter out rows randomly. I found the following code sample in the SQL Server Books Online article Limiting Results Sets by Using TABLESAMPLE:
If you really want a random sample of individual rows, modify your query to filter out rows randomly, instead of using TABLESAMPLE. For example, the following query uses the NEWID function to return approximately one percent of the rows of the Sales.SalesOrderDetail table:
SELECT * FROM Sales.SalesOrderDetail WHERE 0.01 >= CAST(CHECKSUM(NEWID(),SalesOrderID) & 0x7fffffff AS float) / CAST (0x7fffffff AS int)
The SalesOrderID column is included in the CHECKSUM expression so that NEWID() evaluates once per row to achieve sampling on a per-row basis. The expression CAST(CHECKSUM(NEWID(), SalesOrderID) & 0x7fffffff AS float / CAST (0x7fffffff AS int) evaluates to a random float value between 0 and 1.
When run against a table with 1,000,000 rows, here are my results:
SET STATISTICS TIME ON
SET STATISTICS IO ON
/* newid()
rows returned: 10000
logical reads: 3359
CPU time: 3312 ms
elapsed time = 3359 ms
*/
SELECT TOP 1 PERCENT Number
FROM Numbers
ORDER BY newid()
/* TABLESAMPLE
rows returned: 9269 (varies)
logical reads: 32
CPU time: 0 ms
elapsed time: 5 ms
*/
SELECT Number
FROM Numbers
TABLESAMPLE (1 PERCENT)
/* Filter
rows returned: 9994 (varies)
logical reads: 3359
CPU time: 641 ms
elapsed time: 627 ms
*/
SELECT Number
FROM Numbers
WHERE 0.01 >= CAST(CHECKSUM(NEWID(), Number) & 0x7fffffff AS float)
/ CAST (0x7fffffff AS int)
SET STATISTICS IO OFF
SET STATISTICS TIME OFF
If you can get away with using TABLESAMPLE, it will give you the best performance. Otherwise use the newid()/filter method. newid()/order by should be last resort if you have a large result set.
I'm not really sure of the syntax {el => this.inputEntry = el}, but when clearing an input field you assign a ref like you mentioned.
<input type="text" ref="someName" />
Then in the onClick function after you've finished using the input value, just use...
this.refs.someName.value = '';
Edit
Actually the {el => this.inputEntry = el} is the same as this I believe. Maybe someone can correct me. The value for el must be getting passed in from somewhere, to act as the reference.
function (el) {
this.inputEntry = el;
}
Open a PL/SQL object in the Editor.
Click on the main toolbar or select Session | Toggle Compiling with Debug. This enables debugging.
Compile the object on the database.
Select one of the following options on the Execute toolbar to begin debugging: Execute PL/SQL with debugger () Step over Step into Run to cursor
try this : here select is your select element
let select = document.getElementsByClassName('lstSelected')[0],
options = select.options,
len = options.length,
data='',
i=0;
while (i<len){
if (options[i].selected)
data+= "&" + select.name + '=' + options[i].value;
i++;
}
return data;
Data is in the form of query string i.e.name=value&name=anotherValue
Apparently Chrome and Safari are wrong: onchange
should only be triggered when the user releases the mouse. To get continuous updates, you should use the oninput
event, which will capture live updates in Firefox, Safari and Chrome, both from the mouse and the keyboard.
However, oninput
is not supported in IE10, so your best bet is to combine the two event handlers, like this:
<span id="valBox"></span>
<input type="range" min="5" max="10" step="1"
oninput="showVal(this.value)" onchange="showVal(this.value)">
Check out this Bugzilla thread for more information.
The problem is most probably between a . and a _. Say in my query I put
SELECT ..... FROM LOCATION.PT
instead of
SELECT ..... FROM LOCATION_PT
So I think MySQL would think LOCATION as a database name and was giving access privilege error.
From the proxy_pass documentation:
A special case is using variables in the proxy_pass statement: The requested URL is not used and you are fully responsible to construct the target URL yourself.
Since you're using $1 in the target, nginx relies on you to tell it exactly what to pass. You can fix this in two ways. First, stripping the beginning of the uri with a proxy_pass is trivial:
location /service/ {
# Note the trailing slash on the proxy_pass.
# It tells nginx to replace /service/ with / when passing the request.
proxy_pass http://apache/;
}
Or if you want to use the regex location, just include the args:
location ~* ^/service/(.*) {
proxy_pass http://apache/$1$is_args$args;
}
Also a good script, although my laptop ran out of memory, but this was on a very large table
https://basitaalishan.com/2014/02/23/rebuild-all-indexes-on-all-tables-in-the-sql-server-database/
USE [<mydatabasename>]
Go
--/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
--Arguments Data Type Description
-------------- ------------ ------------
--@FillFactor [int] Specifies a percentage that indicates how full the Database Engine should make the leaf level
-- of each index page during index creation or alteration. The valid inputs for this parameter
-- must be an integer value from 1 to 100 The default is 0.
-- For more information, see http://technet.microsoft.com/en-us/library/ms177459.aspx.
--@PadIndex [varchar](3) Specifies index padding. The PAD_INDEX option is useful only when FILLFACTOR is specified,
-- because PAD_INDEX uses the percentage specified by FILLFACTOR. If the percentage specified
-- for FILLFACTOR is not large enough to allow for one row, the Database Engine internally
-- overrides the percentage to allow for the minimum. The number of rows on an intermediate
-- index page is never less than two, regardless of how low the value of fillfactor. The valid
-- inputs for this parameter are ON or OFF. The default is OFF.
-- For more information, see http://technet.microsoft.com/en-us/library/ms188783.aspx.
--@SortInTempDB [varchar](3) Specifies whether to store temporary sort results in tempdb. The valid inputs for this
-- parameter are ON or OFF. The default is OFF.
-- For more information, see http://technet.microsoft.com/en-us/library/ms188281.aspx.
--@OnlineRebuild [varchar](3) Specifies whether underlying tables and associated indexes are available for queries and data
-- modification during the index operation. The valid inputs for this parameter are ON or OFF.
-- The default is OFF.
-- Note: Online index operations are only available in Enterprise edition of Microsoft
-- SQL Server 2005 and above.
-- For more information, see http://technet.microsoft.com/en-us/library/ms191261.aspx.
--@DataCompression [varchar](4) Specifies the data compression option for the specified index, partition number, or range of
-- partitions. The options for this parameter are as follows:
-- > NONE - Index or specified partitions are not compressed.
-- > ROW - Index or specified partitions are compressed by using row compression.
-- > PAGE - Index or specified partitions are compressed by using page compression.
-- The default is NONE.
-- Note: Data compression feature is only available in Enterprise edition of Microsoft
-- SQL Server 2005 and above.
-- For more information about compression, see http://technet.microsoft.com/en-us/library/cc280449.aspx.
--@MaxDOP [int] Overrides the max degree of parallelism configuration option for the duration of the index
-- operation. The valid input for this parameter can be between 0 and 64, but should not exceed
-- number of processors available to SQL Server.
-- For more information, see http://technet.microsoft.com/en-us/library/ms189094.aspx.
--- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
-- Ensure a USE <databasename> statement has been executed first.
SET NOCOUNT ON;
DECLARE @Version [numeric] (18, 10)
,@SQLStatementID [int]
,@CurrentTSQLToExecute [nvarchar](max)
,@FillFactor [int] = 100 -- Change if needed
,@PadIndex [varchar](3) = N'OFF' -- Change if needed
,@SortInTempDB [varchar](3) = N'OFF' -- Change if needed
,@OnlineRebuild [varchar](3) = N'OFF' -- Change if needed
,@LOBCompaction [varchar](3) = N'ON' -- Change if needed
,@DataCompression [varchar](4) = N'NONE' -- Change if needed
,@MaxDOP [int] = NULL -- Change if needed
,@IncludeDataCompressionArgument [char](1);
IF OBJECT_ID(N'TempDb.dbo.#Work_To_Do') IS NOT NULL
DROP TABLE #Work_To_Do
CREATE TABLE #Work_To_Do
(
[sql_id] [int] IDENTITY(1, 1)
PRIMARY KEY ,
[tsql_text] [varchar](1024) ,
[completed] [bit]
)
SET @Version = CAST(LEFT(CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128)), CHARINDEX('.', CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128))) - 1) + N'.' + REPLACE(RIGHT(CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128)), LEN(CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128))) - CHARINDEX('.', CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128)))), N'.', N'') AS [numeric](18, 10))
IF @DataCompression IN (N'PAGE', N'ROW', N'NONE')
AND (
@Version >= 10.0
AND SERVERPROPERTY(N'EngineEdition') = 3
)
BEGIN
SET @IncludeDataCompressionArgument = N'Y'
END
IF @IncludeDataCompressionArgument IS NULL
BEGIN
SET @IncludeDataCompressionArgument = N'N'
END
INSERT INTO #Work_To_Do ([tsql_text], [completed])
SELECT 'ALTER INDEX [' + i.[name] + '] ON' + SPACE(1) + QUOTENAME(t2.[TABLE_CATALOG]) + '.' + QUOTENAME(t2.[TABLE_SCHEMA]) + '.' + QUOTENAME(t2.[TABLE_NAME]) + SPACE(1) + 'REBUILD WITH (' + SPACE(1) + + CASE
WHEN @PadIndex IS NULL
THEN 'PAD_INDEX =' + SPACE(1) + CASE i.[is_padded]
WHEN 1
THEN 'ON'
WHEN 0
THEN 'OFF'
END
ELSE 'PAD_INDEX =' + SPACE(1) + @PadIndex
END + CASE
WHEN @FillFactor IS NULL
THEN ', FILLFACTOR =' + SPACE(1) + CONVERT([varchar](3), REPLACE(i.[fill_factor], 0, 100))
ELSE ', FILLFACTOR =' + SPACE(1) + CONVERT([varchar](3), @FillFactor)
END + CASE
WHEN @SortInTempDB IS NULL
THEN ''
ELSE ', SORT_IN_TEMPDB =' + SPACE(1) + @SortInTempDB
END + CASE
WHEN @OnlineRebuild IS NULL
THEN ''
ELSE ', ONLINE =' + SPACE(1) + @OnlineRebuild
END + ', STATISTICS_NORECOMPUTE =' + SPACE(1) + CASE st.[no_recompute]
WHEN 0
THEN 'OFF'
WHEN 1
THEN 'ON'
END + ', ALLOW_ROW_LOCKS =' + SPACE(1) + CASE i.[allow_row_locks]
WHEN 0
THEN 'OFF'
WHEN 1
THEN 'ON'
END + ', ALLOW_PAGE_LOCKS =' + SPACE(1) + CASE i.[allow_page_locks]
WHEN 0
THEN 'OFF'
WHEN 1
THEN 'ON'
END + CASE
WHEN @IncludeDataCompressionArgument = N'Y'
THEN CASE
WHEN @DataCompression IS NULL
THEN ''
ELSE ', DATA_COMPRESSION =' + SPACE(1) + @DataCompression
END
ELSE ''
END + CASE
WHEN @MaxDop IS NULL
THEN ''
ELSE ', MAXDOP =' + SPACE(1) + CONVERT([varchar](2), @MaxDOP)
END + SPACE(1) + ')'
,0
FROM [sys].[tables] t1
INNER JOIN [sys].[indexes] i ON t1.[object_id] = i.[object_id]
AND i.[index_id] > 0
AND i.[type] IN (1, 2)
INNER JOIN [INFORMATION_SCHEMA].[TABLES] t2 ON t1.[name] = t2.[TABLE_NAME]
AND t2.[TABLE_TYPE] = 'BASE TABLE'
INNER JOIN [sys].[stats] AS st WITH (NOLOCK) ON st.[object_id] = t1.[object_id]
AND st.[name] = i.[name]
SELECT @SQLStatementID = MIN([sql_id])
FROM #Work_To_Do
WHERE [completed] = 0
WHILE @SQLStatementID IS NOT NULL
BEGIN
SELECT @CurrentTSQLToExecute = [tsql_text]
FROM #Work_To_Do
WHERE [sql_id] = @SQLStatementID
PRINT @CurrentTSQLToExecute
EXEC [sys].[sp_executesql] @CurrentTSQLToExecute
UPDATE #Work_To_Do
SET [completed] = 1
WHERE [sql_id] = @SQLStatementID
SELECT @SQLStatementID = MIN([sql_id])
FROM #Work_To_Do
WHERE [completed] = 0
END
I think SetInterval
and SetTimeout
are different. SetInterval
executes the block according to the time set while, SetTimeout
executes the block of code once.
Try these set of codes after the timeout countdown seconds:
setInterval(function(e){
alert('Ugbana Kelvin');
}, 2000);
and then try
setTimeout(function(e){
alert('Ugbana Kelvin');
}, 2000);
You can see the differences for yourself.
If you would like to add vector to itself both popular solutions will fail:
std::vector<std::string> v, orig;
orig.push_back("first");
orig.push_back("second");
// BAD:
v = orig;
v.insert(v.end(), v.begin(), v.end());
// Now v contains: { "first", "second", "", "" }
// BAD:
v = orig;
std::copy(v.begin(), v.end(), std::back_inserter(v));
// std::bad_alloc exception is generated
// GOOD, but I can't guarantee it will work with any STL:
v = orig;
v.reserve(v.size()*2);
v.insert(v.end(), v.begin(), v.end());
// Now v contains: { "first", "second", "first", "second" }
// GOOD, but I can't guarantee it will work with any STL:
v = orig;
v.reserve(v.size()*2);
std::copy(v.begin(), v.end(), std::back_inserter(v));
// Now v contains: { "first", "second", "first", "second" }
// GOOD (best):
v = orig;
v.insert(v.end(), orig.begin(), orig.end()); // note: we use different vectors here
// Now v contains: { "first", "second", "first", "second" }
It appears you may just have missed the "messages"
property in the data
, so the loop is likely iterating the root Object
rather than the Array
:
for (var key in data.messages) {
var obj = data.messages[key];
// ...
}
Unless data
was set to messages
before the given snippet.
Though, you should consider changing that to a normal for
loop for the Array
:
for (var i = 0, l = data.messages.length; i < l; i++) {
var obj = data.messages[i];
// ...
}
To align some elements (headerElement) in the center and the last element to the right (headerEnd).
.headerElement {
margin-right: 5%;
margin-left: 5%;
}
.headerEnd{
margin-left: auto;
}
The answer is to DISABLE "Enable auto-completion on each input". Tested and works perfectly.
A great way to find out:
public static void main(String args[]) {
int i = null;
}
Try to compile.
"ABABAB".replace(/B/g, "A");
As always: don't use regex unless you have to. For a simple string replace, the idiom is:
'ABABAB'.split('B').join('A')
Then you don't have to worry about the quoting issues mentioned in Gracenotes's answer.
You can read the lines and replace all special characters safely this way.
Keep in mind that if you use \\W
you will not replace underscores.
Scanner scan = new Scanner(System.in);
while(scan.hasNextLine()){
System.out.println(scan.nextLine().replaceAll("[^a-zA-Z0-9]", ""));
}
jQuery needs to be the first script you import. The first script on your page
<script type="text/javascript" src="/test/wp-content/themes/child/script/jquery.jcarousel.min.js"></script>
appears to be a jQuery plugin, which is likely generating an error since jQuery hasn't been loaded on the page yet.
You can force the annotation library in your test using:
androidTestCompile 'com.android.support:support-annotations:23.1.0'
Something like this:
// Force usage of support annotations in the test app, since it is internally used by the runner module.
androidTestCompile 'com.android.support:support-annotations:23.1.0'
androidTestCompile 'com.android.support.test:runner:0.4.1'
androidTestCompile 'com.android.support.test:rules:0.4.1'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
androidTestCompile 'com.android.support.test.espresso:espresso-intents:2.2.1'
androidTestCompile 'com.android.support.test.espresso:espresso-web:2.2.1'
Another solution is to use this in the top level file:
configurations.all {
resolutionStrategy.force 'com.android.support:support-annotations:23.1.0'
}
This example is from the MSDN page on ResourceManager.GetString():
// Create a resource manager to retrieve resources.
ResourceManager rm = new ResourceManager("items", Assembly.GetExecutingAssembly());
// Retrieve the value of the string resource named "welcome".
// The resource manager will retrieve the value of the
// localized resource using the caller's current culture setting.
String str = rm.GetString("welcome");
Use this format: ${__time(yyyy-MM-dd'T'hh:mm:ss.SS'Z')}
Which will give you: 2018-01-16T08:32:28.75Z
for date-time comparison, you can use valueOf
function of the moment which provides milliseconds of the date-time, which is best for comparison:
let date1 = moment('01-02-2020','DD-MM-YYYY').valueOf()_x000D_
let date2 = moment('11-11-2012','DD-MM-YYYY').valueOf()_x000D_
_x000D_
// alert((date1 > date2 ? 'date1' : 'date2') + " is greater..." )_x000D_
_x000D_
if (date1 > date2) {_x000D_
alert("date1 is greater..." )_x000D_
} else {_x000D_
alert("date2 is greater..." )_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
Removing only decimal part can be done as follows:
number.replace(/(\.\d+)+/,'');
This would convert 13.6667px into 13px (leaving units px untouched).
CREATE TABLE sometable (t TIMESTAMP, d DATE);
INSERT INTO sometable SELECT '2011/05/26 09:00:00';
UPDATE sometable SET d = t; -- OK
-- UPDATE sometable SET d = t::date; OK
-- UPDATE sometable SET d = CAST (t AS date); OK
-- UPDATE sometable SET d = date(t); OK
SELECT * FROM sometable ;
t | d
---------------------+------------
2011-05-26 09:00:00 | 2011-05-26
(1 row)
Another test kit:
SELECT pg_catalog.date(t) FROM sometable;
date
------------
2011-05-26
(1 row)
SHOW datestyle ;
DateStyle
-----------
ISO, MDY
(1 row)
This works for me:
$(function () {
$('#datetimepicker5').datetimepicker({
use24hours: true,
format: 'HH:mm'
});
});
Important: It only worked at the point I used uppercase "H" as time format.
$property_images = $_FILES['property_images']['name'];
if(!empty($property_images))
{
for($up=0;$up<count($property_images);$up++)
{
move_uploaded_file($_FILES['property_images']['tmp_name'][$up],'../images/property_images/'.$_FILES['property_images']['name'][$up]);
}
}
There's always the hardware route. Purchase two USB to serial converters, and connect them via a NULL modem.
Pro tips: 1) Windows may assign new COM ports to the adapters after every device sleep or reboot. 2) The market leaders in chips for USB to serial are Prolific and FTDI. Both companies are battling knockoffs, and may be blocked in future official Windows drivers. The Linux drivers however work fine with the clones.
In my opinion the bare minimum implementation has two requirements. A state that keeps track of whether the modal is open or not, and a portal to render the modal outside of the standard react tree.
The ModalContainer component below implements those requirements along with corresponding render functions for the modal and the trigger, which is responsible for executing the callback to open the modal.
import React from 'react';
import PropTypes from 'prop-types';
import Portal from 'react-portal';
class ModalContainer extends React.Component {
state = {
isOpen: false,
};
openModal = () => {
this.setState(() => ({ isOpen: true }));
}
closeModal = () => {
this.setState(() => ({ isOpen: false }));
}
renderModal() {
return (
this.props.renderModal({
isOpen: this.state.isOpen,
closeModal: this.closeModal,
})
);
}
renderTrigger() {
return (
this.props.renderTrigger({
openModal: this.openModal
})
)
}
render() {
return (
<React.Fragment>
<Portal>
{this.renderModal()}
</Portal>
{this.renderTrigger()}
</React.Fragment>
);
}
}
ModalContainer.propTypes = {
renderModal: PropTypes.func.isRequired,
renderTrigger: PropTypes.func.isRequired,
};
export default ModalContainer;
And here's a simple use case...
import React from 'react';
import Modal from 'react-modal';
import Fade from 'components/Animations/Fade';
import ModalContainer from 'components/ModalContainer';
const SimpleModal = ({ isOpen, closeModal }) => (
<Fade visible={isOpen}> // example use case with animation components
<Modal>
<Button onClick={closeModal}>
close modal
</Button>
</Modal>
</Fade>
);
const SimpleModalButton = ({ openModal }) => (
<button onClick={openModal}>
open modal
</button>
);
const SimpleButtonWithModal = () => (
<ModalContainer
renderModal={props => <SimpleModal {...props} />}
renderTrigger={props => <SimpleModalButton {...props} />}
/>
);
export default SimpleButtonWithModal;
I use render functions, because I want to isolate state management and boilerplate logic from the implementation of the rendered modal and trigger component. This allows the rendered components to be whatever you want them to be. In your case, I suppose the modal component could be a connected component that receives a callback function that dispatches an asynchronous action.
If you need to send dynamic props to the modal component from the trigger component, which hopefully doesn't happen too often, I recommend wrapping the ModalContainer with a container component that manages the dynamic props in its own state and enhance the original render methods like so.
import React from 'react'
import partialRight from 'lodash/partialRight';
import ModalContainer from 'components/ModalContainer';
class ErrorModalContainer extends React.Component {
state = { message: '' }
onError = (message, callback) => {
this.setState(
() => ({ message }),
() => callback && callback()
);
}
renderModal = (props) => (
this.props.renderModal({
...props,
message: this.state.message,
})
)
renderTrigger = (props) => (
this.props.renderTrigger({
openModal: partialRight(this.onError, props.openModal)
})
)
render() {
return (
<ModalContainer
renderModal={this.renderModal}
renderTrigger={this.renderTrigger}
/>
)
}
}
ErrorModalContainer.propTypes = (
ModalContainer.propTypes
);
export default ErrorModalContainer;
There are two typical ways of declaring a function. I prefer the second approach.
function function_name {
command...
}
or
function_name () {
command...
}
To call a function with arguments:
function_name "$arg1" "$arg2"
The function refers to passed arguments by their position (not by name), that is $1
, $2
, and so forth. $0
is the name of the script itself.
Example:
function_name () {
echo "Parameter #1 is $1"
}
Also, you need to call your function after it is declared.
#!/usr/bin/env sh
foo 1 # this will fail because foo has not been declared yet.
foo() {
echo "Parameter #1 is $1"
}
foo 2 # this will work.
Output:
./myScript.sh: line 2: foo: command not found
Parameter #1 is 2
Quick compatibility build script (also works on Windows):
"build": "react-scripts build && rm -rf docs && mv build docs"
Having been bitten by this, I have a habit of including locally defined variables in the innermost scope which I use to transfer to any closure. In your example:
foreach (var s in strings)
query = query.Where(i => i.Prop == s); // access to modified closure
I do:
foreach (var s in strings)
{
string search = s;
query = query.Where(i => i.Prop == search); // New definition ensures unique per iteration.
}
Once you have that habit, you can avoid it in the very rare case you actually intended to bind to the outer scopes. To be honest, I don't think I have ever done so.
@Davy Ladman your solution with shift are corrent but only for ip starting with number less or equal 99, infact first octect must be cast up to long.
Anyway convert back with long type is quite difficult because store 64 bit (not 32 for Ip) and fill 4 bytes with zeroes
static uint ToInt(string addr)
{
return BitConverter.ToUInt32(IPAddress.Parse(addr).GetAddressBytes(), 0);
}
static string ToAddr(uint address)
{
return new IPAddress(address).ToString();
}
Enjoy!
Massimo
function arrayColumn(arr, n) {_x000D_
return arr.map(x=> x[n]);_x000D_
}_x000D_
_x000D_
var twoDimensionalArray = [_x000D_
[1, 2, 3],_x000D_
[4, 5, 6],_x000D_
[7, 8, 9]_x000D_
];_x000D_
_x000D_
console.log(arrayColumn(twoDimensionalArray, 1));
_x000D_
Assuming your have a value like the following
var obj = {"0":"1","1":"2","2":"3","3":"4"};
Then you can turn this into a javascript array using the following
var arr = [];
json = JSON.stringify(eval('(' + obj + ')')); //convert to json string
arr = $.parseJSON(json); //convert to javascript array
This works for converting json into multi-diminsional javascript arrays as well.
None of the other methods on this page seemed to work completely for me when working with php json-encoded strings except the method I am mentioning herein.
This method name should do the trick:
Page<QueuedBook> findByBookIdRegion(Region region, Pageable pageable);
More info on that in the section about query derivation of the reference docs.
First, verify that the mod_rewrite module is installed. Then, be careful to understand how it works, many people get it backwards.
You don't hide urls or extensions. What you do is create a NEW url that directs to the old one, for example
The URL to put on your web site will be yoursite.com/play?m=asdf
or better yet
yoursite.com/asdf
Even though the directory asdf doesn't exist. Then with mod_rewrite installed you put this in .htaccess. Basically it says, if the requested URL is NOT a file and is NOT a directory, direct it to my script:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /play.php [L]
Almost done - now you just have to write some stuff into your PHP script to parse out the new URL. You want to do this so that the OLD ones work too - what you do is maintain a system by which the variable is always exactly the same OR create a database table that correlates the "SEO friendly URL" with the product id. An example might be
/Some-Cool-Video (which equals product ID asdf)
The advantage to this? Search engines will index the keywords "Some Cool Video." asdf? Who's going to search for that?
I can't give you specifics of how to program this, but take the query string, strip off the end
yoursite.com/Some-Cool-Video
turns into "asdf"
Then set the m variable to this
m=asdf
So both URL's will still go to the same product
yoursite.com/play.php?m=asdf
yoursite.com/Some-Cool-Video
mod_rewrite can do lots of other important stuff too, Google for it and get it activated on your server (it's probably already installed.)
I use the mouse:
I found this code at jwt.io and it works well.
//this is used to parse base64
function url_base64_decode(str) {
var output = str.replace(/-/g, '+').replace(/_/g, '/');
switch (output.length % 4) {
case 0:
break;
case 2:
output += '==';
break;
case 3:
output += '=';
break;
default:
throw 'Illegal base64url string!';
}
var result = window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
try{
return decodeURIComponent(escape(result));
} catch (err) {
return result;
}
}
In some cases(certain development platforms),
the best answer(for now) faces a problem of invalid base64 length.
So, I needed a more stable way.
I hope it would help you.
You can use JPQL as well as JPA Criteria API for any kind of DTO projection(Mapping only selected columns to a DTO class) . Look at below code snippets showing how to selectively select various columns instead of selecting all columns . These example also show how to select various columns from joining multiple columns . I hope this helps .
JPQL code :
String dtoProjection = "new com.katariasoft.technologies.jpaHibernate.college.data.dto.InstructorDto"
+ "(i.id, i.name, i.fatherName, i.address, id.proofNo, "
+ " v.vehicleNumber, v.vechicleType, s.name, s.fatherName, "
+ " si.name, sv.vehicleNumber , svd.name) ";
List<InstructorDto> instructors = queryExecutor.fetchListForJpqlQuery(
"select " + dtoProjection + " from Instructor i " + " join i.idProof id " + " join i.vehicles v "
+ " join i.students s " + " join s.instructors si " + " join s.vehicles sv "
+ " join sv.documents svd " + " where i.id > :id and svd.name in (:names) "
+ " order by i.id , id.proofNo , v.vehicleNumber , si.name , sv.vehicleNumber , svd.name ",
CollectionUtils.mapOf("id", 2, "names", Arrays.asList("1", "2")), InstructorDto.class);
if (Objects.nonNull(instructors))
instructors.forEach(i -> i.setName("Latest Update"));
DataPrinters.listDataPrinter.accept(instructors);
JPA Criteria API code :
@Test
public void fetchFullDataWithCriteria() {
CriteriaBuilder cb = criteriaUtils.criteriaBuilder();
CriteriaQuery<InstructorDto> cq = cb.createQuery(InstructorDto.class);
// prepare from expressions
Root<Instructor> root = cq.from(Instructor.class);
Join<Instructor, IdProof> insIdProofJoin = root.join(Instructor_.idProof);
Join<Instructor, Vehicle> insVehicleJoin = root.join(Instructor_.vehicles);
Join<Instructor, Student> insStudentJoin = root.join(Instructor_.students);
Join<Student, Instructor> studentInsJoin = insStudentJoin.join(Student_.instructors);
Join<Student, Vehicle> studentVehicleJoin = insStudentJoin.join(Student_.vehicles);
Join<Vehicle, Document> vehicleDocumentJoin = studentVehicleJoin.join(Vehicle_.documents);
// prepare select expressions.
CompoundSelection<InstructorDto> selection = cb.construct(InstructorDto.class, root.get(Instructor_.id),
root.get(Instructor_.name), root.get(Instructor_.fatherName), root.get(Instructor_.address),
insIdProofJoin.get(IdProof_.proofNo), insVehicleJoin.get(Vehicle_.vehicleNumber),
insVehicleJoin.get(Vehicle_.vechicleType), insStudentJoin.get(Student_.name),
insStudentJoin.get(Student_.fatherName), studentInsJoin.get(Instructor_.name),
studentVehicleJoin.get(Vehicle_.vehicleNumber), vehicleDocumentJoin.get(Document_.name));
// prepare where expressions.
Predicate instructorIdGreaterThan = cb.greaterThan(root.get(Instructor_.id), 2);
Predicate documentNameIn = cb.in(vehicleDocumentJoin.get(Document_.name)).value("1").value("2");
Predicate where = cb.and(instructorIdGreaterThan, documentNameIn);
// prepare orderBy expressions.
List<Order> orderBy = Arrays.asList(cb.asc(root.get(Instructor_.id)),
cb.asc(insIdProofJoin.get(IdProof_.proofNo)), cb.asc(insVehicleJoin.get(Vehicle_.vehicleNumber)),
cb.asc(studentInsJoin.get(Instructor_.name)), cb.asc(studentVehicleJoin.get(Vehicle_.vehicleNumber)),
cb.asc(vehicleDocumentJoin.get(Document_.name)));
// prepare query
cq.select(selection).where(where).orderBy(orderBy);
DataPrinters.listDataPrinter.accept(queryExecutor.fetchListForCriteriaQuery(cq));
}
The overriding method CAN throw any unchecked (runtime) exception, regardless of whether the overridden method declares the exception
Example:
class Super {
public void test() {
System.out.println("Super.test()");
}
}
class Sub extends Super {
@Override
public void test() throws IndexOutOfBoundsException {
// Method can throw any Unchecked Exception
System.out.println("Sub.test()");
}
}
class Sub2 extends Sub {
@Override
public void test() throws ArrayIndexOutOfBoundsException {
// Any Unchecked Exception
System.out.println("Sub2.test()");
}
}
class Sub3 extends Sub2 {
@Override
public void test() {
// Any Unchecked Exception or no exception
System.out.println("Sub3.test()");
}
}
class Sub4 extends Sub2 {
@Override
public void test() throws AssertionError {
// Unchecked Exception IS-A RuntimeException or IS-A Error
System.out.println("Sub4.test()");
}
}
To sort in ascending order :
Collections.sort(lList);
And for reverse order :
Collections.reverse(lList);
Assuming the question is about a DOMString as input and the goal is to get an Array, that when interpreted as string (e.g. written to a file on disk), would be UTF-8 encoded:
Now that nearly all modern browsers support Typed Arrays, it'd be ashamed if this approach is not listed:
.readAsArrayBuffer()
function of a File ReaderExample:
// Create a Blob with an Euro-char (U+20AC)
var b = new Blob(['€']);
var fr = new FileReader();
fr.onload = function() {
ua = new Uint8Array(fr.result);
// This will log "3|226|130|172"
// E2 82 AC
// In UTF-16, it would be only 2 bytes long
console.log(
fr.result.byteLength + '|' +
ua[0] + '|' +
ua[1] + '|' +
ua[2] + ''
);
};
fr.readAsArrayBuffer(b);
Play with that on JSFiddle. I haven't benchmarked this yet but I can imagine this being efficient for large DOMStrings as input.
Consider the following code with your current instruction pointer (the line that will be executed next, indicated by ->
) at the f(x)
line in g()
, having been called by the g(2)
line in main()
:
public class testprog {
static void f (int x) {
System.out.println ("num is " + (x+0)); // <- STEP INTO
}
static void g (int x) {
-> f(x); //
f(1); // <----------------------------------- STEP OVER
}
public static void main (String args[]) {
g(2);
g(3); // <----------------------------------- STEP OUT OF
}
}
If you were to step into at that point, you will move to the println()
line in f()
, stepping into the function call.
If you were to step over at that point, you will move to the f(1)
line in g()
, stepping over the function call.
Another useful feature of debuggers is the step out of or step return. In that case, a step return will basically run you through the current function until you go back up one level. In other words, it will step through f(x)
and f(1)
, then back out to the calling function to end up at g(3)
in main()
.
EDIT: I just realised after reading your question again, that i did not answer your question. You want to enter multiple lines in the same plot. However, I'll leave it be, because this served me very well multiple times. I hope you find usefull someday
I found this a while back when learning python
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure()
# create figure window
gs = gridspec.GridSpec(a, b)
# Creates grid 'gs' of a rows and b columns
ax = plt.subplot(gs[x, y])
# Adds subplot 'ax' in grid 'gs' at position [x,y]
ax.set_ylabel('Foo') #Add y-axis label 'Foo' to graph 'ax' (xlabel for x-axis)
fig.add_subplot(ax) #add 'ax' to figure
you can make different sizes in one figure as well, use slices in that case:
gs = gridspec.GridSpec(3, 3)
ax1 = plt.subplot(gs[0,:]) # row 0 (top) spans all(3) columns
consult the docs for more help and examples. This little bit i typed up for myself once, and is very much based/copied from the docs as well. Hope it helps... I remember it being a pain in the #$% to get acquainted with the slice notation for the different sized plots in one figure. After that i think it's very simple :)
Just append word native to your HADOOP_OPTS
like this:
export HADOOP_OPTS="$HADOOP_OPTS -Djava.library.path=$HADOOP_HOME/lib/native"
PS: Thank Searene
Just set the label
and tooltip
options like so
...
options: {
legend: {
display: false
},
tooltips: {
callbacks: {
label: function(tooltipItem) {
return tooltipItem.yLabel;
}
}
}
}
Fiddle - http://jsfiddle.net/g19220r6/
Most terse version I can think of
Len(Trim(TextBox1.Value)) = 0
If you need to do this multiple times, wrap it in a function
Public Function HasContent(text_box as Object) as Boolean
HasContent = (Len(Trim(text_box.Value)) > 0)
End Function
Usage
If HasContent(TextBox1) Then
' ...
It may be relevant to see if it's running in PHP via command line as well-
<path-to-php-binary>php -i | grep memcache
Yet another alternative is double brace initialization, e.g.
new ArrayList<String>() {{ add(s); }};
but it is inefficient and obscure. Therefore only suitable:
UPDATE: TensorFlow supports Python 3.6 on Windows since version 1.2.0 (see the release notes)
TensorFlow only supports Python 3.5 64-bit as of now. Support for Python 3.6 is a work in progress and you can track it here as well as chime in the discussion.
The only alternative to use Python 3.6 with TensorFlow on Windows currently is building TF from source.
If you don't want to uninstall your Anaconda distribution for Python 3.6 and install a previous release you can create a conda environment for Python=3.5 as in:
conda create --name tensorflow python=3.5
activate tensorflow
pip install tensorflow-gpu
The difference between two lists (say list1 and list2) can be found using the following simple function.
def diff(list1, list2):
c = set(list1).union(set(list2)) # or c = set(list1) | set(list2)
d = set(list1).intersection(set(list2)) # or d = set(list1) & set(list2)
return list(c - d)
or
def diff(list1, list2):
return list(set(list1).symmetric_difference(set(list2))) # or return list(set(list1) ^ set(list2))
By Using the above function, the difference can be found using diff(temp2, temp1)
or diff(temp1, temp2)
. Both will give the result ['Four', 'Three']
. You don't have to worry about the order of the list or which list is to be given first.
This depends upon scenarios.
Let's say you have some business functionality and you need to process something with that value further but having null
value at time of processing would impact it.
Then, in that case, you can use Optional<?>
.
String nullName = null;
String name = Optional.ofNullable(nullName)
.map(<doSomething>)
.orElse("Default value in case of null");
curl's --data
will by default send Content-Type: application/x-www-form-urlencoded
in the request header. However, when using Postman's raw
body mode, Postman sends Content-Type: text/plain
in the request header.
So to achieve the same thing as Postman, specify -H "Content-Type: text/plain"
for curl:
curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/
Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network
tab :
This is what I came up with for a gradle build script:
task doLast {
ext.FindFile = { list, curPath ->
def files = file(curPath).listFiles().sort()
files.each { File file ->
if (file.isFile()) {
list << file
}
else {
list << file // If you want the directories in the list
list = FindFile( list, file.path)
}
}
return list
}
def list = []
def theFile = FindFile(list, "${project.projectDir}")
list.each {
println it.path
}
}
The Eclipse releases are named after the moons of Jupiter, and each denotes a successive release.
Helios is the current release you can download eclipse as your programming needs http://www.eclipse.org/downloads/
In my case I had Java 7 and 8 (both x64) installed and I want to redirect to java 7 but everything is set to use Java 8. Java uses the PATH environment variable:
C:\ProgramData\Oracle\Java\javapath
as the first option to look for its folder runtime (is a hidden folder). This path contains 3 symlinks that can't be edited.
In my pc, the PATH environment variable looks like this:
C:\ProgramData\Oracle\Java\javapath;C:\Windows\System32;C:\Program Files\Java\jdk1.7.0_21\bin;
In my case, It should look like this:
C:\Windows\System32;C:\Program Files\Java\jdk1.7.0_21\bin;
I had to cut and paste the symlinks to somewhere else so java can't find them, and I can restore them later.
After setting the JAVA_HOME and JRE_HOME environment variables to the desired java folders' runtimes (in my case it is Java 7), the command java -version
should show your desired java runtime. I remark there's no need to mess with the registry.
Tested on Win7 x64.
Using the .not()
method with selecting an entire element is also an option.
This way could be usefull if you want to do another action with that element directly.
$(".thisClass").not($("#thisId")[0].doAnotherAction()).doAction();
Your local branch doensn't know about the remote branch. If you don't tell git that your local branch (master) is supposed to compare itself to the remote counterpart (origin/master in this case); then git status won't tell you the difference between your branch and the remote one. So you should use:
git branch --set-upstream-to origin/master
or with the short option:
git branch -u origin/master
This options --set-upstream-to (or -u in short) was introduced in git 1.8.0.
Once you have set this option; git status
will show you something like:
# Your branch is ahead of 'origin/master' by 1 commit.
As you can see in the Java Source of the java.lang.String class:
/**
* Allocates a new <code>String</code> that contains characters from
* a subarray of the character array argument. The <code>offset</code>
* argument is the index of the first character of the subarray and
* the <code>count</code> argument specifies the length of the
* subarray. The contents of the subarray are copied; subsequent
* modification of the character array does not affect the newly
* created string.
*
* @param value array that is the source of characters.
* @param offset the initial offset.
* @param count the length.
* @exception IndexOutOfBoundsException if the <code>offset</code>
* and <code>count</code> arguments index characters outside
* the bounds of the <code>value</code> array.
*/
public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.value = new char[count];
this.count = count;
System.arraycopy(value, offset, this.value, 0, count);
}
Parameter references are surrounded by <code></code>
tags, which means that the Javadoc syntax does not provide any way to do such a thing. (I think String.class is a good example of javadoc usage).
Solution that work on IE10: (I needed a csv file, but it's enough to change type and filename to txt)
var csvContent=data; //here we load our csv data
var blob = new Blob([csvContent],{
type: "text/csv;charset=utf-8;"
});
navigator.msSaveBlob(blob, "filename.csv")
Here's what I think is a better method:
public int getYearsBetweenDates(Date first, Date second) {
Calendar firstCal = GregorianCalendar.getInstance();
Calendar secondCal = GregorianCalendar.getInstance();
firstCal.setTime(first);
secondCal.setTime(second);
secondCal.add(Calendar.DAY_OF_YEAR, 1 - firstCal.get(Calendar.DAY_OF_YEAR));
return secondCal.get(Calendar.YEAR) - firstCal.get(Calendar.YEAR);
}
EDIT
Apart from a bug which I fixed, this method does not work well with leap years. Here's a complete test suite. I guess you're better off using the accepted answer.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
class YearsBetweenDates {
public static int getYearsBetweenDates(Date first, Date second) {
Calendar firstCal = GregorianCalendar.getInstance();
Calendar secondCal = GregorianCalendar.getInstance();
firstCal.setTime(first);
secondCal.setTime(second);
secondCal.add(Calendar.DAY_OF_YEAR, 1 - firstCal.get(Calendar.DAY_OF_YEAR));
return secondCal.get(Calendar.YEAR) - firstCal.get(Calendar.YEAR);
}
private static class TestCase {
public Calendar date1;
public Calendar date2;
public int expectedYearDiff;
public String comment;
public TestCase(Calendar date1, Calendar date2, int expectedYearDiff, String comment) {
this.date1 = date1;
this.date2 = date2;
this.expectedYearDiff = expectedYearDiff;
this.comment = comment;
}
}
private static TestCase[] tests = {
new TestCase(
new GregorianCalendar(2014, Calendar.JULY, 15),
new GregorianCalendar(2015, Calendar.JULY, 15),
1,
"exactly one year"),
new TestCase(
new GregorianCalendar(2014, Calendar.JULY, 15),
new GregorianCalendar(2017, Calendar.JULY, 14),
2,
"one day less than 3 years"),
new TestCase(
new GregorianCalendar(2015, Calendar.NOVEMBER, 3),
new GregorianCalendar(2017, Calendar.MAY, 3),
1,
"a year and a half"),
new TestCase(
new GregorianCalendar(2016, Calendar.JULY, 15),
new GregorianCalendar(2017, Calendar.JULY, 15),
1,
"leap years do not compare correctly"),
};
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
for (TestCase t : tests) {
int diff = getYearsBetweenDates(t.date1.getTime(), t.date2.getTime());
String result = diff == t.expectedYearDiff ? "PASS" : "FAIL";
System.out.println(t.comment + ": " +
df.format(t.date1.getTime()) + " -> " +
df.format(t.date2.getTime()) + " = " +
diff + ": " + result);
}
}
}
Using numpy version 1.10.4 and pandas version 0.17.1,
dates = np.array(['2010-10-17', '2011-05-13', '2012-01-15'], dtype=np.datetime64)
pd.to_datetime(dates).year
I get what you're looking for:
array([2010, 2011, 2012], dtype=int32)
As long as you override equals()
on each key and value contained in the map, then m1.equals(m2)
should be reliable to check for maps equality.
The same result can be obtained also by comparing toString()
of each map as you suggested, but using equals()
is a more intuitive approach.
May not be your specific situation, but if you store arrays in the map, may be a little tricky, because they must be compared value by value, or using Arrays.equals()
. More details about this see here.
Given this file:
$ cat words.txt
line1 word1 word2
line2 word3 word4
line3 word5 word6
If you just want one word at a time (ignoring the meaning of spaces vs line breaks in the file):
with open('words.txt','r') as f:
for line in f:
for word in line.split():
print(word)
Prints:
line1
word1
word2
line2
...
word6
Similarly, if you want to flatten the file into a single flat list of words in the file, you might do something like this:
with open('words.txt') as f:
flat_list=[word for line in f for word in line.split()]
>>> flat_list
['line1', 'word1', 'word2', 'line2', 'word3', 'word4', 'line3', 'word5', 'word6']
Which can create the same output as the first example with print '\n'.join(flat_list)
...
Or, if you want a nested list of the words in each line of the file (for example, to create a matrix of rows and columns from a file):
with open('words.txt') as f:
matrix=[line.split() for line in f]
>>> matrix
[['line1', 'word1', 'word2'], ['line2', 'word3', 'word4'], ['line3', 'word5', 'word6']]
If you want a regex solution, which would allow you to filter wordN
vs lineN
type words in the example file:
import re
with open("words.txt") as f:
for line in f:
for word in re.findall(r'\bword\d+', line):
# wordN by wordN with no lineN
Or, if you want that to be a line by line generator with a regex:
with open("words.txt") as f:
(word for line in f for word in re.findall(r'\w+', line))
As mentioned in a previous reply, this generally comes when compiling copy pasted code. If you have a bash shell, the following command generally works:
iconv -f utf-8 -t ascii//translit input.c > output.c
When I want to access the application file version (what is set in Assembly Information -> File version), say to set a label's text to it on form load to display the version, I have just used
versionlabel.Text = "Version " + Application.ProductVersion;
This approach requires a reference to System.Windows.Forms
.
You can do this using Input.setSelectionRange
, part of the Range API for interacting with text selections and the text cursor:
var searchInput = $('#Search');
// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;
searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);
Demo: Fiddle
576 is the minimum maximum reassembly buffer size, i.e. each implementation must be able to reassemble packets of at least that size. See IETF RFC 1122 for details.
you can just use GNU find.
find . -printf "%m:%f\n"
From Python 2.5 onwards you can do:
value = b if a > 10 else c
Previously you would have to do something like the following, although the semantics isn't identical as the short circuiting effect is lost:
value = [c, b][a > 10]
There's also another hack using 'and ... or' but it's best to not use it as it has an undesirable behaviour in some situations that can lead to a hard to find bug. I won't even write the hack here as I think it's best not to use it, but you can read about it on Wikipedia if you want.
I don't know TeamCity so I hope this can work for you.
The best way I've found to do this is with MSDeploy.exe. This is part of the WebDeploy project run by Microsoft. You can download the bits here.
With WebDeploy, you run the command line
msdeploy.exe -verb:sync -source:contentPath=c:\webApp -dest:contentPath=c:\DeployedWebApp
This does the same thing as the VS Publish command, copying only the necessary bits to the deployment folder.
Awesome tutorial: 3 Different Ways to Display Progress in an ASP.NET AJAX Application
I found the answer, For those who are looking for the same thing here is how I did it. You should not consider uploading images to the database instead you can store the name of the uploaded file in your database and then retrieve the file name and use it where ever you want to display the image.
HTML CODE
<input type="file" name="imageUpload" id="imageUpload">
PHP CODE
if(isset($_POST['submit'])) {
//Process the image that is uploaded by the user
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
$image=basename( $_FILES["imageUpload"]["name"],".jpg"); // used to store the filename in a variable
//storind the data in your database
$query= "INSERT INTO items VALUES ('$id','$title','$description','$price','$value','$contact','$image')";
mysql_query($query);
require('heading.php');
echo "Your add has been submited, you will be redirected to your account page in 3 seconds....";
header( "Refresh:3; url=account.php", true, 303);
}
CODE TO DISPLAY THE IMAGE
while($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td><img src='uploads/$row[6].jpg' height='150px' width='300px'></td>";
echo "</tr>\n";
}
Try this, usually works for me:
app.set('appPath', 'public');
app.use(express.static(__dirname +'/public'));
app.route('/*')
.get(function(req, res) {
res.sendfile(app.get('appPath') + '/index.html');
});
Where the directory public contains my index.html and references all my angular files in the folder bower_components.
The express.static portion I believe serves the static files correctly (.js and css files as referenced by your index.html). Judging by your code, you will probably need to use this line instead:
app.use(express.static(__dirname));
as it seems all your JS files, index.html and your JS server file are in the same directory.
I think what @T.J. Crowder was trying to say was use app.route to send different files other than index.html, as just using index.html will have your program just look for .html files and cause the JS error.
Hope this works!
If you're writing a Chrome Extension and get this error, then be sure you have added the API's base URL to your manifest.json
's permissions block, example:
"permissions": [
"https://itunes.apple.com/"
]
I simply declared as below in web.xml file and Its working for me :
<welcome-file-list>
<welcome-file>/WEB-INF/jsps/index.jsp</welcome-file>
</welcome-file-list>
And NO html/jsp pages present in public directory except static resources(css, js, images). Now I can access my index page with URL like : http://localhost:8080/app/ Its calling /WEB-INF/jsps/index.jsp page. When hosted live in production the final URL looks like https://eisdigital.com/
Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this. http://technet.microsoft.com/en-us/library/ee176949.aspx
Set-ExecutionPolicy RemoteSigned
Run this python script on your powershell script helloworld.py
:
# -*- coding: iso-8859-1 -*-
import subprocess, sys
p = subprocess.Popen(["powershell.exe",
"C:\\Users\\USER\\Desktop\\helloworld.ps1"],
stdout=sys.stdout)
p.communicate()
This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.
C:\Users\MacEwin\Desktop>python helloworld.py
Hello World
A slightly more general solution based on join
, that works even for pandas.Timestamp
:
print("\n".join(map(str, my_list)))
Use the below code in your rounded_edittext.xml :
<?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:thickness="0dp"
android:shape="rectangle">
<stroke android:width="2dp"
android:color="#2F6699"/>
<corners android:radius="3dp" />
<gradient android:startColor="#C8C8C8"
android:endColor="#FFFFFF"
android:type="linear"
android:angle="270"/>
</shape>
controller:
use App\your_model_name;
funtion index()
{
$post = your_model_name::all();
return view('index')->with('this_will_be_used_as_variable_in_views',$post);
}
index:
<h1> posts</h1>
@if(count($this_will_be_used_as_variable_in_views)>0)
@foreach($this_will_be_used_as_variable_in_views as $any_variable)
<ul>
<p> {{$any_variable->enter_table_field}} </p>
<p> {{$any_variable->created_at}} </p>
</ul>
@endforeach
@else
<p> empty </p>
@endif
Hope this helps! :)
Here is another simple answer, but without using classes.
from tkinter import *
def raise_frame(frame):
frame.tkraise()
root = Tk()
f1 = Frame(root)
f2 = Frame(root)
f3 = Frame(root)
f4 = Frame(root)
for frame in (f1, f2, f3, f4):
frame.grid(row=0, column=0, sticky='news')
Button(f1, text='Go to frame 2', command=lambda:raise_frame(f2)).pack()
Label(f1, text='FRAME 1').pack()
Label(f2, text='FRAME 2').pack()
Button(f2, text='Go to frame 3', command=lambda:raise_frame(f3)).pack()
Label(f3, text='FRAME 3').pack(side='left')
Button(f3, text='Go to frame 4', command=lambda:raise_frame(f4)).pack(side='left')
Label(f4, text='FRAME 4').pack()
Button(f4, text='Goto to frame 1', command=lambda:raise_frame(f1)).pack()
raise_frame(f1)
root.mainloop()
I know this is a very old question, but I googled my way here and found the answer provided not 100% satisfying, because as gcl1 mentioned - this way the footer is not really a footer to the screen - it's just an "add-on" to the list.
Bottom line - for others who may google their way here - I found the following suggestion here: Fixed and always visible footer below ListFragment
Try doing as follows, where the emphasis is on the button (or any footer element) listed first in the XML - and then the list is added as "layout_above":
<RelativeLayout>
<Button android:id="@+id/footer" android:layout_alignParentBottom="true"/>
<ListView android:id="@android:id/list" **android:layout_above**="@id/footer"> <!-- the list -->
</RelativeLayout>
From memory, you call stringstream::str()
to get the std::string
value out.
It is just to initialize the instance's variables.
E.g. create a crawler
instance with a specific database name (from your example above).
There are two obvious choices: Joshua Ulrich's df[,c("A","B","E")]
or
df[,c(1,2,5)]
as in
> df <- data.frame(A=c(1,2),B=c(3,4),C=c(5,6),D=c(7,7),E=c(8,8),F=c(9,9))
> df
A B C D E F
1 1 3 5 7 8 9
2 2 4 6 7 8 9
> df[,c(1,2,5)]
A B E
1 1 3 8
2 2 4 8
> df[,c("A","B","E")]
A B E
1 1 3 8
2 2 4 8
This will work for MYSQL
SELECT Name FROM Employees WHERE Name REGEXP '^[B].*$'
In this REGEXP stands for regular expression
and
this is for T-SQL
SELECT Name FROM Employees WHERE Name LIKE '[B]%'
To get this:
Stick this in a user control:
<UserControl.Resources>
<Color x:Key="FilledColor" A="255" B="155" R="155" G="155"/>
<Color x:Key="UnfilledColor" A="0" B="155" R="155" G="155"/>
<Style x:Key="BusyAnimationStyle" TargetType="Control">
<Setter Property="Background" Value="#7F000000"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Control">
<ControlTemplate.Resources>
<Storyboard x:Key="Animation0" BeginTime="00:00:00.0" RepeatBehavior="Forever">
<ColorAnimationUsingKeyFrames Storyboard.TargetName="ellipse0" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)">
<SplineColorKeyFrame KeyTime="00:00:00.0" Value="{StaticResource FilledColor}"/>
<SplineColorKeyFrame KeyTime="00:00:01.6" Value="{StaticResource UnfilledColor}"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Key="Animation1" BeginTime="00:00:00.2" RepeatBehavior="Forever">
<ColorAnimationUsingKeyFrames Storyboard.TargetName="ellipse1" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)">
<SplineColorKeyFrame KeyTime="00:00:00.0" Value="{StaticResource FilledColor}"/>
<SplineColorKeyFrame KeyTime="00:00:01.6" Value="{StaticResource UnfilledColor}"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Key="Animation2" BeginTime="00:00:00.4" RepeatBehavior="Forever">
<ColorAnimationUsingKeyFrames Storyboard.TargetName="ellipse2" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)">
<SplineColorKeyFrame KeyTime="00:00:00.0" Value="{StaticResource FilledColor}"/>
<SplineColorKeyFrame KeyTime="00:00:01.6" Value="{StaticResource UnfilledColor}"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Key="Animation3" BeginTime="00:00:00.6" RepeatBehavior="Forever">
<ColorAnimationUsingKeyFrames Storyboard.TargetName="ellipse3" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)">
<SplineColorKeyFrame KeyTime="00:00:00.0" Value="{StaticResource FilledColor}"/>
<SplineColorKeyFrame KeyTime="00:00:01.6" Value="{StaticResource UnfilledColor}"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Key="Animation4" BeginTime="00:00:00.8" RepeatBehavior="Forever">
<ColorAnimationUsingKeyFrames Storyboard.TargetName="ellipse4" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)">
<SplineColorKeyFrame KeyTime="00:00:00.0" Value="{StaticResource FilledColor}"/>
<SplineColorKeyFrame KeyTime="00:00:01.6" Value="{StaticResource UnfilledColor}"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Key="Animation5" BeginTime="00:00:01.0" RepeatBehavior="Forever">
<ColorAnimationUsingKeyFrames Storyboard.TargetName="ellipse5" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)">
<SplineColorKeyFrame KeyTime="00:00:00.0" Value="{StaticResource FilledColor}"/>
<SplineColorKeyFrame KeyTime="00:00:01.6" Value="{StaticResource UnfilledColor}"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Key="Animation6" BeginTime="00:00:01.2" RepeatBehavior="Forever">
<ColorAnimationUsingKeyFrames Storyboard.TargetName="ellipse6" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)">
<SplineColorKeyFrame KeyTime="00:00:00.0" Value="{StaticResource FilledColor}"/>
<SplineColorKeyFrame KeyTime="00:00:01.6" Value="{StaticResource UnfilledColor}"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Key="Animation7" BeginTime="00:00:01.4" RepeatBehavior="Forever">
<ColorAnimationUsingKeyFrames Storyboard.TargetName="ellipse7" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)">
<SplineColorKeyFrame KeyTime="00:00:00.0" Value="{StaticResource FilledColor}"/>
<SplineColorKeyFrame KeyTime="00:00:01.6" Value="{StaticResource UnfilledColor}"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</ControlTemplate.Resources>
<ControlTemplate.Triggers>
<Trigger Property="IsVisible" Value="True">
<Trigger.EnterActions>
<BeginStoryboard Storyboard="{StaticResource Animation0}" x:Name="Storyboard0" />
<BeginStoryboard Storyboard="{StaticResource Animation1}" x:Name="Storyboard1"/>
<BeginStoryboard Storyboard="{StaticResource Animation2}" x:Name="Storyboard2"/>
<BeginStoryboard Storyboard="{StaticResource Animation3}" x:Name="Storyboard3"/>
<BeginStoryboard Storyboard="{StaticResource Animation4}" x:Name="Storyboard4"/>
<BeginStoryboard Storyboard="{StaticResource Animation5}" x:Name="Storyboard5"/>
<BeginStoryboard Storyboard="{StaticResource Animation6}" x:Name="Storyboard6"/>
<BeginStoryboard Storyboard="{StaticResource Animation7}" x:Name="Storyboard7"/>
</Trigger.EnterActions>
<Trigger.ExitActions>
<StopStoryboard BeginStoryboardName="Storyboard0"/>
<StopStoryboard BeginStoryboardName="Storyboard1"/>
<StopStoryboard BeginStoryboardName="Storyboard2"/>
<StopStoryboard BeginStoryboardName="Storyboard3"/>
<StopStoryboard BeginStoryboardName="Storyboard4"/>
<StopStoryboard BeginStoryboardName="Storyboard5"/>
<StopStoryboard BeginStoryboardName="Storyboard6"/>
<StopStoryboard BeginStoryboardName="Storyboard7"/>
</Trigger.ExitActions>
</Trigger>
</ControlTemplate.Triggers>
<Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}">
<Grid>
<Canvas Height="60" Width="60">
<Canvas.Resources>
<Style TargetType="Ellipse">
<Setter Property="Width" Value="15"/>
<Setter Property="Height" Value="15" />
<Setter Property="Fill" Value="#009B9B9B" />
</Style>
</Canvas.Resources>
<Ellipse x:Name="ellipse0" Canvas.Left="1.75" Canvas.Top="21"/>
<Ellipse x:Name="ellipse1" Canvas.Top="7" Canvas.Left="6.5"/>
<Ellipse x:Name="ellipse2" Canvas.Left="20.5" Canvas.Top="0.75"/>
<Ellipse x:Name="ellipse3" Canvas.Left="34.75" Canvas.Top="6.75"/>
<Ellipse x:Name="ellipse4" Canvas.Left="40.5" Canvas.Top="20.75" />
<Ellipse x:Name="ellipse5" Canvas.Left="34.75" Canvas.Top="34.5"/>
<Ellipse x:Name="ellipse6" Canvas.Left="20.75" Canvas.Top="39.75"/>
<Ellipse x:Name="ellipse7" Canvas.Top="34.25" Canvas.Left="7" />
<Ellipse Width="39.5" Height="39.5" Canvas.Left="8.75" Canvas.Top="8" Visibility="Hidden"/>
</Canvas>
<Label Content="{Binding Path=Text}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Control Style="{StaticResource BusyAnimationStyle}"/>
To get a cool disappearing effect on each ellipse add the following after each ColorAnimationUsingKeyFrames
element. Be sure to point it to the correct ellipse..
<ColorAnimationUsingKeyFrames Storyboard.TargetName="ellipse0" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)">
<SplineColorKeyFrame KeyTime="00:00:00.0" Value="{StaticResource FilledColor}"/>
<SplineColorKeyFrame KeyTime="00:00:01.6" Value="{StaticResource UnfilledColor}"/>
</ColorAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.TargetName="ellipse0" Storyboard.TargetProperty="Width" >
<DoubleAnimationUsingKeyFrames.KeyFrames>
<SplineDoubleKeyFrame KeyTime="00:00:00.0" Value="15" />
<SplineDoubleKeyFrame KeyTime="00:00:01.0" Value="12" />
<SplineDoubleKeyFrame KeyTime="00:00:01.6" Value="0" />
</DoubleAnimationUsingKeyFrames.KeyFrames>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.TargetName="ellipse0" Storyboard.TargetProperty="Height" >
<DoubleAnimationUsingKeyFrames.KeyFrames>
<SplineDoubleKeyFrame KeyTime="00:00:00.0" Value="15" />
<SplineDoubleKeyFrame KeyTime="00:00:01.0" Value="12" />
<SplineDoubleKeyFrame KeyTime="00:00:01.6" Value="0" />
</DoubleAnimationUsingKeyFrames.KeyFrames>
</DoubleAnimationUsingKeyFrames>
I think style no. 111 (Japan) should work:
SELECT CONVERT(DATETIME, '2012-08-17', 111)
And if that doesn't work for some reason - you could always just strip out the dashes and then you have the totally reliable ISO-8601 format (YYYYMMDD
) which works for any language and date format setting in SQL Server:
SELECT CAST(REPLACE('2012-08-17', '-', '') AS DATETIME)
If you try to check angular version in the browser, for me only this worked Ctrl+Shift+i and paste below command in console:
document.querySelector('[ng-version]').getAttribute('ng-version')
ex:
This is what I achieved, but had to set width, and it cannot be percentual.
.trunc{_x000D_
width:250px; _x000D_
white-space: nowrap; _x000D_
overflow: hidden; _x000D_
text-overflow: ellipsis;_x000D_
}_x000D_
table tr td {_x000D_
padding: 5px_x000D_
}_x000D_
table tr td {_x000D_
background: salmon_x000D_
}_x000D_
table tr td:first-child {_x000D_
background: lightsalmon_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<table>_x000D_
_x000D_
<tr>_x000D_
<td>Quisque dignissim ante in tincidunt gravida. Maecenas lectus turpis</td>_x000D_
<td>_x000D_
<div class="trunc">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
or this: http://collaboradev.com/2015/03/28/responsive-css-truncate-and-ellipsis/
As it is written before, some folders (/META-INF/resources/, /resources/, /static/, /public/) serve static content by default, conroller misconfiguration can break this behaviour.
It is a common pitfall that people define the base url of a controller in the @RestController
annotation, instead of the @RequestMapping
annotation on the top of the controllers.
This is wrong:
@RestController("/api/base")
public class MyController {
@PostMapping
public String myPostMethod( ...) {
The above example will prevent you from opening the index.html. The Spring expects a POST method at the root, because the myPostMethod
is mapped to the "/" path.
You have to use this instead:
@RestController
@RequestMapping("/api/base")
public class MyController {
@PostMapping
public String myPostMethod( ...) {
Create a URI like this one:
https://maps.google.com/?q=[lat],[long]
For example:
https://maps.google.com/?q=-37.866963,144.980615
or, if you are using the javascript API
map.setCenter(new GLatLng(0,0))
This, and other helpful info comes from here:
https://developers.google.com/maps/documentation/javascript/reference/?csw=1#Map
Difference between STATIC MEMORY ALLOCATION & DYNAMIC MEMORY ALLOCATION
Memory is allocated before the execution of the program begins
(During Compilation).
Memory is allocated during the execution of the program.
No memory allocation or deallocation actions are performed during Execution.
Memory Bindings are established and destroyed during the Execution.
Variables remain permanently allocated.
Allocated only when program unit is active.
Implemented using stacks and heaps.
Implemented using data segments.
Pointer is needed to accessing variables.
No need of Dynamically allocated pointers.
Faster execution than Dynamic.
Slower execution than static.
More memory Space required.
Less Memory space required.
UPDATE `table` SET table_column='test';
Chrome 36.0.1985.125 WEDNESDAY, JULY 16, 2014 Release note
From my observation, this update fixed the issue on using window.close()
to close the popup window. You will see this in the console when it fail, "Scripts may close only the windows that were opened by it.". That means The hacky workarounds (Brock Adams's answer) may not work in the latest release.
So, in the previous Chrome released builds, the below code block may worked but not with this update.
window.open('', '_self', '');
window.close();
For this update, you have to update your code accordingly to close the popup window. One of the solution is to grab the popup window id and use
chrome.windows.remove(integer windowId, function callback)
method to remove it. Chrome extension windows API can be found at chrome.windows.
Actually my chrome extension MarkView was facing this issue and I had to update my code to make it work for this Chrome Update. By the way, MarkView is tool to read and write Awesome Markdown Files, it provides features including Content Outline, Sortable Tables and code block syntax highlight with line number.
I also created this post, any comments are welcome.
Use jsbeautifier instead of trying to do it manually.
The first path in the path variable needs to be the NPM path. Opening the Node.js command prompt I found that the ng command worked there. I dug into the shortcut and found that it references a command to ensure the first Path variable is NPM. To Fix:
%AppData%\npm
Once I did that I was able to close powershell and reopen and all worked.
So the package will be downloaded in a temp folder C:\Users\U122337.BOSTONADVISORS\AppData\Local\Temp\Rtmp404t8Y\downloaded_packages from where it will be installed into your library folder, e.g. C:\R\library\zoo
What you have to do once install command is done: Open Packages menu -> Load package...
You will see your package on the list. You can automate this: How to load packages in R automatically?
You can change the style applied to each activity, or if you only want to change the behavior for a specific activity, you can try this:
setDisplayOptions(int options, int mask) --- Set selected display
or
setDisplayOptions(int options) --- Set display options.
To display title on actionbar, set display options in onCreate()
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE, ActionBar.DISPLAY_SHOW_TITLE);
To hide title on actionbar.
getSupportActionBar().setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
Details here.
No matter what we tried we couldn't manage to get the timeout below 21 seconds when the server we were checking was down.
To work around this we combined a TcpClient check to see if the domain was alive followed by a separate check to see if the URL was active
public static bool IsUrlAlive(string aUrl, int aTimeoutSeconds)
{
try
{
//check the domain first
if (IsDomainAlive(new Uri(aUrl).Host, aTimeoutSeconds))
{
//only now check the url itself
var request = System.Net.WebRequest.Create(aUrl);
request.Method = "HEAD";
request.Timeout = aTimeoutSeconds * 1000;
var response = (HttpWebResponse)request.GetResponse();
return response.StatusCode == HttpStatusCode.OK;
}
}
catch
{
}
return false;
}
private static bool IsDomainAlive(string aDomain, int aTimeoutSeconds)
{
try
{
using (TcpClient client = new TcpClient())
{
var result = client.BeginConnect(aDomain, 80, null, null);
var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(aTimeoutSeconds));
if (!success)
{
return false;
}
// we have connected
client.EndConnect(result);
return true;
}
}
catch
{
}
return false;
}
In my case my request object inherited from base object. Without knowingly I added a property with int? in my request object and my base object also has same property ( same name ) with int datatype. I noticed this and deleted the property which I added in request object and after that it worked fine.
This worked for me. Repeatedly calls a function updating the graph every time.
import matplotlib.pyplot as plt
import matplotlib.animation as anim
def plot_cont(fun, xmax):
y = []
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
def update(i):
yi = fun()
y.append(yi)
x = range(len(y))
ax.clear()
ax.plot(x, y)
print i, ': ', yi
a = anim.FuncAnimation(fig, update, frames=xmax, repeat=False)
plt.show()
"fun" is a function that returns an integer. FuncAnimation will repeatedly call "update", it will do that "xmax" times.
I tend to disagree with the idea of using new "too much". Though the original poster's use of new with system classes is a bit ridiculous. (int *i; i = new int[9999];
? really? int i[9999];
is much clearer.) I think that is what was getting the commenter's goat.
When you're working with system objects, it's very rare that you'd need more than one reference to the exact same object. As long as the value is the same, that's all that matters. And system objects don't typically take up much space in memory. (one byte per character, in a string). And if they do, the libraries should be designed to take that memory management into account (if they're written well). In these cases, (all but one or two of the news in his code), new is practically pointless and only serves to introduce confusions and potential for bugs.
When you're working with your own classes/objects, however (e.g. the original poster's Line class), then you have to begin thinking about the issues like memory footprint, persistence of data, etc. yourself. At this point, allowing multiple references to the same value is invaluable - it allows for constructs like linked lists, dictionaries, and graphs, where multiple variables need to not only have the same value, but reference the exact same object in memory. However, the Line class doesn't have any of those requirements. So the original poster's code actually has absolutely no needs for new
.
This is normally a file access permissions issue but I see your already addressing that in point b, but it's worth going over just in case. Another option is to use LOAD DATA LOCAL INFILE which gets past a lot of these issues of file access permissions. To use this method though you need to copy the file locally (in the mysql folder is best) first. •If LOCAL is specified, the file is read by the client program on the client host and sent to the server.
Insufficient Directory Permissions
The error in this example has resulted because the file you are trying to import is not in a directory which is readable by the user the MySql server is running as. Note that all the parent directories of the directory the is in need to be readable by the MySql user for this to work. Saving the file to /tmp will usually work as this is usually readable (and writable) by all users. The error code number is 13. Source
EDIT:
Remember you will need permissions on not just the folder the holds the file but also the upper directories.
Example from this post on the MySql Forums.
If your file was contained within the following strucutre: /tmp/imports/site1/data.file
you would need (I think, 755 worked) r+x for 'other' on these directories:
/tmp
/tmp/imports
As well as the main two:
/tmp/imports/site1
/tmp/imports/site1/data.file
You need the file and directory to be world-readable. Apologies if you've already tried this method but it may be worth retracing your steps, never hurts to double check.
There is no benefit to using new Object();
- whereas {};
can make your code more compact, and more readable.
For defining empty objects they're technically the same. The {}
syntax is shorter, neater (less Java-ish), and allows you to instantly populate the object inline - like so:
var myObject = {
title: 'Frog',
url: '/img/picture.jpg',
width: 300,
height: 200
};
For arrays, there's similarly almost no benefit to ever using new Array();
over [];
- with one minor exception:
var emptyArray = new Array(100);
creates a 100 item long array with all slots containing undefined
- which may be nice/useful in certain situations (such as (new Array(9)).join('Na-Na ') + 'Batman!'
).
new Object();
- it's clunkier than {};
and looks silly.[];
- except when you need to quickly create an "empty" array with a predefined length.As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.
This is some pseudocodish JavaScript:
Client:
var websocket = new WebSocket("server address");
websocket.onmessage = function(str) {
console.log("Someone sent: ", str);
};
// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
id: "client1"
}));
// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
to: "client2",
data: "foo"
}));
Server:
var clients = {};
server.on("data", function(client, str) {
var obj = JSON.parse(str);
if("id" in obj) {
// New client, add it to the id/client object
clients[obj.id] = client;
} else {
// Send data to the client requested
clients[obj.to].send(obj.data);
}
});
ERRORLEVEL
will contain the return code of the last command. Sadly you can only check >=
for it.
Note specifically this line in the MSDN documentation for the If
statement:
errorlevel Number
Specifies a true condition only if the previous program run by Cmd.exe returned an exit code equal to or greater than Number.
So to check for 0 you need to think outside the box:
IF ERRORLEVEL 1 GOTO errorHandling
REM no error here, errolevel == 0
:errorHandling
Or if you want to code error handling first:
IF NOT ERRORLEVEL 1 GOTO no_error
REM errorhandling, errorlevel >= 1
:no_error
Further information about BAT programming: http://www.ericphelps.com/batch/
Or more specific for Windows cmd
: MSDN using batch files
Unity is an IoC. The point of IoC is to abstract the wiring of dependencies between types outside of the types themselves. This has a couple of advantages. First of all, it is done centrally which means you don't have to change a lot of code when dependencies change (which may be the case for unit tests).
Furthermore, if the wiring is done using configuration data instead of code, you can actually rewire the dependencies after deployment and thus change the behavior of the application without changing the code.
It looks like some space include in the text. Use
lvTwoOrMoreOptions.SelectedItems[0].Text.ToString().Trim()
and convert to int32.
hope this code will solve you
From comments
if your ListView is in report mode (i.e. it looks like a grid) then you will need the SubItems property. lvTwoOrMoreOptions.SelectedItems
gets you each items in the list view - SubItems gets you the columns. So lvTwoOrMoreOptions.SelectedItems[0].SubItems[0]
is the first column value,
You can do the same in insider's edition, There is an option on right top corner to switch to the panel to sidebar https://code.visualstudio.com/insiders/
Simply:
pop: returns the item at the top then remove it from the stack
push: add an item onto the top of the stack.
Here goes the explanation. Look at the picture ->
By calling Movetower(3,a,b,c)
, you intend to move all the 3 discs from tower A
to tower B
. So the sequential calls are ->
1. Movetower(3,a,b,c) // No Move needed
2. Movetower(2,a,c,b) // No move needed
3. Movetower(1,a,b,c) // Here is the time to move, move disc1 from a to b
4. Movetower(2,a,c,b) // Returning to this call again, this is the time to move disc2 from a to c
5. Movetower(1,b,c,a) // Again the time to move, this time disc1 from b to c
6. Movetower(3,a,b,c) // Returning to this call again, this is the time to move disc3 from a to b
7. Movetower(2,c,b,a) // Not the time to move
8. Movetower(1,c,a,b) // Here is the time to move, move disc1 from c to a
9. Movetower(2,c,b,a) // Returning to this call again, this is the time to move disc2 from c to b
10.Movetower(1,c,a,b) // Here is the time to move, move disc1 from a to b
Hope it helps :)
For Animation : https://www.cs.cmu.edu/~cburch/survey/recurse/hanoiex.html
we have to create your own docker volume mapped with the host directory before we mention in the docker-compose.yml as external
1.Create volume named share
docker volume create --driver local \
--opt type=none \
--opt device=/home/mukundhan/share \
--opt o=bind share
2.Use it in your docker-compose
version: "3"
volumes:
share:
external: true
services:
workstation:
container_name: "workstation"
image: "ubuntu"
stdin_open: true
tty: true
volumes:
- share:/share:consistent
- ./source:/source:consistent
working_dir: /source
ipc: host
privileged: true
shm_size: '2gb'
db:
container_name: "db"
image: "ubuntu"
stdin_open: true
tty: true
volumes:
- share:/share:consistent
working_dir: /source
ipc: host
This way we can share the same directory with many services running in different containers
You can use dtype=np.int64
instead of dtype=int
So long as Excel can open the file, the functionality to change the format of the opened file is built in.
To convert an .html file, open it using Excel (File - Open) and then save it as a .xlsx file from Excel (File - Save as).
To do it using VBA, the code would look like this:
Sub Open_HTML_Save_XLSX()
Workbooks.Open Filename:="C:\Temp\Example.html"
ActiveWorkbook.SaveAs Filename:= _
"C:\Temp\Example.xlsx", FileFormat:= _
xlOpenXMLWorkbook
End Sub
I would do something like this:
Select count(*), productid
from products
where keyword = '$keyword'
group by productid
that will give you a list like
count(*) productid
----------------------
5 12345
3 93884
9 93493
This allows you to see how many of each distinct productid ID is associated with the keyword.
If you have ids in both tables, the following works:
update table2
set value = (select value from table1 where table1.id = table2.id)
Perhaps a better approach is a join:
update table2
set value = table1.value
from table1
where table1.id = table2.id
Note that this syntax works in SQL Server but may be different in other databases.
Create a file called gradle.properties
inside the project folder where the build.gradle
file is present. Add the following entry
systemProp.http.proxyHost=proxy_url
systemProp.http.proxyPort=proxy_port
systemProp.http.proxyUser=USER
systemProp.http.proxyPassword=PWD
systemProp.https.proxyHost=proxy_url
systemProp.https.proxyPort=proxy_port
systemProp.https.proxyUser=USER
systemProp.https.proxyPassword=PWD
If you are using DNS for proxy then add it like systemProp.https.proxyHost=www.proxysite.com
For IP just specify the IP with out http://
or https://
Check gradle official doc for more details and setting up proxy at global level
function relativepath($to){
$a=explode("/",$_SERVER["PHP_SELF"] );
$index= array_search("$to",$a);
$str="";
for ($i = 0; $i < count($a)-$index-2; $i++) {
$str.= "../";
}
return $str;
}
Here is the best solution i made about that, you just need to specify at which level you want to stop, but the problem is that you have to use this folder name one time.
You are supposed to check the mutex variable before using the area protected by the mutex. So your pthread_mutex_lock() could (depending on implementation) wait until mutex1 is released or return a value indicating that the lock could not be obtained if someone else has already locked it.
Mutex is really just a simplified semaphore. If you read about them and understand them, you understand mutexes. There are several questions regarding mutexes and semaphores in SO. Difference between binary semaphore and mutex, When should we use mutex and when should we use semaphore and so on. The toilet example in the first link is about as good an example as one can think of. All code does is to check if the key is available and if it is, reserves it. Notice that you don't really reserve the toilet itself, but the key.
Let assume i am having a RestController
with GET/POST/PUT/DELETE
operations and i have to write unit test using spring boot.I will just share code of RestController class and respective unit test.Wont be sharing any other related code to the controller ,can have assumption on that.
@RestController
@RequestMapping(value = “/myapi/myApp” , produces = {"application/json"})
public class AppController {
@Autowired
private AppService service;
@GetMapping
public MyAppResponse<AppEntity> get() throws Exception {
MyAppResponse<AppEntity> response = new MyAppResponse<AppEntity>();
service.getApp().stream().forEach(x -> response.addData(x));
return response;
}
@PostMapping
public ResponseEntity<HttpStatus> create(@RequestBody AppRequest request) throws Exception {
//Validation code
service.createApp(request);
return ResponseEntity.ok(HttpStatus.OK);
}
@PutMapping
public ResponseEntity<HttpStatus> update(@RequestBody IDMSRequest request) throws Exception {
//Validation code
service.updateApp(request);
return ResponseEntity.ok(HttpStatus.OK);
}
@DeleteMapping
public ResponseEntity<HttpStatus> delete(@RequestBody AppRequest request) throws Exception {
//Validation
service.deleteApp(request.id);
return ResponseEntity.ok(HttpStatus.OK);
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Main.class)
@WebAppConfiguration
public abstract class BaseTest {
protected MockMvc mvc;
@Autowired
WebApplicationContext webApplicationContext;
protected void setUp() {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
protected String mapToJson(Object obj) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(obj);
}
protected <T> T mapFromJson(String json, Class<T> clazz)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json, clazz);
}
}
public class AppControllerTest extends BaseTest {
@MockBean
private IIdmsService service;
private static final String URI = "/myapi/myApp";
@Override
@Before
public void setUp() {
super.setUp();
}
@Test
public void testGet() throws Exception {
AppEntity entity = new AppEntity();
List<AppEntity> dataList = new ArrayList<AppEntity>();
AppResponse<AppEntity> dataResponse = new AppResponse<AppEntity>();
entity.setId(1);
entity.setCreated_at("2020-02-21 17:01:38.717863");
entity.setCreated_by(“Abhinav Kr”);
entity.setModified_at("2020-02-24 17:01:38.717863");
entity.setModified_by(“Jyoti”);
dataList.add(entity);
dataResponse.setData(dataList);
Mockito.when(service.getApp()).thenReturn(dataList);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(URI)
.accept(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
String expectedJson = this.mapToJson(dataResponse);
String outputInJson = mvcResult.getResponse().getContentAsString();
assertEquals(HttpStatus.OK.value(), response.getStatus());
assertEquals(expectedJson, outputInJson);
}
@Test
public void testCreate() throws Exception {
AppRequest request = new AppRequest();
request.createdBy = 1;
request.AppFullName = “My App”;
request.appTimezone = “India”;
String inputInJson = this.mapToJson(request);
Mockito.doNothing().when(service).createApp(Mockito.any(AppRequest.class));
service.createApp(request);
Mockito.verify(service, Mockito.times(1)).createApp(request);
RequestBuilder requestBuilder = MockMvcRequestBuilders.post(URI)
.accept(MediaType.APPLICATION_JSON).content(inputInJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
@Test
public void testUpdate() throws Exception {
AppRequest request = new AppRequest();
request.id = 1;
request.modifiedBy = 1;
request.AppFullName = “My App”;
request.appTimezone = “Bharat”;
String inputInJson = this.mapToJson(request);
Mockito.doNothing().when(service).updateApp(Mockito.any(AppRequest.class));
service.updateApp(request);
Mockito.verify(service, Mockito.times(1)).updateApp(request);
RequestBuilder requestBuilder = MockMvcRequestBuilders.put(URI)
.accept(MediaType.APPLICATION_JSON).content(inputInJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
@Test
public void testDelete() throws Exception {
AppRequest request = new AppRequest();
request.id = 1;
String inputInJson = this.mapToJson(request);
Mockito.doNothing().when(service).deleteApp(Mockito.any(Integer.class));
service.deleteApp(request.id);
Mockito.verify(service, Mockito.times(1)).deleteApp(request.id);
RequestBuilder requestBuilder = MockMvcRequestBuilders.delete(URI)
.accept(MediaType.APPLICATION_JSON).content(inputInJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
}
Because you haven't declared it. If you want to use a variable of another class you must use
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var DestViewController : ViewController = segue.destinationViewController as ViewController
DestViewController.signedIn = false
}
You have to put this code at the end of the NewClass code
If your List
is sorted and has good random access (as ArrayList
does), you should look into Collections.binarySearch
. Otherwise, you should use List.indexOf
, as others have pointed out.
But your algorithm is sound, fwiw (other than the ==
others have pointed out).
In your .htaccess you can add:
PHP 5.x
<IfModule mod_php5.c>
php_value memory_limit 64M
</IfModule>
PHP 7.x
<IfModule mod_php7.c>
php_value memory_limit 64M
</IfModule>
If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.
If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.
Read more on http://support.tigertech.net/php-value
It can be this:
If you are using cpanel for your website smtp restrictions are problem and cause this error. SMTP Restrictions
It's exactly what the error says. You didn't create any RestTemplate
bean, so it can't autowire any. If you need a RestTemplate
you'll have to provide one. For example, add the following to TestMicroServiceApplication.java:
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
Note, in earlier versions of the Spring cloud starter for Eureka, a RestTemplate
bean was created for you, but this is no longer true.
(WINDOWS - AWS solution)
Solved for windows by putting tripple quotes around files and paths.
Benefits:
1) Prevents excludes that quietly were getting ignored.
2) Files/folders with spaces in them, will no longer kick errors.
aws_command = 'aws s3 sync """D:/""" """s3://mybucket/my folder/" --exclude """*RECYCLE.BIN/*""" --exclude """*.cab""" --exclude """System Volume Information/*""" '
r = subprocess.run(f"powershell.exe {aws_command}", shell=True, capture_output=True, text=True)
If you're just starting out learning javascript & don't want to spend time creating an entire webpage just for embedding test scripts, just open Dev Tools in a new tab in Chrome Browser, and click on Console
.
Then type out some test scripts: eg.
console.log('Aha!')
Then press Enter after every line (to submit for execution by Chrome)
or load your own "external script file":
document.createElement('script').src = 'http://example.com/file.js';
Then call your functions:
console.log(file.function('?????'))
Tested in Google Chrome 85.0.4183.121
It's not open source, but you can at least get a free personal use license to Prince, which really does a lovely job.
I created a web site https://www.swdoc.org/ that specifically addresses the problem. So it automates swagger.json -> Asciidoc, Asciidoc -> pdf
transformation as suggested in the answers. Benefit of this is that you dont need to go through the installation procedures. It accepts a spec document in form of url or just a raw json. Project is written in C# and its page is https://github.com/Irdis/SwDoc
EDIT
It might be a good idea to validate your json specs here: http://editor.swagger.io/ if you are having any problems with SwDoc, like the pdf being generated incomplete.
You can open default sms App and pass details as below :
Note : If u want to send to many numbers, separate each number with ";" inside string
String mblNumVar = "9876543210;9123456789";
Intent smsMsgAppVar = new Intent(Intent.ACTION_VIEW);
smsMsgAppVar.setData(Uri.parse("sms:" + mblNumVar));
smsMsgAppVar.putExtra("sms_body", "Hello Msg Tst Txt");
startActivity(smsMsgAppVar);
|Or| Use this function :
void openSmsMsgAppFnc(String mblNumVar, String smsMsgVar)
{
Intent smsMsgAppVar = new Intent(Intent.ACTION_VIEW);
smsMsgAppVar.setData(Uri.parse("sms:" + mblNumVar));
smsMsgAppVar.putExtra("sms_body", smsMsgVar);
startActivity(smsMsgAppVar);
}
You can Use Direct in bootstrap model also.
<div class="modal fade" id="myModal" data-keyboard="false" data-backdrop="static">
A Modern Solution
Most of the proposed solutions here will break with nested tables or other elements inside your td elements. I frequently use other elements inside my tables, but only want to export the topmost table. I took some of the code found here from Calumah and added in some modern vanilla ES6 JS.
Using textContent is a better solution than innerText as innerText will return any HTML inside your td elements. However, even textContent will return the text from nested elements. An even better solution is to use custom data attributes on your td and pull the values for you CSV from there.
Happy coding!
function downloadAsCSV(tableEle, separator = ','){
let csvRows = []
//only get direct children of the table in question (thead, tbody)
Array.from(tableEle.children).forEach(function(node){
//using scope to only get direct tr of node
node.querySelectorAll(':scope > tr').forEach(function(tr){
let csvLine = []
//again scope to only get direct children
tr.querySelectorAll(':scope > td').forEach(function(td){
//clone as to not remove anything from original
let copytd = td.cloneNode(true)
let data
if(copytd.dataset.val) data = copytd.dataset.val.replace(/(\r\n|\n|\r)/gm, '')
else {
Array.from(copytd.children).forEach(function(remove){
//remove nested elements before getting text
remove.parentNode.removeChild(remove)
})
data = copytd.textContent.replace(/(\r\n|\n|\r)/gm, '')
}
data = data.replace(/(\s\s)/gm, ' ').replace(/"/g, '""')
csvLine.push('"'+data+'"')
})
csvRows.push(csvLine.join(separator))
})
})
var a = document.createElement("a")
a.style = "display: none; visibility: hidden" //safari needs visibility hidden
a.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csvRows.join('\n'))
a.download = 'testfile.csv'
document.body.appendChild(a)
a.click()
a.remove()
}
Edit: cloneNode() updated to cloneNode(true) to get insides
If you have installed mysql using Homebrew by specifying a version then mysql_config would be present here. - /usr/local/Cellar/[email protected]/5.6.47/bin
you can find the path of the sql bin by using ls command in /usr/local/ directory
/usr/local/Cellar/[email protected]/5.6.47/bin
Add the path to bash profile like this.
nano ~/.bash_profile
export PATH="/usr/local/Cellar/[email protected]/5.6.47/bin:$PATH"
You can use StringUtils’s TraditionalBinarPrefix
:
public static String humanReadableInt(long number) {
return TraditionalBinaryPrefix.long2String(number, ””, 1);
}
I think this is the easiest way to loop in react js
<ul>
{yourarray.map((item)=><li>{item}</li>)}
</ul>
As in your example, the fit_start_time
is not later than the fit_end_time
.
Try it the other way round:
var fit_start_time = $("#fit_start_time").val(); //2013-09-5
var fit_end_time = $("#fit_end_time").val(); //2013-09-10
if(Date.parse(fit_start_time) <= Date.parse(fit_end_time)){
alert("Please select a different End Date.");
}
Update
Your code implies that you want to see the alert
with the current variables you have. If this is the case then the above code is correct. If you're intention (as per the implication of the alert message
) is to make sure their fit_start_time
variable is a date that is before the fit_end_time
, then your original code is fine, but the data you're getting from the jQuery .val()
methods is not parsing correctly. It would help if you gave us the actual HTML which the selector is sniffing at.
i think this solution is faster and simple. i use always CTE/recursive beacuse WHILE is so slow on mssql. I use it in projects I work with and large databases.
/*
Function: dbo.kSql_ReplaceRegExp
Create Date: 20.02.2021
Author: Karcan Ozbal
Description: The given string value will be replaced according to the given regexp/pattern.
Parameter(s): @Value : Value/Text to REPLACE.
@RegExp : The regexp/pattern to be used for REPLACE operation.
Usage: select dbo.kSql_ReplaceRegExp('2T3EST5','%[0-9]%')
Output: 'TEST'
*/
ALTER FUNCTION [dbo].[kSql_ReplaceRegExp](
@Value nvarchar(max),
@RegExp nvarchar(50)
)
RETURNS nvarchar(max)
AS
BEGIN
DECLARE @Result nvarchar(max)
;WITH CTE AS (
SELECT NUM = 1, VALUE = @Value, IDX = PATINDEX(@RegExp, @Value)
UNION ALL
SELECT NUM + 1, VALUE = REPLACE(VALUE, SUBSTRING(VALUE,IDX,1),''), IDX = PATINDEX(@RegExp, REPLACE(VALUE, SUBSTRING(VALUE,IDX,1),''))
FROM CTE
WHERE IDX > 0
)
SELECT TOP(1) @Result = VALUE
FROM CTE
ORDER BY NUM DESC
OPTION (maxrecursion 0)
RETURN @Result
END
umount -a -t cifs -l
worked like a charm for me on CentOS 6.3. It saved me a server reboot.
Since I cannot comment, adding this note in addition to @jethro answer.
I found out that you also need to do the FOREIGN KEY line as the last part of create the table statement, otherwise you will get a syntax error when installing your app. What I mean is, you cannot do something like this:
private static final String TASK_TABLE_CREATE = "create table "
+ TASK_TABLE + " (" + TASK_ID
+ " integer primary key autoincrement, " + TASK_TITLE
+ " text not null, " + TASK_NOTES + " text not null, "
+ TASK_CAT + " integer,"
+ " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+" ("+CAT_ID+"), "
+ TASK_DATE_TIME + " text not null);";
Where I put the TASK_DATE_TIME after the foreign key line.
If you wanted to load message files for different languages, just use the shared.loader= of catalina.properties... for more info, visit http://theswarmintelligence.blogspot.com/2012/08/use-resource-bundle-messages-files-out.html
I used:
Tel: <a href="tel:+123 123456789">+123 123456789</a>
and the result is:
Tel: +123 123456789
Where "Tel:" stands for pure text and only the number is coded and clickable.
This also works specially if you are looping over an object.
unset($object[$key])
Newer versions of PHP throw fatal error Fatal error: Cannot use object of type Object as array
as mentioned by @CXJ . In that case you can use brackets instead
unset($object->{$key})
The copy
command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.
Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).
I tried a variation of your command as follows in SQL*Plus (with no errors):
copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;
After I executed the above statement, I also truncate the new_emp table and executed this command:
copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;
With SQL Developer, you could do the following to perform a similar approach to copying objects:
On the tool bar, select Tools>Database copy.
Identify source and destination connections with the copy options you would like.
For object type, select table(s).
The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).
DISCLAIMER: you probably should not use this hack. See comments below.
Here is another hack for adding comments in JSON. Since:
{"a": 1, "a": 2}
Is equivalent to
{"a": 2}
You can do something like:
{
"devDependencies": "'mocha' not needed as should be globally installed",
"devDependencies" : {
"should": "*"
}
}
You can create a function for it:
typedef struct {
int id;
char name;
} employee;
void set_iv(employee *em);
int main(){
employee em0; set_iv(&em0);
}
void set_iv(employee *em){
(*em).id = 0;
(*em).name = "none";
}
Here's a simple PHP command line script that will do what you need:
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$database = 'database';
$db = mysql_connect($host, $user, $pass);
mysql_query("use $database", $db);
/********************************************************************************/
// Parameters: filename.csv table_name
$argv = $_SERVER[argv];
if($argv[1]) { $file = $argv[1]; }
else {
echo "Please provide a file name\n"; exit;
}
if($argv[2]) { $table = $argv[2]; }
else {
$table = pathinfo($file);
$table = $table['filename'];
}
/********************************************************************************/
// Get the first row to create the column headings
$fp = fopen($file, 'r');
$frow = fgetcsv($fp);
foreach($frow as $column) {
if($columns) $columns .= ', ';
$columns .= "`$column` varchar(250)";
}
$create = "create table if not exists $table ($columns);";
mysql_query($create, $db);
/********************************************************************************/
// Import the data into the newly created table.
$file = $_SERVER['PWD'].'/'.$file;
$q = "load data infile '$file' into table $table fields terminated by ',' ignore 1 lines";
mysql_query($q, $db);
?>
It will create a table based on the first row and import the remaining rows into it. Here is the command line syntax:
php csv_import.php csv_file.csv table_name
use this code
SELECT *
FROM paypal_ipn_orders
GROUP BY payer_email
HAVING COUNT( payer_email) >1
select convert_tz(now(),@@session.time_zone,'+05:30')
replace '+05:30' with desired timezone. see here - https://stackoverflow.com/a/3984412/2359994
to format into desired time format, eg:
select DATE_FORMAT(convert_tz(now(),@@session.time_zone,'+05:30') ,'%b %d %Y %h:%i:%s %p')
you will get similar to this -> Dec 17 2014 10:39:56 AM
To accomplish what you're describing will take two steps...
Step 1: To add the file to the source tarball, include it in the MANIFEST
Create a MANIFEST template in the folder that contains setup.py
The MANIFEST is basically a text file with a list of all the files that will be included in the source tarball.
Here's what the MANIFEST for my project look like:
Note: While sdist does add some files automatically, I prefer to explicitly specify them to be sure instead of predicting what it does and doesn't.
Step 2: To install the data file to the source folder, modify setup.py
Since you're looking to add a data file (LICENSE.txt) to the source install folder you need to modify the data install path to match the source install path. This is necessary because, by default, data files are installed to a different location than source files.
To modify the data install dir to match the source install dir...
Pull the install dir info from distutils with:
from distutils.command.install import INSTALL_SCHEMES
Modify the data install dir to match the source install dir:
for scheme in INSTALL_SCHEMES.values():
scheme['data'] = scheme['purelib']
And, add the data file and location to setup():
data_files=[('', ['LICENSE.txt'])]
Note: The steps above should accomplish exactly what you described in a standard manner without requiring any extension libraries.
No, that's the correct way to do it. This worked exactly as it should, something you can work from perhaps:
using System;
class Program {
static void Main(string[] args) {
System.AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
throw new Exception("Kaboom");
}
static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) {
Console.WriteLine(e.ExceptionObject.ToString());
Console.WriteLine("Press Enter to continue");
Console.ReadLine();
Environment.Exit(1);
}
}
Do keep in mind that you cannot catch type and file load exceptions generated by the jitter this way. They happen before your Main() method starts running. Catching those requires delaying the jitter, move the risky code into another method and apply the [MethodImpl(MethodImplOptions.NoInlining)] attribute to it.
Create Function :
Create FUNCTION [dbo].[PadLeft]
(
@Text NVARCHAR(MAX) ,
@Replace NVARCHAR(MAX) ,
@Len INT
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE @var NVARCHAR(MAX)
SELECT @var = ISNULL(LTRIM(RTRIM(@Text)) , '')
RETURN RIGHT(REPLICATE(@Replace,@Len)+ @var, @Len)
END
Example:
Select dbo.PadLeft('123456','0',8)
There is a better solution to this answer that is more Angular based.
Save your string in a variable in the .ts file
MyStrings = ["one","two","three"]
In the html file use *ngFor.
<div class="one" *ngFor="let string of MyStrings; let i = index">
<div class="two">{{string}}</div>
</div>
if you want to dynamically insert the div element, just push more strings into the MyStrings array
myFunction(nextString){
this.MyString.push(nextString)
}
this way every time you click the button containing the myFunction(nextString) you effectively add another class="two" div which acts the same way as inserting it into the DOM with pure javascript.
Here's a slightly different solution. Instead of multi-line, I focused on just the last line, and instead of a constant block size, I have a dynamic (doubling) block size. See comments for more info.
# Get last line of a text file using seek method. Works with non-constant block size.
# IDK if that speed things up, but it's good enough for us,
# especially with constant line lengths in the file (provided by len_guess),
# in which case the block size doubling is not performed much if at all. Currently,
# we're using this on a textfile format with constant line lengths.
# Requires that the file is opened up in binary mode. No nonzero end-rel seeks in text mode.
REL_FILE_END = 2
def lastTextFileLine(file, len_guess=1):
file.seek(-1, REL_FILE_END) # 1 => go back to position 0; -1 => 1 char back from end of file
text = file.read(1)
tot_sz = 1 # store total size so we know where to seek to next rel file end
if text != b'\n': # if newline is the last character, we want the text right before it
file.seek(0, REL_FILE_END) # else, consider the text all the way at the end (after last newline)
tot_sz = 0
blocks = [] # For storing succesive search blocks, so that we don't end up searching in the already searched
j = file.tell() # j = end pos
not_done = True
block_sz = len_guess
while not_done:
if j < block_sz: # in case our block doubling takes us past the start of the file (here j also = length of file remainder)
block_sz = j
not_done = False
tot_sz += block_sz
file.seek(-tot_sz, REL_FILE_END) # Yes, seek() works with negative numbers for seeking backward from file end
text = file.read(block_sz)
i = text.rfind(b'\n')
if i != -1:
text = text[i+1:].join(reversed(blocks))
return str(text)
else:
blocks.append(text)
block_sz <<= 1 # double block size (converge with open ended binary search-like strategy)
j = j - block_sz # if this doesn't work, try using tmp j1 = file.tell() above
return str(b''.join(reversed(blocks))) # if newline was never found, return everything read
Ideally, you'd wrap this in a class LastTextFileLine and keep track of a moving average of line lengths. This would give you a good len_guess maybe.
Django has a 'slugify' function which does this, as well as other URL-friendly optimisations. It's hidden away in the defaultfilters module.
>>> from django.template.defaultfilters import slugify
>>> slugify("This should be connected")
this-should-be-connected
This isn't exactly the output you asked for, but IMO it's better for use in URLs.
The correct answer to this particular questions is "don't select". Sometimes you have to select or activate, but 99% of the time you don't. If your code looks like
Select something
Do something to the selection
Select something else
Do something to the selection
You probably need to refactor and consider not selecting.
The error, Method 'Range' of object '_Worksheet' failed, error 1004, that you're getting is because the sheet with the button on it doesn't have a range named "Result". Most (maybe all) properties that return an object have a default Parent object. In this case, you're using the Range property to return a Range object. Because you don't qualify the Range property, Excel uses the default.
The default Parent object can be different based on the circumstances. If your code were in a standard module, then the ActiveSheet would be the default Parent and Excel would try to resolve ActiveSheet.Range("Result"). Your code is in a sheet's class module (the sheet with the button on it). When the unqualified reference is used there, the default Parent is the sheet that's attached to that module. In this case they're the same because the sheet has to be active to click the button, but that isn't always the case.
When Excel gives the error that includes text like '_Object' (yours said '_Worksheet') it's always referring to the default Parent object - the underscore gives that away. Generally the way to fix that is to qualify the reference by being explicit about the parent. But in the case of selecting and activating when you don't need to, it's better to just refactor the code.
Here's one way to write your code without any selecting or activating.
Private Sub cmdRecord_Click()
Dim shSource As Worksheet
Dim shDest As Worksheet
Dim rNext As Range
'Me refers to the sheet whose class module you're in
'Me.Parent refers to the workbook
Set shSource = Me.Parent.Worksheets("BxWsn Simulation")
Set shDest = Me.Parent.Worksheets("Reslt Record")
Set rNext = shDest.Cells(shDest.Rows.Count, 1).End(xlUp).Offset(1, 0)
shSource.Range("Result").Copy
rNext.PasteSpecial xlPasteFormulasAndNumberFormats
Application.CutCopyMode = False
End Sub
When I'm in a class module, like the sheet's class module that you're working in, I always try to do things in terms of that class. So I use Me.Parent instead of ActiveWorkbook. It makes the code more portable and prevents unexpected problems when things change.
I'm sure the code you have now runs in milliseconds, so you may not care, but avoiding selecting will definitely speed up your code and you don't have to set ScreenUpdating. That may become important as your code grows or in a different situation.
It's because your '/new_sandbox/'
begins with a /
and thus is assumed to be relative to the root directory. Remove the leading /
.
If you do not want to create your own button component, a quick and dirty solution is to wrap the button in a view, which allows you to at least apply layout styling.
For example this would create a row of buttons:
<View style={{flexDirection: 'row'}}>
<View style={{flex:1 , marginRight:10}} >
<Button title="Save" onPress={() => {}}></Button>
</View>
<View style={{flex:1}} >
<Button title="Cancel" onPress={() => {}}></Button>
</View>
</View>
There is a module called 'pdb' in python. At the top of your python script you do
import pdb
pdb.set_trace()
and you will enter into debugging mode. You can use 's' to step, 'n' to follow next line similar to what you would do with 'gdb' debugger.
There is no newline, just the div
is a block element.
You can make the div
inline by adding display: inline
, which may be what you want.
You can't prevent the user from refreshing, nor should you really be trying. You should go back to why you need this solution, what's the root problem here?. Start there and find a different way to go about solving the problem. Perhaps is you elaborated on why you think you need to do this it would help in finding such a solution.
Breaking fundamental browser features is never a good idea, over 99.999999999% of the internet works and refreshes with F5, this is an expectation of the user, one you shouldn't break.
I got this solution for truncating leading zeros(number or any string) in javascript:
<script language="JavaScript" type="text/javascript">
<!--
function trimNumber(s) {
while (s.substr(0,1) == '0' && s.length>1) { s = s.substr(1,9999); }
return s;
}
var s1 = '00123';
var s2 = '000assa';
var s3 = 'assa34300';
var s4 = 'ssa';
var s5 = '121212000';
alert(s1 + '=' + trimNumber(s1));
alert(s2 + '=' + trimNumber(s2));
alert(s3 + '=' + trimNumber(s3));
alert(s4 + '=' + trimNumber(s4));
alert(s5 + '=' + trimNumber(s5));
// end hiding contents -->
</script>
You could try something like this:
echo 'maps.google.com' | rev | cut -d'.' -f 1 | rev
Explanation
rev
reverses "maps.google.com" to be moc.elgoog.spam
cut
uses dot (ie '.') as the delimiter, and chooses the first field, which is moc
com
There are several ways you can do it.
Option 1:
Create different perfect images for different dpi and place them in related drawable folder. Then set
android:background="@drawable/your_image"
Option 2:
Add a single large image. Use FrameLayout. As a first child add an ImageView
. Set the following in your ImageView.
android:src="@drawable/your_image"
android:scaleType = "centerCrop"
$(function() {
$('.phrase .items').each(function(i, items_list){
var myText = "";
$(items_list).find('li').each(function(j, li){
alert(li.text());
})
alert(myText);
});
};
In VueJs function you can use this as well... A working solution using recursion. Base credits Samadhan Sakhale
check_objects(obj1, obj2) {
try {
var flag = true;
if (Object.keys(obj1).length == Object.keys(obj2).length) {
for (let key in obj1) {
if(typeof (obj1[key]) != typeof (obj2[key]))
{
return false;
}
if (obj1[key] == obj2[key]) {
continue;
}
else if(typeof (obj1[key]) == typeof (new Object()))
{
if(!this.check_objects(obj1[key], obj2[key])) {
return false;
}
}
else {
return false;
}
}
}
else {
return false
}
}
catch {
return false;
}
return flag;
},
If you want a popup window rather than a <div />
, I would suggest the following approach.
In your parent page, you call a small helper method to show the popup window:
<input type="button" name="choice" onClick="selectValue('sku1')" value="?">
Add the following JS methods:
function selectValue(id)
{
// open popup window and pass field id
window.open('sku.php?id=' + encodeURIComponent(id),'popuppage',
'width=400,toolbar=1,resizable=1,scrollbars=yes,height=400,top=100,left=100');
}
function updateValue(id, value)
{
// this gets called from the popup window and updates the field with a new value
document.getElementById(id).value = value;
}
Your sku.php
receives the selected field via $_GET['id']
and uses it to construct the parent callback function:
?>
<script type="text/javascript">
function sendValue(value)
{
var parentId = <?php echo json_encode($_GET['id']); ?>;
window.opener.updateValue(parentId, value);
window.close();
}
</script>
For each row in your popup, change code to this:
<td><input type=button value="Select" onClick="sendValue('<?php echo $rows['packcode']; ?>')" /></td>
Following this approach, the popup window doesn't need to know how to update fields in the parent form.
This was kind of an annoying issue for me. No suggestions seemed to help my particular case, since I needed to include the "non-modular" headers in my individual file header file. The work around I used was sticking the import call in the prefix header file.
You can use javascript function .find()
As it says in MDN, it will return the first value that is true. If such an element is found, find immediately returns the value of that element. Otherwise, find returns undefined
.
var array1 = ["cat", "sum","fun", "run"];_x000D_
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];_x000D_
_x000D_
found = array1.find( val => array2.includes(val) )_x000D_
console.log(found)
_x000D_
If you are using PhpMyAdmin sometimes it don't show the foreign key to delete.
The error code gives us the name of the foreign key and the table where it was defined, so the code is:
ALTER TABLE your_table DROP FOREIGN KEY foreign_key_name;
With regards to your first question, the array is passed by reference UNLESS it is modified within the method / function you're calling. If you attempt to modify the array within the method / function, a copy of it is made first, and then only the copy is modified. This makes it seem as if the array is passed by value when in actual fact it isn't.
For example, in this first case, even though you aren't defining your function to accept $my_array by reference (by using the & character in the parameter definition), it still gets passed by reference (ie: you don't waste memory with an unnecessary copy).
function handle_array($my_array) {
// ... read from but do not modify $my_array
print_r($my_array);
// ... $my_array effectively passed by reference since no copy is made
}
However if you modify the array, a copy of it is made first (which uses more memory but leaves your original array unaffected).
function handle_array($my_array) {
// ... modify $my_array
$my_array[] = "New value";
// ... $my_array effectively passed by value since requires local copy
}
FYI - this is known as "lazy copy" or "copy-on-write".
Sometimes you can retreive the phonenumber with a USSD request to your operator. For example I can get my phonenumber by dialing *116# This can probably be done within an app, I guess, if the USSD responce somehow could be catched. Offcourse this is not a method I would recommend to use within an app that is to be distributed, the code may even differ between operators.
my combination looks like this. it fades out and fades in on each scroll down/up. otherwise you have to scroll up to the header, for fading the header in.
var header = $("#header");
$('#content-container').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta > 0) {
if (header.data('faded')) {
header.data('faded', 0).stop(true).fadeTo(800, 1);
}
}
else{
if (!header.data('faded')) header.data('faded', 1).stop(true).fadeTo(800, 0);
}
});
the above one is not optimized for touch/mobile, I think this one does it better for all mobile:
var iScrollPos = 0;
var header = $("#header");
$('#content-container').scroll(function () {
var iCurScrollPos = $(this).scrollTop();
if (iCurScrollPos > iScrollPos) {
if (!header.data('faded')) header.data('faded', 1).stop(true).fadeTo(800, 0);
} else {
//Scrolling Up
if (header.data('faded')) {
header.data('faded', 0).stop(true).fadeTo(800, 1);
}
}
iScrollPos = iCurScrollPos;
});
return
should be used for recursive functions/methods or you want to use the returned value for later applications in your algorithm.
print
should be used when you want to display a meaningful and desired output to the user and you don't want to clutter the screen with intermediate results that the user is not interested in, although they are helpful for debugging your code.
The following code shows how to use return
and print
properly:
def fact(x):
if x < 2:
return 1
return x * fact(x - 1)
print(fact(5))
This explanation is true for all of the programming languages not just python.
You could try something like this:
I have initialzed the array for having value 5, you could put your number similarly.
int[] arr = new int[10]; // your initial array
arr = arr.Select(i => 5).ToArray(); // array initialized to 5.
I believe you are getting an empty array because PHP is expecting the posted data to be in a Querystring format (key=value&key1=value1).
Try changing your curl request to:
curl -i -X POST -d 'json={"screencast":{"subject":"tools"}}' \
http://localhost:3570/index.php/trainingServer/screencast.json
and see if that helps any.
I'm surprised nobody has mentioned the new Fetch API, supported by all browsers except IE11 at the time of writing. It simplifies the XMLHttpRequest syntax you see in many of the other examples.
The API includes a lot more, but start with the fetch()
method. It takes two arguments:
Simple GET:
const userAction = async () => {
const response = await fetch('http://example.com/movies.json');
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
Recreating the previous top answer, a POST:
const userAction = async () => {
const response = await fetch('http://example.com/movies.json', {
method: 'POST',
body: myBody, // string or object
headers: {
'Content-Type': 'application/json'
}
});
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
I was able to resolve it by updating sdk version and tools in gradle
compileSdkVersion 26
buildToolsVersion "26.0.1"
and support library 26.0.1
https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-1
To parse JSON in VBA without adding a huge library to your workbook project, I created the following solution. It's extremely fast and stores all of the keys and values in a dictionary for easy access:
Function ParseJSON(json$, Optional key$ = "obj") As Object
p = 1
token = Tokenize(json)
Set dic = CreateObject("Scripting.Dictionary")
If token(p) = "{" Then ParseObj key Else ParseArr key
Set ParseJSON = dic
End Function
Function ParseObj(key$)
Do: p = p + 1
Select Case token(p)
Case "]"
Case "[": ParseArr key
Case "{"
If token(p + 1) = "}" Then
p = p + 1
dic.Add key, "null"
Else
ParseObj key
End If
Case "}": key = ReducePath(key): Exit Do
Case ":": key = key & "." & token(p - 1)
Case ",": key = ReducePath(key)
Case Else: If token(p + 1) <> ":" Then dic.Add key, token(p)
End Select
Loop
End Function
Function ParseArr(key$)
Dim e&
Do: p = p + 1
Select Case token(p)
Case "}"
Case "{": ParseObj key & ArrayID(e)
Case "[": ParseArr key
Case "]": Exit Do
Case ":": key = key & ArrayID(e)
Case ",": e = e + 1
Case Else: dic.Add key & ArrayID(e), token(p)
End Select
Loop
End Function
The code above does use a few helper functions, but the above is the meat of it.
The strategy used here is to employ a recursive tokenizer. I found it interesting enough to write an article about this solution on Medium. It explains the details.
Here is the full (yet surprisingly short) code listing, including all of the helper functions:
'-------------------------------------------------------------------
' VBA JSON Parser
'-------------------------------------------------------------------
Option Explicit
Private p&, token, dic
Function ParseJSON(json$, Optional key$ = "obj") As Object
p = 1
token = Tokenize(json)
Set dic = CreateObject("Scripting.Dictionary")
If token(p) = "{" Then ParseObj key Else ParseArr key
Set ParseJSON = dic
End Function
Function ParseObj(key$)
Do: p = p + 1
Select Case token(p)
Case "]"
Case "[": ParseArr key
Case "{"
If token(p + 1) = "}" Then
p = p + 1
dic.Add key, "null"
Else
ParseObj key
End If
Case "}": key = ReducePath(key): Exit Do
Case ":": key = key & "." & token(p - 1)
Case ",": key = ReducePath(key)
Case Else: If token(p + 1) <> ":" Then dic.Add key, token(p)
End Select
Loop
End Function
Function ParseArr(key$)
Dim e&
Do: p = p + 1
Select Case token(p)
Case "}"
Case "{": ParseObj key & ArrayID(e)
Case "[": ParseArr key
Case "]": Exit Do
Case ":": key = key & ArrayID(e)
Case ",": e = e + 1
Case Else: dic.Add key & ArrayID(e), token(p)
End Select
Loop
End Function
'-------------------------------------------------------------------
' Support Functions
'-------------------------------------------------------------------
Function Tokenize(s$)
Const Pattern = """(([^""\\]|\\.)*)""|[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?|\w+|[^\s""']+?"
Tokenize = RExtract(s, Pattern, True)
End Function
Function RExtract(s$, Pattern, Optional bGroup1Bias As Boolean, Optional bGlobal As Boolean = True)
Dim c&, m, n, v
With CreateObject("vbscript.regexp")
.Global = bGlobal
.MultiLine = False
.IgnoreCase = True
.Pattern = Pattern
If .TEST(s) Then
Set m = .Execute(s)
ReDim v(1 To m.Count)
For Each n In m
c = c + 1
v(c) = n.value
If bGroup1Bias Then If Len(n.submatches(0)) Or n.value = """""" Then v(c) = n.submatches(0)
Next
End If
End With
RExtract = v
End Function
Function ArrayID$(e)
ArrayID = "(" & e & ")"
End Function
Function ReducePath$(key$)
If InStr(key, ".") Then ReducePath = Left(key, InStrRev(key, ".") - 1)
End Function
Function ListPaths(dic)
Dim s$, v
For Each v In dic
s = s & v & " --> " & dic(v) & vbLf
Next
Debug.Print s
End Function
Function GetFilteredValues(dic, match)
Dim c&, i&, v, w
v = dic.keys
ReDim w(1 To dic.Count)
For i = 0 To UBound(v)
If v(i) Like match Then
c = c + 1
w(c) = dic(v(i))
End If
Next
ReDim Preserve w(1 To c)
GetFilteredValues = w
End Function
Function GetFilteredTable(dic, cols)
Dim c&, i&, j&, v, w, z
v = dic.keys
z = GetFilteredValues(dic, cols(0))
ReDim w(1 To UBound(z), 1 To UBound(cols) + 1)
For j = 1 To UBound(cols) + 1
z = GetFilteredValues(dic, cols(j - 1))
For i = 1 To UBound(z)
w(i, j) = z(i)
Next
Next
GetFilteredTable = w
End Function
Function OpenTextFile$(f)
With CreateObject("ADODB.Stream")
.Charset = "utf-8"
.Open
.LoadFromFile f
OpenTextFile = .ReadText
End With
End Function
Actually, I've seen this sort of thing used in BIRT reports. The query passed to the BIRT runtime is of the form:
select a,b,c from t where a = ?
and the '?' is replaced at runtime by an actual parameter value selected from a drop-down box. The choices in the drop-down are given by:
select distinct a from t
union all
select '*' from sysibm.sysdummy1
so that you get all possible values plus "*
". If the user selects "*
" from the drop down box (meaning all values of a should be selected), the query has to be modified (by Javascript) before being run.
Since the "?" is a positional parameter and MUST remain there for other things to work, the Javascript modifies the query to be:
select a,b,c from t where ((a = ?) or (1==1))
That basically removes the effect of the where clause while still leaving the positional parameter in place.
I've also seen the AND case used by lazy coders whilst dynamically creating an SQL query.
Say you have to dynamically create a query that starts with select * from t
and checks:
some people would add the first with a WHERE and subsequent ones with an AND thus:
select * from t where name = 'Bob' and salary > 20000
Lazy programmers (and that's not necessarily a bad trait) wouldn't distinguish between the added conditions, they'd start with select * from t where 1=1
and just add AND clauses after that.
select * from t where 1=1 and name = 'Bob' and salary > 20000