I usually use sys.platform
(docs) to get the platform. sys.platform
will distinguish between linux, other unixes, and OS X, while os.name
is "posix
" for all of them.
For much more detailed information, use the platform module. This has cross-platform functions that will give you information on the machine architecture, OS and OS version, version of Python, etc. Also it has os-specific functions to get things like the particular linux distribution.
Interesting results on windows 8:
>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'post2008Server'
Edit: That's a bug
You should be able to rely on os.name.
import os
if os.name == 'nt':
# ...
edit: Now I'd say the clearest way to do this is via the platform module, as per the other answer.
There is no way to convert a VBScript (.vbs file) into an executable (.exe file) because VBScript is not a compiled language. The process of converting source code into native executable code is called "compilation", and it's not supported by scripting languages like VBScript.
Certainly you can add your script to a self-extracting archive using something like WinZip, but all that will do is compress it. It's doubtful that the file size will shrink noticeably, and since it's a plain-text file to begin with, it's really not necessary to compress it at all. The only purpose of a self-extracting archive is that decompression software (like WinZip) is not required on the end user's computer to be able to extract or "decompress" the file. If it isn't compressed in the first place, this is a moot point.
Alternatively, as you mentioned, there are ways to wrap VBScript code files in a standalone executable file, but these are just wrappers that automatically execute the script (in its current, uncompiled state) when the user double-clicks on the .exe file. I suppose that can have its benefits, but it doesn't sound like what you're looking for.
In order to truly convert your VBScript into an executable file, you're going to have to rewrite it in another language that can be compiled. Visual Basic 6 (the latest version of VB, before the .NET Framework was introduced) is extremely similar in syntax to VBScript, but does support compiling to native code. If you move your VBScript code to VB 6, you can compile it into a native executable. Running the .exe file will require that the user has the VB 6 Run-time libraries installed, but they come built into most versions of Windows that are found now in the wild.
Alternatively, you could go ahead and make the jump to Visual Basic .NET, which remains somewhat similar in syntax to VB 6 and VBScript (although it won't be anywhere near a cut-and-paste migration). VB.NET programs will also compile to an .exe file, but they require the .NET Framework runtime to be installed on the user's computer. Fortunately, this has also become commonplace, and it can be easily redistributed if your users don't happen to have it. You mentioned going this route in your question (porting your current script in to VB Express 2008, which uses VB.NET), but that you were getting a lot of errors. That's what I mean about it being far from a cut-and-paste migration. There are some huge differences between VB 6/VBScript and VB.NET, despite some superficial syntactical similarities. If you want help migrating over your VBScript, you could post a question here on Stack Overflow. Ultimately, this is probably the best way to do what you want, but I can't promise you that it will be simple.
Also, you can display current position by "drag" listener and write it to visible or hidden field. You may also need to store zoom. Here's copy&paste from working tool:
function map_init() {
var lt=48.451778;
var lg=31.646305;
var myLatlng = new google.maps.LatLng(lt,lg);
var mapOptions = {
center: new google.maps.LatLng(lt,lg),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'),mapOptions);
var marker = new google.maps.Marker({
position:myLatlng,
map:map,
draggable:true
});
google.maps.event.addListener(
marker,
'drag',
function() {
document.getElementById('lat1').innerHTML = marker.position.lat().toFixed(6);
document.getElementById('lng1').innerHTML = marker.position.lng().toFixed(6);
document.getElementById('zoom').innerHTML = mapObject.getZoom();
// Dynamically show it somewhere if needed
$(".x").text(marker.position.lat().toFixed(6));
$(".y").text(marker.position.lng().toFixed(6));
$(".z").text(map.getZoom());
}
);
}
You can define more details by extending AbstractMongoConfiguration.
@Configuration
@EnableMongoRepositories("demo.mongo.model")
public class SpringMongoConfig extends AbstractMongoConfiguration {
@Value("${spring.profiles.active}")
private String profileActive;
@Value("${spring.application.name}")
private String proAppName;
@Value("${spring.data.mongodb.host}")
private String mongoHost;
@Value("${spring.data.mongodb.port}")
private String mongoPort;
@Value("${spring.data.mongodb.database}")
private String mongoDB;
@Override
public MongoMappingContext mongoMappingContext()
throws ClassNotFoundException {
// TODO Auto-generated method stub
return super.mongoMappingContext();
}
@Override
@Bean
public Mongo mongo() throws Exception {
return new MongoClient(mongoHost + ":" + mongoPort);
}
@Override
protected String getDatabaseName() {
// TODO Auto-generated method stub
return mongoDB;
}
}
It seems that you'll need two fields, a choice list for the currency and a number field for the value.
A common technique in such case is to use a div or span for the display (form fields offscreen), and on click switch to the form elements for editing.
For those who have trouble achieving the same in the Android browser with the touch event, use:
html, body {
-webkit-touch-callout: none;
-webkit-user-select: none;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
-webkit-tap-highlight-color: transparent;
}
A beginner's mistake...i was using app.use(express.json());
in a local module instead of the main file (entry point).
{
"files.useExperimentalFileWatcher" : true
}
in Code -> Preferences -> Settings
Tested with Visual Studio Code Version 1.26.1 on mac and win
I've used VideoCapX for our project. It will stream out as MMS/ASF stream which can be open by media player. You can then embed media player into your webpage.
If you won't need much control, or if you want to try out VideoCapX without writing a code, try U-Broadcast, they use VideoCapX behind the scene.
FYI...if you use TortoiseSVN and you want to create a simple batch file to xcopy (or directory mirror) entire repositories into a "safe" location on a periodic basis, then this is the specific code that you might want to use. It copies over the hidden directories/files, maintains read-only attributes, and all subdirectories and best of all, doesn't prompt for input. Just make sure that you assign folder1 (safe repo) and folder2 (usable repo) correctly.
@echo off
echo "Setting variables..."
set folder1="Z:\Path\To\Backup\Repo\Directory"
set folder2="\\Path\To\Usable\Repo\Directory"
echo "Removing sandbox version..."
IF EXIST %folder1% (
rmdir %folder1% /s /q
)
echo "Copying official repository into backup location..."
xcopy /e /i /v /h /k %folder2% %folder1%
And, that's it folks!
Add to your scheduled tasks and never look back.
Normal Class
: A Java class
Java Beans
:
Pojo
:
Plain Old Java Object is a Java object not bound by any restriction other than those forced by the Java Language Specification. I.e., a POJO should not have to
Normally, the error will occur due to an unsuitable AVD emulator for the type of app you are developing for. For example if you are developing an app for a wearable but you are trying to use a phone emulator to run it.
>>> import string
>>> import random
the following logic still generates 6 character random sample
>>> print ''.join(random.sample((string.ascii_uppercase+string.digits),6))
JT7K3Q
No need to multiply by 6
>>> print ''.join(random.sample((string.ascii_uppercase+string.digits)*6,6))
TK82HK
Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:
Public Sub SubA()
On Error Goto ProcError
Connection.Open
Open File for Writing
SomePreciousResource.GrabIt
ProcExit:
Connection.Close
Connection = Nothing
Close File
SomePreciousResource.Release
Exit Sub
ProcError:
MsgBox Err.Description
Resume ProcExit
End Sub
In Sql Server it is an option. Turning it on sucks.
I'm not sure about MySql.
In case anyone comes here from Google trying to figure out how to prevent someone from closing a modal, don't forget that there's also a close button on the top right of the modal that needs to be removed.
I used some CSS to hide it:
#Modal .modal-header button.close {
visibility: hidden;
}
Note that using "display: none;" gets overwritten when the modal is created, so don't use that.
The .title()
method can't work well,
>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
Try string.capwords()
method,
import string
string.capwords("they're bill's friends from the UK")
>>>"They're Bill's Friends From The Uk"
From the Python documentation on capwords:
Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join(). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words.
I was also looking for this today and found: http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256BFB0077DFFD
Don't know if that's a good solution though they do mention some performance considerations taken into account.
I like the idea of a jQuery helper method. @David I'd rather see your compare method to work like:
jQuery.compare(a, b)
I doesn't make sense to me to be doing:
$(a).compare(b)
where a and b are arrays. Normally when you $(something) you'd be passing a selector string to work with DOM elements.
Also regarding sorting and 'caching' the sorted arrays:
It seems what we need to do is to copy the arrays before working on them. The best answer I could find for how to do that in a jQuery way was by none other than John Resig here on SO! What is the most efficient way to deep clone an object in JavaScript? (see comments on his answer for the array version of the object cloning recipe)
In which case I think the code for it would be:
jQuery.extend({
compare: function (arrayA, arrayB) {
if (arrayA.length != arrayB.length) { return false; }
// sort modifies original array
// (which are passed by reference to our method!)
// so clone the arrays before sorting
var a = jQuery.extend(true, [], arrayA);
var b = jQuery.extend(true, [], arrayB);
a.sort();
b.sort();
for (var i = 0, l = a.length; i < l; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
});
var a = [1, 2, 3];
var b = [2, 3, 4];
var c = [3, 4, 2];
jQuery.compare(a, b);
// false
jQuery.compare(b, c);
// true
// c is still unsorted [3, 4, 2]
list()
is inherently slower than []
, because
there is symbol lookup (no way for python to know in advance if you did not just redefine list to be something else!),
there is function invocation,
then it has to check if there was iterable argument passed (so it can create list with elements from it) ps. none in our case but there is "if" check
In most cases the speed difference won't make any practical difference though.
Try to use
You can find all embeded code in 'Embeded Code' section and that looks like this
<iframe width="560" height="315" src="https://www.youtube.com/embed/YOUR_VIDEO_CODE" frameborder="0" allowfullscreen></iframe>
The sql array type is not neccessary. Not if the element type is a primitive one. (Varchar, number, date,...)
Very basic sample:
declare
type TPidmList is table of sgbstdn.sgbstdn_pidm%type;
pidms TPidmList;
begin
select distinct sgbstdn_pidm
bulk collect into pidms
from sgbstdn
where sgbstdn_majr_code_1 = 'HS04'
and sgbstdn_program_1 = 'HSCOMPH';
-- do something with pidms
open :someCursor for
select value(t) pidm
from table(pidms) t;
end;
When you want to reuse it, then it might be interesting to know how that would look like. If you issue several commands than those could be grouped in a package. The private package variable trick from above has its downsides. When you add variables to a package, you give it state and now it doesn't act as a stateless bunch of functions but as some weird sort of singleton object instance instead.
e.g. When you recompile the body, it will raise exceptions in sessions that already used it before. (because the variable values got invalided)
However, you could declare the type in a package (or globally in sql), and use it as a paramter in methods that should use it.
create package Abc as
type TPidmList is table of sgbstdn.sgbstdn_pidm%type;
function CreateList(majorCode in Varchar,
program in Varchar) return TPidmList;
function Test1(list in TPidmList) return PLS_Integer;
-- "in" to make it immutable so that PL/SQL can pass a pointer instead of a copy
procedure Test2(list in TPidmList);
end;
create package body Abc as
function CreateList(majorCode in Varchar,
program in Varchar) return TPidmList is
result TPidmList;
begin
select distinct sgbstdn_pidm
bulk collect into result
from sgbstdn
where sgbstdn_majr_code_1 = majorCode
and sgbstdn_program_1 = program;
return result;
end;
function Test1(list in TPidmList) return PLS_Integer is
result PLS_Integer := 0;
begin
if list is null or list.Count = 0 then
return result;
end if;
for i in list.First .. list.Last loop
if ... then
result := result + list(i);
end if;
end loop;
end;
procedure Test2(list in TPidmList) as
begin
...
end;
return result;
end;
How to call it:
declare
pidms constant Abc.TPidmList := Abc.CreateList('HS04', 'HSCOMPH');
xyz PLS_Integer;
begin
Abc.Test2(pidms);
xyz := Abc.Test1(pidms);
...
open :someCursor for
select value(t) as Pidm,
xyz as SomeValue
from table(pidms) t;
end;
Yes, here is the process:
# Navigate to a directory and initiate a local repository
git init
# Add remote repository to be tracked for changes:
git remote add origin https://github.com/username/repository_name.git
# Track all changes made on above remote repository
# This will show files on remote repository not available on local repository
git fetch
# Add file present in staging area for checkout
git check origin/master -m /path/to/file
# NOTE: /path/to/file is a relative path from repository_name
git add /path/to/file
# Verify track of file(s) being committed to local repository
git status
# Commit to local repository
git commit -m "commit message"
# You may perform a final check of the staging area again with git status
Here's a one-liner to get the filename for a module, suitable for shell aliasing:
echo 'import sys; t=__import__(sys.argv[1],fromlist=[\".\"]); print(t.__file__)' | python -
Set up as an alias:
alias getpmpath="echo 'import sys; t=__import__(sys.argv[1],fromlist=[\".\"]); print(t.__file__)' | python - "
To use:
$ getpmpath twisted
/usr/lib64/python2.6/site-packages/twisted/__init__.pyc
$ getpmpath twisted.web
/usr/lib64/python2.6/site-packages/twisted/web/__init__.pyc
Another solution, you can do it using ResourceLoader
like this:
import org.springframework.core.io.Resource;
import org.apache.commons.io.FileUtils;
@Autowire
private ResourceLoader resourceLoader;
...
Resource resource = resourceLoader.getResource("classpath:/path/to/you/dir");
File file = resource.getFile();
Iterator<File> fi = FileUtils.iterateFiles(file, null, true);
while(fi.hasNext()) {
load(fi.next())
}
Laravel has the Carbon
dependency attached to it.
Carbon::now()
, include the Carbon\Carbon
namespace if necessary.
Edit (usage and docs)
Say I want to retrieve the date and time and output it as a string.
$mytime = Carbon\Carbon::now();
echo $mytime->toDateTimeString();
This will output in the usual format of Y-m-d H:i:s
, there are many pre-created formats and you will unlikely need to mess with PHP date time strings again with Carbon.
Documentation: https://github.com/briannesbitt/Carbon
String formats for Carbon: http://carbon.nesbot.com/docs/#api-formatting
So many average answers here...
Some linked list implementations use underlying blocks of pre allocated nodes. If they don't do this than constant time / linear time is less relevant as memory performance will be poor and cache performance even worse.
Use linked lists when
1) You want thread safety. You can build better thread safe algos. Locking costs will dominate a concurrent style list.
2) If you have a large queue like structures and want to remove or add anywhere but the end all the time . >100K lists exists but are not that common.
Few things to try, Ensure the Framework and all it's headers are imported into your project properly.
Also in your Build Settings
set YES
to Always search user paths
, and make sure your User header paths
are pointing to the Framework.
Finally, Build->Clean and Restart Xcode.
Hope this helps !
UPDATE: According to SDWebImage's installation, it's required you make a modification to Header Search Path
and not User header paths
, As seen below.
Have you done this as well? I suggest slowly, re-doing all the installation steps from the beginning.
Another convoluted answer which should technically work and is ok for a small number of data points is to plot all your data points as 1 series in order to get your connecting line. Then plot each point as its own series. Then format data labels to display series name for each of the individual data points.
In short it works ok for a small data set or just key points from a data set.
For future googlers, in 2016 there is a browser safe pure CSS way of hiding empty images using the attribute selector:
img[src="Error.src"] {
display: none;
}
Edit: I'm back - for future googlers, in 2019 there is a way to style the actual alt text and alt text image in the Shadow Dom, but it only works in developer tools. So you can't use it. Sorry. It would be so nice.
#alttext-container {
opacity: 0;
}
#alttext-image {
opacity: 0;
}
#alttext {
opacity: 0;
}
Unless you are using Bytecode Enhancement, you cannot fetch lazily the parent-side @OneToOne
association.
However, most often, you don't even need the parent-side association if you use @MapsId
on the client side:
@Entity(name = "PostDetails")
@Table(name = "post_details")
public class PostDetails {
@Id
private Long id;
@Column(name = "created_on")
private Date createdOn;
@Column(name = "created_by")
private String createdBy;
@OneToOne(fetch = FetchType.LAZY)
@MapsId
private Post post;
public PostDetails() {}
public PostDetails(String createdBy) {
createdOn = new Date();
this.createdBy = createdBy;
}
//Getters and setters omitted for brevity
}
With @MapsId
, the id
property in the child table serves as both Primary Key and Foreign Key to the parent table Primary Key.
So, if you have a reference to the parent Post
entity, you can easily fetch the child entity using the parent entity identifier:
PostDetails details = entityManager.find(
PostDetails.class,
post.getId()
);
This way, you won't have N+1 query issues that could be caused by the mappedBy
@OneToOne
association on the parent side.
If you know x
and y
are both strings, using ===
is not strictly necessary, but is still good practice.
Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string
rather than an actual string, which may complicate things.
Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===
. Just go with that.
Would it be possible for you to use a special command for saving these files?
If you do :set binary, :w and :set nobinary the file will be written without newline if there was none to start with.
This sequence of commands could be put into a user defined command or a mapping, of course.
action=""
will resolve to the page's address. action="#"
will resolve to the page's address + #
, which will mean an empty fragment identifier.
Doing the latter might prevent a navigation (new load) to the same page and instead try to jump to the element with the id in the fragment identifier. But, since it's empty, it won't jump anywhere.
Usually, authors just put #
in href-like attributes when they're not going to use the attribute where they're using scripting instead. In these cases, they could just use action=""
(or omit it if validation allows).
You need to put your main code on the OnStart
method.
This other SO answer of mine might help.
You will need to put some code to enable debugging within visual-studio while maintaining your application valid as a windows-service. This other SO thread cover the issue of debugging a windows-service.
EDIT:
Please see also the documentation available here for the OnStart
method at the MSDN where one can read this:
Do not use the constructor to perform processing that should be in OnStart. Use OnStart to handle all initialization of your service. The constructor is called when the application's executable runs, not when the service runs. The executable runs before OnStart. When you continue, for example, the constructor is not called again because the SCM already holds the object in memory. If OnStop releases resources allocated in the constructor rather than in OnStart, the needed resources would not be created again the second time the service is called.
You need to have a launch configuration inside Eclipse in order to adjust the JVM parameters.
After running your program with either F11 or Ctrl-F11, open the launch configurations in Run -> Run Configurations... and open your program under "Java Applications". Select the Arguments pane, where you will find "VM arguments".
This is where -Xss1024k
goes.
If you want the launch configuration to be a file in your workspace (so you can right click and run it), select the Common pane, and check the Save as -> Shared File checkbox and browse to the location you want the launch file. I usually have them in a separate folder, as we check them into CVS.
You don't need to use id for textview. You can learn more from android arrayadapter. The below code initializes the arrayadapter.
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.single_item, eatables);
Here is some code that show how it works.
class Test
{
public static void main(String args[])
{
System.out.println(Test.test());
}
public static String test()
{
try {
System.out.println("try");
throw new Exception();
} catch(Exception e) {
System.out.println("catch");
return "return";
} finally {
System.out.println("finally");
return "return in finally";
}
}
}
The results is:
try
catch
finally
return in finally
Another "Up Tick" for AR..., but if you don't have to use interop I would avoid it altogether. This product is actually quite interesting: http://www.clearoffice.com/ and it provides a very intuitive, fully managed, api for manipulation excel files and seems to be free. (at least for the time being) SpreadSheetGear is also excellent but pricey.
my two cents.
The second one is fastest. Using strlen
will be close if the string is indeed empty, but strlen
will always iterate through every character of the string, so if it is not empty, it will do much more work than you need it to.
As James mentioned, the third option wipes the string out before checking, so the check will always succeed but it will be meaningless.
The answer for git branch -r --contains <commit>
works well for normal remote branches, but if the commit is only in the hidden head
namespace that GitHub creates for PRs, you'll need a few more steps.
Say, if PR #42 was from deleted branch and that PR thread has the only reference to the commit on the repo, git branch -r
doesn't know about PR #42 because refs like refs/pull/42/head
aren't listed as a remote branch by default.
In .git/config
for the [remote "origin"]
section add a new line:
fetch = +refs/pull/*/head:refs/remotes/origin/pr/*
(This gist has more context.)
Then when you git fetch
you'll get all the PR branches, and when you run git branch -r --contains <commit>
you'll see origin/pr/42
contains the commit.
You can use savefig()
to export to an image file:
plt.savefig('filename.png')
In addition, you can specify the dpi
argument to some scalar value, for example:
plt.savefig('filename.png', dpi=300)
This is the best way for me:
cat filename.tsv |
while read FILENAME
do
sudo find /PATH_FROM/ -name "$FILENAME" -maxdepth 4 -exec cp '{}' /PATH_TO/ \; ;
done
Nope. Once the event has been canceled, it is canceled.
You can re-fire the event later on though, using a flag to determine whether your custom code has already run or not - such as this (please ignore the blatant namespace pollution):
var lots_of_stuff_already_done = false;
$('.button').on('click', function(e) {
if (lots_of_stuff_already_done) {
lots_of_stuff_already_done = false; // reset flag
return; // let the event bubble away
}
e.preventDefault();
// do lots of stuff
lots_of_stuff_already_done = true; // set flag
$(this).trigger('click');
});
A more generalized variant (with the added benefit of avoiding the global namespace pollution) could be:
function onWithPrecondition(callback) {
var isDone = false;
return function(e) {
if (isDone === true)
{
isDone = false;
return;
}
e.preventDefault();
callback.apply(this, arguments);
isDone = true;
$(this).trigger(e.type);
}
}
Usage:
var someThingsThatNeedToBeDoneFirst = function() { /* ... */ } // do whatever you need
$('.button').on('click', onWithPrecondition(someThingsThatNeedToBeDoneFirst));
Bonus super-minimalistic jQuery plugin with Promise
support:
(function( $ ) {
$.fn.onButFirst = function(eventName, /* the name of the event to bind to, e.g. 'click' */
workToBeDoneFirst, /* callback that must complete before the event is re-fired */
workDoneCallback /* optional callback to execute before the event is left to bubble away */) {
var isDone = false;
this.on(eventName, function(e) {
if (isDone === true) {
isDone = false;
workDoneCallback && workDoneCallback.apply(this, arguments);
return;
}
e.preventDefault();
// capture target to re-fire event at
var $target = $(this);
// set up callback for when workToBeDoneFirst has completed
var successfullyCompleted = function() {
isDone = true;
$target.trigger(e.type);
};
// execute workToBeDoneFirst callback
var workResult = workToBeDoneFirst.apply(this, arguments);
// check if workToBeDoneFirst returned a promise
if (workResult && $.isFunction(workResult.then))
{
workResult.then(successfullyCompleted);
}
else
{
successfullyCompleted();
}
});
return this;
};
}(jQuery));
Usage:
$('.button').onButFirst('click',
function(){
console.log('doing lots of work!');
},
function(){
console.log('done lots of work!');
});
Rohit Sahu's answer worked best for me in Windows 10. The PowerShell solution ran, but no shortcut appeared. The JScript solution gave me syntax errors. I didn't try mklink, since I didn't want to mess with permissions.
I wanted the shortcut to appear on the desktop. But I also needed to set the icon, the description, and the working directory. Note that MyApp48.bmp is a 48x48 pixel image. Here's my mod of Rohit's solution:
@echo off
cd c:\MyApp
echo Set oWS = WScript.CreateObject("WScript.Shell") > CreateShortcut.vbs
echo sLinkFile = "%userprofile%\Desktop\MyApp.lnk" >> CreateShortcut.vbs
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> CreateShortcut.vbs
echo oLink.TargetPath = "C:\MyApp\MyApp.bat" >> CreateShortcut.vbs
echo oLink.WorkingDirectory = "C:\MyApp" >> CreateShortcut.vbs
echo oLink.Description = "My Application" >> CreateShortcut.vbs
echo oLink.IconLocation = "C:\MyApp\MyApp48.bmp" >> CreateShortcut.vbs
echo oLink.Save >> CreateShortcut.vbs
cscript CreateShortcut.vbs
del CreateShortcut.vbs
With the addition of Python 3, here is an updated code that works:
import numpy as n
import scipy as s
import matplotlib.pylab as p #pylab is part of matplotlib
xa=0.252
xb=1.99
C=n.linspace(xa,xb,100)
print(C)
iter=1000
Y = n.ones(len(C))
for x in range(iter):
Y = Y**2 - C #get rid of early transients
for x in range(iter):
Y = Y**2 - C
p.plot(C,Y, '.', color = 'k', markersize = 2)
p.show()
try running SHOW CREATE VIEW my_view_name
in the sql portion of phpmyadmin and you will have a better idea of what is inside the view
Also, you can just set the ViewName:
return View("ViewName");
Full controller example:
public ActionResult SomeAction() {
if (condition)
{
return View("CustomView");
}else{
return View();
}
}
This works on MVC 5.
The better solution is enable the longpath parameter from Git.
git config --system core.longpaths true
But a workaround that works is remove the node_modules folder from Git:
$ git rm -r --cached node_modules
$ vi .gitignore
Add node_modules in a new row inside the .gitignore file. After doing this, push your modifications:
$ git add .gitignore
$ git commit -m "node_modules removed"
$ git push
The apps UI only works for panels.
The best you can do is to draw a button yourself and put that into your spreadsheet. Than you can add a macro to it.
Go into "Insert > Drawing...", Draw a button and add it to the spreadsheet. Than click it and click "assign Macro...", then insert the name of the function you wish to execute there. The function must be defined in a script in the spreadsheet.
Alternatively you can also draw the button somewhere else and insert it as an image.
More info: https://developers.google.com/apps-script/guides/menus
Typically one would use one (or more) image tags, maybe in combination with setting div background images in css to act as the submit button. The actual submit would be done in javascript on the click event.
A tutorial on the subject.
For Java 7, increment operator '++' works on Integers. Below is a tested example
Integer i = new Integer( 12 );
System.out.println(i); //12
i = i++;
System.out.println(i); //13
Using Concat on the group by will work
SELECT clients.id, clients.name, portfolios.id, SUM ( portfolios.portfolio + portfolios.cash ) AS total
FROM clients, portfolios
WHERE clients.id = portfolios.client_id
GROUP BY CONCAT(portfolios.id, "-", clients.id)
ORDER BY total DESC
LIMIT 30
The extra [ ] on the outside of your second syntax are unnecessary, and possibly confusing. You may use them, but if you must you need to have whitespace between them.
Alternatively:
while [ $stats -gt 300 ] || [ $stats -eq 0 ]
You can return json in PHP this way:
header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;
As an extension to @JBNizet's answer for more technical users here's what implementation of org.w3c.dom.Node
interface in com.sun.org.apache.xerces.internal.dom.ParentNode
looks like, gives you the idea how it actually works.
public void normalize() {
// No need to normalize if already normalized.
if (isNormalized()) {
return;
}
if (needsSyncChildren()) {
synchronizeChildren();
}
ChildNode kid;
for (kid = firstChild; kid != null; kid = kid.nextSibling) {
kid.normalize();
}
isNormalized(true);
}
It traverses all the nodes recursively and calls kid.normalize()
This mechanism is overridden in org.apache.xerces.dom.ElementImpl
public void normalize() {
// No need to normalize if already normalized.
if (isNormalized()) {
return;
}
if (needsSyncChildren()) {
synchronizeChildren();
}
ChildNode kid, next;
for (kid = firstChild; kid != null; kid = next) {
next = kid.nextSibling;
// If kid is a text node, we need to check for one of two
// conditions:
// 1) There is an adjacent text node
// 2) There is no adjacent text node, but kid is
// an empty text node.
if ( kid.getNodeType() == Node.TEXT_NODE )
{
// If an adjacent text node, merge it with kid
if ( next!=null && next.getNodeType() == Node.TEXT_NODE )
{
((Text)kid).appendData(next.getNodeValue());
removeChild( next );
next = kid; // Don't advance; there might be another.
}
else
{
// If kid is empty, remove it
if ( kid.getNodeValue() == null || kid.getNodeValue().length() == 0 ) {
removeChild( kid );
}
}
}
// Otherwise it might be an Element, which is handled recursively
else if (kid.getNodeType() == Node.ELEMENT_NODE) {
kid.normalize();
}
}
// We must also normalize all of the attributes
if ( attributes!=null )
{
for( int i=0; i<attributes.getLength(); ++i )
{
Node attr = attributes.item(i);
attr.normalize();
}
}
// changed() will have occurred when the removeChild() was done,
// so does not have to be reissued.
isNormalized(true);
}
Hope this saves you some time.
Just to add yet another solution :P, I went with a combination of @spheenik and @collin-anderson 's solutions.
# Ensure that we have an ssh config with AddKeysToAgent set to true
if [ ! -f ~/.ssh/config ] || ! cat ~/.ssh/config | grep AddKeysToAgent | grep yes > /dev/null; then
echo "AddKeysToAgent yes" >> ~/.ssh/config
fi
# Ensure a ssh-agent is running so you only have to enter keys once
if [ ! -S ~/.ssh/ssh_auth_sock ]; then
eval `ssh-agent`
ln -sf "$SSH_AUTH_SOCK" ~/.ssh/ssh_auth_sock
fi
export SSH_AUTH_SOCK=~/.ssh/ssh_auth_sock
Could be a little more elegant but its simple and readable. This solution:
AddKeysToAgent yes
is in your ssh config so keys will be automatically added upon useComments welcome :)
What you can do is to wrap the invocation into a function of its own.
So that
foo()
def foo():
print "Hi!"
will break, but
def bar():
foo()
def foo():
print "Hi!"
bar()
will be working properly.
General rule in Python
is not that function should be defined higher in the code (as in Pascal
), but that it should be defined before its usage.
Hope that helps.
To pass a NULL to MySQL, you do just that.
INSERT INTO table (field,field2) VALUES (NULL,3)
So, in your code, check if $intLat, $intLng
are empty
, if they are, use NULL
instead of '$intLat'
or '$intLng'
.
$intLat = !empty($intLat) ? "'$intLat'" : "NULL";
$intLng = !empty($intLng) ? "'$intLng'" : "NULL";
$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long',
$intLat, $intLng)";
using a switch case
switch ($num){
case ($num>= $value1 && $num<= $value2):
echo "within range 1";
break;
case ($num>= $value3 && $num<= $value4):
echo "within range 2";
break;
.
.
.
.
.
default: //default
echo "within no range";
break;
}
I encountered the same issue on Mac OSX, using a ZSH shell: in this case there is no -t
option for mv
, so I had to find another solution.
However the following command succeeded:
find .* * -maxdepth 0 -not -path '.git' -not -path '.backup' -exec mv '{}' .backup \;
The secret was to quote the braces. No need for the braces to be at the end of the exec
command.
I tested under Ubuntu 14.04 (with BASH and ZSH shells), it works the same.
However, when using the +
sign, it seems indeed that it has to be at the end of the exec
command.
You can use Linq to cleverly initialize your list with a default value. (Similar to David B's answer.)
var defaultStrings = (new int[10]).Select(x => "my value").ToList();
Go one step farther and initialize each string with distinct values "string 1", "string 2", "string 3", etc:
int x = 1;
var numberedStrings = (new int[10]).Select(x => "string " + x++).ToList();
This following has worked best for me:
HTML:
<input type="submit"/>
CSS:
input[type=submit] {
background: url(http://yourURLhere) no-repeat;
border: 0;
display: block;
font-size:0;
height: 38px;
width: 171px;
}
If you don't set value
on your <input type="submit"/>
it will place the default text "Submit" inside your button. SO, just set the font-size: 0;
on your submit and then make sure you set a height
and width
for your input type so that your image will display. DON'T forget media queries for your submit if you need them, for example:
CSS:
@media (min-width:600px) {
input[type=submit] {
width:200px;
height: 44px;
}
}
This means when the screen is at exactly 600px wide or greater the button will change it's dimensions
This is really linked to HotSpot and the default option values (Java HotSpot VM Options) which differ between client and server configuration.
From Chapter 2 of the whitepaper (The Java HotSpot Performance Engine Architecture):
The JDK includes two flavors of the VM -- a client-side offering, and a VM tuned for server applications. These two solutions share the Java HotSpot runtime environment code base, but use different compilers that are suited to the distinctly unique performance characteristics of clients and servers. These differences include the compilation inlining policy and heap defaults.
Although the Server and the Client VMs are similar, the Server VM has been specially tuned to maximize peak operating speed. It is intended for executing long-running server applications, which need the fastest possible operating speed more than a fast start-up time or smaller runtime memory footprint.
The Client VM compiler serves as an upgrade for both the Classic VM and the just-in-time (JIT) compilers used by previous versions of the JDK. The Client VM offers improved run time performance for applications and applets. The Java HotSpot Client VM has been specially tuned to reduce application start-up time and memory footprint, making it particularly well suited for client environments. In general, the client system is better for GUIs.
So the real difference is also on the compiler level:
The Client VM compiler does not try to execute many of the more complex optimizations performed by the compiler in the Server VM, but in exchange, it requires less time to analyze and compile a piece of code. This means the Client VM can start up faster and requires a smaller memory footprint.
The Server VM contains an advanced adaptive compiler that supports many of the same types of optimizations performed by optimizing C++ compilers, as well as some optimizations that cannot be done by traditional compilers, such as aggressive inlining across virtual method invocations. This is a competitive and performance advantage over static compilers. Adaptive optimization technology is very flexible in its approach, and typically outperforms even advanced static analysis and compilation techniques.
Note: The release of jdk6 update 10 (see Update Release Notes:Changes in 1.6.0_10) tried to improve startup time, but for a different reason than the hotspot options, being packaged differently with a much smaller kernel.
G. Demecki points out in the comments that in 64-bit versions of JDK, the -client
option is ignored for many years.
See Windows java
command:
-client
Selects the Java HotSpot Client VM.
A 64-bit capable JDK currently ignores this option and instead uses the Java Hotspot Server VM.
If none of the above work, quotation marks around the stash itself might work for you:
git stash pop "stash@{0}"
In my case,I was getting error while refreshing gradle ('View'->Tool Windows->Gradle) tab and hit "refresh" and getting this error no such property gradleversion for class jetgradleplugin.
Had to install latest intellij compatible with gradle 5+
This is a good use case for Objective C categories.
For Base64 encoding:
#import <Foundation/NSString.h>
@interface NSString (NSStringAdditions)
+ (NSString *) base64StringFromData:(NSData *)data length:(int)length;
@end
-------------------------------------------
#import "NSStringAdditions.h"
static char base64EncodingTable[64] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};
@implementation NSString (NSStringAdditions)
+ (NSString *) base64StringFromData: (NSData *)data length: (int)length {
unsigned long ixtext, lentext;
long ctremaining;
unsigned char input[3], output[4];
short i, charsonline = 0, ctcopy;
const unsigned char *raw;
NSMutableString *result;
lentext = [data length];
if (lentext < 1)
return @"";
result = [NSMutableString stringWithCapacity: lentext];
raw = [data bytes];
ixtext = 0;
while (true) {
ctremaining = lentext - ixtext;
if (ctremaining <= 0)
break;
for (i = 0; i < 3; i++) {
unsigned long ix = ixtext + i;
if (ix < lentext)
input[i] = raw[ix];
else
input[i] = 0;
}
output[0] = (input[0] & 0xFC) >> 2;
output[1] = ((input[0] & 0x03) << 4) | ((input[1] & 0xF0) >> 4);
output[2] = ((input[1] & 0x0F) << 2) | ((input[2] & 0xC0) >> 6);
output[3] = input[2] & 0x3F;
ctcopy = 4;
switch (ctremaining) {
case 1:
ctcopy = 2;
break;
case 2:
ctcopy = 3;
break;
}
for (i = 0; i < ctcopy; i++)
[result appendString: [NSString stringWithFormat: @"%c", base64EncodingTable[output[i]]]];
for (i = ctcopy; i < 4; i++)
[result appendString: @"="];
ixtext += 3;
charsonline += 4;
if ((length > 0) && (charsonline >= length))
charsonline = 0;
}
return result;
}
@end
For Base64 decoding:
#import <Foundation/Foundation.h>
@class NSString;
@interface NSData (NSDataAdditions)
+ (NSData *) base64DataFromString:(NSString *)string;
@end
-------------------------------------------
#import "NSDataAdditions.h"
@implementation NSData (NSDataAdditions)
+ (NSData *)base64DataFromString: (NSString *)string
{
unsigned long ixtext, lentext;
unsigned char ch, inbuf[4], outbuf[3];
short i, ixinbuf;
Boolean flignore, flendtext = false;
const unsigned char *tempcstring;
NSMutableData *theData;
if (string == nil)
{
return [NSData data];
}
ixtext = 0;
tempcstring = (const unsigned char *)[string UTF8String];
lentext = [string length];
theData = [NSMutableData dataWithCapacity: lentext];
ixinbuf = 0;
while (true)
{
if (ixtext >= lentext)
{
break;
}
ch = tempcstring [ixtext++];
flignore = false;
if ((ch >= 'A') && (ch <= 'Z'))
{
ch = ch - 'A';
}
else if ((ch >= 'a') && (ch <= 'z'))
{
ch = ch - 'a' + 26;
}
else if ((ch >= '0') && (ch <= '9'))
{
ch = ch - '0' + 52;
}
else if (ch == '+')
{
ch = 62;
}
else if (ch == '=')
{
flendtext = true;
}
else if (ch == '/')
{
ch = 63;
}
else
{
flignore = true;
}
if (!flignore)
{
short ctcharsinbuf = 3;
Boolean flbreak = false;
if (flendtext)
{
if (ixinbuf == 0)
{
break;
}
if ((ixinbuf == 1) || (ixinbuf == 2))
{
ctcharsinbuf = 1;
}
else
{
ctcharsinbuf = 2;
}
ixinbuf = 3;
flbreak = true;
}
inbuf [ixinbuf++] = ch;
if (ixinbuf == 4)
{
ixinbuf = 0;
outbuf[0] = (inbuf[0] << 2) | ((inbuf[1] & 0x30) >> 4);
outbuf[1] = ((inbuf[1] & 0x0F) << 4) | ((inbuf[2] & 0x3C) >> 2);
outbuf[2] = ((inbuf[2] & 0x03) << 6) | (inbuf[3] & 0x3F);
for (i = 0; i < ctcharsinbuf; i++)
{
[theData appendBytes: &outbuf[i] length: 1];
}
}
if (flbreak)
{
break;
}
}
}
return theData;
}
@end
in addition to a watchpoint nested inside a breakpoint you can also set a single breakpoint on the 'filename:line_number' and use a condition. I find it sometimes easier.
(gdb) break iter.c:6 if i == 5
Breakpoint 2 at 0x4004dc: file iter.c, line 6.
(gdb) c
Continuing.
0
1
2
3
4
Breakpoint 2, main () at iter.c:6
6 printf("%d\n", i);
If like me you get tired of line numbers changing, you can add a label then set the breakpoint on the label like so:
#include <stdio.h>
main()
{
int i = 0;
for(i=0;i<7;++i) {
looping:
printf("%d\n", i);
}
return 0;
}
(gdb) break main:looping if i == 5
If you want to select every element that has class attribute "myclass" use
$('#mydiv .myclass');
If you want to select only div elements that has class attribute "myclass" use
$("div#mydiv div.myclass");
find more about jquery selectors refer these articles
At least on firefox, you can set a "title" attribute on the option tag:
<option value="" title="Tooltip">Some option</option>
The $@
and $<
are special macros.
Where:
$@
is the file name of the target.
$<
is the name of the first dependency.
For me it was a ternary statement:
It was complaining about this line in particular, about the semicolon:
let num_coin = val.num_coin ? val.num_coin || 2;
I changed it to:
let num_coin = val.num_coin || 2;
It may sound silly but in my case the USB cable was too long (even if good quality). It worked with my tablet but not with the phone. To check this, if you run on Linux run lsusb to make sure that your device is at least officially connect to the usb port.
uchar * value = img2.data; //Pointer to the first pixel data ,it's return array in all values
int r = 2;
for (size_t i = 0; i < img2.cols* (img2.rows * img2.channels()); i++)
{
if (r > 2) r = 0;
if (r == 0) value[i] = 0;
if (r == 1)value[i] = 0;
if (r == 2)value[i] = 255;
r++;
}
If you aren't comfortable with using negative margins, check this out.
div {
position: fixed;
left: 50%;
bottom: 20px;
transform: translate(-50%, -50%);
margin: 0 auto;
}
<div>
Your Text
</div>
Especially useful when you don't know the width of the div.
align="center"
has no effect.
Since you have position:absolute
, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.
#manipulate {
position:absolute;
width:300px;
height:300px;
background:#063;
bottom:0px;
right:25%;
left:50%;
margin-left:-150px;
}
Regarding answers by @Hugh Bothwell, @mortehu and @glglgl.
Setup Dataset for testing
import random
dataset = [random.randint(0,15) if random.random() > .6 else None for i in range(1000)]
Define implementations
def not_none(x, y=None):
if x is None:
return y
return x
def coalesce1(*arg):
return reduce(lambda x, y: x if x is not None else y, arg)
def coalesce2(*args):
return next((i for i in args if i is not None), None)
Make test function
def test_func(dataset, func):
default = 1
for i in dataset:
func(i, default)
Results on mac i7 @2.7Ghz using python 2.7
>>> %timeit test_func(dataset, not_none)
1000 loops, best of 3: 224 µs per loop
>>> %timeit test_func(dataset, coalesce1)
1000 loops, best of 3: 471 µs per loop
>>> %timeit test_func(dataset, coalesce2)
1000 loops, best of 3: 782 µs per loop
Clearly the not_none
function answers the OP's question correctly and handles the "falsy" problem. It is also the fastest and easiest to read. If applying the logic in many places, it is clearly the best way to go.
If you have a problem where you want to find the 1st non-null value in a iterable, then @mortehu's response is the way to go. But it is a solution to a different problem than OP, although it can partially handle that case. It cannot take an iterable AND a default value. The last argument would be the default value returned, but then you wouldn't be passing in an iterable in that case as well as it isn't explicit that the last argument is a default to value.
You could then do below, but I'd still use not_null
for the single value use case.
def coalesce(*args, **kwargs):
default = kwargs.get('default')
return next((a for a in arg if a is not None), default)
I would use
like 'Express Edition%'
Example:
DECLARE @edition varchar(50);
set @edition = cast((select SERVERPROPERTY ('edition')) as varchar)
DECLARE @isExpress bit
if @edition like 'Express Edition%'
set @isExpress = 1;
else
set @isExpress = 0;
print @isExpress
gradlew
is a wrapper(w - character) that uses gradle
.
Under the hood gradlew
performs three main things:
gradle
versiongradle
taskUsing Gradle Wrapper we can distribute/share a project to everybody to use the same version and Gradle's functionality(compile, build, install...) even if it has not been installed.
To create a wrapper run:
gradle wrapper
This command generate:
gradle-wrapper.properties
will contain the information about the Gradle distribution
*./
Is used on Unix to specify the current directory
Most SFTP servers support SCP as well which can be a lot easier to find libraries for. You could even just call an existing client from your code like pscp included with PuTTY.
If the type of file you're working with is something simple like a text or XML file, you could even go so far as to write your own client/server implementation to manipulate the file using something like .NET Remoting or web services.
array.sort(key = lambda x:x[1])
You can easily sort using this snippet, where 1 is the index of the element.
Until Android 7.1 you will get it with:
Build.SERIAL
On Android 8 (SDK 26) and above, this field will return UNKNOWN
and must be accessed with:
Build.getSerial()
which requires the dangerous permission
android.permission.READ_PHONE_STATE
.
Since Android Q using Build.getSerial()
gets a bit more complicated by requiring:
android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE
(which can only be acquired by system apps), or for the calling package to be the device or profile owner and have the READ_PHONE_STATE
permission. This means most apps won't be able to uses this feature. See the Android Q announcement from Google.
If you just require a unique identifier, it's best to avoid using hardware identifiers as Google continuously tries to make it harder to access them for privacy reasons. You could just generate a UUID.randomUUID().toString();
and save it the first time it needs to be accessed in e.g. shared preferences. Alternatively you could use ANDROID_ID
which is a 8 byte long hex string unique to the device, user and (only Android 8+) app installation. For more info on that topic, see Best practices for unique identifiers.
(T)Activator.CreateInstance(typeof(T), param1, param2);
You can use TimerTask for Cronjobs.
Main.java
public class Main{
public static void main(String[] args){
Timer t = new Timer();
MyTask mTask = new MyTask();
// This task is scheduled to run every 10 seconds
t.scheduleAtFixedRate(mTask, 0, 10000);
}
}
MyTask.java
class MyTask extends TimerTask{
public MyTask(){
//Some stuffs
}
@Override
public void run() {
System.out.println("Hi see you after 10 seconds");
}
}
Alternative You can also use ScheduledExecutorService.
Facing the very same problem (avoiding the default path in a network) I came up to this solution with the hints given in other answers.
The solution is editing the Rprofile
file to overwrite the variable R_LIBS_USER
which by default points to the home directory.
Here the steps:
~\target
.Rprofile
file. In my case it was at C:\Program Files\R\R-3.3.3\library\base\R\Rprofile
.R_LIBS_USER
. In my case, I replaced the this line file.path(Sys.getenv("R_USER"), "R",
with file.path("~\target", "R",
.The documentation that support this solution is here
Original file with:
if(!nzchar(Sys.getenv("R_LIBS_USER")))
Sys.setenv(R_LIBS_USER=
file.path(Sys.getenv("R_USER"), "R",
"win-library",
paste(R.version$major,
sub("\\..*$", "", R.version$minor),
sep=".")
))
Modified file:
if(!nzchar(Sys.getenv("R_LIBS_USER")))
Sys.setenv(R_LIBS_USER=
file.path("~\target", "R",
"win-library",
paste(R.version$major,
sub("\\..*$", "", R.version$minor),
sep=".")
))
If your JSON is without key you can do it like this:
library[library.length] = {"foregrounds" : foregrounds,"backgrounds" : backgrounds};
So, try this:
var library = {[{
"title" : "Gold Rush",
"foregrounds" : ["Slide 1","Slide 2","Slide 3"],
"backgrounds" : ["1.jpg","","2.jpg"]
}, {
"title" : California",
"foregrounds" : ["Slide 1","Slide 2","Slide 3"],
"backgrounds" : ["3.jpg","4.jpg","5.jpg"]
}]
}
Then:
library[library.length] = {"title" : "Gold Rush", "foregrounds" : ["Howdy","Slide 2"], "backgrounds" : ["1.jpg",""]};
Best answer doesn't work for me. I needed ssh://
from the beggining.
# does not work
git remote set-url origin [email protected]:10000/aaa/bbbb/ccc.git
# work
git remote set-url origin ssh://[email protected]:10000/aaa/bbbb/ccc.git
Faced exactly the same issue while upgrading my application from java 6 to java 8 on tomcat 7.0.19. After upgrading the tomcat to 7.0.59, this issue is resolved.
Pyperclip seems to be up to the task.
You need to do a couple of things to use the library:
Make sure that you have both the *.lib and the *.dll from the library you want to use. If you don't have the *.lib, skip #2
Put a reference to the *.lib in the project. Right click the project name in the Solution Explorer and then select Configuration Properties->Linker->Input and put the name of the lib in the Additional Dependencies property.
You have to make sure that VS can find the lib you just added so you have to go to the Tools menu and select Options... Then under Projects and Solutions select VC++ Directories,edit Library Directory option. From within here you can set the directory that contains your new lib by selecting the 'Library Files' in the 'Show Directories For:' drop down box. Just add the path to your lib file in the list of directories. If you dont have a lib you can omit this, but while your here you will also need to set the directory which contains your header files as well under the 'Include Files'. Do it the same way you added the lib.
After doing this you should be good to go and can use your library. If you dont have a lib file you can still use the dll by importing it yourself. During your applications startup you can explicitly load the dll by calling LoadLibrary (see: http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx for more info)
Cheers!
EDIT
Remember to use #include < Foo.h > as opposed to #include "foo.h". The former searches the include path. The latter uses the local project files.
Assuming you are trying to find if a div exists
$('div').length ? alert('div found') : alert('Div not found')
There is collection of Func<...>
classes - Func that is probably what you are looking for:
void MyMethod(Func<int> param1 = null)
This defines method that have parameter param1
with default value null
(similar to AS), and a function that returns int
. Unlike AS in C# you need to specify type of the function's arguments.
So if you AS usage was
MyMethod(function(intArg, stringArg) { return true; })
Than in C# it would require param1
to be of type Func<int, siring, bool>
and usage like
MyMethod( (intArg, stringArg) => { return true;} );
OneToOneField: if second table is related with
table2_col1 = models.OneToOneField(table1,on_delete=models.CASCADE, related_name='table1_id')
table2 will contains only one record corresponding to table1's pk value, i.e table2_col1 will have unique value equal to pk of table
table2_col1 == models.ForeignKey(table1, on_delete=models.CASCADE, related_name='table1_id')
table2 may contains more than one record corresponding to table1's pk value.
Just extending on the many other excellent answers - if you are using jQuery - you could just do something like
$.fn.getMonthName = function(date) {
var monthNames = [
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
];
return monthNames[date.getMonth()];
};
where date
is equal to the var d = new Date(somevalue)
. The primary advantage of this is per @nickf said about avoiding the global namespace.
What worked for me (on Windows, using git version 1.8.3.msysgit.0):
git submodule init
and git submodule update
After doing all that, everything is in the state I would expect. I imagine other users of the repository will have similar pain when they come to update though - it would be wise to explain these steps in your commit message!
Yes, you can, but you need a few tools first. You need to know a little about basic coding, FTP clients, port scanners and brute force tools, if it has a .htaccess file.
If not just try tgp.linkurl.htm or html, ie default.html
, www/home/siteurl/web/
, or wap /index/ default /includes/ main/ files/ images/ pics/ vids/
, could be possible file locations on the server, so try all of them so www/home/siteurl/web/includes/.htaccess
or default.html
. You'll hit a file after a few tries then work off that. Yahoo has a site file viewer too: you can try to scan sites file indexes.
Alternatively, try brutus aet, trin00, trinity.x, or whiteshark airtool to crack the site's FTP login (but it's illegal and I do not condone that).
One thing that took me a while to figure out, use 'http' to access the proxy, even if you're trying to proxy through to a https server. This works for me using Charles (osx protocol analyser):
var http = require('http');
http.get ({
host: '127.0.0.1',
port: 8888,
path: 'https://www.google.com/accounts/OAuthGetRequestToken'
}, function (response) {
console.log (response);
});
malloc for single chars or integers and calloc for dynamic arrays. ie pointer = ((int *)malloc(sizeof(int)) == NULL)
, you can do arithmetic within the brackets of malloc
but you shouldnt because you should use calloc
which has the definition of void calloc(count, size)
which means how many items you want to store ie count and size of data ie int
, char
etc.
The path should be something like: "Images\a.bmp"
. (Note the lack of a leading slash, and the slashes being back slashes.)
And then:
pictureBox1.Image = Image.FromFile(@"Images\a.bmp");
I just tried it to make sure, and it works. This is besides the other answer that you got - to "copy always".
If you want to use a format that allows you to keep the number like your entry this format works for me:
"# \\%"
Were I you I would do something like this:
Before doing anything please keep a copy (better safe than sorry)
git checkout master
git checkout -b temp
git reset --hard <sha-1 of your first commit>
git add .
git commit -m 'Squash all commits in single one'
git push origin temp
After doing that you can delete other branches.
Result: You are going to have a branch with only 2 commits.
Use
git log --oneline
to see your commits in a minimalistic way and to find SHA-1 for commits!
You need to float all the buttons to left and make sure its width to fit within outer container.
CSS:
.btn{
float:left;
}
HTML:
<button type="submit" class="btn" onClick="return false;" >Save</button>
<button type="submit" class="btn" onClick="return false;">Publish</button>
<button class="btn">Back</button>
By default .vs folder is hidden (at least in my case).
If you are not able to find the .vs folder, follow the below steps.
Attributes
section, click Hidden
check box(default unchecked),step 3
, this time you need to uncheck
the 'Hidden' option that you checked previously.Now should be able to see .vs folder.
For long long (or __int64) using MSVS, you should use %I64d:
__int64 a;
time_t b;
...
fprintf(outFile,"%I64d,%I64d\n",a,b); //I is capital i
To check if a Variant
is Null, you need to do it like:
Isnull(myvar) = True
or
Not Isnull(myvar)
<button></button>
)<button></button>
(Hint: IE6)Another IE problem when using <button />
:
And while we're talking about IE, it's got a couple of bugs related to the width of buttons. It'll mysteriously add extra padding when you're trying to add styles, meaning you have to add a tiny hack to get things under control.
try to add jackson dependency
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.3</version>
<exclusions>
<exclusion>
<artifactId>jackson-annotations</artifactId>
<groupId>com.fasterxml.jackson.core</groupId>
</exclusion>
</exclusions>
</dependency>
This is the behavior of ln
if the second arg is a directory. It places a link to the first arg inside it. If you want /etc/nginx
to be the symlink, you should remove that directory first and run that same command.
When it can be the same header for all requests or you dispose the client after each request you can use the DefaultRequestHeaders.Add
option:
client.DefaultRequestHeaders.Add("apikey","xxxxxxxxx");
I've just bumped into this myself and this variation worked for me:
db.foo.remove({**_id**: new ObjectId("4f872685a64eed5a980ca536")})
Let's fit the model:
> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)
Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)
Residuals:
Min 1Q Median 3Q Max
-245.74 -113.99 -32.05 104.96 484.81
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 811.2267 76.9755 10.539 2.29e-13 ***
body.weight 7.0595 0.9776 7.221 7.03e-09 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433
F-statistic: 52.15 on 1 and 42 DF, p-value: 7.025e-09
The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).
This can be computed using confint
:
> confint(fit, 'body.weight', level=0.95)
2.5 % 97.5 %
body.weight 5.086656 9.0324
Try this:
String result = "34.1 -118.33\n<!--ABCDEFG-->";
result = result.substring(0, result.indexOf("\n"));
Sam's solution should be sufficient. I've used combination of both histogram difference and template matching because not one method was working for me 100% of the times. I've given less importance to histogram method though. Here's how I've implemented in simple python script.
import cv2
class CompareImage(object):
def __init__(self, image_1_path, image_2_path):
self.minimum_commutative_image_diff = 1
self.image_1_path = image_1_path
self.image_2_path = image_2_path
def compare_image(self):
image_1 = cv2.imread(self.image_1_path, 0)
image_2 = cv2.imread(self.image_2_path, 0)
commutative_image_diff = self.get_image_difference(image_1, image_2)
if commutative_image_diff < self.minimum_commutative_image_diff:
print "Matched"
return commutative_image_diff
return 10000 //random failure value
@staticmethod
def get_image_difference(image_1, image_2):
first_image_hist = cv2.calcHist([image_1], [0], None, [256], [0, 256])
second_image_hist = cv2.calcHist([image_2], [0], None, [256], [0, 256])
img_hist_diff = cv2.compareHist(first_image_hist, second_image_hist, cv2.HISTCMP_BHATTACHARYYA)
img_template_probability_match = cv2.matchTemplate(first_image_hist, second_image_hist, cv2.TM_CCOEFF_NORMED)[0][0]
img_template_diff = 1 - img_template_probability_match
# taking only 10% of histogram diff, since it's less accurate than template method
commutative_image_diff = (img_hist_diff / 10) + img_template_diff
return commutative_image_diff
if __name__ == '__main__':
compare_image = CompareImage('image1/path', 'image2/path')
image_difference = compare_image.compare_image()
print image_difference
The reason why your current approach doesn't work is because Jackson is used by default to serialize and to deserialize objects. However, it doesn't know how to serialize the JSONObject
. If you want to create a dynamic JSON structure, you can use a Map
, for example:
@GetMapping
public Map<String, String> sayHello() {
HashMap<String, String> map = new HashMap<>();
map.put("key", "value");
map.put("foo", "bar");
map.put("aa", "bb");
return map;
}
This will lead to the following JSON response:
{ "key": "value", "foo": "bar", "aa": "bb" }
This is a bit limited, since it may become a bit more difficult to add child objects. Jackson has its own mechanism though, using ObjectNode
and ArrayNode
. To use it, you have to autowire ObjectMapper
in your service/controller. Then you can use:
@GetMapping
public ObjectNode sayHello() {
ObjectNode objectNode = mapper.createObjectNode();
objectNode.put("key", "value");
objectNode.put("foo", "bar");
objectNode.put("number", 42);
return objectNode;
}
This approach allows you to add child objects, arrays, and use all various types.
You can use FLOOR
:
select x, ABS(x) - FLOOR(ABS(x))
from (
select 2.938 as x
) a
Output:
x
-------- ----------
2.938 0.938
Or you can use SUBSTRING
:
select x, SUBSTRING(cast(x as varchar(max)), charindex(cast(x as varchar(max)), '.') + 3, len(cast(x as varchar(max))))
from (
select 2.938 as x
) a
None of the above answers worked for me using git version 1.8.3.msysgit.0 and TortoiseGit 1.8.4.0.
In my particular situation, I have to connect to the remote git repo over HTTPS, using a full blown e-mail address as username.
In this situation, wincred
did not appear to work.
Using the email address as a part of the repo URL also did not work, as the software seems to be confused by the double appearance of the '@' character in the URL.
I did manage to overcome the problem using winstore
. Here is what I did:
winstore
from http://gitcredentialstore.codeplex.com/git-credential-winstore.exe
to install it.This will copy the git-credential-winstore.exe
to a local directory and add two lines to your global .gitconfig
. You can verify this by examining your global .gitconfig
. This is easiest done via right mouse button on a folder, "TortoiseGit > Settings > Git > Edit global .gitconfig". The file should contain two lines like:
[credential]
helper = !'C:\\Users\\yourlogin\\AppData\\Roaming\\GitCredStore\\git-credential-winstore.exe'
You are now ready to go:
winstore
works. Enter the correct authentication and the pull should succeed.Done!
Enjoy your interactions with the remote repo while winstore
takes care of the authentication.
(*) Alternatively, if you don't like the blank selection in the TortoiseGit Credential settings helper pull down menu, you can use the "Advanced" option:
Enter the Helper path as below. Note: a regular Windows path notation (e.g. "C:\Users...") will not work here, you have to replicate the exact line that installing winstore
created in the global .gitconf
without the "helper =" bit.
!'C:\\Users\\yourlogin\\AppData\\Roaming\\GitCredStore\\git-credential-winstore.exe'
Click the "Add New/Save" button
In order to get the PHP output into the HTML file you need to either
Why not use onBackPressed()
?
@Override
public void onBackPressed()
{
// super.onBackPressed(); Do not call me!
// Go to the previous web page.
}
Here is an idea as you may have multiple newline in a textbox:
var text=document.getElementById('post-text').value.split('\n');
var html = text.join('<br />');
This HTML value will preserve newline. Hope this helps.
Testing for name pointing to None
and name existing are two semantically different operations.
To check if val
is None:
if val is None:
pass # val exists and is None
To check if name exists:
try:
val
except NameError:
pass # val does not exist at all
If you want to resize an image after it is loaded, you can attach to the onload
event of the <img>
tag. Note that it may not be supported in all browsers (Microsoft's reference claims it is part of the HTML 4.0 spec, but the HTML 4.0 spec doesn't list the onload
event for <img>
).
The code below is tested and working in: IE 6, 7 & 8, Firefox 2, 3 & 3.5, Opera 9 & 10, Safari 3 & 4 and Google Chrome:
<img src="yourImage.jpg" border="0" height="real_height" width="real_width"
onload="resizeImg(this, 200, 100);">
<script type="text/javascript">
function resizeImg(img, height, width) {
img.height = height;
img.width = width;
}
</script>
As xerq's excellent answer explains, this is a DNS timeout issue.
I wanted to contribute another possible answer for those of you using Windows Subsystem for Linux - there are some cases where something seems to be askew in the client OS after Windows resumes from sleep. Restarting the host OS will fix these issues (it's also likely restarting the WSL service will do the same).
Just use .item + .item
in selector to match from second .item
#box {_x000D_
display: inline-flex;_x000D_
margin: 0 -5px;_x000D_
}_x000D_
.item {_x000D_
background: gray;_x000D_
width: 10px;_x000D_
height: 50px;_x000D_
}_x000D_
_x000D_
#box .item + .item {_x000D_
margin-left: 10px;_x000D_
}
_x000D_
<div id='box'>_x000D_
<div class='item'></div>_x000D_
<div class='item'></div>_x000D_
<div class='item'></div>_x000D_
<div class='item'></div>_x000D_
</div>
_x000D_
Custom domain SSL certs were just added today for $600/cert/month. Sign up for your invite below: http://aws.amazon.com/cloudfront/custom-ssl-domains/
Update: SNI customer provided certs are now available for no additional charge. Much cheaper than $600/mo, and with XP nearly killed off, it should work well for most use cases.
@skalee AWS has a mechanism for achieving what the poster asks for, "implement SSL for an Amazon s3 bucket", it's called CloudFront
. I'm reading "implement" as "use my SSL certs," not "just put an S on the HTTP URL which I'm sure the OP could have surmised.
Since CloudFront costs exactly the same as S3 ($0.12/GB), but has a ton of additional features around SSL AND allows you to add your own SNI cert at no additional cost, it's the obvious fix for "implementing SSL" on your domain.
If the path you want is the one to the workbook running the macro, and that workbook has been saved, then
ThisWorkbook.Path
is what you would use.
static
data members in class?The C++ standard allows only static constant integral or enumeration types to be initialized inside the class. This is the reason a
is allowed to be initialized while others are not.
Reference:
C++03 9.4.2 Static data members
§4
If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.
What are integral types?
C++03 3.9.1 Fundamental types
§7
Types bool, char, wchar_t, and the signed and unsigned integer types are collectively called integral types.43) A synonym for integral type is integer type.
Footnote:
43) Therefore, enumerations (7.2) are not integral; however, enumerations can be promoted to int, unsigned int, long, or unsigned long, as specified in 4.5.
You could use the enum trick to initialize an array inside your class definition.
class A
{
static const int a = 3;
enum { arrsize = 2 };
static const int c[arrsize] = { 1, 2 };
};
Bjarne explains this aptly here:
A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects.
static const
integral types & enums allowed In-class Initialization?The answer is hidden in Bjarne's quote read it closely,
"C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects."
Note that only static const
integers can be treated as compile time constants. The compiler knows that the integer value will not change anytime and hence it can apply its own magic and apply optimizations, the compiler simply inlines such class members i.e, they are not stored in memory anymore, As the need of being stored in memory is removed, it gives such variables the exception to rule mentioned by Bjarne.
It is noteworthy to note here that even if static const
integral values can have In-Class Initialization, taking address of such variables is not allowed. One can take the address of a static member if (and only if) it has an out-of-class definition.This further validates the reasoning above.
enums are allowed this because values of an enumerated type can be used where ints are expected.see citation above
C++11 relaxes the restriction to certain extent.
C++11 9.4.2 Static data members
§3
If a static data member is of const literal type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. A static data member of literal type can be declared in the class definition with the
constexpr specifier;
if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [ Note: In both these cases, the member may appear in constant expressions. —end note ] The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.
Also, C++11 will allow(§12.6.2.8) a non-static data member to be initialized where it is declared(in its class). This will mean much easy user semantics.
Note that these features have not yet been implemented in latest gcc 4.7, So you might still get compilation errors.
C99 requires that when a/b
is representable:
(a/b) * b
+ a%b
shall equal a
This makes sense, logically. Right?
Let's see what this leads to:
Example A. 5/(-3)
is -1
=> (-1) * (-3)
+ 5%(-3)
= 5
This can only happen if 5%(-3)
is 2.
Example B. (-5)/3
is -1
=> (-1) * 3
+ (-5)%3
= -5
This can only happen if (-5)%3
is -2
Be aware that there is org.codehaus.jackson.annotate.JsonProperty
in Jackson 1.x and com.fasterxml.jackson.annotation.JsonProperty
in Jackson 2.x. Check which ObjectMapper you are using (from which version), and make sure you use the proper annotation.
You're getting None
because list.sort()
it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort()
without assigning it to a
again.
There is a built in function sorted()
, which returns a sorted version of the list - a = sorted(a)
will do what you want as well.
Add the following permissions into your manifest file:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
Enable bluetooth use this
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
}else{Toast.makeText(getApplicationContext(), "Bluetooth Al-Ready Enable", Toast.LENGTH_LONG).show();}
Disable bluetooth use this
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
}
For Writing Excel
For Reading Excel
A new C++ Excel extension for PHP, though you'll need to build it yourself, and the docs are pretty sparse when it comes to trying to find out what functionality (I can't even find out from the site what formats it supports, or whether it reads or writes or both.... I'm guessing both) it offers is phpexcellib from SIMITGROUP.
All claim to be faster than PHPExcel from codeplex or from github, but (with the exception of COM, PUNO Ilia's wrapper around libXl and spout) they don't offer both reading and writing, or both xls and xlsx; may no longer be supported; and (while I haven't tested Ilia's extension) only COM and PUNO offers the same degree of control over the created workbook.
You don't need to convert the original entry - you can use TEXT function in the concatenation formula, e.g. with date in A1 use a formula like this
="Today is "&TEXT(A1,"dd-mm-yyyy")
You can change the "dd-mm-yyyy" part as required
This also works:
...
WHERE
(FirstName IS NULL OR FirstName = ISNULL(@FirstName, FirstName)) AND
(LastName IS NULL OR LastName = ISNULL(@LastName, LastName)) AND
(Title IS NULL OR Title = ISNULL(@Title, Title))
Generally you don't want to value only the source
version (javac -source 1.8
for example) but you want to value both the source
and the target
version (javac -source 1.8 -target 1.8
for example).
Note that from Java 9, you have a way to convey both information and in a more robust way for cross-compilation compatibility (javac -release 9
).
Maven that wraps the javac
command provides multiple ways to convey all these JVM standard options.
Using maven-compiler-plugin
or maven.compiler.source
/maven.compiler.target
properties to specify the source
and the target
are equivalent.
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
and
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
are equivalent according to the Maven documentation of the compiler plugin
since the <source>
and the <target>
elements in the compiler configuration use the properties maven.compiler.source
and maven.compiler.target
if they are defined.
The
-source
argument for the Java compiler.
Default value is:1.6
.
User property is:maven.compiler.source
.
The
-target
argument for the Java compiler.
Default value is:1.6
.
User property is:maven.compiler.target
.
About the default values for source
and target
, note that
since the 3.8.0
of the maven compiler, the default values have changed from 1.5
to 1.6
.
<release>
tag — new way to specify Java version in maven-compiler-plugin
3.6You can use the release
argument :
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<release>9</release>
</configuration>
</plugin>
You could also declare just the user property maven.compiler.release
:
<properties>
<maven.compiler.release>9</maven.compiler.release>
</properties>
But at this time the last one will not be enough as the maven-compiler-plugin
default version you use doesn't rely on a recent enough version.
The Maven release
argument conveys release
to the Java compiler to access the JVM standard option newly added to Java 9, JEP 247: Compile for Older Platform Versions.
Compiles against the public, supported and documented API for a specific VM version.
This way provides a standard way to specify the same version for the source
, the target
and the bootstrap
JVM options.
Note that specifying the bootstrap
is a good practice for cross compilations and it will not hurt if you don't make cross compilations either.
Neither maven.compiler.source
/maven.compiler.target
properties or using the maven-compiler-plugin
is better.
It changes nothing in the facts since finally the two ways rely on the same properties and the same mechanism : the maven core compiler plugin.
Well, if you don't need to specify other properties or behavior than Java versions in the compiler plugin, using this way makes more sense as this is more concise:
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
The release
argument (third point) is a way to strongly consider if you want to use the same version for the source
and the target
.
In order to create modular style sheets that are not dependent on the absolute location of a resource, authors may use relative URIs. Relative URIs (as defined in [RFC3986]) are resolved to full URIs using a base URI. RFC 3986, section 5, defines the normative algorithm for this process. For CSS style sheets, the base URI is that of the style sheet, not that of the source document.
For example, suppose the following rule:
body { background: url("yellow") }
is located in a style sheet designated by the URI:
http://www.example.org/style/basic.css
The background of the source document's BODY will be tiled with whatever image is described by the resource designated by the URI
http://www.example.org/style/yellow
User agents may vary in how they handle invalid URIs or URIs that designate unavailable or inapplicable resources.
Taken from the CSS 2.1 spec.
For me I received a 404 error on my websites NOT using IIS Express (using Local IIS) while running an application that WAS using IIS Express. If I would close the browser that was used to run IIS Express, then the 404 would go away. For me I had my IIS Express project calling into Local IIS services, so I converted the IIS Express project to use Local IIS and then everything worked. It seems that you can't run both a non-IIS Express and Local IIS website at the same time for some reason.
I am writing a php extension and also encounter this problem. When i call an extern function with complicated parameters from my extension, this error pop up.
The reason is my not allocating memory for a parameter(char *) in the extern function. If you are writing same kind of extension, please pay attention to this.
I also got same error, compiling with -D flag fixed it, Try this:
g++ -Dstd=c++11
The DataView object itself is used to loop through DataView rows.
DataView rows are represented by the DataRowView object. The DataRowView.Row property provides access to the original DataTable row.
C#
foreach (DataRowView rowView in dataView)
{
DataRow row = rowView.Row;
// Do something //
}
VB.NET
For Each rowView As DataRowView in dataView
Dim row As DataRow = rowView.Row
' Do something '
Next
To get the smallest or largest item in a list, use the built-in min and max functions:
lo = min(L)
hi = max(L)
As with sort, you can pass in a "key" argument that is used to map the list items before they are compared:
lo = min(L, key=int)
hi = max(L, key=int)
http://effbot.org/zone/python-list.htm
Looks like you could use the max function if you map it correctly for strings and use that as the comparison. I would recommend just finding the max once though of course, not for each element in the list.
It should be noted that an ajax file upload exceeding the client_max_body_size
directive for nginx will return this error code.
Please refer following tutorial
i hope it will helpful for you but prior you have to read documentation of NSError
This is very interesting link i found recently ErrorHandling
Assuming you already have node.js installed, you can use browser sync for synchronized browser testing.
The following line is looking for the exact NavigableString 'Python':
>>> soup.body.findAll(text='Python')
[]
Note that the following NavigableString is found:
>>> soup.body.findAll(text='Python Jobs')
[u'Python Jobs']
Note this behaviour:
>>> import re
>>> soup.body.findAll(text=re.compile('^Python$'))
[]
So your regexp is looking for an occurrence of 'Python' not the exact match to the NavigableString 'Python'.
The only way I was able to get C# Express 2008 to work was to move the database file. So, I opened up SQL Server Management Studio and after dropping the database, I copied the file to my project folder. Then I reattached the database to management studio. Now, when I try to attach to the local copy it works. Apparently, you can not use the same database file more than once.
I am a beginner and this helped me:
class List
{
private Element Root;
}
First you create the class List which will contain all the methods. Then you create the Node-Class, I will call it Element
class Element
{
public int Value;
public Element Next;
}
Then you can start adding methods to your List class. Here is a 'add' method for example.
public void Add(int value)
{
Element newElement = new Element();
newElement.Value = value;
Element rootCopy = Root;
Root = newElement;
newElement.Next = rootCopy;
Console.WriteLine(newElement.Value);
}
In Go, there is a general rule that syntax should not hide complex/costly operations. Converting a string
to an interface{}
is done in O(1) time. Converting a []string
to an interface{}
is also done in O(1) time since a slice is still one value. However, converting a []string
to an []interface{}
is O(n) time because each element of the slice must be converted to an interface{}
.
The one exception to this rule is converting strings. When converting a string
to and from a []byte
or a []rune
, Go does O(n) work even though conversions are "syntax".
There is no standard library function that will do this conversion for you. You could make one with reflect, but it would be slower than the three line option.
Example with reflection:
func InterfaceSlice(slice interface{}) []interface{} {
s := reflect.ValueOf(slice)
if s.Kind() != reflect.Slice {
panic("InterfaceSlice() given a non-slice type")
}
// Keep the distinction between nil and empty slice input
if s.IsNil() {
return nil
}
ret := make([]interface{}, s.Len())
for i:=0; i<s.Len(); i++ {
ret[i] = s.Index(i).Interface()
}
return ret
}
Your best option though is just to use the lines of code you gave in your question:
b := make([]interface{}, len(a))
for i := range a {
b[i] = a[i]
}
Your code
enum Test
{
A, B
}
int a = 1;
Solution
Test castEnum = static_cast<Test>(a);
The last question has an easy answer:
> .Machine$sizeof.pointer
[1] 8
Meaning I am running R64. If I were running 32 bit R it would return 4. Just because you are running a 64 bit OS does not mean you will be running 64 bit R, and from the error message it appears you are not.
EDIT: If the package has binaries, then they are in separate directories. The specifics will depend on the OS. Notice that your LoadLibrary error occurred when it attempted to find the dll in ...rJava/libs/x64/...
On my MacOS system the ...rJava/libs/...` folder has 3 subdirectories: i386, ppc, and x86_64. (The ppc files are obviously useless baggage.)
The event
attribute of <f:ajax>
can hold at least all supported DOM events of the HTML element which is been generated by the JSF component in question. An easy way to find them all out is to check all on*
attribues of the JSF input component of interest in the JSF tag library documentation and then remove the "on" prefix. For example, the <h:inputText>
component which renders <input type="text">
lists the following on*
attributes (of which I've already removed the "on" prefix so that it ultimately becomes the DOM event type name):
blur
change
click
dblclick
focus
keydown
keypress
keyup
mousedown
mousemove
mouseout
mouseover
mouseup
select
Additionally, JSF has two more special event names for EditableValueHolder
and ActionSource
components, the real HTML DOM event being rendered depends on the component type:
valueChange
(will render as change
on text/select inputs and as click
on radio/checkbox inputs)action
(will render as click
on command links/buttons)The above two are the default events for the components in question.
Some JSF component libraries have additional customized event names which are generally more specialized kinds of valueChange
or action
events, such as PrimeFaces <p:ajax>
which supports among others tabChange
, itemSelect
, itemUnselect
, dateSelect
, page
, sort
, filter
, close
, etc depending on the parent <p:xxx>
component. You can find them all in the "Ajax Behavior Events" subsection of each component's chapter in PrimeFaces Users Guide.
There are two possible problems:
AJAX is asynchronous, so json
will be undefined when you return from the outer function. When the file has been loaded, the callback function will set json
to some value but at that time, nobody cares anymore.
I see that you tried to fix this with 'async': false
. To check whether this works, add this line to the code and check your browser's console:
console.log(['json', json]);
The path might be wrong. Use the same path that you used to load your script in the HTML document. So if your script is js/script.js
, use js/content.json
Some browsers can show you which URLs they tried to access and how that went (success/error codes, HTML headers, etc). Check your browser's development tools to see what happens.
Here's a solution that works for environments that don't have the string library (Linux kernel, embedded systems, etc):
#define FILENAME ({ \
const char* filename_start = __FILE__; \
const char* filename = filename_start; \
while(*filename != '\0') \
filename++; \
while((filename != filename_start) && (*(filename - 1) != '/')) \
filename--; \
filename; })
Now just use FILENAME
instead of __FILENAME__
. Yes, it's still a runtime thing but it works.
One nice feature of the Immediate Window in Visual Studio is its ability to evaluate the return value of a method particularly if it is called by your client code but it is not part of a variable assignment. In Debug mode, as mentioned, you can interact with variables and execute expressions in memory which plays an important role in being able to do this.
For example, if you had a static method that returns the sum of two numbers such as:
private static int GetSum(int a, int b)
{
return a + b;
}
Then in the Immediate Window you can type the following:
? GetSum(2, 4)
6
As you can seen, this works really well for static methods. However, if the method is non-static then you need to interact with a reference to the object the method belongs to.
For example, let’s say this is what your class looks like:
private class Foo
{
public string GetMessage()
{
return "hello";
}
}
If the object already exists in memory and it’s in scope, then you can call it in the Immediate Window as long as it has been instantiated before your current breakpoint (or, at least, before wherever the code is paused in debug mode):
? foo.GetMessage(); // object ‘foo’ already exists
"hello"
In addition, if you want to interact and test the method directly without relying on an existing instance in memory, then you can instantiate your own instance in the Immediate Window:
? Foo foo = new Foo(); // new instance of ‘Foo’
{temp.Program.Foo}
? foo.GetMessage()
"hello"
You can take it a step further and temporarily assign the method's results to variables if you want to do further evaluations, calculations, etc.:
? string msg = foo.GetMessage();
"hello"
? msg + " there!"
"hello there!"
Furthermore, if you don’t even want to declare a variable name for a new object and just want to run one of its methods/functions then do this:
? new Foo().GetMessage()
"hello"
A very common way to see the value of a method is to select the method name of a class and do a ‘Add Watch’ so that you can see its current value in the Watch window. However, once again, the object needs to be instantiated and in scope for a valid value to be displayed. This is much less powerful and more restrictive than using the Immediate Window.
Along with inspecting methods, you can do simple math equations:
? 5 * 6
30
or compare values:
? 5==6
false
? 6==6
true
The question mark ('?') is unnecessary if you are in directly in the Immediate Window but it is included here for clarity (to distinguish between the typed in expressions versus the results.) However, if you are in the Command Window and need to do some quick stuff in the Immediate Window then precede your statements with '?' and off you go.
Intellisense works in the Immediate Window, but it sometimes can be a bit inconsistent. In my experience, it seems to be only available in Debug mode, but not in design, non-debug mode.
Unfortunately, another drawback of the Immediate Window is that it does not support loops.
If you want to rotate a vector you should construct what is known as a rotation matrix.
Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are
x' = x cos ? - y sin ?
y' = x sin ? + y cos ?
To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider
Unit vector along X axis = <1, 0>
x' = 1 cos 90 - 0 sin 90 = 0
y' = 1 sin 90 + 0 cos 90 = 1
New coordinates of the vector, <x', y'> = <0, 1> ? Y-axis
When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is
|cos ? -sin ?| |x| = |x cos ? - y sin ?| = |x'|
|sin ? cos ?| |y| |x sin ? + y cos ?| |y'|
That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be
|cos ? -sin ? 0| |x| |x cos ? - y sin ?| |x'|
|sin ? cos ? 0| |y| = |x sin ? + y cos ?| = |y'|
| 0 0 1| |z| | z | |z'|
around the Y-axis would be
| cos ? 0 sin ?| |x| | x cos ? + z sin ?| |x'|
| 0 1 0| |y| = | y | = |y'|
|-sin ? 0 cos ?| |z| |-x sin ? + z cos ?| |z'|
around the X-axis would be
|1 0 0| |x| | x | |x'|
|0 cos ? -sin ?| |y| = |y cos ? - z sin ?| = |y'|
|0 sin ? cos ?| |z| |y sin ? + z cos ?| |z'|
Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.
Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.
I hope this clarifies basic rotation.
The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.
I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).
A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.
Find log enabled or not?
SHOW VARIABLES LIKE '%log%';
Set the logs:-
SET GLOBAL general_log = 'ON';
SET GLOBAL slow_query_log = 'ON';
I have recently written a tool for showing console logs in a movable/resizable "window" (actually a div). It provides similar functionality to Firebug's console but you can see it over your page on a tablet. Tablet/Smartphone/Phablet Debug Console
before you run in cmd prompt, make sure "appsettings.json" has same values as "appsettings.Development.json".
In command prompt, go all the way to bin/debug/netcoreapp2.0 folder. then run "dotnet applicationname.dll"
Why not just use atoi? For example:
char myarray[4] = {'-','1','2','3'};
int i = atoi(myarray);
printf("%d\n", i);
Gives me, as expected:
-123
Update: why not - the character array is not null terminated. Doh!
You can do this more simply using plot()
instead of plot_date()
.
First, convert your strings to instances of Python datetime.date
:
import datetime as dt
dates = ['01/02/1991','01/03/1991','01/04/1991']
x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates]
y = range(len(x)) # many thanks to Kyss Tao for setting me straight here
Then plot:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.plot(x,y)
plt.gcf().autofmt_xdate()
Result:
You can iterate over the row data
$('#button').click(function () {
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0]
});
console.log(ids)
alert(table.rows('.selected').data().length + ' row(s) selected');
});
Demo: Fiddle
Ansible has a version_compare
filter since 1.6.
You can do something like below in when
conditional:
when: ansible_distribution_version | version_compare('12.04', '>=')
This will give you support for major & minor versions comparisons and you can compare versions using operators like:
<, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne
You can find more information about this here: Ansible - Version comparison filters
Otherwise if you have really simple case you can use what @ProfHase85 suggested
The comment by @s29 should be an answer:
One way to add a directory to the virtual environment is to install virtualenvwrapper (which is useful for many things) and then do
mkvirtualenv myenv
workon myenv
add2virtualenv . #for current directory
add2virtualenv ~/my/path
If you want to remove these path edit the file myenvhomedir/lib/python2.7/site-packages/_virtualenv_path_extensions.pth
Documentation on virtualenvwrapper can be found at http://virtualenvwrapper.readthedocs.org/en/latest/
Specific documentation on this feature can be found at http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html?highlight=add2virtualenv
The problem is the way you're using forEach()
, as it will always return undefined
. You're probably looking for the map()
method, which returns a new array:
var tifOptions = Object.keys(tifs).map(function(key) {
return <option value={key}>{tifs[key]}</option>
});
If you still want to use forEach()
, you'd have to do something like this:
var tifOptions = [];
Object.keys(tifs).forEach(function(key) {
tifOptions.push(<option value={key}>{tifs[key]}</option>);
});
Update:
If you're writing ES6, you can accomplish the same thing a bit neater using an arrow function:
const tifOptions = Object.keys(tifs).map(key =>
<option value={key}>{tifs[key]}</option>
)
Here's a fiddle showing all options mentioned above: https://jsfiddle.net/fs7sagep/
The whole git resetting business looked far to complicating for me.
So I did something along the lines to get my src folder in the state i had a few commits ago
# reset the local state
git reset <somecommit> --hard
# copy the relevant part e.g. src (exclude is only needed if you specify .)
tar cvfz /tmp/current.tgz --exclude .git src
# get the current state of git
git pull
# remove what you don't like anymore
rm -rf src
# restore from the tar file
tar xvfz /tmp/current.tgz
# commit everything back to git
git commit -a
# now you can properly push
git push
This way the state of affairs in the src is kept in a tar file and git is forced to accept this state without too much fiddling basically the src directory is replaced with the state it had several commits ago.
From this reference:
An int was originally intended to be the "natural" word size of the processor. Many modern processors can handle different word sizes with equal ease.
Also, this bit:
On many (but not all) C and C++ implementations, a long is larger than an int. Today's most popular desktop platforms, such as Windows and Linux, run primarily on 32 bit processors and most compilers for these platforms use a 32 bit int which has the same size and representation as a long.
No need for Xargs and all , ls is more than enough.
ls -1 *.txt
displays row wise
Why not something like this?
It uses a combination of lists, iteration, and interpolation.
@mixin placeholder ($rules) {
@each $rule in $rules {
::-webkit-input-placeholder,
:-moz-placeholder,
::-moz-placeholder,
:-ms-input-placeholder {
#{nth($rule, 1)}: #{nth($rule, 2)};
}
}
}
$rules: (('border', '1px solid red'),
('color', 'green'));
@include placeholder( $rules );
In PostgreSQL 9.5 and newer you can use INSERT ... ON CONFLICT UPDATE
.
See the documentation.
A MySQL INSERT ... ON DUPLICATE KEY UPDATE
can be directly rephrased to a ON CONFLICT UPDATE
. Neither is SQL-standard syntax, they're both database-specific extensions. There are good reasons MERGE
wasn't used for this, a new syntax wasn't created just for fun. (MySQL's syntax also has issues that mean it wasn't adopted directly).
e.g. given setup:
CREATE TABLE tablename (a integer primary key, b integer, c integer);
INSERT INTO tablename (a, b, c) values (1, 2, 3);
the MySQL query:
INSERT INTO tablename (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
becomes:
INSERT INTO tablename (a, b, c) values (1, 2, 10)
ON CONFLICT (a) DO UPDATE SET c = tablename.c + 1;
Differences:
You must specify the column name (or unique constraint name) to use for the uniqueness check. That's the ON CONFLICT (columnname) DO
The keyword SET
must be used, as if this was a normal UPDATE
statement
It has some nice features too:
You can have a WHERE
clause on your UPDATE
(letting you effectively turn ON CONFLICT UPDATE
into ON CONFLICT IGNORE
for certain values)
The proposed-for-insertion values are available as the row-variable EXCLUDED
, which has the same structure as the target table. You can get the original values in the table by using the table name. So in this case EXCLUDED.c
will be 10
(because that's what we tried to insert) and "table".c
will be 3
because that's the current value in the table. You can use either or both in the SET
expressions and WHERE
clause.
For background on upsert see How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?
in this example we run 2 line insert into query and if all of them true it run but if not no run anything and ROLLBACK
DECLARE @rowcount int set @rowcount = 0 ;
BEGIN TRANSACTION [Tran1]
BEGIN TRY
insert into [database].[dbo].[tbl1] (fld1) values('1') ;
set @rowcount = (@rowcount + @@ROWCOUNT);
insert into [database].[dbo].[tbl2] (fld1) values('2') ;
set @rowcount = (@rowcount + @@ROWCOUNT);
IF @rowcount = 2
COMMIT TRANSACTION[Tran1]
ELSE
ROLLBACK TRANSACTION[Tran1]
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION[Tran1]
END CATCH
First of all, MEAN is an acronym for MongoDB, Express, Angular and Node.js.
It generically identifies the combined used of these technologies in a "stack". There is no such a thing as "The MEAN framework".
Lior Kesos at Linnovate took advantage of this confusion. He bought the domain MEAN.io and put some code at https://github.com/linnovate/mean
They luckily received a lot of publicity, and theree are more and more articles and video about MEAN. When you Google "mean framework", mean.io is the first in the list.
Unfortunately the code at https://github.com/linnovate/mean seems poorly engineered.
In February I fell in the trap myself. The site mean.io had a catchy design and the Github repo had 1000+ stars. The idea of questioning the quality did not even pass through my mind. I started experimenting with it but it did not take too long to stumble upon things that were not working, and puzzling pieces of code.
The commit history was also pretty concerning. They re-engineered the code and directory structure multiple times, and merging the new changes is too time consuming.
The nice things about both mean.io and mean.js code is that they come with Bootstrap integration. They also come with Facebook, Github, Linkedin etc authentication through PassportJs and an example of a model (Article) on the backend on MongoDB that sync with the frontend model with AngularJS.
According to Linnovate's website:
Linnovate is the leading Open Source company in Israel, with the most experienced team in the country, dedicated to the creation of high-end open source solutions. Linnovate is the only company in Israel which gives an A-Z services for enterprises for building and maintaining their next web project.
From the website it looks like that their core skill set is Drupal (a PHP content management system) and only lately they started using Node.js and AngularJS.
Lately I was reading the Mean.js Blog and things became clearer. My understanding is that the main Javascript developer (Amos Haviv) left Linnovate to work on Mean.js leaving MEAN.io project with people that are novice Node.js developers that are slowing understanding how things are supposed to work.
In the future things may change but for now I would avoid to use mean.io. If you are looking for a boilerplate for a quickstart Mean.js seems a better option than mean.io.
In order to do this without FuncAnimation (eg you want to execute other parts of the code while the plot is being produced or you want to be updating several plots at the same time), calling draw
alone does not produce the plot (at least with the qt backend).
The following works for me:
import matplotlib.pyplot as plt
plt.ion()
class DynamicUpdate():
#Suppose we know the x range
min_x = 0
max_x = 10
def on_launch(self):
#Set up plot
self.figure, self.ax = plt.subplots()
self.lines, = self.ax.plot([],[], 'o')
#Autoscale on unknown axis and known lims on the other
self.ax.set_autoscaley_on(True)
self.ax.set_xlim(self.min_x, self.max_x)
#Other stuff
self.ax.grid()
...
def on_running(self, xdata, ydata):
#Update data (with the new _and_ the old points)
self.lines.set_xdata(xdata)
self.lines.set_ydata(ydata)
#Need both of these in order to rescale
self.ax.relim()
self.ax.autoscale_view()
#We need to draw *and* flush
self.figure.canvas.draw()
self.figure.canvas.flush_events()
#Example
def __call__(self):
import numpy as np
import time
self.on_launch()
xdata = []
ydata = []
for x in np.arange(0,10,0.5):
xdata.append(x)
ydata.append(np.exp(-x**2)+10*np.exp(-(x-7)**2))
self.on_running(xdata, ydata)
time.sleep(1)
return xdata, ydata
d = DynamicUpdate()
d()
I also got the same error using the code:
MailMessage mail = new MailMessage();
mail.To.Add(txtEmail.Text.Trim());
mail.To.Add("[email protected]");
mail.From = new MailAddress("[email protected]");
mail.Subject = "Confirmation of Registration on Job Junction.";
string Body = "Hi, this mail is to test sending mail using Gmail in ASP.NET";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
// smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
// smtp.Port = 587;
//Or your Smtp Email ID and Password
smtp.UseDefaultCredentials = false;
// smtp.EnableSsl = true;
smtp.Send(mail);
But moving 2 lines upward fixed the problem:
MailMessage mail = new MailMessage();
mail.To.Add(txtEmail.Text.Trim());
mail.To.Add("[email protected]");
mail.From = new MailAddress("[email protected]");
mail.Subject = "Confirmation of Registration on Job Junction.";
string Body = "Hi, this mail is to test sending mail using Gmail in ASP.NET";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
// smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
// smtp.Port = 587;
//Or your Smtp Email ID and Password
smtp.Send(mail);
unsigned char c;
for( int i = 7; i >= 0; i-- ) {
printf( "%d", ( c >> i ) & 1 ? 1 : 0 );
}
printf("\n");
Explanation:
With every iteration, the most significant bit is being read from the byte by shifting it and binary comparing with 1.
For example, let's assume that input value is 128, what binary translates to 1000 0000. Shifting it by 7 will give 0000 0001, so it concludes that the most significant bit was 1. 0000 0001 & 1 = 1. That's the first bit to print in the console. Next iterations will result in 0 ... 0.
I think you conclusions are correct but not accurate.
As the docs indicates, socket.recv
is majorly focused on the network buffers.
When socket is blocking, socket.recv
will return as long as the network buffers have bytes. If bytes in the network buffers are more than socket.recv
can handle, it will return the maximum number of bytes it can handle. If bytes in the network buffers are less than socket.recv
can handle, it will return all the bytes in the network buffers.
Similar to Chris Marasti-Georg's example, instead using inline javascript. Essentially add onkeypress to the fields you want the enter key to work with. This example acts on the password field.
<html>
<head><title>title</title></head>
<body>
<form action="" method="get">
Name: <input type="text" name="name"/><br/>
Pwd: <input type="password" name="password" onkeypress="if(event.keyCode==13) {javascript:form.submit();}" /><br/>
<input type="submit" onClick="javascript:form.submit();"/>
</form>
</body>
</html>
You cannot install a release ipa directly on your device. Ipa generated withAppStore Distribution Profile requires to be distributed from App Store or TestFlight. However, I found that app panel was removed even for installing ad hoc ipa from iTunes 12.7. I found a workaround to install ad-hoc apps which might help to them who cannot install even ad hoc ipa. Please follow the instructions below,
You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:
@(deletedView ? "Deleted" : "Created by")
Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.
git config --global core.autocrlf false
works well for global settings.
But if you are using Visual Studio, might also need to modify .gitattributes
for some type of projects (e.g c# class library application):
* text=auto
Try this
function sendRequest(method, url, payload, done){
var datatype = (method === "JSONP")? "jsonp" : "json";
$http({
method: method,
url: url,
dataType: datatype,
data: payload || {},
cache: true,
timeout: 1000 * 60 * 10
}).then(
function(res){
done(null, res.data); // server response
},
function(res){
responseHandler(res, done);
}
);
}
function responseHandler(res, done){
switch(res.status){
default: done(res.status + ": " + res.statusText);
}
}
In extremely non-technical terms, it may mean that you forgot to put "ejb:" or "jdbc:" or something at the very beginning of the URI you are trying to connect.
"Using the dollar sign is not very common in JavaScript, but professional programmers often use it as an alias for the main function in a JavaScript library.
In the JavaScript library jQuery, for instance, the main function
$
is used to select HTML elements. In jQuery$("p");
means "select all p elements". "
edgesForExtendedLayout
does the trick for iOS 7. However, if you build the app across iOS 7 SDK and deploy it in iOS 6, the navigation bar appears translucent and the views go beneath it. So, to fix it for both iOS 7 as well as for iOS 6 do this:
self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
self.edgesForExtendedLayout = UIRectEdgeNone; // iOS 7 specific
You can use GROUP_CONCAT
:
SELECT person_id,
GROUP_CONCAT(hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
As Ludwig stated in his comment, you can add the DISTINCT
operator to avoid duplicates:
SELECT person_id,
GROUP_CONCAT(DISTINCT hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
As Jan stated in their comment, you can also sort the values before imploding it using ORDER BY
:
SELECT person_id,
GROUP_CONCAT(hobbies ORDER BY hobbies ASC SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
As Dag stated in his comment, there is a 1024 byte limit on the result. To solve this, run this query before your query:
SET group_concat_max_len = 2048;
Of course, you can change 2048
according to your needs. To calculate and assign the value:
SET group_concat_max_len = CAST(
(SELECT SUM(LENGTH(hobbies)) + COUNT(*) * LENGTH(', ')
FROM peoples_hobbies
GROUP BY person_id) AS UNSIGNED);
Your result will vary depending on what kind of terminal or console program you're on, but yes, on most \b
is a nondestructive backspace. It moves the cursor backward, but doesn't erase what's there.
So for the hello worl
part, the code outputs
hello worl ^
...(where ^
shows where the cursor is) Then it outputs two \b
characters which moves the cursor backward two places without erasing (on your terminal):
hello worl ^
Note the cursor is now on the r
. Then it outputs d
, which overwrites the r
and gives us:
hello wodl ^
Finally, it outputs \n
, which is a non-destructive newline (again, on most terminals, including apparently yours), so the l
is left unchanged and the cursor is moved to the beginning of the next line.
Although this is old post... i had similar situation that gave me headache. Finally, i figured that i was including sub pages in index.php with "@include ..." "@" hides all errors even if display_errors is ON
Type this in cell B1, and copy down...
="X"&A1
This would also work:
=CONCATENATE("X",A1)
And here's one of many ways to do this in VBA (Disclaimer: I don't code in VBA very often!):
Sub AddX()
Dim i As Long
With ActiveSheet
For i = 1 To .Range("A65536").End(xlUp).Row Step 1
.Cells(i, 2).Value = "X" & Trim(Str(.Cells(i, 1).Value))
Next i
End With
End Sub
I use a hidden textbox to edit all the listview items/subitems. The only problem is that the textbox needs to disappear as soon as any event takes place outside the textbox and the listview doesn't trigger the scroll event so if you scroll the listview the textbox will still be visible. To bypass this problem I created the Scroll event with this overrided listview.
Here is my code, I constantly reuse it so it might be help for someone:
ListViewItem.ListViewSubItem SelectedLSI;
private void listView2_MouseUp(object sender, MouseEventArgs e)
{
ListViewHitTestInfo i = listView2.HitTest(e.X, e.Y);
SelectedLSI = i.SubItem;
if (SelectedLSI == null)
return;
int border = 0;
switch (listView2.BorderStyle)
{
case BorderStyle.FixedSingle:
border = 1;
break;
case BorderStyle.Fixed3D:
border = 2;
break;
}
int CellWidth = SelectedLSI.Bounds.Width;
int CellHeight = SelectedLSI.Bounds.Height;
int CellLeft = border + listView2.Left + i.SubItem.Bounds.Left;
int CellTop =listView2.Top + i.SubItem.Bounds.Top;
// First Column
if (i.SubItem == i.Item.SubItems[0])
CellWidth = listView2.Columns[0].Width;
TxtEdit.Location = new Point(CellLeft, CellTop);
TxtEdit.Size = new Size(CellWidth, CellHeight);
TxtEdit.Visible = true;
TxtEdit.BringToFront();
TxtEdit.Text = i.SubItem.Text;
TxtEdit.Select();
TxtEdit.SelectAll();
}
private void listView2_MouseDown(object sender, MouseEventArgs e)
{
HideTextEditor();
}
private void listView2_Scroll(object sender, EventArgs e)
{
HideTextEditor();
}
private void TxtEdit_Leave(object sender, EventArgs e)
{
HideTextEditor();
}
private void TxtEdit_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
HideTextEditor();
}
private void HideTextEditor()
{
TxtEdit.Visible = false;
if (SelectedLSI != null)
SelectedLSI.Text = TxtEdit.Text;
SelectedLSI = null;
TxtEdit.Text = "";
}
To send to both remote with one command, you can create a alias for it:
git config alias.pushall '!git push origin devel && git push github devel'
With this, when you use the command git pushall
, it will update both repositories.
The answers so far describe why, but here is a something else you might want to consider:
You can can call a method from an instantiable class by appending a method call to its constructor,
Object instance = new Constuctor().methodCall();
or
primitive name = new Constuctor().methodCall();
This is useful it you only wish to use a method of an instantiable class once within a single scope. If you are calling multiple methods from an instantiable class within a single scope, definitely create a referable instance.
Get private variable's value using Reflection:
var _barVariable = typeof(Foo).GetField("_bar", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectForFooClass);
Set value for private variable using Reflection:
typeof(Foo).GetField("_bar", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectForFoocClass, "newValue");
Where objectForFooClass is a non null instance for the class type Foo.
You can use the pskill
function in the R
"tools" package to interrupt the current process and return to the console. Concretely, I have the following function defined in a startup file that I source at the beginning of each script. You can also copy it directly at the start of your code, however. Then insert halt()
at any point in your code to stop script execution on the fly. This function works well on GNU/Linux and judging from the R
documentation, it should also work on Windows (but I didn't check).
# halt: interrupts the current R process; a short iddle time prevents R from
# outputting further results before the SIGINT (= Ctrl-C) signal is received
halt <- function(hint = "Process stopped.\n") {
writeLines(hint)
require(tools, quietly = TRUE)
processId <- Sys.getpid()
pskill(processId, SIGINT)
iddleTime <- 1.00
Sys.sleep(iddleTime)
}
Here's the one-liner solution:
#include <iostream>
#include <string>
int main() {
std::string s = std::string("Hi") + " there" + " friends";
std::cout << s << std::endl;
std::string r = std::string("Magic number: ") + std::to_string(13) + "!";
std::cout << r << std::endl;
return 0;
}
Although it's a tiny bit ugly, I think it's about as clean as you cat get in C++.
We are casting the first argument to a std::string
and then using the (left to right) evaluation order of operator+
to ensure that its left operand is always a std::string
. In this manner, we concatenate the std::string
on the left with the const char *
operand on the right and return another std::string
, cascading the effect.
Note: there are a few options for the right operand, including const char *
, std::string
, and char
.
It's up to you to decide whether the magic number is 13 or 6227020800.
if someone is running Eclipse in Ubuntu and have this problem I have found the answer by following these steps:
JOptionPane.showMessageDialog(btn1, "you are clicked save button","title of dialog",2);
btn1 is a JButton variable and its used in this dialog to dialog open position btn1 or textfield etc, by default use null position of the frame.next your message and next is the title of dialog. 2 numbers of alert type icon 3 is the information 1,2,3,4. Ok I hope you understand it
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
Here $users
is a PDOStatement
object over which you can iterate. The first iteration outputs all results, the second does nothing since you can only iterate over the result once. That's because the data is being streamed from the database and iterating over the result with foreach
is essentially shorthand for:
while ($row = $users->fetch()) ...
Once you've completed that loop, you need to reset the cursor on the database side before you can loop over it again.
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
$result = $users->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
echo $key . "-" . $value . "<br/>";
}
Here all results are being output by the first loop. The call to fetch
will return false
, since you have already exhausted the result set (see above), so you get an error trying to loop over false
.
In the last example you are simply fetching the first result row and are looping over it.
http://nodeca.github.io/pica/demo/
In modern browser you can use canvas to load/save image data. But you should keep in mind several things if you resize image on the client:
Try using the following code snippet. This should solve your issue.
body, html {
overflow-x: hidden;
overflow-y: auto;
}
You can use the NotMapped
attribute data annotation to instruct Code-First to exclude a particular property
public class Customer
{
public int CustomerID { set; get; }
public string FirstName { set; get; }
public string LastName{ set; get; }
[NotMapped]
public int Age { set; get; }
}
[NotMapped]
attribute is included in the System.ComponentModel.DataAnnotations
namespace.
You can alternatively do this with Fluent API
overriding OnModelCreating
function in your DBContext
class:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Ignore(t => t.LastName);
base.OnModelCreating(modelBuilder);
}
http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx
The version I checked is EF 4.3
, which is the latest stable version available when you use NuGet.
Edit : SEP 2017
Data annotation
If you are using asp.net core (2.0 at the time of this writing), The [NotMapped]
attribute can be used on the property level.
public class Customer
{
public int Id { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
[NotMapped]
public int FullName { set; get; }
}
Fluent API
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
base.OnModelCreating(modelBuilder);
}
public DbSet<Customer> Customers { get; set; }
}