I think that you should make the reference to your config file
26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf
you can try to start your redis server like
./redis-server /path/to/redis-stable/redis.conf
I use method 3 because it's the most understandable for others (whenever you see an <a>
tag, you know it's a link) and when you are part of a team, you have to make simple things ;).
And finally I don't think it's useful and efficient to use JS simply to navigate to an other page.
Abstraction is about identifying commonalities and reducing features that you have to work with at different levels of your code.
e.g. I may have a Vehicle
class. A Car
would derive from a Vehicle
, as would a Motorbike
. I can ask each Vehicle
for the number of wheels, passengers etc. and that info has been abstracted and identified as common from Cars
and Motorbikes
.
In my code I can often just deal with Vehicles
via common methods go()
, stop()
etc. When I add a new Vehicle type later (e.g. Scooter
) the majority of my code would remain oblivious to this fact, and the implementation of Scooter
alone worries about Scooter
particularities.
I find it most simple and easy to understand in the following way:
async Task SendPostRequest()
{
HttpClient client = new HttpClient();
var requestContent = new StringContent(<content>);
requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.PostAsync(<url>, requestContent);
var responseString = await response.Content.ReadAsStringAsync();
}
...
SendPostRequest().Wait();
In some cases, static methods can be difficult to test, especially if they need to be mocked, which is why most mocking frameworks don't support them. I found this blog post to be very useful in determining how to mock static methods and classes.
The most common use of union
I regularly come across is aliasing.
Consider the following:
union Vector3f
{
struct{ float x,y,z ; } ;
float elts[3];
}
What does this do? It allows clean, neat access of a Vector3f vec;
's members by either name:
vec.x=vec.y=vec.z=1.f ;
or by integer access into the array
for( int i = 0 ; i < 3 ; i++ )
vec.elts[i]=1.f;
In some cases, accessing by name is the clearest thing you can do. In other cases, especially when the axis is chosen programmatically, the easier thing to do is to access the axis by numerical index - 0 for x, 1 for y, and 2 for z.
Super short answer: designing maintainable websites is difficult with tables, and simple with the standard way to do it.
A website isn't a table, it's a collection of components that interact with each other. Describing it as a table doesn't make sense.
Simple
public Date convertFrom(LocalDate date) {
return java.sql.Timestamp.valueOf(date.atStartOfDay());
}
It may also happen in the following case:
eg. if we consider the push function of a stack:
typedef struct stack
{
int a[20];
int head;
}stack;
void push(stack **s)
{
int data;
printf("Enter data:");
scanf("%d",&(*s->a[++*s->head])); /* this is where the error is*/
}
main()
{
stack *s;
s=(stack *)calloc(1,sizeof(stack));
s->head=-1;
push(&s);
return 0;
}
The error is in the push function and in the commented line. The pointer s
has to be included within the parentheses. The correct code:
scanf("%d",&( (*s)->a[++(*s)->head]));
xlarge screens are at least 960dp x 720dp layout-xlarge 10" tablet (720x1280 mdpi, 800x1280 mdpi, etc.)
large screens are at least 640dp x 480dp tweener tablet like the Streak (480x800 mdpi), 7" tablet (600x1024 mdpi)
normal screens are at least 470dp x 320dp layout typical phone screen (480x800 hdpi)
small screens are at least 426dp x 320dp typical phone screen (240x320 ldpi, 320x480 mdpi, etc.)
I would use one repository per project. That way, the history becomes easier to browse through.
I would also check the version of the third party library I'm using, into the repository of the project using it.
In Java 8,
For small files:
String line = Files.readAllLines(Paths.get("file.txt")).get(n);
For large files:
String line;
try (Stream<String> lines = Files.lines(Paths.get("file.txt"))) {
line = lines.skip(n).findFirst().get();
}
In Java 7
String line;
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
for (int i = 0; i < n; i++)
br.readLine();
line = br.readLine();
}
Source: Reading nth line from file
This did the trick for me:
echo trim($entry->title);
The newly popular tidyr
package does this with separate
. It uses regular expressions so you'll have to escape the |
df <- data.frame(ID=11:13, FOO=c('a|b', 'b|c', 'x|y'))
separate(data = df, col = FOO, into = c("left", "right"), sep = "\\|")
ID left right
1 11 a b
2 12 b c
3 13 x y
though in this case the defaults are smart enough to work (it looks for non-alphanumeric characters to split on).
separate(data = df, col = FOO, into = c("left", "right"))
This script:
import subprocess
import os
with open(os.devnull, "wb") as limbo:
for n in xrange(1, 10):
ip="192.168.0.{0}".format(n)
result=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip],
stdout=limbo, stderr=limbo).wait()
if result:
print ip, "inactive"
else:
print ip, "active"
will produce something like this output:
192.168.0.1 active
192.168.0.2 active
192.168.0.3 inactive
192.168.0.4 inactive
192.168.0.5 inactive
192.168.0.6 inactive
192.168.0.7 active
192.168.0.8 inactive
192.168.0.9 inactive
You can capture the output if you replace limbo
with subprocess.PIPE
and use communicate()
on the Popen
object:
p=Popen( ... )
output=p.communicate()
result=p.wait()
This way you get the return value of the command and can capture the text. Following the manual this is the preferred way to operate a subprocess if you need flexibility:
The underlying process creation and management in this module is handled by the Popen class. It offers a lot of flexibility so that developers are able to handle the less common cases not covered by the convenience functions.
In addition to other answers which helped me, you can also add to surrounding div. In my case this was for sign on with user Name/Password fields.
<div (keyup.enter)="login()" class="container-fluid">
Since April 2018, Google made some changes to the Autoplay Policy. You not only need to add the autoplay=1
as a query param, but also add allow='autoplay'
as an iframe's attribute
So you will have to do something like this:
<iframe src="https://www.youtube.com/embed/VIDEO_ID?autoplay=1" allow='autoplay'></iframe>
.bashrc
is not sourced when you log in using SSH. You need to source it in your .bash_profile
like this:
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
You have to set height as a string value when you use pixels.
document.getElementById('chartdiv').style.height = "200px"
Also try adding a DOCTYPE to your HTML for Internet Explorer.
<!DOCTYPE html>
<html> ...
How To Read XML Data into a DataSet by Using Visual C# .NET contains some details. Basically, you can use the overloaded DataSet method ReadXml to get the data into a DataSet. Your XML data will be in the first DataTable there.
There is also a DataTable.ReadXml method.
If your server is Apache, you should be able to configure it to see the repository list with viewvc - this is the most basic one, other more complex interfaces exist but this is not your purpose here.
In some versions, ViewVC is an option of the standard installation now, for instance from Collabnet.
Edit: Nevermind my previous idea just above, Peter has a much simpler way of sending the repository list.
From there, you will have to:
Unfortunately in this case I cannot think of something more straightforward.
There are examples on SO on how to extract text from HTML pages in Python, this would be a good option since Python also has bindings for SVN, to perform the repository search - you can still call svn
directly from Python if you prefer.
If Python is not your cup of tea, you will have to process that differently with GNU tools (wget, then parsing tools or existing packages - I can't be of much help there, Carl gave you some more details in this post).
They are largely the same, except that:
The alias declaration is compatible with templates, whereas the C style typedef is not.
Best Solution to print any text in red color in Java is:
System.err.print("Hello World");
I want to create a 2D array that each cell is an ArrayList!
If you want to create a 2D array of ArrayList
.Then you can do this :
ArrayList[][] table = new ArrayList[10][10];
table[0][0] = new ArrayList(); // add another ArrayList object to [0,0]
table[0][0].add(); // add object to that ArrayList
Have a look at Process Utilities > Process monitor
from http://www.sysinternals.com.
This is tool that allows you monitor what a process does. If you monitor this service process, you should see an access denied somewhere, and on what resource the access denied is given.
Have you tried just changing the port number of MySQL and see if it works?
Right click your WAMP icon
Choose MySQL, in the menu choose "Use a port other than 3306"
Change port number to be "3307"
C:\Users\username\AppData\Local\Android\sdk\extras\intel\Hardware_Accelerated_Execution_Manager\intelhaxm-android.exe
check this location in windows
Something like this might work for you:
"UPDATE myTable SET ... ;
UPDATE myTable SET ... ;
UPDATE myTable SET ... ;
UPDATE myTable SET ... ;"
If any of the posX or posY values are the same, then they could be combined into one query
UPDATE myTable SET posX='39' WHERE id IN('2','3','40');
lst *= 0
has the same effect as
lst[:] = []
It's a little simpler and maybe easier to remember. Other than that there's not much to say
The efficiency seems to be about the same
An Intent is an "intention" to perform an action; in other words,
a messaging object you can use to request an action from another app component
An Intent is basically a message to say you did or want something to happen. Depending on the intent, apps or the OS might be listening for it and will react accordingly. Think of it as a blast email to a bunch of friends, in which you tell your friend John to do something, or to friends who can do X ("intent filters"), to do X. The other folks will ignore the email, but John (or friends who can do X) will react to it.
To listen for an broadcast intent (like the phone ringing, or an SMS is received), you implement a broadcast receiver, which will be passed the intent. To declare that you can handle another's app intent like "take picture", you declare an intent filter in your app's manifest file.
If you want to fire off an intent to do something, like pop up the dialer, you fire off an intent saying you will.
You can remove the existing options by using the empty
method, and then add your new options:
var option = $('<option></option>').attr("value", "option value").text("Text");
$("#selectId").empty().append(option);
If you have your new options in an object you can:
var newOptions = {"Option 1": "value1",
"Option 2": "value2",
"Option 3": "value3"
};
var $el = $("#selectId");
$el.empty(); // remove old options
$.each(newOptions, function(key,value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
Edit: For removing the all the options but the first, you can use the :gt
selector, to get all the option
elements with index greater than zero and remove
them:
$('#selectId option:gt(0)').remove(); // remove all options, but not the first
I tried printing Multiple Tables using Mahesh Example above. Posting for convenience of others
USE MyDataBase
DECLARE @RECORDS_THAT_NEED_TO_SEND_EMAIL TABLE (ID INT IDENTITY(1,1),
POS_ID INT,
POS_NUM VARCHAR(100) NULL,
DEPARTMENT VARCHAR(100) NULL,
DISTRICT VARCHAR(50) NULL,
COST_LOC VARCHAR(100) NULL,
EMPLOYEE_NAME VARCHAR(200) NULL)
INSERT INTO @RECORDS_THAT_NEED_TO_SEND_EMAIL(POS_ID,POS_NUM,DISTRICT,COST_LOC,DEPARTMENT,EMPLOYEE_NAME)
SELECT uvwpos.POS_ID,uvwpos.POS_NUM,uvwpos.DISTRICT, uvwpos.COST_LOC,uvwpos.DEPARTMENT,uvemp.LAST_NAME + ' ' + uvemp.FIRST_NAME
FROM uvwPOSITIONS uvwpos LEFT JOIN uvwEMPLOYEES uvemp
on uvemp.POS_ID=uvwpos.POS_ID
WHERE uvwpos.ACTIVE=1 AND uvwpos.POS_NUM LIKE 'sde%'AND (
(RTRIM(LTRIM(LEFT(uvwpos.DEPARTMENT,LEN(uvwpos.DEPARTMENT)-1))) <> RTRIM(LTRIM(uvwpos.COST_LOC)))
OR (uvwpos.DISTRICT IS NULL)
OR (uvwpos.COST_LOC IS NULL) )
DECLARE @RESULT_DISTRICT_ISEMPTY varchar(4000)
DECLARE @RESULT_COST_LOC_ISEMPTY varchar(4000)
DECLARE @RESULT_COST_LOC__AND_DISTRICT_NOT_MATCHING varchar(4000)
DECLARE @BODY NVARCHAR(MAX)
DECLARE @HTMLHEADER VARCHAR(100)
DECLARE @HTMLFOOTER VARCHAR(100)
SET @HTMLHEADER='<html><body>'
SET @HTMLFOOTER ='</body></html>'
SET @RESULT_DISTRICT_ISEMPTY = '';
SET @BODY =@HTMLHEADER+ '<H3>PositionNumber where District is Empty.</H3>
<table border = 1>
<tr>
<th> POS_ID </th> <th> POS_NUM </th> <th> DEPARTMENT </th> <th> DISTRICT </th> <th> COST_LOC </th></tr>'
SET @RESULT_DISTRICT_ISEMPTY = CAST(( SELECT [POS_ID] AS 'td','',RTRIM([POS_NUM]) AS 'td','',
ISNULL(LEFT(DEPARTMENT,LEN(DEPARTMENT)-1),' ') AS 'td','', ISNULL([DISTRICT],' ') AS 'td','',ISNULL([COST_LOC],' ') AS 'td'
FROM @RECORDS_THAT_NEED_TO_SEND_EMAIL
WHERE DISTRICT IS NULL
FOR XML PATH('tr'), ELEMENTS ) AS VARCHAR(MAX))
SET @BODY = @BODY + @RESULT_DISTRICT_ISEMPTY +'</table>'
DECLARE @RESULT_COST_LOC_ISEMPTY_HEADER VARCHAR(400)
SET @RESULT_COST_LOC_ISEMPTY_HEADER ='<H3>PositionNumber where COST_LOC is Empty.</H3>
<table border = 1>
<tr>
<th> POS_ID </th> <th> POS_NUM </th> <th> DEPARTMENT </th> <th> DISTRICT </th> <th> COST_LOC </th></tr>'
SET @RESULT_COST_LOC_ISEMPTY = CAST(( SELECT [POS_ID] AS 'td','',RTRIM([POS_NUM]) AS 'td','',
ISNULL(LEFT(DEPARTMENT,LEN(DEPARTMENT)-1),' ') AS 'td','', ISNULL([DISTRICT],' ') AS 'td','',ISNULL([COST_LOC],' ') AS 'td'
FROM @RECORDS_THAT_NEED_TO_SEND_EMAIL
WHERE COST_LOC IS NULL
FOR XML PATH('tr'), ELEMENTS ) AS VARCHAR(MAX))
SET @BODY = @BODY + @RESULT_COST_LOC_ISEMPTY_HEADER+ @RESULT_COST_LOC_ISEMPTY +'</table>'
DECLARE @RESULT_COST_LOC__AND_DISTRICT_NOT_MATCHING_HEADER VARCHAR(400)
SET @RESULT_COST_LOC__AND_DISTRICT_NOT_MATCHING_HEADER='<H3>PositionNumber where Department and Cost Center are Not Macthing.</H3>
<table border = 1>
<tr>
<th> POS_ID </th> <th> POS_NUM </th> <th> DEPARTMENT </th> <th> DISTRICT </th> <th> COST_LOC </th></tr>'
SET @RESULT_COST_LOC__AND_DISTRICT_NOT_MATCHING = CAST(( SELECT [POS_ID] AS 'td','',RTRIM([POS_NUM]) AS 'td','',
ISNULL(LEFT(DEPARTMENT,LEN(DEPARTMENT)-1),' ') AS 'td','', ISNULL([DISTRICT],' ') AS 'td','',ISNULL([COST_LOC],' ') AS 'td'
FROM @RECORDS_THAT_NEED_TO_SEND_EMAIL
WHERE
(RTRIM(LTRIM(LEFT(DEPARTMENT,LEN(DEPARTMENT)-1))) <> RTRIM(LTRIM(COST_LOC)))
FOR XML PATH('tr'), ELEMENTS ) AS VARCHAR(MAX))
SET @BODY = @BODY + @RESULT_COST_LOC__AND_DISTRICT_NOT_MATCHING_HEADER+ @RESULT_COST_LOC__AND_DISTRICT_NOT_MATCHING +'</table>'
SET @BODY = @BODY + @HTMLFOOTER
USE DDDADMINISTRATION_DB
--SEND EMAIL
exec DDDADMINISTRATION_DB.dbo.uspSMTP_NOTIFY_HTML
@EmailSubject = 'District,Department & CostCenter Discrepancies',
@EmailMessage = @BODY,
@ToEmailAddress = '[email protected]',
@FromEmailAddress = '[email protected]'
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'MY POROFILE', -- replace with your SQL Database Mail Profile
@body = @BODY,
@body_format ='HTML',
@recipients = '[email protected]', -- replace with your email address
@subject = 'District,Department & CostCenter Discrepancies' ;
You can use title
attribute.
<img src="smiley.gif" title="Smiley face"/>
You can change the source of image as you want.
And as @Gray commented:
You can also use the title
on other things like <a ...
anchors, <p>
, <div>
, <input>
, etc.
See: this
You can use the explode function as follows:
$myvalue = 'Test me more';
$arr = explode(' ',trim($myvalue));
echo $arr[0]; // will print Test
How about this:
select * from fab_scheduler where custid = 1334666058 and eventdate = eventdate + INTERVAL 1 DAY
You don't really need a specific client, it's fairly simple with most libraries. For example in jQuery you can just call the generic $.ajax
function with the type of request you want to make:
$.ajax({
url: 'http://example.com/',
type: 'PUT',
data: 'ID=1&Name=John&Age=10', // or $('#myform').serializeArray()
success: function() { alert('PUT completed'); }
});
You can replace PUT
with GET
/POST
/DELETE
or whatever.
Q1:
Business logics can be considered in two categories:
Domain logics like controls on an email address (uniqueness, constraints, etc.), obtaining the price of a product for invoice, or, calculating the shoppingCart's total price based of its product objects.
More broad and complicated workflows which are called business processes, like controlling the registration process for the student (which usually includes several steps and needs different checks and has more complicated constraints).
The first category goes into model and the second one belongs to controller. This is because the cases in the second category are broad application logics and putting them in the model may mix the model's abstraction (for example, it is not clear if we need to put those decisions in one model class or another, since they are related to both!).
See this answer for a specific distinction between model and controller, this link for very exact definitions and also this link for a nice Android example.
The point is that the notes mentioned by "Mud" and "Frank" above both can be true as well as "Pete"'s (business logic can be put in model, or controller, according to the type of business logic).
Finally, note that MVC differs from context to context. For example, in Android applications, some alternative definitions are suggested that differs from web-based ones (see this post for example).
Q2:
Business logic is more general and (as "decyclone" mentioned above) we have the following relation between them:
business rules ? business logics
$ git clone --bare https://github.com/example
This command will make the new "example
" directory itself the $GIT_DIR (instead of example/.git
). Also the branch heads at the remote are copied directly to corresponding local branch heads, without mapping. When this option is used, neither remote-tracking branches nor the related configuration variables are created.
$ git clone --mirror https://github.com/example
As with a bare clone, a mirrored clone includes all remote branches and tags, but all local references (including remote-tracking branches, notes etc.) will be overwritten each time you fetch, so it will always be the same as the original repository.
So now assume the Customer wants to change his name in the webui - then there will be some controller action, where there will be the updated DTO with the old ID and the new name.
Normally, you have the following workflow:
P.S. This operation will inevitably issue 2 queries: select and update. Again, 2 queries, even if you wanna update a single field. However, if you utilize Hibernate's proprietary @DynamicUpdate annotation on top of entity class, it will help you not to include into update statement all the fields, but only those that actually changed.
P.S. If you do not wanna pay for first select statement and prefer to use Spring Data's @Modifying query, be prepared to lose L2C cache region related to modifiable entity; even worse situation with native update queries (see this thread) and also of course be prepared to write those queries manually, test them and support them in the future.
Try this:
jquery
$('#save-source').click(function (e) {
e.preventDefault();
var source = {
'ID': 0,
//'ProductID': $('#ID').val(),
'PartNumber': $('#part-number').val(),
//'VendorID': $('#Vendors').val()
}
$.ajax({
type: "POST",
dataType: "json",
url: "/api/PartSourceAPI",
data: source,
success: function (data) {
alert(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
//jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
}
});
});
Controller
public string Post(PartSourceModel model)
{
return model.PartNumber;
}
View
<label>Part Number</label>
<input type="text" id="part-number" name="part-number" />
<input type="submit" id="save-source" name="save-source" value="Add" />
Now when you click 'Add
' after you fill out the text box, the controller
will spit back out what you wrote in the PartNumber
box in an alert.
If all is you need is convertion from ListItem to your type T you can implement this convertion in T class as conversion operator.
public class T
{
public static implicit operator T(ListItem listItem) => /* ... */;
}
public static string GetAllItems(...)
{
...
List<T> tabListItems = new List<T>();
foreach (ListItem listItem in listCollection)
{
tabListItems.Add(listItem);
}
...
}
When the game starts:
long tStart = System.currentTimeMillis();
When the game ends:
long tEnd = System.currentTimeMillis();
long tDelta = tEnd - tStart;
double elapsedSeconds = tDelta / 1000.0;
There are two ways to achieve that:
-rpath
linker option:gcc XXX.c -o xxx.out -L$HOME/.usr/lib -lXX -Wl,-rpath=/home/user/.usr/lib
Use LD_LIBRARY_PATH
environment variable - put this line in your ~/.bashrc
file:
export LD_LIBRARY_PATH=/home/user/.usr/lib
This will work even for a pre-generated binaries, so you can for example download some packages from the debian.org, unpack the binaries and shared libraries into your home directory, and launch them without recompiling.
For a quick test, you can also do (in bash at least):
LD_LIBRARY_PATH=/home/user/.usr/lib ./xxx.out
which has the advantage of not changing your library path for everything else.
Simply compare the width of the documents root element (i.e. html element) against the inner portion of the window:
if ((window.innerWidth - document.documentElement.clientWidth) >0) console.log('V-scrollbar active')
If you also need to know the scrollbar width:
vScrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
/lkjasdf
has always been faster than :noh
for me.
One way:
set -- $(md5sum $file)
md5=$1
Another way:
md5=$(md5sum $file | while read sum file; do echo $sum; done)
Another way:
md5=$(set -- $(md5sum $file); echo $1)
(Do not try that with back-ticks unless you're very brave and very good with backslashes.)
The advantage of these solutions over other solutions is that they only invoke md5sum
and the shell, rather than other programs such as awk
or sed
. Whether that actually matters is then a separate question; you'd probably be hard pressed to notice the difference.
I use the following manner sqlconnection.state
if(conexion.state != connectionState.open())
conexion.open();
You either use :
background-image: url("images/plaid.jpg");
background-repeat: no-repeat;
... or
background: transparent url("images/plaid.jpg") top left no-repeat;
... but definitively not
background-image: url("images/plaid.jpg") no-repeat;
EDIT : Demo at JSFIDDLE using absolute paths (in case you have troubles referring to your images with relative paths).
Try this
RewriteCond %{HTTP_HOST} !^www. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
A number of the answers here are close, but a little more work than needed.
Create a shortcut to your script and configure it to "Run as Administrator":
Properties...
Target
from <script-path>
to powershell <script-path>
Run as administrator
The easy way: Pick an alternative Color Scheme:
Preferences > Color Scheme > ...pick one
The more complicated way: Edit the current color scheme file:
Preferences > Browse Packages > Color Scheme - Default > ... edit the Color Scheme file you are using:
Looking at the structure of the XML, drill down into dict > settings > settings > dict >
Look for the key (or add it if it's missing): lineHighlight
. Add a string with an #RRGGBB
or #RRGGBBAA
format.
Use .onkeydown
and cancel the removing with return false;
. Like this:
var input = document.getElementById('myInput');
input.onkeydown = function() {
var key = event.keyCode || event.charCode;
if( key == 8 || key == 46 )
return false;
};
Or with jQuery, because you added a jQuery tag to your question:
jQuery(function($) {
var input = $('#myInput');
input.on('keydown', function() {
var key = event.keyCode || event.charCode;
if( key == 8 || key == 46 )
return false;
});
});
?
SELECT [name]
FROM master.dbo.sysdatabases
WHERE dbid > 4
Works on our SQL Server 2008
size_t is returned by various libraries to indicate that the size of that container is non-zero. You use it when you get once back :0
However, in the your example above looping on a size_t is a potential bug. Consider the following:
for (size_t i = thing.size(); i >= 0; --i) {
// this will never terminate because size_t is a typedef for
// unsigned int which can not be negative by definition
// therefore i will always be >= 0
printf("the never ending story. la la la la");
}
the use of unsigned integers has the potential to create these types of subtle issues. Therefore imho I prefer to use size_t only when I interact with containers/types that require it.
Although this is a 9 yr old question, the problem persists!
I have been detecting resize while excluding zoom in a project, so I edited my code to make it work to detect both resize and zoom exclusive from one another. It works most of the time, so if most is good enough for your project, then this should be helpful! It detects zooming 100% of the time in what I've tested so far. The only issue is that if the user gets crazy (ie. spastically resizing the window) or the window lags it may fire as a zoom instead of a window resize.
It works by detecting a change in window.outerWidth
or window.outerHeight
as window resizing while detecting a change in window.innerWidth
or window.innerHeight
independent from window resizing as a zoom.
//init object to store window properties_x000D_
var windowSize = {_x000D_
w: window.outerWidth,_x000D_
h: window.outerHeight,_x000D_
iw: window.innerWidth,_x000D_
ih: window.innerHeight_x000D_
};_x000D_
_x000D_
window.addEventListener("resize", function() {_x000D_
//if window resizes_x000D_
if (window.outerWidth !== windowSize.w || window.outerHeight !== windowSize.h) {_x000D_
windowSize.w = window.outerWidth; // update object with current window properties_x000D_
windowSize.h = window.outerHeight;_x000D_
windowSize.iw = window.innerWidth;_x000D_
windowSize.ih = window.innerHeight;_x000D_
console.log("you're resizing"); //output_x000D_
}_x000D_
//if the window doesn't resize but the content inside does by + or - 5%_x000D_
else if (window.innerWidth + window.innerWidth * .05 < windowSize.iw ||_x000D_
window.innerWidth - window.innerWidth * .05 > windowSize.iw) {_x000D_
console.log("you're zooming")_x000D_
windowSize.iw = window.innerWidth;_x000D_
}_x000D_
}, false);
_x000D_
Note: My solution is like KajMagnus's, but this has worked better for me.
Another option with Filter
Filter(function(x) !all(is.na(x)), df)
NOTE: Data from @Simon O'Hanlon's post.
This will also work
let str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }"
let json = JSON.stringify(eval("("+ str +")"));
A better answer is to leave your script as it was. When doing the Select name
, follow it by -ExpandProperty Name
like so:
Get-ADGroupMember 'Domain Admins' | Select Name -ExpandProperty Name | out-file Admins.txt
DateTime dt = DateTime.ParseExact("11-22-2012 12:00 am", "MM-dd-yyyy hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);
Filter out the null instances before groupingBy.
Here is an exampleMyObjectlist.stream()
.filter(p -> p.getSomeInstance() != null)
.collect(Collectors.groupingBy(MyObject::getSomeInstance));
I realize this has been finished, but you may want to look at strncmp as it allows you to put the length of the string to compare against, so:
function startsWith($haystack, $needle, $case=true) {
if ($case)
return strncasecmp($haystack, $needle, strlen($needle)) == 0;
else
return strncmp($haystack, $needle, strlen($needle)) == 0;
}
As of Room 2.2.0 released October 2019, you can specify a Target Entity for updates. Then if the update parameter is different, Room will only update the partial entity columns. An example for the OP question will show this a bit more clearly.
@Update(entity = Tour::class)
fun update(obj: TourUpdate)
@Entity
public class TourUpdate {
@ColumnInfo(name = "id")
public long id;
@ColumnInfo(name = "endAddress")
private String endAddress;
}
Notice you have to a create a new partial entity called TourUpdate, along with your real Tour entity in the question. Now when you call update with a TourUpdate object, it will update endAddress and leave the startAddress value the same. This works perfect for me for my usecase of an insertOrUpdate method in my DAO that updates the DB with new remote values from the API but leaves the local app data in the table alone.
No, that's not possible. The port is not part of the hostname, so it has no meaning in the hosts
-file.
Here is a function to convert seconds to hh-mm-ss format based on powtac's answer here
/**
* Convert seconds to hh-mm-ss format.
* @param {number} totalSeconds - the total seconds to convert to hh- mm-ss
**/
var SecondsTohhmmss = function(totalSeconds) {
var hours = Math.floor(totalSeconds / 3600);
var minutes = Math.floor((totalSeconds - (hours * 3600)) / 60);
var seconds = totalSeconds - (hours * 3600) - (minutes * 60);
// round seconds
seconds = Math.round(seconds * 100) / 100
var result = (hours < 10 ? "0" + hours : hours);
result += "-" + (minutes < 10 ? "0" + minutes : minutes);
result += "-" + (seconds < 10 ? "0" + seconds : seconds);
return result;
}
Example use
var seconds = SecondsTohhmmss(70);
console.log(seconds);
// logs 00-01-10
Since this is one of the top search results for questions related to this I felt it was worth mentioning how you can make this work with Kendo().DropDownListFor() as well.
Everything is the same as with OnaBai's post except for how you select the item based off of its text and your selector.
To do that you would swap out dataItem.symbol for dataItem.[DataTextFieldName]. Whatever model field you used for .DataTextField() is what you will be comparing against.
@(Html.Kendo().DropDownListFor(model => model.Status.StatusId)
.Name("Status.StatusId")
.DataTextField("StatusName")
.DataValueField("StatusId")
.BindTo(...)
)
//So that your ViewModel gets bound properly on the post, naming is a bit
//different and as such you need to replace the periods with underscores
var ddl = $('#Status_StatusId').data('kendoDropDownList');
ddl.select(function(dataItem) {
return dataItem.StatusName === "Active";
});
<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(function() {
//here you have the control over the body of the iframe document
var iBody = $("#iView").contents().find("body");
//here you have the control over any element (#myContent)
var myContent = iBody.find("#myContent");
});
</script>
</head>
<body>
<iframe src="mifile.html" id="iView" style="width:200px;height:70px;border:dotted 1px red" frameborder="0"></iframe>
</body>
</html>
You need to find reference of existing Fragment and remove that fragment using below code. You need add/commit fragment using one tag ex. "TAG_FRAGMENT".
Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
if(fragment != null)
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
That is it.
In mac osx , you can use the following command:
system_profiler SPUSBDataType
I am having the same problem, and I guess the way of doing this will be to remove the data-toggle attribute and have a custom handler for the links.
Something in the lines of:
$("a[data-target=#myModal]").click(function(ev) {
ev.preventDefault();
var target = $(this).attr("href");
// load the url and show modal on success
$("#myModal .modal-body").load(target, function() {
$("#myModal").modal("show");
});
});
Will try it later and post comments.
This is what I use to sort in memory - it can easily be expanded to sort an array.
Sub sortlist()
Dim xarr As Variant
Dim yarr As Variant
Dim zarr As Variant
xarr = Sheets("sheet").Range("sing col range")
ReDim yarr(1 To UBound(xarr), 1 To 1)
ReDim zarr(1 To UBound(xarr), 1 To 1)
For n = 1 To UBound(xarr)
zarr(n, 1) = 1
Next n
For n = 1 To UBound(xarr) - 1
y = zarr(n, 1)
For a = n + 1 To UBound(xarr)
If xarr(n, 1) > xarr(a, 1) Then
y = y + 1
Else
zarr(a, 1) = zarr(a, 1) + 1
End If
Next a
yarr(y, 1) = xarr(n, 1)
Next n
y = zarr(UBound(xarr), 1)
yarr(y, 1) = xarr(UBound(xarr), 1)
yrng = "A1:A" & UBound(yarr)
Sheets("sheet").Range(yrng) = yarr
End Sub
If none of the above worked for you, you can specify the module explicitly.
Directory:
+-- Project
¦ +-- Dir
¦ ¦ +-- __init__.py
¦ ¦ +-- module.py
¦ ¦ +-- standalone.py
Solution:
#in standalone.py
from Project.Dir.module import ...
module - the module to be imported
Microsoft just added an official prelease version of exactly what you're looking for (called a MultiDictionary) available through NuGet here: https://www.nuget.org/packages/Microsoft.Experimental.Collections/
Info on usage and more details can be found through the official MSDN blog post here: http://blogs.msdn.com/b/dotnet/archive/2014/06/20/would-you-like-a-multidictionary.aspx
I'm the developer for this package, so let me know either here or on MSDN if you have any questions about performance or anything.
Hope that helps.
Update
The MultiValueDictionary
is now on the corefxlab repo, and you can get the NuGet package from this MyGet feed.
The problem with MAC address is that there can be many network adapters connected to the computer. Most of the newest ones have two by default (wi-fi + cable). In such situation one would have to know which adapter's MAC address should be used. I tested MAC solution on my system, but I have 4 adapters (cable, WiFi, TAP adapter for Virtual Box and one for Bluetooth) and I was not able to decide which MAC I should take... If one would decide to use adapter which is currently in use (has addresses assigned) then new problem appears since someone can take his/her laptop and switch from cable adapter to wi-fi. With such condition MAC stored when laptop was connected through cable will now be invalid.
For example those are adapters I found in my system:
lo MS TCP Loopback interface
eth0 Intel(R) Centrino(R) Advanced-N 6205
eth1 Intel(R) 82579LM Gigabit Network Connection
eth2 VirtualBox Host-Only Ethernet Adapter
eth3 Sterownik serwera dostepu do sieci LAN Bluetooth
Code I've used to list them:
Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
while (nis.hasMoreElements()) {
NetworkInterface ni = nis.nextElement();
System.out.println(ni.getName() + " " + ni.getDisplayName());
}
From the options listen on this page, the most acceptable for me, and the one I've used in my solution is the one by @Ozhan Duz, the other one, similar to @finnw answer where he used JACOB, and worth mentioning is com4j - sample which makes use of WMI is available here:
ISWbemLocator wbemLocator = ClassFactory.createSWbemLocator();
ISWbemServices wbemServices = wbemLocator.connectServer("localhost","Root\\CIMv2","","","","",0,null);
ISWbemObjectSet result = wbemServices.execQuery("Select * from Win32_SystemEnclosure","WQL",16,null);
for(Com4jObject obj : result) {
ISWbemObject wo = obj.queryInterface(ISWbemObject.class);
System.out.println(wo.getObjectText_(0));
}
This will print some computer information together with computer Serial Number. Please note that all classes required by this example has to be generated by maven-com4j-plugin. Example configuration for maven-com4j-plugin:
<plugin>
<groupId>org.jvnet.com4j</groupId>
<artifactId>maven-com4j-plugin</artifactId>
<version>1.0</version>
<configuration>
<libId>565783C6-CB41-11D1-8B02-00600806D9B6</libId>
<package>win.wmi</package>
<outputDirectory>${project.build.directory}/generated-sources/com4j</outputDirectory>
</configuration>
<executions>
<execution>
<id>generate-wmi-bridge</id>
<goals>
<goal>gen</goal>
</goals>
</execution>
</executions>
</plugin>
Above's configuration will tell plugin to generate classes in target/generated-sources/com4j directory in the project folder.
For those who would like to see ready-to-use solution, I'm including links to the three classes I wrote to get machine SN on Windows, Linux and Mac OS:
There are multiple options:
txtBox.Focus();
txtBox.SelectionStart = txtBox.Text.Length;
OR
txtBox.Focus();
txtBox.CaretIndex = txtBox.Text.Length;
OR
txtBox.Focus();
txtBox.Select(txtBox.Text.Length, 0);
Use history.replaceState
or history.pushState
* to change the hash. This will not trigger the jump to the associated element.
$(document).on('click', 'a[href^=#]', function(event) {
event.preventDefault();
history.pushState({}, '', this.href);
});
* If you want history forward and backward support
If you are using history.pushState
and you don't want page scrolling when the user uses the history buttons of the browser (forward/backward) check out the experimental scrollRestoration
setting (Chrome 46+ only).
history.scrollRestoration = 'manual';
I done it, below code is working for me....
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.hello_world, container, false);
Button newPage = (Button)v.findViewById(R.id.click);
newPage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), HomeActivity.class);
startActivity(intent);
}
});
return v;
}
and Please make sure that your destination activity should be register in Manifest.xml file,
but in my case all tabs are not shown in HomeActivity, is any solution for that ?
A compact, flexible method for timestamps without fractional seconds would be:
SELECT * FROM table_name
WHERE field_name
BETWEEN UNIX_TIMESTAMP('2010-10-01') AND UNIX_TIMESTAMP('2010-10-31 23:59:59')
If you are using fractional seconds and a recent version of MySQL then you would be better to take the approach of using the >=
and <
operators as per Wouter's answer.
Here is an example of temporal fields defined with fractional second precision (maximum precision in use):
mysql> create table time_info (t_time time(6), t_datetime datetime(6), t_timestamp timestamp(6), t_short timestamp null);
Query OK, 0 rows affected (0.02 sec)
mysql> insert into time_info set t_time = curtime(6), t_datetime = now(6), t_short = t_datetime;
Query OK, 1 row affected (0.01 sec)
mysql> select * from time_info;
+-----------------+----------------------------+----------------------------+---------------------+
| 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34 |
+-----------------+----------------------------+----------------------------+---------------------+
1 row in set (0.00 sec)
I have gone through many links but this answer helped me alot:
$scope.redirectPage = function (data) {
$window.open(data, "popup", "width=1000,height=700,left=300,top=200");
};
** data will be absolute url which you are hitting.
Simple Solution:
JsonElement element = new JsonParser().parse(new InputStreamReader(inputStream));
JSONObject jsonObject = new JSONObject(element.getAsJsonObject().toString());
a nice way from http://try.jquery.com/levels/4/challenges/16 :
adding a + before the string without using parseInt and parseFloat and radix and errors i faced for missing radix parameter
sample
var number= +$('#inputForm').val();
I faced the same issue. Just download and install the SQL Server suite from the following link :http://www.microsoft.com/en-US/download/details.aspx?id=42299
restart your SSMS and you should be able to "Register Local Servers" via right-click on "Local Servers Groups", select "tasks", click "register local servers"
Add default constructors to all the entity classes
Consider using matplotlib.cbook pieces
for example:
import matplotlib.cbook as cbook
segments = cbook.pieces(np.arange(20), 3)
for s in segments:
print s
To expand on Konrad's comment:
and the order of evaluation is not well-defined
Some functional languages have what is called Lazy Evaluation. Which means a function is not executed until the value is needed. Until that time the function itself is what is passed around.
Procedural languages are step 1 step 2 step 3... if in step 2 you say add 2 + 2, it does it right then. In lazy evaluation you would say add 2 + 2, but if the result is never used, it never does the addition.
You can utilize the dependency management mechanism.
If you create entries in the <dependencyManagement> section of your pom for spring-security-web and spring-web with the desired 3.1.0 version set the managed version of the artifact will override those specified in the transitive dependency tree.
I'm not sure if that really saves you any code, but it is a cleaner solution IMO.
I think that you should use a connection pool instead of share a single connection. A connection pool would provide a much better performance, as you can check here.
As stated in the library documentation, it occurs because the MySQL protocol is sequential (this means that you need multiple connections to execute queries in parallel).
Debian 9 solution:
touch /etc/apache2/conf-available/php.conf
Add to file next lines:
<IfModule mod_php5.c>
<IfModule mod_mime.c>
AddType application/x-httpd-php .php
</IfModule>
<FilesMatch ".+\.php$">
SetHandler application/x-httpd-php
</FilesMatch>
</IfModule>
<IfModule mod_php.c>
<IfModule mod_mime.c>
AddType application/x-httpd-php .php
</IfModule>
<FilesMatch ".+\.php$">
SetHandler application/x-httpd-php
</FilesMatch>
</IfModule>
Then run:
a2enconf php && service apache2 restart
The click handler that you are trying to trigger is most likely also attached via $(document).ready()
. What is probably happening is that you are triggering the event before the handler is attached. The solution is to use setTimeout
:
$("document").ready(function() {
setTimeout(function() {
$("ul.galleria li:first-child img").trigger('click');
},10);
});
A delay of 10ms will cause the function to run immediately after all the $(document).ready()
handlers have been called.
OR you check if the element is ready:
$("document").ready(function() {
$("ul.galleria li:first-child img").ready(function() {
$(this).click();
});
});
Easiest way is to just run: which python
, if you are in a virtualenv it will point to its python instead of the global one
Delete all spaces and line breaks between <textarea>
opening and closing </textarea>
tags.
<textarea placeholder="YOUR TEXT"></textarea> ///Correct one
<textarea placeholder="YOUR TEXT"> </textarea> ///Bad one It's treats as a value so browser won't display the Placeholder value
<textarea placeholder="YOUR TEXT">
</textarea> ///Bad one
Clickable smartphone link code:
The following link can be used to make a clickable phone link. You can copy the code below and paste it into your webpage, then edit with your phone number. This code may not work on all phones but does work for iPhone, Droid / Android, and Blackberry.
<a href="tel:1-847-555-5555">1-847-555-5555</a>
Phone number links can be used with the dashes, as shown above, or without them as well as in the following example:
<a href="tel:18475555555">1-847-555-5555</a>
It is also possible to use any text in the link as long as the phone number is set up with the "tel:18475555555" as in this example:
<a href="tel:18475555555">Click Here To Call Support 1-847-555-5555</a>
Below is a clickable telephone hyperlink you can check out. In most non-phone browsers this link will give you a "The webpage cannot be displayed" error or nothing will happen.
NOTE: The iPhone Safari browser will automatically detect a phone number on a page and will convert the text into a call link without using any of the code on this page.
WTAI smartphone link code: The WTAI or "Wireless Telephony Application Interface" link code is shown below. This code is considered to be the correct mobile phone protocol and will work on smartphones like Droid, however, it may not work for Apple Safari on iPhone and the above code is recommended.
<a href="wtai://wp/mc;18475555555">Click Here To Call Support 1-847-555-5555</a>
Xamarin
Label.Font = UIFont.FromName("Copperplate", 10.0f);
Swift
text.font = UIFont.init(name: "Poppins-Regular", size: 14)
To get the list of font family Github/IOS-UIFont-Names
OPTIONS tells you things such as "What methods are allowed for this resource".
HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned. The availability is only a small part of it.
Immutable variable with immutable (read only) list:
val users: List<User> = listOf( User("Tom", 32), User("John", 64) )
Immutable variable with mutable list:
val users: MutableList<User> = mutableListOf( User("Tom", 32), User("John", 64) )
or without initial value - empty list and without explicit variable type:
val users = mutableListOf<User>()
//or
val users = ArrayList<User>()
users.add(anohterUser)
or users += anotherUser
(under the hood it's users.add(anohterUser)
)Mutable variable with immutable list:
var users: List<User> = listOf( User("Tom", 32), User("John", 64) )
or without initial value - empty list and without explicit variable type:
var users = emptyList<User>()
users += anotherUser
- *it creates new ArrayList and assigns it to users
Mutable variable with mutable list:
var users: MutableList<User> = mutableListOf( User("Tom", 32), User("John", 64) )
or without initial value - empty list and without explicit variable type:
var users = emptyList<User>().toMutableList()
//or
var users = ArrayList<User>()
users.add(anohterUser)
users += anotherUser
Error: Kotlin: Assignment operators ambiguity:
public operator fun Collection.plus(element: String): List defined in kotlin.collections
@InlineOnly public inline operator fun MutableCollection.plusAssign(element: String): Unit defined in kotlin.collections
see also:
https://kotlinlang.org/docs/reference/collections.html
You need to split the line first.
import csv
with open('log.txt', 'r') as in_file:
stripped = (line.strip() for line in in_file)
lines = (line.split(",") for line in stripped if line)
with open('log.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('title', 'intro'))
writer.writerows(lines)
It's fatal. The remote server has sent you a RST packet, which indicates an immediate dropping of the connection, rather than the usual handshake. This bypasses the normal half-closed state transition. I like this description:
"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur.
just for modifying certain property from object collection you could directly use forEach with a collection as follows
collection.forEach(c -> c.setXyz(c.getXyz + "a"))
In case anyone still has to support legacy fancybox with jQuery 3.0+ here are some other changes you'll have to make:
.unbind() deprecated
Replace all instances of .unbind
with .off
.removeAttribute() is not a function
Change lines 580-581 to use jQuery's .removeAttr()
instead:
Old code:
580: content[0].style.removeAttribute('filter');
581: wrap[0].style.removeAttribute('filter');
New code:
580: content.removeAttr('filter');
581: wrap.removeAttr('filter');
This combined with the other patch mentioned above solved my compatibility issues.
If you are looking to block the execution of code with call to sleep
, then no, there is no method for that in JavaScript
.
JavaScript
does have setTimeout
method. setTimeout
will let you defer execution of a function for x milliseconds.
setTimeout(myFunction, 3000);
// if you have defined a function named myFunction
// it will run after 3 seconds (3000 milliseconds)
Remember, this is completely different from how sleep
method, if it existed, would behave.
function test1()
{
// let's say JavaScript did have a sleep function..
// sleep for 3 seconds
sleep(3000);
alert('hi');
}
If you run the above function, you will have to wait for 3 seconds (sleep
method call is blocking) before you see the alert 'hi'. Unfortunately, there is no sleep
function like that in JavaScript
.
function test2()
{
// defer the execution of anonymous function for
// 3 seconds and go to next line of code.
setTimeout(function(){
alert('hello');
}, 3000);
alert('hi');
}
If you run test2, you will see 'hi' right away (setTimeout
is non blocking) and after 3 seconds you will see the alert 'hello'.
If you're using PHP 5.3+ take a look at the $before_needle flag of strstr()
$s = 'Posted On April 6th By Some Dude';
echo strstr($s, 'By', true);
'parent.relativePath' points at wrong local POM @ myGroup:myParentArtifactId:1.0, C:\myProjectDir\parent\pom.xml
This indicates that maven did search locally for the parent pom, but found that it was not the correct pom.
pom.xml
of parentpom
correctly define the parent
pom as the pom.xml
of rootpom
?rootpom
folder contain pom.xml
as well as the paretpom
folder?You can use the IAsyncResult and Action class/interface to achieve this.
public void TimeoutExample()
{
IAsyncResult result;
Action action = () =>
{
// Your code here
};
result = action.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(10000))
Console.WriteLine("Method successful.");
else
Console.WriteLine("Method timed out.");
}
You should first pull
the changes from the develop
branch and only then merge them to your branch:
git checkout develop
git pull
git checkout branch-x
git rebase develop
Or, when on branch-x
:
git fetch && git rebase origin/develop
I have an alias that saves me a lot of time. Add to your ~/.gitconfig
:
[alias]
fr = "!f() { git fetch && git rebase origin/"$1"; }; f"
Now, all that you have to do is:
git fr develop
UPDATE: As Brad Parks wrote in his comment there is a much better and easier solution with only one line of JS code:
run
setTimeout(function(){debugger;},5000);
, then go show your element and wait until it breaks into the Debugger
Original answer:
I just had the same problem, and I think I found an "universal" solution. (assuming the site uses jQuery)
Hope it helps someone!
<body>
and click "Edit as HTML"<body>
then press Ctrl+Enter: <div id="debugFreeze" data-rand="0"></div>
setTimeout(function(){$("#debugFreeze").attr("data-rand",Math.random())},5000);
Of course you can modify the javascript and the timing, if you get the idea.
var uniq = allvalues.GroupBy(x => x.Id).Select(y=>y.First()).Distinct();
Easy and simple
legend
and/or colors
to some vertical lines, then use this:import matplotlib.pyplot as plt
# x coordinates for the lines
xcoords = [0.1, 0.3, 0.5]
# colors for the lines
colors = ['r','k','b']
for xc,c in zip(xcoords,colors):
plt.axvline(x=xc, label='line at x = {}'.format(xc), c=c)
plt.legend()
plt.show()
Results:
If you have SSH access, you don't need to SSH first and then copy, just use Secure Copy (SCP) from the destination.
scp user@host:/path/file /localpath/file
Wild card characters are supported, so
scp user@host:/path/folder/* /localpath/folder
will copy all of the remote files in that folder.If copying more then one directory.
note -r will copy all sub-folders and content too.
If you don't want/need to be tied to a concrete class, you can pass JSON directly to a WebAPI controller. The controller is able to accept the JSON by using the ExpandoObject type. Here is the method example:
public void Post([FromBody]ExpandoObject json)
{
var keyValuePairs = ((System.Collections.Generic.IDictionary<string, object>)json);
}
Set the Content-Type header to application/json and send the JSON as the body. The keyValuePairs object will contain the JSON key/value pairs.
Or you can have the method accept the incoming JSON as a JObject type (from Newtonsoft JSON library), and by setting it to a dynamic type, you can access the properties by dot notation.
public void Post([FromBody]JObject _json)
{
dynamic json = _json;
}
It's easy to define one yourself. That's the power of JavaScript.
if(!Array.prototype.last) {
Array.prototype.last = function() {
return this[this.length - 1];
}
}
var arr = [1, 2, 5];
arr.last(); // 5
However, this may cause problems with 3rd-party code which (incorrectly) uses for..in
loops to iterate over arrays.
However, if you are not bound with browser support problems, then using the new ES5 syntax to define properties can solve that issue, by making the function non-enumerable, like so:
Object.defineProperty(Array.prototype, 'last', {
enumerable: false,
configurable: true,
get: function() {
return this[this.length - 1];
},
set: undefined
});
var arr = [1, 2, 5];
arr.last; // 5
In short it is much simple compared to html, the long doctype is removed and also center and font tag is removed. I also answered this difference in my blog : http://ravisinghblog.in/key-difference-between-html-and-html-5/
Just to clarify -- as noted above when rebasing the sense is reversed, so if you see
<<<<<<< HEAD
foo = 12;
=======
foo = 22;
>>>>>>> [your commit message]
Resolve using 'mine' -> foo = 12
Resolve using 'theirs' -> foo = 22
If it is necessary for you to have a relative width (in percentage), you could wrap your div in a absolute positioned one:
div#wrapper {
position: absolute;
width: 100%;
text-align: center;
}
Remember that in order to position an element absolutely, the parent element must be positioned relatively.
Based on my experience, SmartInspect beats both NLog and log4net.
Its extremely easy to use, documentation is great, and you can view and filter previously logged messages with their interactive log viewer, which is a huge real world advantage.
One thing I like is the tabbed views of data, like the browser tabs in Chrome. Each tab can provide a different filtered view of the log.
You can follow below steps to embed the files you want to your website.
References: https://www.steegle.com/websites/google-sites-howtos/embed-drive-pdf
np.count_nonzero(~np.isnan(data))
~
inverts the boolean matrix returned from np.isnan
.
np.count_nonzero
counts values that is not 0\false. .sum
should give the same result. But maybe more clearly to use count_nonzero
Testing speed:
In [23]: data = np.random.random((10000,10000))
In [24]: data[[np.random.random_integers(0,10000, 100)],:][:, [np.random.random_integers(0,99, 100)]] = np.nan
In [25]: %timeit data.size - np.count_nonzero(np.isnan(data))
1 loops, best of 3: 309 ms per loop
In [26]: %timeit np.count_nonzero(~np.isnan(data))
1 loops, best of 3: 345 ms per loop
In [27]: %timeit data.size - np.isnan(data).sum()
1 loops, best of 3: 339 ms per loop
data.size - np.count_nonzero(np.isnan(data))
seems to barely be the fastest here. other data might give different relative speed results.
The sp_xml_preparedocument
stored procedure will parse the XML and the OPENXML
rowset provider will show you a relational view of the XML data.
For details and more examples check the OPENXML documentation.
As for your question,
DECLARE @XML XML
SET @XML = '<rows><row>
<IdInvernadero>8</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>8</IdCaracteristica1>
<IdCaracteristica2>8</IdCaracteristica2>
<Cantidad>25</Cantidad>
<Folio>4568457</Folio>
</row>
<row>
<IdInvernadero>3</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>1</IdCaracteristica1>
<IdCaracteristica2>2</IdCaracteristica2>
<Cantidad>72</Cantidad>
<Folio>4568457</Folio>
</row></rows>'
DECLARE @handle INT
DECLARE @PrepareXmlStatus INT
EXEC @PrepareXmlStatus= sp_xml_preparedocument @handle OUTPUT, @XML
SELECT *
FROM OPENXML(@handle, '/rows/row', 2)
WITH (
IdInvernadero INT,
IdProducto INT,
IdCaracteristica1 INT,
IdCaracteristica2 INT,
Cantidad INT,
Folio INT
)
EXEC sp_xml_removedocument @handle
.NetCore is a fine release from Microsoft and Visual Studio's latest version is also available for mac but there is still some limitation. Like for creating GUI based application on .net core you have to write code manually for everything. Like in older version of VS we just drag and drop the things and magic happens. But in VS latest version for mac every code has to be written manually. However you can make web application and console application easily on VS for mac.
If you're using ZLib in your project, then you need to find :
#if 1
in zconf.h and replace(uncomment) it with :
#if HAVE_UNISTD_H /* ...the rest of the line
If it isn't ZLib I guess you should find some alternative way to do this. GL.
Your regex seems a bit too complex in my opinion. Also, remember that the dot is a special character meaning "any character". The following regex should work (note the escaped dots):
^.*\.(jpg|JPG|gif|GIF|doc|DOC|pdf|PDF)$
You can use a tool like Expresso to test your regular expressions.
in you aspx file you should put the first line as this :
<%@ Page EnableEventValidation="false" %>
if you already have something like <%@ Page
so just add the rest => EnableEventValidation="false" %>
I recommend not to do it.
If you want to copy the current dir's contents, you can run:
docker build -t <imagename:tag> -f- ./ < Dockerfile
This will depend on the logging configuration. The default value will depend on the framework being used. The idea is that later on by changing a configuration setting from INFO to DEBUG you will see a ton of more (or less if the other way around) lines printed without recompiling the whole application.
If you think which one to use then it boils down to thinking what you want to see on which level. For other levels for example in Log4J look at the API, http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Level.html
Just another answer
Array.prototype.filter.call(
document.getElementsByTagName('span'),
function(el) {return el.getAttribute('property') == 'v.name';}
);
In future
Array.prototype.filter.call(
document.getElementsByTagName('span'),
(el) => el.getAttribute('property') == 'v.name'
)
Intro
The call() method calls a function with a given this value and arguments provided individually.
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Given this html markup
<span property="a">apple - no match</span>
<span property="v:name">onion - match</span>
<span property="b">root - match</span>
<span property="v:name">tomato - match</span>
<br />
<button onclick="findSpan()">find span</button>
you can use this javascript
function findSpan(){
var spans = document.getElementsByTagName('span');
var spansV = Array.prototype.filter.call(
spans,
function(el) {return el.getAttribute('property') == 'v:name';}
);
return spansV;
}
See demo
In case someone wanted an example using variables...
#!/bin/bash
# Only continue for 'develop' or 'release/*' branches
BRANCH_REGEX="^(develop$|release//*)"
if [[ $BRANCH =~ $BRANCH_REGEX ]];
then
echo "BRANCH '$BRANCH' matches BRANCH_REGEX '$BRANCH_REGEX'"
else
echo "BRANCH '$BRANCH' DOES NOT MATCH BRANCH_REGEX '$BRANCH_REGEX'"
fi
There is a huge difference.
As most of the answers have already pointed out the theory, I would like to point out an easy example:
int x = 1;
//would print 1 as first statement will x = x and then x will increase
int x = x++;
System.out.println(x);
Now let's see ++x
:
int x = 1;
//would print 2 as first statement will increment x and then x will be stored
int x = ++x;
System.out.println(x);
If nothing worked for you, make sure the file is not open in another program. I was trying to import an xlsx file and Excel was blocking me from doing so.
// app.js
let db = ...; // your db object initialized
const contextMiddleware = (req, res, next) => {
req.db=db;
next();
};
app.use(contextMiddleware);
// routes.js It's just a mapping.
exports.routes = [
['/', controllers.index],
['/posts', controllers.posts.index],
['/posts/:post', controllers.posts.show]
];
// app.js
var { routes } = require('./routes');
routes.forEach(route => app.get(...route));
// You can customize this according to your own needs, like adding post request
The final app.js:
// app.js
var express = require('express');
var app = express.createServer();
let db = ...; // your db object initialized
const contextMiddleware = (req, res, next) => {
req.db=db;
next();
};
app.use(contextMiddleware);
var { routes } = require('./routes');
routes.forEach(route => app.get(...route));
app.listen(3000, function() {
console.log('Application is listening on port 3000');
});
Another version: you can customize this according to your own needs, like adding post request
// routes.js It's just a mapping.
let get = ({path, callback}) => ({app})=>{
app.get(path, callback);
}
let post = ({path, callback}) => ({app})=>{
app.post(path, callback);
}
let someFn = ({path, callback}) => ({app})=>{
// ...custom logic
app.get(path, callback);
}
exports.routes = [
get({path: '/', callback: controllers.index}),
post({path: '/posts', callback: controllers.posts.index}),
someFn({path: '/posts/:post', callback: controllers.posts.show}),
];
// app.js
var { routes } = require('./routes');
routes.forEach(route => route({app}));
Using docker links, you can link the upstream container to the nginx container. An added feature is that docker manages the host file, which means you'll be able to refer to the linked container using a name rather than the potentially random ip.
You can wrap the person objects into another class, that only compares the names of the persons. Afterward, you unwrap the wrapped objects to get a person stream again. The stream operations might look as follows:
persons.stream()
.map(Wrapper::new)
.distinct()
.map(Wrapper::unwrap)
...;
The class Wrapper
might look as follows:
class Wrapper {
private final Person person;
public Wrapper(Person person) {
this.person = person;
}
public Person unwrap() {
return person;
}
public boolean equals(Object other) {
if (other instanceof Wrapper) {
return ((Wrapper) other).person.getName().equals(person.getName());
} else {
return false;
}
}
public int hashCode() {
return person.getName().hashCode();
}
}
If you would like to 'add' additional items to a page, you may want to create an array of maps. This is how I created an array of maps and then added results to it:
import { Product } from '../models/product';
products: Array<Product>; // Initialize the array.
[...]
let i = 0;
this.service.products( i , (result) => {
if ( i == 0 ) {
// Create the first element of the array.
this.products = Array(result);
} else {
// Add to the array of maps.
this.products.push(result);
}
});
Where product.ts look like...
export class Product {
id: number;
[...]
}
I would just point out that... there are many kind of unordered_map
s.
Look up the Wikipedia Article on hash map. Depending on which implementation was used, the characteristics in term of look-up, insertion and deletion might vary quite significantly.
And that's what worries me the most with the addition of unordered_map
to the STL: they will have to choose a particular implementation as I doubt they'll go down the Policy
road, and so we will be stuck with an implementation for the average use and nothing for the other cases...
For example some hash maps have linear rehashing, where instead of rehashing the whole hash map at once, a portion is rehash at each insertion, which helps amortizing the cost.
Another example: some hash maps use a simple list of nodes for a bucket, others use a map, others don't use nodes but find the nearest slot and lastly some will use a list of nodes but reorder it so that the last accessed element is at the front (like a caching thing).
So at the moment I tend to prefer the std::map
or perhaps a loki::AssocVector
(for frozen data sets).
Don't get me wrong, I'd like to use the std::unordered_map
and I may in the future, but it's difficult to "trust" the portability of such a container when you think of all the ways of implementing it and the various performances that result of this.
$result->num_rows; only returns the number of row(s) affected by a query. When you are performing a count(*) on a table it only returns one row so you can not have an other result than 1.
What you can do is:
Update your local git repo:
git fetch
Build a local branch and checkout on it:
git branch pouet && git checkout pouet
Apply the commit you want on this branch:
git cherry-pick abcdefabcdef
(abcdefabcdef is the sha1 of the commit you want to apply)
default_url_options
to use your action_mailer.default_url_options
.In each of your environment files (e.g. development.rb
, production.rb
, etc.) you can specify the default_url_options
to use for action_mailer
:
config.action_mailer.default_url_options = { host: 'lvh.me', port: '3000' }
However, these are not set for MyApp:Application.default_url_options
:
$ MyApp::Application.config.action_mailer.default_url_options
#=> {:host=>"lvh.me", :port=>"3000"}
$ MyApp::Application.default_url_options
#=> {}
That's why you are getting that error in anything outside of ActionMailer
.
You can set your Application's default_url_options
to use what you defined for action_mailer
in the appropriate environment file (development.rb
, production.rb
, etc.).
To keep things as DRY as possible, do this in your config/environment.rb
file so you only have to do this once:
# Initialize the rails application
MyApp::Application.initialize!
# Set the default host and port to be the same as Action Mailer.
MyApp::Application.default_url_options = MyApp::Application.config.action_mailer.default_url_options
Now when you boot up your app, your entire Application's default_url_options
will match your action_mailer.default_url_options
:
$ MyApp::Application.config.action_mailer.default_url_options
#=> {:host=>"lvh.me", :port=>"3000"}
$ MyApp::Application.default_url_options
#=> {:host=>"lvh.me", :port=>"3000"}
Hat tip to @pduersteler for leading me down this path.
If the input happens to be in a bootstrap modal dialog, the answer is different. Copying from How to Set focus to first text input in a bootstrap modal after shown this is what is required:
$('#myModal').on('shown.bs.modal', function () {
$('#textareaID').focus();
})
When you
import App from './App.jsx';
That means it will import whatever you export default
. You can rename App
class inside App.jsx
to whatever you want as long as you export default
it will work but you can only have one export default.
So you only need to export default App
and you don't need to export the rest.
If you still want to export the rest of the components, you will need named export.
https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export
using System;
public static class DataTypeExtensions
{
#region Methods
public static string Left(this string str, int length)
{
str = (str ?? string.Empty);
return str.Substring(0, Math.Min(length, str.Length));
}
public static string Right(this string str, int length)
{
str = (str ?? string.Empty);
return (str.Length >= length)
? str.Substring(str.Length - length, length)
: str;
}
#endregion
}
Shouldn't error, returns nulls as empty string, returns trimmed or base values. Use it like "testx".Left(4) or str.Right(12);
Just like you said
select * from tbl where statusid is null
or
select * from tbl where statusid is not null
If your statusid is not null, then it will be selected just fine when you have an actual value, no need for any "if" logic if that is what you were thinking
select * from tbl where statusid = 123 -- the record(s) returned will not have null statusid
if you want to select where it is null or a value, try
select * from tbl where statusid = 123 or statusid is null
[EDIT 2020]-> Now I totally recommend the answer here, way easier using android studio, faster and no need to wright any code - the one below was back in the eclipse days :) -.
You can use this code in any activity. It will log the hashkey in the logcat, which is the debug key. This is easy, and it's a relief than using SSL.
PackageInfo info;
try {
info = getPackageManager().getPackageInfo("com.you.name", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md;
md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String something = new String(Base64.encode(md.digest(), 0));
//String something = new String(Base64.encodeBytes(md.digest()));
Log.e("hash key", something);
}
} catch (NameNotFoundException e1) {
Log.e("name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("no such an algorithm", e.toString());
} catch (Exception e) {
Log.e("exception", e.toString());
}
You can delete the code after knowing the key ;)
One of the reason may be improper date/time of your PC.
In Ubuntu PC to check the date and time using:
date
Example, One of the ways to update date and time is:
date -s "23 MAR 2017 17:06:00"
When displaying I sometimes make a new file called Funk. This will have the font, size etc. This is the code for the class:
import pygame
def text_to_screen(screen, text, x, y, size = 50,
color = (200, 000, 000), font_type = 'data/fonts/orecrusherexpand.ttf'):
try:
text = str(text)
font = pygame.font.Font(font_type, size)
text = font.render(text, True, color)
screen.blit(text, (x, y))
except Exception, e:
print 'Font Error, saw it coming'
raise e
Then when that has been imported when I want to display text taht updates E.G score I do:
Funk.text_to_screen(screen, 'Text {0}'.format(score), xpos, ypos)
If it is just normal text that isn't being updated:
Funk.text_to_screen(screen, 'Text', xpos, ypos)
You may notice {0} on the first example. That is because when .format(whatever) is used that is what will be updated. If you have something like Score then target score you'd do {0} for score then {1} for target score then .format(score, targetscore)
Go into your AndroidManifest.xml file
Enjoy using a gui rather then messing with an image editor! Hope this helps!
This works in Chrome, Firefox, doesn't work in Safari :(, haven't tested in other browsers
delete window.document.referrer;
window.document.__defineGetter__('referrer', function () {
return "yoururl.com";
});
Saw that here https://gist.github.com/papoms/3481673
Regards
test case: https://jsfiddle.net/bez3w4ko/ (so you can easily test several browsers) and here is a test with iframes https://jsfiddle.net/2vbfpjp1/1/
The easy way that works in 2019
Disable implicit oauth under the security auth and THEN load this:
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token
Specify REDIRECT-URI in your account and type it exactly as specified.
:goto 21490
will take you to the 21490th byte in the buffer.
If you want to ignore lines with only whitespace:
if not line.strip():
... do something
The empty string is a False value.
Or if you really want only empty lines:
if line in ['\n', '\r\n']:
... do something
I had a similar warning/error/failure when I was simply trying to make an executable from two different object files (main.o and add.o). I was using the command:
gcc -o exec main.o add.o
But my program is a C++ program. Using the g++
compiler solved my issue:
g++ -o exec main.o add.o
I was always under the impression that gcc
could figure these things out on its own. Apparently not. I hope this helps someone else searching for this error.
Delete entire node "Element" (inside "Connections" tree) from XML file, used by version 18 or higher.
C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\18.0\UserSettings.xml
Here is what I write to get the timestamp in millionseconds.
#include<sys/time.h>
long long timeInMilliseconds(void) {
struct timeval tv;
gettimeofday(&tv,NULL);
return (((long long)tv.tv_sec)*1000)+(tv.tv_usec/1000);
}
To rollback the last migration you can do:
rake db:rollback
If you want to rollback a specific migration with a version you should do:
rake db:migrate:down VERSION=YOUR_MIGRATION_VERSION
For e.g. if the version is 20141201122027, you will do:
rake db:migrate:down VERSION=20141201122027
to rollback that specific migration.
You're able to do database finds using LIKE with this syntax:
Model::where('column', 'LIKE', '%value%')->get();
The issue I had is that sometimes I will need to get at a value that is deeply
nested. Normally you would need to do a type assertion at each level, so I went
ahead and just made a method that takes a map[string]interface{}
and a
string
key, and returns the resulting map[string]interface{}
.
The issue that cropped up for me was that at some depths you will encounter a Slice instead of Map. So I also added methods to return a Slice from Map, and Map from Slice. I didnt do one for Slice to Slice, but you could easily add that if needed. Here are the methods:
package main
type Slice []interface{}
type Map map[string]interface{}
func (m Map) M(s string) Map {
return m[s].(map[string]interface{})
}
func (m Map) A(s string) Slice {
return m[s].([]interface{})
}
func (a Slice) M(n int) Map {
return a[n].(map[string]interface{})
}
and example code:
package main
import (
"encoding/json"
"fmt"
"log"
"os"
)
func main() {
o, e := os.Open("a.json")
if e != nil {
log.Fatal(e)
}
in_m := Map{}
json.NewDecoder(o).Decode(&in_m)
out_m := in_m.
M("contents").
M("sectionListRenderer").
A("contents").
M(0).
M("musicShelfRenderer").
A("contents").
M(0).
M("musicResponsiveListItemRenderer").
M("navigationEndpoint").
M("browseEndpoint")
fmt.Println(out_m)
}
Meanwhile I have found the (for me) perfect solution: nexe, which creates a single executable from a Node.js application including all of its modules.
It's the next best thing to an ideal solution.
Try GraphIT from TechNewLogic, you can find it on CodePlex here: http://graphit.codeplex.com
Full Disclosure: I am the developer of GraphIT and owner of the developing company.
Just to clarify, you can't do location.split('#')
, location
is an object, not a string. But you can do location.href.split('#');
because location.href
is a string.
I had to do 2 steps:
follow Tiep Phan
solution ... edit config.inc.php
file ...
follow Mahmoud Zalt
solution ... change password within phpmyadmin
Change
Range(DataImportColumn & DataImportRow).Offset(0, 2).Value
to
Cells(DataImportRow,DataImportColumn).Value
When you just have the row and the column then you can use the cells()
object. The syntax is Cells(Row,Column)
Also one more tip. You might want to fully qualify your Cells
object. for example
ThisWorkbook.Sheets("WhatEver").Cells(DataImportRow,DataImportColumn).Value
My solution:
It worked for me after the second try.
The problem is that you are using gulp 4 and the syntax in gulfile.js is of gulp 3. So either downgrade your gulp to 3.x.x or make use of gulp 4 syntaxes.
Syntax Gulp 3:
gulp.task('default', ['sass'], function() {....} );
Syntax Gulp 4:
gulp.task('default', gulp.series(sass), function() {....} );
You can read more about gulp and gulp tasks on: https://medium.com/@sudoanushil/how-to-write-gulp-tasks-ce1b1b7a7e81
I took the answer from @newtover and extended it using the new json_table function in MySql 8. This allows you to create a stored procedure to handle the workload rather than building your own SQL text in code:
drop table if exists `test`;
create table `test` (
`Id` int,
`Number` int,
PRIMARY KEY (`Id`)
);
insert into test (Id, Number) values (1, 1), (2, 2);
DROP procedure IF EXISTS `Test`;
DELIMITER $$
CREATE PROCEDURE `Test`(
p_json json
)
BEGIN
update test s
join json_table(p_json, '$[*]' columns(`id` int path '$.id', `number` int path '$.number')) v
on s.Id=v.id set s.Number=v.number;
END$$
DELIMITER ;
call `Test`('[{"id": 1, "number": 10}, {"id": 2, "number": 20}]');
select * from test;
drop table if exists `test`;
It's a few ms slower than pure SQL but I'm happy to take the hit rather than generate the sql text in code. Not sure how performant it is with huge recordsets (the JSON object has a max size of 1Gb) but I use it all the time when updating 10k rows at a time.
I had the same error, but in a different situation than in the question, but maybe it will be useful to someone.
The problem was adding buckles:
Wrong:
const gamesArray = [myId];
const player = await Player.findByIdAndUpdate(req.player._id, {
gamesId: [gamesArray]
}, { new: true }
Correct:
const gamesArray = [myId];
const player = await Player.findByIdAndUpdate(req.player._id, {
gamesId: gamesArray
}, { new: true }
directoryName = "Photographs"
filePath = os.path.abspath(directoryName)
filePathWithSlash = filePath + "\\"
for counter, filename in enumerate(os.listdir(directoryName)):
filenameWithPath = os.path.join(filePathWithSlash, filename)
os.rename(filenameWithPath, filenameWithPath.replace(filename,"DSC_" + \
str(counter).zfill(4) + ".jpg" ))
# e.g. filename = "photo1.jpg", directory = "c:\users\Photographs"
# The string.replace call swaps in the new filename into
# the current filename within the filenameWitPath string. Which
# is then used by os.rename to rename the file in place, using the
# current (unmodified) filenameWithPath.
# os.listdir delivers the filename(s) from the directory
# however in attempting to "rename" the file using os
# a specific location of the file to be renamed is required.
# this code is from Windows
@Entity
@Table(name = "table_name", uniqueConstraints={@UniqueConstraint(columnNames = "column1"),@UniqueConstraint(columnNames = "column2")})
-- Here both Column1 and Column2 acts as unique constraints separately. Ex : if any time either the value of column1 or column2 value matches then you will get UNIQUE_CONSTRAINT Error.
@Entity
@Table(name = "table_name", uniqueConstraints={@UniqueConstraint(columnNames ={"column1","column2"})})
-- Here both column1 and column2 combined values acts as unique constraints
If you used a raw socket (SOCK_RAW
) and re-implemented TCP in userland, I think the answer is limited in this case only by the number of (local address, source port, destination address, destination port)
tuples (~2^64 per local address).
It would of course take a lot of memory to keep the state of all those connections, and I think you would have to set up some iptables rules to keep the kernel TCP stack from getting upset &/or responding on your behalf.
KEYS command should not be used on Redis production instances if you have a lot of keys, since it may block the Redis event loop for several seconds.
I would generate a dump (bgsave), and then use the following Python package to parse it and extract the data:
https://github.com/sripathikrishnan/redis-rdb-tools
You can have json output, or customize your own output in Python.
You can also do this to set a header for all future gets for the Session object, where x-test will be in all s.get() calls:
s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})
# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})
from: http://docs.python-requests.org/en/latest/user/advanced/#session-objects
If you're building a class library, then perhaps the users of your library would like to use your library asynchronously. I think that's the biggest reason right there.
You also don't know how your library is going to be used. Perhaps the users will be processing lots and lots of requests, and doing so asynchronously will help it perform faster and more efficient.
If you can do so simply, try not to put the burden on the users of your library trying to make the flow asynchronous when you can take care of it for them.
The only reason I wouldn't use the async version is if I were trying to support an older version of .NET that does not already have built in async support.
You can you use a simple solution, just change the class, the HTML Collection filter is updated:
var cur_columns = document.getElementsByClassName('column');
for (i in cur_columns) {
cur_columns[i].className = '';
}
Ref: http://www.w3.org/TR/2011/WD-html5-author-20110705/common-dom-interfaces.html
Assume you want to install package MySQL-python
on Windows, maybe try pip install
command with --global-option
. See the example command below:
pip install MySQL-python ^
--force-reinstall --no-cache-dir ^
--global-option=build_ext ^
--global-option="-IC:\my\install\MySQL-x64\MySQL Connector C 6.0.2\include" ^
--global-option="-LC:\my\install\MySQL-x64\MySQL Connector C 6.0.2\lib\opt" ^
--verbose
For this example, I fully installed 64-bit version of MySQL Connector C
in customized location of C:\my\install\MySQL-x64\MySQL Connector C 6.0.2\
.
By the way, I noticed that pip install MySQL-python
by default always looks into directory C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include
, even if you're using 64-bit and/or have installed the driver at a different location. I tested on Python-2.7, and I guess this is a bug of either Python or MySQL-python.
Hope the above might be of some help.
You can do this way :
TimeSpan duration = new TimeSpan(tickCount)
double minutes = duration.TotalMinutes;
One thing you might try is using -Xverify:all
which will verify bytecode on load and sometimes gives helpful error messages if the bytecode is invalid.
This is all you need.
rsync -e ssh file host:/directory/.
You can select which shapes you want to show along with the Annotations.
extension MKMapView {
func setVisibleMapRectToFitAllAnnotations(animated: Bool = true,
shouldIncludeUserAccuracyRange: Bool = true,
shouldIncludeOverlays: Bool = true,
edgePadding: UIEdgeInsets = UIEdgeInsets(top: 35, left: 35, bottom: 35, right: 35)) {
var mapOverlays = overlays
if shouldIncludeUserAccuracyRange, let userLocation = userLocation.location {
let userAccuracyRangeCircle = MKCircle(center: userLocation.coordinate, radius: userLocation.horizontalAccuracy)
mapOverlays.append(MKOverlayRenderer(overlay: userAccuracyRangeCircle).overlay)
}
if shouldIncludeOverlays {
let annotations = self.annotations.filter { !($0 is MKUserLocation) }
annotations.forEach { annotation in
let cirlce = MKCircle(center: annotation.coordinate, radius: 1)
mapOverlays.append(cirlce)
}
}
let zoomRect = MKMapRect(bounding: mapOverlays)
setVisibleMapRect(zoomRect, edgePadding: edgePadding, animated: animated)
}
}
extension MKMapRect {
init(bounding overlays: [MKOverlay]) {
self = .null
overlays.forEach { overlay in
let rect: MKMapRect = overlay.boundingMapRect
self = self.union(rect)
}
}
}
To read characters try
scan("/PathTo/file.csv", "")
If you're reading numeric values, then just use
scan("/PathTo/file.csv")
scan
by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).
That happens because you're setting the src of the ImageView
instead of the background.
Use this instead:
qImageView.setBackgroundResource(R.drawable.thumbs_down);
Here's a thread that talks about the differences between the two methods.
It's not the same doing a select distinct at the beginning because you are wasting all the calculated rows from the result.
select a.FirstName, a.LastName, v.District
from AddTbl a order by Firstname
natural join (select distinct LastName from
ValTbl v where a.LastName = v.LastName)
try that.
If you dont want to hard-code the cell addresses you can use the ROW()
function.
eg: =AVERAGE(INDIRECT("A" & ROW()), INDIRECT("C" & ROW()))
Its probably not the best way to do it though! Using Auto-Fill and static columns like @JaiGovindani suggests would be much better.
@Alexander Thanks for solution
Below is code exactly what you looking for
import React, {PropTypes,} from 'react';
import {View, Text, StyleSheet,TouchableHighlight,ScrollView,Image, Component, AppRegistry} from "react-native";
class mainview extends React.Component {
constructor(props) {
super(props);
}
render() {
return(
<View style={styles.mainviewStyle}>
<ContainerView/>
<View style={styles.footer}>
<TouchableHighlight style={styles.bottomButtons}>
<Text style={styles.footerText}>A</Text>
</TouchableHighlight>
<TouchableHighlight style={styles.bottomButtons}>
<Text style={styles.footerText}>B</Text>
</TouchableHighlight>
</View>
</View>
);
}
}
class ContainerView extends React.Component {
constructor(props) {
super(props);
}
render() {
return(
<ScrollView style = {styles.scrollViewStyle}>
<View>
<Text style={styles.textStyle}> Example for ScrollView and Fixed Footer</Text>
</View>
</ScrollView>
);
}
}
var styles = StyleSheet.create({
mainviewStyle: {
flex: 1,
flexDirection: 'column',
},
footer: {
position: 'absolute',
flex:0.1,
left: 0,
right: 0,
bottom: -10,
backgroundColor:'green',
flexDirection:'row',
height:80,
alignItems:'center',
},
bottomButtons: {
alignItems:'center',
justifyContent: 'center',
flex:1,
},
footerText: {
color:'white',
fontWeight:'bold',
alignItems:'center',
fontSize:18,
},
textStyle: {
alignSelf: 'center',
color: 'orange'
},
scrollViewStyle: {
borderWidth: 2,
borderColor: 'blue'
}
});
AppRegistry.registerComponent('TRYAPP', () => mainview) //Entry Point and Root Component of The App
Below is the Screenshot
You could use a C function getaddrinfo() to get the numerical address - both ipv4 and ipv6. See the example code here
If your program is running at an interactive console, pressing CTRL + C will raise a KeyboardInterrupt
exception on the main thread.
If your Python program doesn't catch it, the KeyboardInterrupt
will cause Python to exit. However, an except KeyboardInterrupt:
block, or something like a bare except:
, will prevent this mechanism from actually stopping the script from running.
Sometimes if KeyboardInterrupt
is not working you can send a SIGBREAK
signal instead; on Windows, CTRL + Pause/Break may be handled by the interpreter without generating a catchable KeyboardInterrupt
exception.
However, these mechanisms mainly only work if the Python interpreter is running and responding to operating system events. If the Python interpreter is not responding for some reason, the most effective way is to terminate the entire operating system process that is running the interpreter. The mechanism for this varies by operating system.
In a Unix-style shell environment, you can press CTRL + Z to suspend whatever process is currently controlling the console. Once you get the shell prompt back, you can use jobs
to list suspended jobs, and you can kill the first suspended job with kill %1
. (If you want to start it running again, you can continue the job in the foreground by using fg %1
; read your shell's manual on job control for more information.)
Alternatively, in a Unix or Unix-like environment, you can find the Python process's PID (process identifier) and kill it by PID. Use something like ps aux | grep python
to find which Python processes are running, and then use kill <pid>
to send a SIGTERM
signal.
The kill
command on Unix sends SIGTERM
by default, and a Python program can install a signal handler for SIGTERM
using the signal
module. In theory, any signal handler for SIGTERM
should shut down the process gracefully. But sometimes if the process is stuck (for example, blocked in an uninterruptable IO sleep state), a SIGTERM
signal has no effect because the process can't even wake up to handle it.
To forcibly kill a process that isn't responding to signals, you need to send the SIGKILL
signal, sometimes referred to as kill -9
because 9
is the numeric value of the SIGKILL
constant. From the command line, you can use kill -KILL <pid>
(or kill -9 <pid>
for short) to send a SIGKILL
and stop the process running immediately.
On Windows, you don't have the Unix system of process signals, but you can forcibly terminate a running process by using the TerminateProcess
function. Interactively, the easiest way to do this is to open Task Manager, find the python.exe
process that corresponds to your program, and click the "End Process" button. You can also use the taskkill
command for similar purposes.
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Content-Type: application/xml; charset=utf-8");
Not a full answer Ok so this is just to supplement the information about parseInt, which is still very valid. Express doesn't allow the req or res objects to be modified at all (immutable). So if you want to modify/use this data effectively, you must copy it to another variable (var year = req.params.year).
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.
In order to keep both versions, I just changed the value of PATH environment variable by putting the new version's git path "/usr/local/git/bin/" at the beginning, it forces to use the newest version:
$ echo $PATH
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/git/bin/
$ git --version
git version 2.4.9 (Apple Git-60)
original value: /usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/git/bin/
new value: /usr/local/git/bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin
$ export PATH=/usr/local/git/bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin
$ git --version
git version 2.13.0
Your problem is that you have declare twice the exec-maven-plugin :
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>C:\apache-camel-2.11.0\examples\camel-example-smooks-
integration\src\main\java\example\Main< /mainClass>
</configuration>
</plugin>
...
< plugin>
< groupId>org.codehaus.mojo</groupId>
< artifactId>exec-maven-plugin</artifactId>
< version>1.2</version>
< /plugin>
More on schemas:
In SQL 2005 a schema is a way to group objects. It is a container you can put objects into. People can own this object. You can grant rights on the schema.
In 2000 a schema was equivalent to a user. Now it has broken free and is quite useful. You could throw all your user procs in a certain schema and your admin procs in another. Grant EXECUTE to the appropriate user/role and you're through with granting EXECUTE on specific procedures. Nice.
The dot notation would go like this:
Server.Database.Schema.Object
or
myserver01.Adventureworks.Accounting.Beans
I personally use a more generic function that works for any property of any array:
function lookup(array, prop, value) {
for (var i = 0, len = array.length; i < len; i++)
if (array[i] && array[i][prop] === value) return array[i];
}
You just call it like this:
lookup(purposeObjects, "purpose", "daily");
As documentation says:
Raised when the part of a "multipart/form-data" request identified by its name cannot be found.
This may be because the request is not a multipart/form-data either because the part is not present in the request, or because the web application is not configured correctly for processing multipart requests -- e.g. no MultipartResolver.
You need to set the thumbnail class to position relative then the post-content to absolute.
Check this fiddle
.post-content {
top:0;
left:0;
position: absolute;
}
.thumbnail{
position:relative;
}
Giving it top and left 0 will make it appear in the top left corner.
Linux users can find the locations of all the installed packages like this:
pip list | xargs -exec pip show
char members[255] = {0};
If you used homebrew to install ruby, this answer worked for me.
brew unlink ruby && brew link ruby
OSX 10.9.4
System.String is a reference type so you don't need to do anything like
Nullable<string>
It already has a null value (the null reference):
string x = null; // No problems here
What I really wanted was a GUI to reorder them and output them as one file
Playlist Producer does exactly that, decoding and reencoding them into a combined MP3. It's designed for creating mix tapes or simple podcasts, but you might find it useful.
(Disclosure: I wrote the software, and I profit if you buy the Pro Edition. The Lite edition is a free version with a few limitations).
You can run build
for a specific service by running docker-compose up --build <service name>
where the service name must match how did you call it in your docker-compose file.
Example
Let's assume that your docker-compose file contains many services (.net app - database - let's encrypt... etc) and you want to update only the .net app which named as application
in docker-compose file.
You can then simply run docker-compose up --build application
Extra parameters
In case you want to add extra parameters to your command such as -d
for running in the background, the parameter must be before the service name:
docker-compose up --build -d application
Its simple:
Make your element hidden first like this:
<div id="hidden" style="display:none;">
Hi this is hidden
</div>
Then call your javascript:
<script type="text/javascript">
$(document).ready(function() {
$.fancybox("#hidden");
});
</script>
Check out the image below:
Another example:
<div id="example2" style="display:none;">
<img src="http://theinstitute.ieee.org/img/07tiProductsandServicesiStockphoto-1311258460873.jpg" />
</div>
<script type="text/javascript">
$(document).ready(function() {
$.fancybox("#example2");
});
</script>
You could set your property in the model's constructor
public YourModel()
{
As = true;
}
I faced the same problem. Found the fix here.
Basically just install this.
shasum output:
3e0de8af516c15547602977db939d8c2e44fcc0b visualcppbuildtools_full.exe
md5sum output:
MD5 (visualcppbuildtools_full.exe) = 8d4afd3b226babecaa4effb10d69eb2e
Run your pip installation command again. If everything works fine, its good. Or you might face the following error like me:
Finished generating code
LINK : fatal error LNK1158: cannot run 'rc.exe'
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1158
Found the fix for the above problem here: Visual Studio can't build due to rc.exe
That basically says
Add this to your PATH environment variables:
C:\Program Files (x86)\Windows Kits\8.1\bin\x86
Copy these files:
rc.exe
rcdll.dll
From
C:\Program Files (x86)\Windows Kits\8.1\bin\x86
To
C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin
It works like a charm
git config information will stored in ~/.gitconfig
in unix platform.
In Windows it will be stored in C:/users/<NAME>/.gitconfig.
You can edit it manually by opening this files and deleting the fields which you are interested.
I'd like to add that inline functions are crucial when you are building shared library. Without marking function inline, it will be exported into the library in the binary form. It will be also present in the symbols table, if exported. On the other side, inlined functions are not exported, neither to the library binaries nor to the symbols table.
It may be critical when library is intended to be loaded at runtime. It may also hit binary-compatible-aware libraries. In such cases don't use inline.
To see command-line flags, use:
gcc -march=native -E -v - </dev/null 2>&1 | grep cc1
If you want to see the compiler/precompiler defines set by certain parameters, do this:
echo | gcc -dM -E - -march=native
Firstly, you should use randrange(0,1000)
or randint(0,999)
, not randint(0,1000)
. The upper limit of randint
is inclusive.
For efficiently, randint
is simply a wrapper of randrange
which calls random
, so you should just use random
. Also, use xrange
as the argument to sample
, not range
.
You could use
[a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]
to generate 10,000 numbers in the range using sample
10 times.
(Of course this won't beat NumPy.)
$ python2.7 -m timeit -s 'from random import randrange' '[randrange(1000) for _ in xrange(10000)]'
10 loops, best of 3: 26.1 msec per loop
$ python2.7 -m timeit -s 'from random import sample' '[a%1000 for a in sample(xrange(10000),10000)]'
100 loops, best of 3: 18.4 msec per loop
$ python2.7 -m timeit -s 'from random import random' '[int(1000*random()) for _ in xrange(10000)]'
100 loops, best of 3: 9.24 msec per loop
$ python2.7 -m timeit -s 'from random import sample' '[a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]'
100 loops, best of 3: 3.79 msec per loop
$ python2.7 -m timeit -s 'from random import shuffle
> def samplefull(x):
> a = range(x)
> shuffle(a)
> return a' '[a for a in samplefull(1000) for _ in xrange(10000/1000)]'
100 loops, best of 3: 3.16 msec per loop
$ python2.7 -m timeit -s 'from numpy.random import randint' 'randint(1000, size=10000)'
1000 loops, best of 3: 363 usec per loop
But since you don't care about the distribution of numbers, why not just use:
range(1000)*(10000/1000)
?
A good book on Subversion is Pragmatic Version Control using Subversion where your question is explained, and it gives a lot more information.