As a generic answer, not specifically directed at this task: In many cases, you can significantly speed up any program by making improvements at a high level. Like calculating data once instead of multiple times, avoiding unnecessary work completely, using caches in the best way, and so on. These things are much easier to do in a high level language.
Writing assembler code, it is possible to improve on what an optimising compiler does, but it is hard work. And once it's done, your code is much harder to modify, so it is much more difficult to add algorithmic improvements. Sometimes the processor has functionality that you cannot use from a high level language, inline assembly is often useful in these cases and still lets you use a high level language.
In the Euler problems, most of the time you succeed by building something, finding why it is slow, building something better, finding why it is slow, and so on and so on. That is very, very hard using assembler. A better algorithm at half the possible speed will usually beat a worse algorithm at full speed, and getting the full speed in assembler isn't trivial.
New Updates for iOS Device Support file. Don't need to update Xcode.
You just need to add support file to Xcode's DeviceSupport folder.
iOS 12.3.1 Developer Disk Image
Extract the zip and then copy folder.
Paste this folder in this path
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport
Quit the Xcode and restart, it will work.
CSS:
.headercss {
width: 100%;
height: 320px;
background-color: #000000;
position: fixed;
}
Attribute position: fixed
will keep it stuck, while other content will be scrollable. Don't forget to set width:100%
to make it fill fully to the right.
Here's a fixed version of it: http://play.golang.org/p/w2ZcOzGHKR
The biggest fix that was needed is when Unmarshalling an array, that property needs to be an array/slice in the struct as well.
For example:
{ "things": ["a", "b", "c"] }
Would Unmarshal into a:
type Item struct {
Things []string
}
And not into:
type Item struct {
Things string
}
The other thing to watch out for when Unmarshaling is that the types line up exactly. It will fail when Unmarshalling a JSON string representation of a number into an int
or float
field -- "1"
needs to Unmarshal into a string
, not into an int
like we saw with ShippingAdditionalCost int
A good answer for me was to install libtool:
sudo apt-get install libtool
CSS
select{
color:red;
}
HTML
<select id="sel" onclick="document.getElementById('sel').style.color='green';">
<option>Select Your Option</option>
<option value="">INDIA</option>
<option value="">USA</option>
</select>
The above code will change the colour of text on click of the select box.
and if you want every option different colour, give separate class or id to all options.
Before answering, I would like to give you some data from Wiki
Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding.
When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.
To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.
gcc provides functionality to disable structure padding. i.e to avoid these meaningless bytes in some cases. Consider the following structure:
typedef struct
{
char Data1;
int Data2;
unsigned short Data3;
char Data4;
}sSampleStruct;
sizeof(sSampleStruct)
will be 12 rather than 8. Because of structure padding. By default, In X86, structures will be padded to 4-byte alignment:
typedef struct
{
char Data1;
//3-Bytes Added here.
int Data2;
unsigned short Data3;
char Data4;
//1-byte Added here.
}sSampleStruct;
We can use __attribute__((packed, aligned(X)))
to insist particular(X) sized padding. X should be powers of two. Refer here
typedef struct
{
char Data1;
int Data2;
unsigned short Data3;
char Data4;
}__attribute__((packed, aligned(1))) sSampleStruct;
so the above specified gcc attribute does not allow the structure padding. so the size will be 8 bytes.
If you wish to do the same for all the structures, simply we can push the alignment value to stack using #pragma
#pragma pack(push, 1)
//Structure 1
......
//Structure 2
......
#pragma pack(pop)
I guess a little more convenient and structured way is to use Html helper. In your view it can be look like:
@{
var htmlAttr = new Dictionary<string, object>();
htmlAttr.Add("id", strElementId);
if (!CSSClass.IsEmpty())
{
htmlAttr.Add("class", strCSSClass);
}
}
@* ... *@
@Html.TextBox("somename", "", htmlAttr)
If this way will be useful for you i recommend to define dictionary htmlAttr
in your model so your view doesn't need any @{ }
logic blocks (be more clear).
Adobe Illustrator uses bezier curves like SVG, and for circles it creates four points. You can create a circle with two elliptical arc commands...but then for a circle in SVG I would use a <circle />
:)
Minimal example
And just to make what Mizux said as a minimal example:
main_c.c
#include <stdio.h>
int main(void) {
puts("hello");
}
main_cpp.cpp
#include <iostream>
int main(void) {
std::cout << "hello" << std::endl;
}
Then, without any Makefile
:
make CFLAGS='-g -O3' \
CXXFLAGS='-ggdb3 -O0' \
CPPFLAGS='-DX=1 -DY=2' \
CCFLAGS='--asdf' \
main_c \
main_cpp
runs:
cc -g -O3 -DX=1 -DY=2 main_c.c -o main_c
g++ -ggdb3 -O0 -DX=1 -DY=2 main_cpp.cpp -o main_cpp
So we understand that:
make
had implicit rules to make main_c
and main_cpp
from main_c.c
and main_cpp.cpp
.c
compilation.cpp
compilationThose variables are only used in make's implicit rules automatically: if compilation had used our own explicit rules, then we would have to explicitly use those variables as in:
main_c: main_c.c
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ $<
main_cpp: main_c.c
$(CXX) $(CXXFLAGS) $(CPPFLAGS) -o $@ $<
to achieve a similar affect to the implicit rules.
We could also name those variables however we want: but since Make already treats them magically in the implicit rules, those make good name choices.
Tested in Ubuntu 16.04, GNU Make 4.1.
Replace:
Response.Write("<script language=javascript>alert('ERROR');</script>);
With
Response.Write("<script language=javascript>alert('ERROR');</script>");
In other words, you're missing a closing "
at the end of the Response.Write
statement.
It's worth mentioning that the code shown in the screenshot appears to correctly contain a closing double quote, however your best bet overall would be to use the ClientScriptManager.RegisterScriptBlock method:
var clientScript = Page.ClientScript;
clientScript.RegisterClientScriptBlock(this.GetType(), "AlertScript", "alert('ERROR')'", true);
This will take care of wrapping the script with <script>
tags and writing the script into the page for you.
import base64
coded_string = '''Q5YACgA...'''
base64.b64decode(coded_string)
worked for me. At the risk of pasting an offensively-long result, I got:
>>> base64.b64decode(coded_string)
2: 'C\x96\x00\n\x00\x00\x00\x00C\x96\x00\x1b\x00\x00\x00\x00C\x96\x00-\x00\x00\x00\x00C\x96\x00?\x00\x00\x00\x00C\x96\x07M\x00\x00\x00\x00C\x96\x07_\x00\x00\x00\x00C\x96\x07p\x00\x00\x00\x00C\x96\x07\x82\x00\x00\x00\x00C\x96\x07\x94\x00\x00\x00\x00C\x96\x07\xa6Cq\xf0\x7fC\x96\x07\xb8DJ\x81\xc7C\x96\x07\xcaD\xa5\x9dtC\x96\x07\xdcD\xb6\x97\x11C\x96\x07\xeeD\x8b\x8flC\x96\x07\xffD\x03\xd4\xaaC\x96\x08\x11B\x05&\xdcC\x96\x08#\x00\x00\x00\x00C\x96\x085C\x0c\xc9\xb7C\x96\x08GCy\xc0\xebC\x96\x08YC\x81\xa4xC\x96\x08kC\x0f@\x9bC\x96\x08}\x00\x00\x00\x00C\x96\x08\x8e\x00\x00\x00\x00C\x96\x08\xa0\x00\x00\x00\x00C\x96\x08\xb2\x00\x00\x00\x00C\x96\x86\xf9\x00\x00\x00\x00C\x96\x87\x0b\x00\x00\x00\x00C\x96\x87\x1d\x00\x00\x00\x00C\x96\x87/\x00\x00\x00\x00C\x96\x87AA\x0b\xe7PC\x96\x87SCI\xf5gC\x96\x87eC\xd4J\xeaC\x96\x87wD\r\x17EC\x96\x87\x89D\x00F6C\x96\x87\x9bC\x9cg\xdeC\x96\x87\xadB\xd56\x0cC\x96\x87\xbf\x00\x00\x00\x00C\x96\x87\xd1\x00\x00\x00\x00C\x96\x87\xe3\x00\x00\x00\x00C\x96\x87\xf5\x00\x00\x00\x00C\x9cY}\x00\x00\x00\x00C\x9cY\x90\x00\x00\x00\x00C\x9cY\xa4\x00\x00\x00\x00C\x9cY\xb7\x00\x00\x00\x00C\x9cY\xcbC\x1f\xbd\xa3C\x9cY\xdeCCz{C\x9cY\xf1CD\x02\xa7C\x9cZ\x05C+\x9d\x97C\x9cZ\x18C\x03R\xe3C\x9cZ,\x00\x00\x00\x00C\x9cZ?
[stuff omitted as it exceeded SO's body length limits]
\xbb\x00\x00\x00\x00D\xc5!7\x00\x00\x00\x00D\xc5!\xb2\x00\x00\x00\x00D\xc7\x14x\x00\x00\x00\x00D\xc7\x14\xf6\x00\x00\x00\x00D\xc7\x15t\x00\x00\x00\x00D\xc7\x15\xf2\x00\x00\x00\x00D\xc7\x16pC5\x9f\xf9D\xc7\x16\xeeC[\xb5\xf5D\xc7\x17lCG\x1b;D\xc7\x17\xeaB\xe3\x0b\xa6D\xc7\x18h\x00\x00\x00\x00D\xc7\x18\xe6\x00\x00\x00\x00D\xc7\x19d\x00\x00\x00\x00D\xc7\x19\xe2\x00\x00\x00\x00D\xc7\xfe\xb4\x00\x00\x00\x00D\xc7\xff3\x00\x00\x00\x00D\xc7\xff\xb2\x00\x00\x00\x00D\xc8\x001\x00\x00\x00\x00'
What problem are you having, specifically?
I couldn't draw a circle inside my ConstraintLayout for some reason, I just couldn't use any of the answers above.
What did work perfectly is a simple TextView with the text that comes out, when you press "Alt+7":
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#0075bc"
android:textSize="40dp"
android:text="•"></TextView>
Some readers will have another issue and need this fix. read the links below. the same problem occured with visual studio 2015 with the advent of windows sdk 10 which brings up libucrt. ucrt is the windows implementation of C Runtime (CRT) aka the posix runtime library. You most likely have code that was ported from unix... Welcome to the drawback
https://github.com/lordmulder/libsndfile-MSVC/blob/master/src/sf_unistd.h
https://lists.gnu.org/archive/html/bug-gnulib/2011-09/msg00224.html
https://msdn.microsoft.com/en-us/library/y23kc048.aspx
https://blogs.msdn.microsoft.com/vcblog/2015/03/03/introducing-the-universal-crt/
Quick function based on responses.
loadCSS = function(href) {
var cssLink = $("<link>");
$("head").append(cssLink); //IE hack: append before setting href
cssLink.attr({
rel: "stylesheet",
type: "text/css",
href: href
});
};
Usage:
loadCSS("/css/file.css");
./me casts raise_dead()
I was looking for something like this, but I also needed to reuse the same string minus two parameters so I ended up with something like:
my_exe ()
{
mysql -sN -e "select $1 from heat.stack where heat.stack.name=\"$2\";"
}
This is something I use to monitor openstack heat stack creation. In this case I expect two conditions, an action 'CREATE' and a status 'COMPLETE' on a stack named "Somestack"
To get those variables I can do something like:
ACTION=$(my_exe action Somestack)
STATUS=$(my_exe status Somestack)
if [[ "$ACTION" == "CREATE" ]] && [[ "$STATUS" == "COMPLETE" ]]
...
I am using following function for several years. And it is working fine:
function timeDifference($timestamp)
{
$otherDate=$timestamp;
$now=@date("Y-m-d H:i:s");
$secondDifference=@strtotime($now)-@strtotime($otherDate);
$extra="";
if ($secondDifference == 2592000) {
// months
$difference = $secondDifference/2592000;
$difference = round($difference,0);
if ($difference>1) { $extra="s"; }
$difference = $difference." month".$extra." ago";
}else if($secondDifference > 2592000)
{$difference=timestamp($timestamp);}
elseif ($secondDifference >= 604800) {
// weeks
$difference = $secondDifference/604800;
$difference = round($difference,0);
if ($difference>1) { $extra="s"; }
$difference = $difference." week".$extra." ago";
}
elseif ($secondDifference >= 86400) {
// days
$difference = $secondDifference/86400;
$difference = round($difference,0);
if ($difference>1) { $extra="s"; }
$difference = $difference." day".$extra." ago";
}
elseif ($secondDifference >= 3600) {
// hours
$difference = $secondDifference/3600;
$difference = round($difference,0);
if ($difference>1) { $extra="s"; }
$difference = $difference." hour".$extra." ago";
}
elseif ($secondDifference < 3600) {
// hours
// for seconds (less than minute)
if($secondDifference<=60)
{
if($secondDifference==0)
{
$secondDifference=1;
}
if ($secondDifference>1) { $extra="s"; }
$difference = $secondDifference." second".$extra." ago";
}
else
{
$difference = $secondDifference/60;
if ($difference>1) { $extra="s"; }else{$extra="";}
$difference = round($difference,0);
$difference = $difference." minute".$extra." ago";
}
}
$FinalDifference = $difference;
return $FinalDifference;
}
You can try fxCanvas: https://code.google.com/p/fxcanvas/
It implements almost all Canvas API within flash shim.
i had to use a csv parser about 5 years ago. seems there are at least two csv standards: http://en.wikipedia.org/wiki/Comma-separated_values and what microsoft does in excel.
i found this libaray which eats both: http://ostermiller.org/utils/CSV.html, but afaik, it has no way of inferring what data type the columns were.
I also faced the same issue. I found the solutions like following.
Solution 1: I kept my script tag in the body.
<body>
<form> . . . . </form>
<script type="text/javascript" src="<%= My.Working.Common.Util.GetSiteLocation()%>Scripts/Common.js"></script> </body>
Now conflicts regarding the tags will resolve.
Solution 2:
We can also solve this one of the above solutions like Replace the code block with <%# instead of <%= But the problem is it will give only relative path. If you want really absolute path it won't work.
Solution 1 works for me. Next is your choice.
That helped me with my code.
When I tried feltering only a type of files and show them on screen by adding a condition that tests on each line.
Like this
elif command == 'ls':
print("directory of ", ftp.pwd())
data = []
ftp.dir(data.append)
for line in data:
x = line.split(".")
formats=["gz", "zip", "rar", "tar", "bz2", "xz"]
if x[-1] in formats:
print ("-", line)
If all vectors have equal size, create a matrix and plot it.
Each column is plotted with a different color automatically
Then you can use legend
to indicate columns:
data = randn(100, 5);
figure;
plot(data);
legend(cellstr(num2str((1:size(data,2))')))
Or, if you have a cell with kernels names, use
legend(names)
Can be achieved also with scriptrunner
ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30
Which also have some features as rollback , timeout and waiting.
Here is a solution using a generic template type:
public static <T> List<T> copyList(List<T> source) {
List<T> dest = new ArrayList<T>();
for (T item : source) { dest.add(item); }
return dest;
}
For that you need reflection in C/C++ language, that doesn't exists. You need to have some meta data describing the structure of your classes (members, inherited base classes). For the moment C/C++ compilers doesn't provide automatically that information in built binaries.
I had the same idea in mind, and I used GCC XML project to get this information. It outputs XML data describing class structures. I have built a project and I'm explaining some key points in this page :
Serialization is easy, but we have to deal with complex data structure implementations (std::string, std::map for example) that play with allocated buffers. Deserialization is more complex and you need to rebuild your object with all its members, plus references to vtables ... a painful implementation.
For example you can serialize like that :
// Random class initialization
com::class1* aObject = new com::class1();
for (int i=0; i<10; i++){
aObject->setData(i,i);
}
aObject->pdata = new char[7];
for (int i=0; i<7; i++){
aObject->pdata[i] = 7-i;
}
// dictionary initialization
cjson::dictionary aDict("./data/dictionary.xml");
// json transformation
std::string aJson = aDict.toJson<com::class1>(aObject);
// print encoded class
cout << aJson << std::endl ;
To deserialize data it works like that:
// decode the object
com::class1* aDecodedObject = aDict.fromJson<com::class1>(aJson);
// modify data
aDecodedObject->setData(4,22);
// json transformation
aJson = aDict.toJson<com::class1>(aDecodedObject);
// print encoded class
cout << aJson << std::endl ;
Ouptuts:
>:~/cjson$ ./main
{"_index":54,"_inner": {"_ident":"test","pi":3.141593},"_name":"first","com::class0::_type":"type","com::class0::data":[0,1,2,3,4,5,6,7,8,9],"com::classb::_ref":"ref","com::classm1::_type":"typem1","com::classm1::pdata":[7,6,5,4,3,2,1]}
{"_index":54,"_inner":{"_ident":"test","pi":3.141593},"_name":"first","com::class0::_type":"type","com::class0::data":[0,1,2,3,22,5,6,7,8,9],"com::classb::_ref":"ref","com::classm1::_type":"typem1","com::classm1::pdata":[7,6,5,4,3,2,1]}
>:~/cjson$
Usually these implementations are compiler dependent (ABI Specification for example), and requires external description to work (GCCXML output), such are not really easy to integrate to projects.
this is better function
function RGB2HTML(red, green, blue)
{
var decColor =0x1000000+ blue + 0x100 * green + 0x10000 *red ;
return '#'+decColor.toString(16).substr(1);
}
this link helped me to solve this issue
Here is the solution: For centos: try
sudo yum install --setopt=obsoletes=0 \
> docker-ce-17.03.2.ce-1.el7.centos.x86_64 \
> docker-ce-selinux-17.03.2.ce-1.el7.centos.noarch
For Rhel:
sudo yum install --setopt=obsoletes=0 docker-ce-17.03.3.ce-1.el7.x86_64.rpm docker-ce-selinux-17.03.3.ce-1.el7.noarch.rpm
Do note that it needs to be in the numeric data type in the first place.
import pandas as pd
df['column'] = pd.to_numeric(df['column'], errors='coerce')
Next find the mean on one column or for all numeric columns using describe()
.
df['column'].mean()
df.describe()
Example of result from describe:
column
count 62.000000
mean 84.678548
std 216.694615
min 13.100000
25% 27.012500
50% 41.220000
75% 70.817500
max 1666.860000
There is nothing to do with jQuery and if you want to use it I advice you to do
if (window.console) {
console.log("your message")
}
So you don't break your code when it is not available.
As suggested in the comment, you can also execute that in one place and then use console.log
as normal
if (!window.console) { window.console = { log: function(){} }; }
The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.
from PIL import Image
jpgfile = Image.open("picture.jpg")
print(jpgfile.bits, jpgfile.size, jpgfile.format)
That is working for me. Could be a browser issue as mentioned, or maybe jQuery isn't registered properly, or perhaps the real issue is more complicated (that you made a simpler version to ask this). PS - did have to click out of the text box to make it fire.
Double Click the Login Button in the NETBEANS or add the Event Listener on Click Event (ActionListener)
btnLogin.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
this.setVisible(false);
new FrmMain().setVisible(true); // Main Form to show after the Login Form..
}
});
Example downloader class without Alamofire:
class Downloader {
class func load(URL: NSURL) {
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = "GET"
let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if (error == nil) {
// Success
let statusCode = (response as NSHTTPURLResponse).statusCode
println("Success: \(statusCode)")
// This is your file-variable:
// data
}
else {
// Failure
println("Failure: %@", error.localizedDescription);
}
})
task.resume()
}
}
This is how to use it in your own code:
class Foo {
func bar() {
if var URL = NSURL(string: "http://www.mywebsite.com/myfile.pdf") {
Downloader.load(URL)
}
}
}
Swift 3 Version
Also note to download large files on disk instead instead in memory. see `downloadTask:
class Downloader {
class func load(url: URL, to localUrl: URL, completion: @escaping () -> ()) {
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = try! URLRequest(url: url, method: .get)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Success: \(statusCode)")
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: localUrl)
completion()
} catch (let writeError) {
print("error writing file \(localUrl) : \(writeError)")
}
} else {
print("Failure: %@", error?.localizedDescription);
}
}
task.resume()
}
}
It's an indication that connection pooling is being used (which is a good thing).
WebConfigurationManager.ConnectionStrings["YourConnectionString"].ProviderName;
I believe you are looking for -maxdepth 1
.
If you want the accepted answer to work in JQuery 3 change the code like this:
var scrollItems = menuItems.map(function () {
var id = $(this).attr("href");
try {
var item = $(id);
if (item.length) {
return item;
}
} catch {}
});
I also added a try-catch to prevent javascript from crashing if there is no element by that id. Feel free to improve it even more ;)
Instagram now allows businesses to schedule their posts, using the new Content Publishing Beta endpoints.
https://developers.facebook.com/blog/post/2018/01/30/instagram-graph-api-updates/
However, this blog post - https://business.instagram.com/blog/instagram-api-features-updates - makes it clear that they are only opening that API to their Facebook Marketing Partners or Instagram Partners.
To get started with scheduling posts, please work with one of our Facebook Marketing Partners or Instagram Partners.
This link from Facebook - https://developers.facebook.com/docs/instagram-api/content-publishing - lists it as a closed beta.
The Content Publishing API is in closed beta with Facebook Marketing Partners and Instagram Partners only. We are not accepting new applicants at this time.
But this is how you would do it:
You have a photo at...
https://www.example.com/images/bronz-fonz.jpg
You want to publish it with the hashtag "#BronzFonz".
You could use the /user/media
edge to create the container like this:
POST graph.facebook.com
/17841400008460056/media?
image_url=https%3A%2F%2Fwww.example.com%2Fimages%2Fbronz-fonz.jpg&
caption=%23BronzFonz
This would return a container ID (let's say 17889455560051444), which you would then publish using the /user/media_publish edge, like this:
POST graph.facebook.com
/17841405822304914/media_publish
?creation_id=17889455560051444
This example from the docs.
I used app.all
The app.all() method is useful for mapping “global” logic for specific path prefixes or arbitrary matches.
In my case, I'm using confit for configuration management,
app.all('*', function (req, res, next) {
confit(basedir).create(function (err, config) {
if (err) {
throw new Error('Failed to load configuration ', err);
}
app.set('config', config);
next();
});
});
In routes, you simply do req.app.get('config').get('cookie');
If you don't mind using a bit of JavaScript, jQuery's fadeTo() works nicely in every browser I've tried.
jQuery(selector).fadeTo(speed, opacity);
you can use siblings and removeClass method
$('.nav-link li').click(function() {
$(this).addClass('active').siblings().removeClass('active');
});
Technically C# Extension have no equivalent in Java. But if you do want to implement such functions for a cleaner code and maintainability, you have to use Manifold framework.
package extensions.java.lang.String;
import manifold.ext.api.*;
@Extension
public class MyStringExtension {
public static void print(@This String thiz) {
System.out.println(thiz);
}
@Extension
public static String lineSeparator() {
return System.lineSeparator();
}
}
list(your_iterator)
If the table doesn't exist, you can create one with the same schema like so:
CREATE TABLE table2 LIKE table1;
Then, to copy the data over:
INSERT INTO table2 SELECT * FROM table1
android:minSdkVersion
and android:targetSdkVersion
both are Integer value we need to declare in android manifest file but both are having different properties.
android:minSdkVersion:
This is minimum required API level to run an android app. If we will install the same app on lower API version the parser error will be appear, and application not support problem will appear.
android:targetSdkVersion:
Target sdk version is to set the Target API level of app. if this attribute not declared in manifest, minSdk version will be your TargetSdk Version. This is always true that "app support installation on all higher version of API we declared as TargetSdk Version". To make app limited target we need to declare maxSdkVersion in our manifest file...
The answers here, are way too complex. Here's something I've recently used:
<?php global $product; ?>
<img src="<?php echo wp_get_attachment_url( $product->get_image_id() ); ?>" />
Using wp_get_attachment_url()
to display the
On the face of it, it looks okay - if you call eraseCookie()
on each cookie that is read from document.cookie
, then all of your cookies will be gone.
Try this:
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
eraseCookie(cookies[i].split("=")[0]);
All of this with the following caveat:
I faced this error when I created an empty project with the MVC folders and then deployed the application to the server. My issue was that I didn't define the authentication in Web.config
, so all I had to do was add this line to a system.web
tag.
<system.web>
<authentication mode="None"/>
</system.web>
I would like to make a addon for tiago's answer:
Suppose you're hiding element using ng-show
and adding a required
attribute on the same:
<div ng-show="false">
<input required name="something" ng-model="name"/>
</div>
will throw an error something like :
An invalid form control with name='' is not focusable
This is because you just cannot impose required
validation on hidden
elements. Using ng-required
makes it easier to conditionally apply required validation which is just awesome!!
I am using xcode with ios 8 just uncheck the connect harware keyboard option in your Simulator-> Hardware-> Keyboard-> Connect Hardware Keyboard.
This will solve the issue.
You may do....in easy way...within one line Logic
#include <stdio.h>
int main()
{
int a, b;
printf("Enter A :");
scanf("%d",&a);
printf("Enter B :");
scanf("%d",&b);
int a = 1,b = 2;
a=a^b^(b=a);
printf("\nValue of A=%d B=%d ",a,b);
return 1;
}
or
#include <stdio.h>
int main()
{
int a, b;
printf("Enter A :");
scanf("%d",&a);
printf("Enter B :");
scanf("%d",&b);
int a = 1,b = 2;
a=a+b-(b=a);
printf("\nValue of A=%d B=%d ",a,b);
return 1;
}
This is not optimal performance-wise, but a pretty straight-forward Linq approach:
string strippedString = new string(
yourString.Where(c => c <= sbyte.MaxValue).ToArray()
);
The downside is that all the "surviving" characters are first put into an array of type char[]
which is then thrown away after the string
constructor no longer uses it.
After long search I found a working solution. My database does not use the sys.foreign_key_columns and the information_schema.key_column_usage only contain primary keys.
I use SQL Server 2015
SOLUTION 1 (rarely used)
If other solutions does not work, this will work fine:
WITH CTE AS
(
SELECT
TAB.schema_id,
TAB.name,
COL.name AS COLNAME,
COl.is_identity
FROM
sys.tables TAB INNER JOIN sys.columns COL
ON TAB.object_id = COL.object_id
)
SELECT
DB_NAME() AS [Database],
SCHEMA_NAME(Child.schema_id) AS 'Schema',
Child.name AS 'ChildTable',
Child.COLNAME AS 'ChildColumn',
Parent.name AS 'ParentTable',
Parent.COLNAME AS 'ParentColumn'
FROM
cte Child INNER JOIN CTE Parent
ON
Child.COLNAME=Parent.COLNAME AND
Child.name<>Parent.name AND
Child.is_identity+1=Parent.is_identity
SOLUTION 2 (commonly used)
In most of the cases this will work just fine:
SELECT
DB_NAME() AS [Database],
SCHEMA_NAME(fk.schema_id) AS 'Schema',
fk.name 'Name',
tp.name 'ParentTable',
cp.name 'ParentColumn',
cp.column_id,
tr.name 'ChildTable',
cr.name 'ChildColumn',
cr.column_id
FROM
sys.foreign_keys fk
INNER JOIN
sys.tables tp ON fk.parent_object_id = tp.object_id
INNER JOIN
sys.tables tr ON fk.referenced_object_id = tr.object_id
INNER JOIN
sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
INNER JOIN
sys.columns cp ON fkc.parent_column_id = cp.column_id AND fkc.parent_object_id = cp.object_id
INNER JOIN
sys.columns cr ON fkc.referenced_column_id = cr.column_id AND fkc.referenced_object_id = cr.object_id
WHERE
-- CONCAT(SCHEMA_NAME(fk.schema_id), '.', tp.name, '.', cp.name) LIKE '%my_table_name%' OR
-- CONCAT(SCHEMA_NAME(fk.schema_id), '.', tr.name, '.', cr.name) LIKE '%my_table_name%'
ORDER BY
tp.name, cp.column_id
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
Double d = scan.nextDouble();
String newStr = "";
Scanner charScanner = new Scanner( System.in ).useDelimiter( "(\\b|\\B)" ) ;
while( charScanner.hasNext() ) {
String c = charScanner.next();
if (c.equalsIgnoreCase("\r")) {
break;
}
else {
newStr += c;
}
}
System.out.println("String: " + newStr);
System.out.println("Int: " + i);
System.out.println("Double: " + d);
This code works fine
Grant required permission ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION after start service
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.location.LocationListener;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnCanceledListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import java.util.concurrent.TimeUnit;
/**
* Created by Ketan Ramani on 05/11/18.
*/
public class BackgroundLocationUpdateService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
/* Declare in manifest
<service android:name=".BackgroundLocationUpdateService"/>
*/
private final String TAG = "BackgroundLocationUpdateService";
private final String TAG_LOCATION = "TAG_LOCATION";
private Context context;
private boolean stopService = false;
/* For Google Fused API */
protected GoogleApiClient mGoogleApiClient;
protected LocationSettingsRequest mLocationSettingsRequest;
private String latitude = "0.0", longitude = "0.0";
private FusedLocationProviderClient mFusedLocationClient;
private SettingsClient mSettingsClient;
private LocationCallback mLocationCallback;
private LocationRequest mLocationRequest;
private Location mCurrentLocation;
/* For Google Fused API */
@Override
public void onCreate() {
super.onCreate();
context = this;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
StartForeground();
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
try {
if (!stopService) {
//Perform your task here
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (!stopService) {
handler.postDelayed(this, TimeUnit.SECONDS.toMillis(10));
}
}
}
};
handler.postDelayed(runnable, 2000);
buildGoogleApiClient();
return START_STICKY;
}
@Override
public void onDestroy() {
Log.e(TAG, "Service Stopped");
stopService = true;
if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
Log.e(TAG_LOCATION, "Location Update Callback Removed");
}
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void StartForeground() {
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);
String CHANNEL_ID = "channel_location";
String CHANNEL_NAME = "channel_location";
NotificationCompat.Builder builder = null;
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
notificationManager.createNotificationChannel(channel);
builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
builder.setChannelId(CHANNEL_ID);
builder.setBadgeIconType(NotificationCompat.BADGE_ICON_NONE);
} else {
builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
}
builder.setContentTitle("Your title");
builder.setContentText("You are now online");
Uri notificationSound = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(notificationSound);
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.ic_logo);
builder.setContentIntent(pendingIntent);
Notification notification = builder.build();
startForeground(101, notification);
}
@Override
public void onLocationChanged(Location location) {
Log.e(TAG_LOCATION, "Location Changed Latitude : " + location.getLatitude() + "\tLongitude : " + location.getLongitude());
latitude = String.valueOf(location.getLatitude());
longitude = String.valueOf(location.getLongitude());
if (latitude.equalsIgnoreCase("0.0") && longitude.equalsIgnoreCase("0.0")) {
requestLocationUpdate();
} else {
Log.e(TAG_LOCATION, "Latitude : " + location.getLatitude() + "\tLongitude : " + location.getLongitude());
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onConnected(@Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10 * 1000);
mLocationRequest.setFastestInterval(5 * 1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
mLocationSettingsRequest = builder.build();
mSettingsClient
.checkLocationSettings(mLocationSettingsRequest)
.addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
Log.e(TAG_LOCATION, "GPS Success");
requestLocationUpdate();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
int REQUEST_CHECK_SETTINGS = 214;
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult((AppCompatActivity) context, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sie) {
Log.e(TAG_LOCATION, "Unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.e(TAG_LOCATION, "Location settings are inadequate, and cannot be fixed here. Fix in Settings.");
}
}
}).addOnCanceledListener(new OnCanceledListener() {
@Override
public void onCanceled() {
Log.e(TAG_LOCATION, "checkLocationSettings -> onCanceled");
}
});
}
@Override
public void onConnectionSuspended(int i) {
connectGoogleClient();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
buildGoogleApiClient();
}
protected synchronized void buildGoogleApiClient() {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
mSettingsClient = LocationServices.getSettingsClient(context);
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
connectGoogleClient();
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
Log.e(TAG_LOCATION, "Location Received");
mCurrentLocation = locationResult.getLastLocation();
onLocationChanged(mCurrentLocation);
}
};
}
private void connectGoogleClient() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int resultCode = googleAPI.isGooglePlayServicesAvailable(context);
if (resultCode == ConnectionResult.SUCCESS) {
mGoogleApiClient.connect();
}
}
@SuppressLint("MissingPermission")
private void requestLocationUpdate() {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}
}
In Activity
Start Service : startService(new Intent(this, BackgroundLocationUpdateService.class));
Stop Service : stopService(new Intent(this, BackgroundLocationUpdateService.class));
In Fragment
Start Service : getActivity().startService(new Intent(getActivity().getBaseContext(), BackgroundLocationUpdateService.class));
Stop Service : getActivity().stopService(new Intent(getActivity(), BackgroundLocationUpdateService.class));
toString() returns a string/textual representation of the object. Commonly used for diagnostic purposes like debugging, logging etc., the toString() method is used to read meaningful details about the object.
It is automatically invoked when the object is passed to println, print, printf, String.format(), assert or the string concatenation operator.
The default implementation of toString() in class Object returns a string consisting of the class name of this object followed by @ sign and the unsigned hexadecimal representation of the hash code of this object using the following logic,
getClass().getName() + "@" + Integer.toHexString(hashCode())
For example, the following
public final class Coordinates {
private final double x;
private final double y;
public Coordinates(double x, double y) {
this.x = x;
this.y = y;
}
public static void main(String[] args) {
Coordinates coordinates = new Coordinates(1, 2);
System.out.println("Bourne's current location - " + coordinates);
}
}
prints
Bourne's current location - Coordinates@addbf1 //concise, but not really useful to the reader
Now, overriding toString() in the Coordinates class as below,
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
results in
Bourne's current location - (1.0, 2.0) //concise and informative
The usefulness of overriding toString() becomes even more when the method is invoked on collections containing references to these objects. For example, the following
public static void main(String[] args) {
Coordinates bourneLocation = new Coordinates(90, 0);
Coordinates bondLocation = new Coordinates(45, 90);
Map<String, Coordinates> locations = new HashMap<String, Coordinates>();
locations.put("Jason Bourne", bourneLocation);
locations.put("James Bond", bondLocation);
System.out.println(locations);
}
prints
{James Bond=(45.0, 90.0), Jason Bourne=(90.0, 0.0)}
instead of this,
{James Bond=Coordinates@addbf1, Jason Bourne=Coordinates@42e816}
Few implementation pointers,
Provide accessors/getters for all of the instance fields that are contained in the string returned. For example, in the Coordinates class,
public double getX() {
return x;
}
public double getY() {
return y;
}
A comprehensive coverage of the toString() method is in Item 10 of the book, Effective Java™, Second Edition, By Josh Bloch.
I know that there exists a command line option, -vm
, to specify the path to the executable of the Java runtime. This may be the same as in eclipse.ini.
On the HTTP Response where you are returning the PDF file, ensure the content disposition header looks like:
Content-Disposition: attachment; filename=quot.pdf;
See content-disposition on the wikipedia MIME page.
@JustGoscha's answer is spot on, but that's a lot to type when I want access, so I added this to the bottom of my app.js. Then all I have to type is x = getSrv('$http')
to get the http service.
// @if DEBUG
function getSrv(name, element) {
element = element || '*[ng-app]';
return angular.element(element).injector().get(name);
}
// @endif
It adds it to the global scope but only in debug mode. I put it inside the @if DEBUG
so that I don't end up with it in the production code. I use this method to remove debug code from prouduction builds.
try this
var locations = [
['San Francisco: Power Outage', 37.7749295, -122.4194155,'http://labs.google.com/ridefinder/images/mm_20_purple.png'],
['Sausalito', 37.8590937, -122.4852507,'http://labs.google.com/ridefinder/images/mm_20_red.png'],
['Sacramento', 38.5815719, -121.4943996,'http://labs.google.com/ridefinder/images/mm_20_green.png'],
['Soledad', 36.424687, -121.3263187,'http://labs.google.com/ridefinder/images/mm_20_blue.png'],
['Shingletown', 40.4923784, -121.8891586,'http://labs.google.com/ridefinder/images/mm_20_yellow.png']
];
//inside the loop
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: locations[i][3]
});
x = int(input("press 1 for dec to oct,bin,hex \n press 2 for bin to dec,hex,oct \n press 3 for oct to bin,hex,dec \n press 4 for hex to bin,dec,oct \n"))
if x is 1:
decimal =int(input('Enter the decimal number: '))
print(bin(decimal),"in binary.")
print(oct(decimal),"in octal.")
print(hex(decimal),"in hexadecimal.")
if x is 2:
binary = input("Enter number in Binary Format: ");
decimal = int(binary, 2);
print(binary,"in Decimal =",decimal);
print(binary,"in Hexadecimal =",hex(decimal));
print(binary,"in octal =",oct(decimal));
if x is 3:
octal = input("Enter number in Octal Format: ");
decimal = int(octal, 8);
print(octal,"in Decimal =",decimal);
print(octal,"in Hexadecimal =",hex(decimal));
print(octal,"in Binary =",bin(decimal));
if x is 4:
hex = input("Enter number in hexa-decimal Format: ");
decimal = int(hex, 16);
print(hex,"in Decimal =",decimal);
print(hex,"in octal =",oct(decimal));
print(hex,"in Binary =",bin(decimal));
Suppose you worked in feature/task1 with multiple commits.
Go to your project branch (project/my_project)
git checkout project/my_project
Create a new branch (feature/task1_bugfix)
git checkout -b feature/task1_bugfix
Marge with the --squash
option
git merge --squash feature/task1
Create a single commit
git commit -am "add single comments"
Push your branch
git push --set-upstream origin feature/task1_bugfix
Here you can check for couple of things.
DateTime.TryParseExact
. Check the complete list of formats, available here. CultureInfo.InvariantCulture
which is more likely add problem. So instead of passing a NULL
value or setting it to CultureInfo provider = new CultureInfo("en-US")
, you may write it like.
.
if (!DateTime.TryParseExact(txtStartDate.Text, formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out startDate))
{
//your condition fail code goes here
return false;
}
else
{
//success code
}
Enable compression via .htaccess
For most people reading this, compression is enabled by adding some code to a file called .htaccess on their web host/server. This means going to the file manager (or wherever you go to add or upload files) on your webhost.
The .htaccess file controls many important things for your site.
The code below should be added to your .htaccess file...
<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>
Save the .htaccess file and then refresh your webpage.
Check to see if your compression is working using the Gzip compression tool.
To add another alternative to tuple(l)
, as of Python >= 3.5
you can do:
t = *l, # or t = (*l,)
short, a bit faster but probably suffers from readability.
This essentially unpacks the list l
inside a tuple literal which is created due to the presence of the single comma ,
.
P.s: The error you are receiving is due to masking of the name tuple
i.e you assigned to the name tuple somewhere e.g tuple = (1, 2, 3)
.
Using del tuple
you should be good to go.
I had this exception in the case of a test for checking some actual accessed URLs by users.
And the URLs are sometime contains an illegal-character and hang by this error.
So I make a function to encode only the characters in the URL string like this.
String encodeIllegalChar(String uriStr,String enc)
throws URISyntaxException,UnsupportedEncodingException {
String _uriStr = uriStr;
int retryCount = 17;
while(true){
try{
new URI(_uriStr);
break;
}catch(URISyntaxException e){
String reason = e.getReason();
if(reason == null ||
!(
reason.contains("in path") ||
reason.contains("in query") ||
reason.contains("in fragment")
)
){
throw e;
}
if(0 > retryCount--){
throw e;
}
String input = e.getInput();
int idx = e.getIndex();
String illChar = String.valueOf(input.charAt(idx));
_uriStr = input.replace(illChar,URLEncoder.encode(illChar,enc));
}
}
return _uriStr;
}
test:
String q = "\\'|&`^\"<>)(}{][";
String url = "http://test.com/?q=" + q + "#" + q;
String eic = encodeIllegalChar(url,'UTF-8');
System.out.println(String.format(" original:%s",url));
System.out.println(String.format(" encoded:%s",eic));
System.out.println(String.format(" uri-obj:%s",new URI(eic)));
System.out.println(String.format("re-decoded:%s",URLDecoder.decode(eic)));
Previous answers seem to be outdated.
Java's File.renameTo() is probably the easiest solution for API 7, and seems to work fine. Be carefull IT DOES NOT THROW EXCEPTIONS, but returns true/false!!!
Note that there seem to be problems with it in previous versions (same as NIO).
If you need to use a previous version, check here.
Here's an example for API7:
File f1= new File("C:\\Users\\.....\\foo");
File f2= new File("C:\\Users\\......\\foo.old");
System.err.println("Result of move:"+f1.renameTo(f2));
Alternatively:
System.err.println("Move:" +f1.toURI() +"--->>>>"+f2.toURI());
Path b1=Files.move(f1.toPath(), f2.toPath(), StandardCopyOption.ATOMIC_MOVE ,StandardCopyOption.REPLACE_EXISTING ););
System.err.println("Move: RETURNS:"+b1);
I wonder why no one have mentioned this simple pattern? :
(function(next) {
//do something
next()
}(function() {
//do some more
}))
Using timeouts just for blindly waiting is bad practice; and involving promises just adds more complexity to the code. In OP's case:
(function(next) {
for(i=0;i<x;i++){
// do something
if (i==x-1) next()
}
}(function() {
// now wait for firstFunction to finish...
// do something else
}))
a small demo -> http://jsfiddle.net/5jdeb93r/
If you're working in the Jupyter (formerly IPython) notebook, you can
import IPython.display as ipd
ipd.Audio(filename='path/to/file.mp3')
I have a simple script I use for this:
me@mycomputer:~$ cat /usr/local/bin/c
#!/bin/sh
echo "$*" | sed 's/x/\*/g' | bc -l
It changes x
to *
since *
is a special character in the shell. Use it as follows:
c 5x5
c 5-4.2 + 1
c '(5 + 5) * 30'
(you still have to use quotes if the expression contains any parentheses).You need to do two additional things after following the link that you have mentioned in your post:
One have to map the changed login cridentials in phpmyadmin's config.inc.php
and second, you need to restart your web and mysql servers..
php version is not the issue here..you need to go to phpmyadmin installation directory and find file config.inc.php
and in that file put your current mysql password at line
$cfg['Servers'][$i]['user'] = 'root'; //mysql username here
$cfg['Servers'][$i]['password'] = 'password'; //mysql password here
On Linux package glibc-headers provides header #include <ieee754.h>
with floating point types definitions, e.g.:
union ieee754_double
{
double d;
/* This is the IEEE 754 double-precision format. */
struct
{
#if __BYTE_ORDER == __BIG_ENDIAN
unsigned int negative:1;
unsigned int exponent:11;
/* Together these comprise the mantissa. */
unsigned int mantissa0:20;
unsigned int mantissa1:32;
#endif /* Big endian. */
#if __BYTE_ORDER == __LITTLE_ENDIAN
# if __FLOAT_WORD_ORDER == __BIG_ENDIAN
unsigned int mantissa0:20;
unsigned int exponent:11;
unsigned int negative:1;
unsigned int mantissa1:32;
# else
/* Together these comprise the mantissa. */
unsigned int mantissa1:32;
unsigned int mantissa0:20;
unsigned int exponent:11;
unsigned int negative:1;
# endif
#endif /* Little endian. */
} ieee;
/* This format makes it easier to see if a NaN is a signalling NaN. */
struct
{
#if __BYTE_ORDER == __BIG_ENDIAN
unsigned int negative:1;
unsigned int exponent:11;
unsigned int quiet_nan:1;
/* Together these comprise the mantissa. */
unsigned int mantissa0:19;
unsigned int mantissa1:32;
#else
# if __FLOAT_WORD_ORDER == __BIG_ENDIAN
unsigned int mantissa0:19;
unsigned int quiet_nan:1;
unsigned int exponent:11;
unsigned int negative:1;
unsigned int mantissa1:32;
# else
/* Together these comprise the mantissa. */
unsigned int mantissa1:32;
unsigned int mantissa0:19;
unsigned int quiet_nan:1;
unsigned int exponent:11;
unsigned int negative:1;
# endif
#endif
} ieee_nan;
};
#define IEEE754_DOUBLE_BIAS 0x3ff /* Added to exponent. */
This should work. getElementsByClassName
returns an array Array-like object(see edit) of the elements matching the criteria.
var elements = document.getElementsByClassName("classname");
var myFunction = function() {
var attribute = this.getAttribute("data-myattribute");
alert(attribute);
};
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', myFunction, false);
}
jQuery does the looping part for you, which you need to do in plain JavaScript.
If you have ES6 support you can replace your last line with:
Array.from(elements).forEach(function(element) {
element.addEventListener('click', myFunction);
});
Note: Older browsers (like IE6, IE7, IE8) don´t support getElementsByClassName
and so they return undefined
.
EDIT : Correction
getElementsByClassName
doesnt return an array, but a HTMLCollection in most, or a NodeList in some browsers (Mozilla ref). Both of these types are Array-Like, (meaning that they have a length property and the objects can be accessed via their index), but are not strictly an Array or inherited from an Array. (meaning other methods that can be performed on an Array cannot be performed on these types)
Thanks to user @Nemo for pointing this out and having me dig in to fully understand.
There are a number of limitations, notably:
http://www.dotnetspider.com/tutorials/SqlServer-Tutorial-158.aspx http://www.microsoft.com/sqlserver/2008/en/us/editions.aspx
With regards to the number of databases, this MSDN article says there's no limit:
The 4 GB database size limit applies only to data files and not to log files. However, there are no limits to the number of databases that can be attached to the server.
However, as mentioned in the comments and above, the database size limit was raised to 10GB in 2008 R2 and 2012. Also, this 10GB limit only applies to relational data, and Filestream data does not count towards this limit (http://msdn.microsoft.com/en-us/library/bb895334.aspx).
The best one that I found is http://www.favicomatic.com/ I say best because it gave me the crispest favicon, and required no editing after their transformation. It will generate favicons at 16x16 and 32x32 and to quote them "Every damn size, sir!" Also, their site looks cool and is easy to use.
They also generate the html that you need to use for the files they generate.
<link rel="apple-touch-icon-precomposed" sizes="57x57" href="apple-touch-icon-57x57.png" />
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="apple-touch-icon-114x114.png" />
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="apple-touch-icon-72x72.png" />
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="apple-touch-icon-144x144.png" />
<link rel="apple-touch-icon-precomposed" sizes="60x60" href="apple-touch-icon-60x60.png" />
<link rel="apple-touch-icon-precomposed" sizes="120x120" href="apple-touch-icon-120x120.png" />
<link rel="apple-touch-icon-precomposed" sizes="76x76" href="apple-touch-icon-76x76.png" />
<link rel="apple-touch-icon-precomposed" sizes="152x152" href="apple-touch-icon-152x152.png" />
<link rel="icon" type="image/png" href="favicon-196x196.png" sizes="196x196" />
<link rel="icon" type="image/png" href="favicon-96x96.png" sizes="96x96" />
<link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16" />
<link rel="icon" type="image/png" href="favicon-128.png" sizes="128x128" />
<meta name="application-name" content=" "/>
<meta name="msapplication-TileColor" content="#FFFFFF" />
<meta name="msapplication-TileImage" content="mstile-144x144.png" />
<meta name="msapplication-square70x70logo" content="mstile-70x70.png" />
<meta name="msapplication-square150x150logo" content="mstile-150x150.png" />
<meta name="msapplication-wide310x150logo" content="mstile-310x150.png" />
<meta name="msapplication-square310x310logo" content="mstile-310x310.png" />
I looked at the first 20 or so google results, and this was by far the best.
This is what I use with JQuery:
$('.button').on('click', function () {
var obj = document.createElement("audio");
obj.src = "linktoyourfile.wav";
obj.play();
});
Implode will combine an array into a string for you, but to make an SQL query out a kay/value pair you'll have to write your own function.
If week 1 always starts on the first Monday
of the month try this formula for week number
=INT((6+DAY(A1+1-WEEKDAY(A1-1)))/7)
That gets the week number from the date in A1 with no intermediate calculations - if you want to use your "Monday's date" in B1 you can use this version
=INT((DAY(B1)+6)/7)
Save this xml and add as a background for the linear layout....
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="4dp" android:color="#FF00FF00" />
<solid android:color="#ffffff" />
<padding android:left="7dp" android:top="7dp"
android:right="7dp" android:bottom="0dp" />
<corners android:radius="4dp" />
</shape>
Hope this helps! :)
After posting this I did come up with a way that works. However, I don't feel it is the best way to handle this. Any suggestions on a better one?
//Check to see if we get rows back, if we do just bind.
if (dtFunding.Rows.Count != 0)
{
grdFunding.DataSource = dtFunding;
grdFunding.DataBind();
}
else
{
//Other wise add a emtpy "New Row" to the datatable and then hide it after binding.
dtFunding.Rows.Add(dtFunding.NewRow());
grdFunding.DataSource = dtFunding;
grdFunding.DataBind();
grdFunding.Rows[0].Visible = false;
}
Linkage determines whether identifiers that have identical names refer to the same object, function, or other entity, even if those identifiers appear in different translation units. The linkage of an identifier depends on how it was declared. There are three types of linkages:
C++ only : You can also have linkage between C++ and non-C++ code fragments, which is called language linkage.
Source :IBM Program Linkage
DECLARE @string NVARCHAR(50)
SET @string = 'CUT STRING'
SELECT LEFT(@string,(PATINDEX('% %',@string)))
Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf
between host and guest (there is known performance issues if there are large numbers of files/directories).
/vagrant
in guestVagrant is mounting the current working directory (where Vagrantfile
resides) as /vagrant
in the guest, this is the default behaviour.
See docs
NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.
You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true
in your Vagrantfile
.
Based on the output /tmp
on host was NOT mounted during up time.
Use VAGRANT_INFO=debug vagrant up
or VAGRANT_INFO=debug vagrant reload
to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp
on host should be drwxrwxrwt
).
I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)
config.vm.synced_folder "/tmp", "/tmp/src"
output
$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src
Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw)
.
I don't recall of a "indexOf" on arrays other than coding it for yourself... though you could probably use one of the many java.util.Arrays#binarySearch(...)
methods (see the Arrays javadoc) if your array contains primitive types
window.location.hash = 'whatever';
You can loop through the columns collection of the datatable.
VB
Dim dt As New DataTable()
For Each column As DataColumn In dt.Columns
Console.WriteLine(column.ColumnName)
Next
C#
DataTable dt = new DataTable();
foreach (DataColumn column in dt.Columns)
{
Console.WriteLine(column.ColumnName);
}
Hope this helps!
import org.apache.commons.io.filefilter.WildcardFileFilter;
.........
.........
File dir = new File(fileDir);
FileFilter fileFilter = new WildcardFileFilter("*.txt");
File[] files = dir.listFiles(fileFilter);
The code above works great for me
When you declare a reference variable (i.e., an object), you are really creating a pointer to an object. Consider the following code where you declare a variable of primitive type int
:
int x;
x = 10;
In this example, the variable x
is an int
and Java will initialize it to 0
for you. When you assign the value of 10
on the second line, your value of 10
is written into the memory location referred to by x
.
But, when you try to declare a reference type, something different happens. Take the following code:
Integer num;
num = new Integer(10);
The first line declares a variable named num
, but it does not actually contain a primitive value yet. Instead, it contains a pointer (because the type is Integer
which is a reference type). Since you have not yet said what to point to, Java sets it to null
, which means "I am pointing to nothing".
In the second line, the new
keyword is used to instantiate (or create) an object of type Integer
, and the pointer variable num
is assigned to that Integer
object.
The NullPointerException
(NPE) occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable (called dereferencing). So you are pointing to something that does not actually exist.
Dereferencing usually happens when using .
to access a method or field, or using [
to index an array.
If you attempt to dereference num
before creating the object you get a NullPointerException
. In the most trivial cases, the compiler will catch the problem and let you know that "num may not have been initialized
," but sometimes you may write code that does not directly create the object.
For instance, you may have a method as follows:
public void doSomething(SomeObject obj) {
// Do something to obj, assumes obj is not null
obj.myMethod();
}
In which case, you are not creating the object obj
, but rather assuming that it was created before the doSomething()
method was called. Note, it is possible to call the method like this:
doSomething(null);
In which case, obj
is null
, and the statement obj.myMethod()
will throw a NullPointerException
.
If the method is intended to do something to the passed-in object as the above method does, it is appropriate to throw the NullPointerException
because it's a programmer error and the programmer will need that information for debugging purposes.
In addition to NullPointerException
s thrown as a result of the method's logic, you can also check the method arguments for null
values and throw NPEs explicitly by adding something like the following near the beginning of a method:
// Throws an NPE with a custom error message if obj is null
Objects.requireNonNull(obj, "obj must not be null");
Note that it's helpful to say in your error message clearly which object cannot be null
. The advantage of validating this is that 1) you can return your own clearer error messages and 2) for the rest of the method you know that unless obj
is reassigned, it is not null and can be dereferenced safely.
Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething()
could be written as:
/**
* @param obj An optional foo for ____. May be null, in which case
* the result will be ____.
*/
public void doSomething(SomeObject obj) {
if(obj == null) {
// Do something
} else {
// Do something else
}
}
Finally, How to pinpoint the exception & cause using Stack Trace
What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
Sonar with find bugs can detect NPE. Can sonar catch null pointer exceptions caused by JVM Dynamically
Now Java 14 has added a new language feature to show the root cause of NullPointerException. This language feature has been part of SAP commercial JVM since 2006. The following is 2 minutes read to understand this amazing language feature.
https://jfeatures.com/blog/NullPointerException
In Java 14, the following is a sample NullPointerException Exception message:
in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.size()" because "list" is null
Arr1 becomes an array of 'Variant' by the first statement of your code:
Dim arr1() As Variant
Array of size zero is not empty, as like an empty box exists in real world.
If you define a variable of 'Variant', that will be empty when it is created.
Following code will display "Empty".
Dim a as Variant
If IsEmpty(a) then
MsgBox("Empty")
Else
MsgBox("Not Empty")
End If
You can use Comparator.reverseOrder()
to have a comparator giving the reverse of the natural ordering.
If you want to reverse the ordering of an existing comparator, you can use Comparator.reversed()
.
Sample code:
Stream.of(1, 4, 2, 5)
.sorted(Comparator.reverseOrder());
// stream is now [5, 4, 2, 1]
Stream.of("foo", "test", "a")
.sorted(Comparator.comparingInt(String::length).reversed());
// stream is now [test, foo, a], sorted by descending length
This is really fast and dirty, but it gets the job done: jsFiddle
#img1, #img2, #img3, #img4 {
width:100%;
height:100%;
position:fixed;
z-index:-1;
animation-name: test;
animation-duration: 5s;
opacity:0;
}
#img2 {
animation-delay:5s;
-webkit-animation-delay:5s
}
#img3 {
animation-delay:10s;
-webkit-animation-delay:10s
}
#img4 {
animation-delay:15s;
-webkit-animation-delay:15s
}
@-webkit-keyframes test {
0% {
opacity: 0;
}
50% {
opacity: 1;
}
100% {
}
}
@keyframes test {
0% {
opacity: 0;
}
50% {
opacity: 1;
}
100% {
}
}
I'm working on something similar for my site using jQuery, but the transition is triggered when the user scrolls down the page - jsFiddle
It's a good practice if you need them. It's also a good practice is they make sense, so future coders can understand what you're doing.
But generally, no it's not a good practice to attach 10 class names to an object because most likely whatever you're using them for, you could accomplish the same thing with far fewer classes. Probably just 1 or 2.
To qualify that statement, javascript plugins and scripts may append far more classnames to do whatever it is they're going to do. Modernizr for example appends anywhere from 5 - 25 classes to your body tag, and there's a very good reason for it. jQuery UI appends lots of classnames when you use one of the widgets in that library.
what about that simple way)
$(document).ready ->
$('#datepicker').datepicker( dateFormat: 'yy-mm-dd', onSelect: (dateStr) ->
alert dateStr # yy-mm-dd
#OR
alert $("#datepicker").val(); # yy-mm-dd
Have you tried starting it as an administrator? Start Visual Studio as an administrator if you use it, because working with .bat
files requires those privileges.
In Centos
sudo yum install php-xml
and restart apache
sudo service httpd restart
You could opt for Views as shown below:
CREATE VIEW AuthorizedUserProjectView AS select t1.username as username, t1.email as useremail, p.id as projectid,
(select m.role from userproject m where m.projectid = p.id and m.userid = t1.id) as role
FROM authorizeduser as t1, project as p
and then work on the view for selecting or updating:
select * from AuthorizedUserProjectView where projectid = 49
which yields the result as shown in the picture below i.e. for non-matching column null has been filled in.
[Result of select on the view][1]
For me adding AppRoutingModule to my imports solved the problem.
imports: [
BrowserModule,
AppRoutingModule,
RouterModule.forRoot([
{
path: 'new-cmp',
component: NewCmpComponent
}
])
]
Public Oracle Java 6 releases do not support TLSv1.2. Paid-for releases of Java 6 (post-EOL) might. (UPDATE - TLSv1.1 is available for Java 1.6 from update 111 onwards; source)
Contact Oracle sales.
Other alternatives are:
Use an alternative JCE implementation such as Bouncy Castle. See this answer for details on how to do it. It changes the default SSLSocketFactory
implementation, so that your application will use BC transparently. (Other answers show how to use the BC SSLSocketFactory
implementation explicitly, but that approach will entail modifying application or library code that that is opening sockets.)
Use an IBM Java 6 ... if available for your platform. According to "IBM SDK, Java Technology Edition fixes to mitigate against the POODLE security vulnerability (CVE-2014-3566)":
"TLSv1.1 and TLSv1.2 are available only for Java 6 service refresh 10, Java 6.0.1 service refresh 1 (J9 VM2.6), and later releases."
However, I'd advise upgrading to a Java 11 (now). Java 6 was EOL'd in Feb 2013, and continuing to use it is potentially risky. Free Oracle Java 8 is EOL for many use-cases. (Tell or remind the boss / the client. They need to know.)
try once:-
USE master
DECLARE @portNumber NVARCHAR(10)
EXEC xp_instance_regread
@rootkey = 'HKEY_LOCAL_MACHINE',
@key =
'Software\Microsoft\Microsoft SQL Server\MSSQLServer\SuperSocketNetLib\Tcp\IpAll',
@value_name = 'TcpDynamicPorts',
@value = @portNumber OUTPUT
SELECT [Port Number] = @portNumber
GO
int max = 50;
int min = 1;
double random = Math.random() * 49 + 1;
or
int random = (int )(Math.random() * 50 + 1);
This will give you value from 1 to 50 in case of int or 1.0 (inclusive) to 50.0 (exclusive) in case of double
Why?
random() method returns a random number between 0.0 and 0.9..., you multiply it by 50, so upper limit becomes 0.0 to 49.999... when you add 1, it becomes 1.0 to 50.999..., now when you truncate to int, you get 1 to 50. (thanks to @rup in comments). leepoint's awesome write-up on both the approaches.
Random rand = new Random();
int value = rand.nextInt(50);
This will give value from 0 to 49.
For 1 to 50: rand.nextInt((max - min) + 1) + min;
Source of some Java Random awesomeness.
I'm rather shocked that this has not been answered since the solution is very simple.
As mentioned in previous posts, you would not want to convert it using C#, but just once. This is easy to do with PuTTYGen.
Enjoy!
@DSM's answer is perfectly fine in almost any normal scenario. But if you're the type of programmer who wants to go a little deeper than the surface level, you might be interested to know that it is a little faster to call numpy functions on the underlying .to_numpy()
(or .values
for <0.24) array instead of directly calling the (cythonized) functions defined on the DataFrame/Series objects.
For example, you can use ndarray.max()
along the first axis.
# Data borrowed from @DSM's post.
df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
df
A B
0 1 -2
1 2 8
2 3 1
df['C'] = df[['A', 'B']].values.max(1)
# Or, assuming "A" and "B" are the only columns,
# df['C'] = df.values.max(1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
If your data has NaN
s, you will need numpy.nanmax
:
df['C'] = np.nanmax(df.values, axis=1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
You can also use numpy.maximum.reduce
. numpy.maximum
is a ufunc (Universal Function), and every ufunc has a reduce
:
df['C'] = np.maximum.reduce(df['A', 'B']].values, axis=1)
# df['C'] = np.maximum.reduce(df[['A', 'B']], axis=1)
# df['C'] = np.maximum.reduce(df, axis=1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
np.maximum.reduce
and np.max
appear to be more or less the same (for most normal sized DataFrames)—and happen to be a shade faster than DataFrame.max
. I imagine this difference roughly remains constant, and is due to internal overhead (indexing alignment, handling NaNs, etc).
The graph was generated using perfplot. Benchmarking code, for reference:
import pandas as pd
import perfplot
np.random.seed(0)
df_ = pd.DataFrame(np.random.randn(5, 1000))
perfplot.show(
setup=lambda n: pd.concat([df_] * n, ignore_index=True),
kernels=[
lambda df: df.assign(new=df.max(axis=1)),
lambda df: df.assign(new=df.values.max(1)),
lambda df: df.assign(new=np.nanmax(df.values, axis=1)),
lambda df: df.assign(new=np.maximum.reduce(df.values, axis=1)),
],
labels=['df.max', 'np.max', 'np.maximum.reduce', 'np.nanmax'],
n_range=[2**k for k in range(0, 15)],
xlabel='N (* len(df))',
logx=True,
logy=True)
if you have more files in my case i have 7000 image files when i try to add them from project's route folder it hasn't added them but when i go to the image folder everything is ok. Go through the target folder and command like abows
git add .
git commit -am "image uploading"
git push origin master
git push origin master Enumerating objects: 6574, done. Counting objects: 100% (6574/6574), done. Delta compression using up to 4 threads Compressing objects: 100% (6347/6347), done. Writing objects: 28% (1850/6569), 142.17 MiB | 414.00 KiB/s
Here is better solution if you want to make multiple text to bold. I've improved Eitan's code. thanks Eitan.
public static SpannableStringBuilder makeSectionOfTextBold(String text, String... textToBold) {
SpannableStringBuilder builder = new SpannableStringBuilder(text);
for (String textItem :
textToBold) {
if (textItem.length() > 0 && !textItem.trim().equals("")) {
//for counting start/end indexes
String testText = text.toLowerCase(Locale.US);
String testTextToBold = textItem.toLowerCase(Locale.US);
int startingIndex = testText.indexOf(testTextToBold);
int endingIndex = startingIndex + testTextToBold.length();
if (startingIndex >= 0 && endingIndex >= 0) {
builder.setSpan(new StyleSpan(Typeface.BOLD), startingIndex, endingIndex, 0);
}
}
}
return builder;
}
When you start up or just join a project based on webapplications, the design of interface is maybe good. Otherwise this should be changed. In order to Web 2.0 applications you will work with dynamic contents, many effects and other stuff. All these things are fine, but no one thought about to style up the JavaScript alert and confirm boxes. Here is the they way,.. completely dynamic, JS and CSS driven Create simple html file
<html>
<head>
<title>jsConfirmSyle</title>
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<script type="text/javascript" src="jsConfirmStyle.js"></script>
<script type="text/javascript">
function confirmation() {
var answer = confirm("Wanna visit google?")
if (answer){
window.location = "http://www.google.com/";
}
}
</script>
<style type="text/css">
body {
background-color: white;
font-family: sans-serif;
}
#jsconfirm {
border-color: #c0c0c0;
border-width: 2px 4px 4px 2px;
left: 0;
margin: 0;
padding: 0;
position: absolute;
top: -1000px;
z-index: 100;
}
#jsconfirm table {
background-color: #fff;
border: 2px groove #c0c0c0;
height: 150px;
width: 300px;
}
#jsconfirmtitle {
background-color: #B0B0B0;
font-weight: bold;
height: 20px;
text-align: center;
}
#jsconfirmbuttons {
height: 50px;
text-align: center;
}
#jsconfirmbuttons input {
background-color: #E9E9CF;
color: #000000;
font-weight: bold;
width: 125px;
height: 33px;
padding-left: 20px;
}
#jsconfirmleft{
background-image: url(left.png);
}
#jsconfirmright{
background-image: url(right.png);
}
< /style>
</head>
<body>
<p><br />
<a href="#"
onclick="javascript:showConfirm('Please confirm','Are you really really sure to visit google?','Yes','http://www.google.com','No','#')">JsConfirmStyled</a></p>
<p><a href="#" onclick="confirmation()">standard</a></p>
</body>
</html>
Then create simple js file name jsConfirmStyle.js. Here is simple js code
ie5=(document.getElementById&&document.all&&document.styleSheets)?1:0;
nn6=(document.getElementById&&!document.all)?1:0;
xConfirmStart=800;
yConfirmStart=100;
if(ie5||nn6) {
if(ie5) cs=2,th=30;
else cs=0,th=20;
document.write(
"<div id='jsconfirm'>"+
"<table>"+
"<tr><td id='jsconfirmtitle'></td></tr>"+
"<tr><td id='jsconfirmcontent'></td></tr>"+
"<tr><td id='jsconfirmbuttons'>"+
"<input id='jsconfirmleft' type='button' value='' onclick='leftJsConfirm()' onfocus='if(this.blur)this.blur()'>"+
" "+
"<input id='jsconfirmright' type='button' value='' onclick='rightJsConfirm()' onfocus='if(this.blur)this.blur()'>"+
"</td></tr>"+
"</table>"+
"</div>"
);
}
document.write("<div id='jsconfirmfade'></div>");
function leftJsConfirm() {
document.getElementById('jsconfirm').style.top=-1000;
document.location.href=leftJsConfirmUri;
}
function rightJsConfirm() {
document.getElementById('jsconfirm').style.top=-1000;
document.location.href=rightJsConfirmUri;
}
function confirmAlternative() {
if(confirm("Scipt requieres a better browser!")) document.location.href="http://www.mozilla.org";
}
leftJsConfirmUri = '';
rightJsConfirmUri = '';
/**
* Show the message/confirm box
*/
function showConfirm(confirmtitle,confirmcontent,confirmlefttext,confirmlefturi,confirmrighttext,con firmrighturi) {
document.getElementById("jsconfirmtitle").innerHTML=confirmtitle;
document.getElementById("jsconfirmcontent").innerHTML=confirmcontent;
document.getElementById("jsconfirmleft").value=confirmlefttext;
document.getElementById("jsconfirmright").value=confirmrighttext;
leftJsConfirmUri=confirmlefturi;
rightJsConfirmUri=confirmrighturi;
xConfirm=xConfirmStart, yConfirm=yConfirmStart;
if(ie5) {
document.getElementById("jsconfirm").style.left='25%';
document.getElementById("jsconfirm").style.top='35%';
}
else if(nn6) {
document.getElementById("jsconfirm").style.top='25%';
document.getElementById("jsconfirm").style.left='35%';
}
else confirmAlternative();
}
let httpParams = new HttpParams();
Object.keys(data).forEach(function (key) {
httpParams = httpParams.append(key, data[key]);
});
Since 5.0.0-beta.6 (2017-09-03) they added new feature (accept object map for HttpClient headers & params)
Going forward the object can be passed directly instead of HttpParams.
getCountries(data: any) {
// We don't need any more these lines
// let httpParams = new HttpParams();
// Object.keys(data).forEach(function (key) {
// httpParams = httpParams.append(key, data[key]);
// });
return this.httpClient.get("/api/countries", {params: data})
}
I realize this is pretty late, but I had a similar problem and I figured I'd post what worked for me. I used the iconv utility (e.g., "iconv file.pcl -f UTF-8 -t ISO-8859-1 -c"
). The "-c" option skips characters that can't be translated.
A Find/Replace solution:
Regex Find:\s+
Replace with: //single space
Date
has the time part, so we only need to extract it from Date
I personally prefer the default format
parameter of the Date
when date and time needs to be separated instead of using the extra SimpleDateFormat
Date date = new Date()
String datePart = date.format("dd/MM/yyyy")
String timePart = date.format("HH:mm:ss")
println "datePart : " + datePart + "\ttimePart : " + timePart
You can simply use padding-left:60% (for ex) to align your content to right and simultaneously wrap the content in responsive container (I required navbar in my case) to ensure it works in all examples.
df.apply(pd.value_counts).fillna(0)
value_counts - Returns object containing counts of unique values
apply - count frequency in every column. If you set axis=1
, you get frequency in every row
fillna(0) - make output more fancy. Changed NaN to 0
Including the fb:app_id
tag in your HTML HEAD will allow the Facebook scraper to associate the Open Graph entity for that URL with an application. This will allow any admins of that app to view Insights about that URL and any social plugins connected with it.
The fb:admins
tag is similar, but allows you to just specify each user ID that you would like to give the permission to do the above.
You can include either of these tags or both, depending on how many people you want to admin the Insights, etc. A single as fb:admins
is pretty much a minimum requirement. The rest of the Open Graph tags will still be picked up when people share and like your URL, however it may cause problems in the future, so please include one of the above.
fb:admins is specified like this:
<meta property="fb:admins" content="USER_ID"/>
OR
<meta property="fb:admins" content="USER_ID,USER_ID2,USER_ID3"/>
and fb:app_id like this:
<meta property="fb:app_id" content="APPID"/>
SELECT prosrc FROM pg_proc WHERE proname = 'function_name';
This tells the function handler how to invoke the function. It might be the actual source code of the function for interpreted languages, a link symbol, a file name, or just about anything else, depending on the implementation language/call convention
Starting with Python 3.6, formatting in Python can be done using formatted string literals or f-strings:
hours, minutes, seconds = 6, 56, 33
f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}'
or the str.format
function starting with 2.7:
"{:02}:{:02}:{:02} {}".format(hours, minutes, seconds, "pm" if hours > 12 else "am")
or the string formatting %
operator for even older versions of Python, but see the note in the docs:
"%02d:%02d:%02d" % (hours, minutes, seconds)
And for your specific case of formatting time, there’s time.strftime
:
import time
t = (0, 0, 0, hours, minutes, seconds, 0, 0, 0)
time.strftime('%I:%M:%S %p', t)
There is another scenario where this issue reproduces (as in my case). When THE CLIENT REQUEST doesn't contain the right extension on the url, the controller can't identify the desired result format.
For example: the controller is set to respond_to :json
(as a single option, without a HTML response)- while the client call is set to /reservations
instead of /reservations.json
.
Bottom line, change the client call to /reservations.json
.
There could be different reasons why it doesn't work for you: perhaps you need to qualify the name with std::
, or perhaps you do not have C++11 support.
This works, provided you have C++11 support:
#include <string>
int main()
{
std::string s = std::to_string(42);
}
To enable C++11 support with g++ or clang, you need to pass the option -std=c++0x
. You can also use -std=c++11
on the newer versions of those compilers.
You're using S_ISREG()
and S_ISDIR()
correctly, you're just using them on the wrong thing.
In your while((dit = readdir(dip)) != NULL)
loop in main
, you're calling stat
on currentPath
over and over again without changing currentPath
:
if(stat(currentPath, &statbuf) == -1) {
perror("stat");
return errno;
}
Shouldn't you be appending a slash and dit->d_name
to currentPath
to get the full path to the file that you want to stat
? Methinks that similar changes to your other stat
calls are also needed.
This can't be done by using a Comparator
, as it will always get the key of the map to compare. TreeMap
can only sort by the key.
1. About @Component
@Component functs similarily to @Configuration.
They both indicate that the annotated class has one or more beans need to be registered to Spring-IOC-Container
.
The class annotated by @Component, we call it Component of Spring
. It is a concept that contains several beans.
Component class
needs to be auto-scanned by Spring for registering those beans of the component class
.
2. About @Bean
@Bean is used to annotate the method of component-class
(as mentioned above). It indicate the instance retured by the annotated method needs to be registered to Spring-IOC-Container
.
3. Conclusion
The difference between them two is relatively obivious, they are used in different circumstances
.
The general usage is:
// @Configuration is implemented by @Component
@Configuration
public ComponentClass {
@Bean
public FirstBean FirstBeanMethod() {
return new FirstBean();
}
@Bean
public SecondBean SecondBeanMethod() {
return new SecondBean();
}
}
The key is in the quotes around the colon and &, i.e. rows(variable & ":" & variable).select
Adapt this:
Rows(x & ":" & y).select
where x and y are your variables.
Some other examples that may help you understand
Rows(x & ":" & x).select
Or
Rows((x+1) & ":" (x*3)).select
Or
Rows((x+2) & ":" & (y-3)).select
Hopefully you get the idea.
If you're open to a PHP solution:
<td><img src='<?PHP
$path1 = "path/to/your/image.jpg";
$path2 = "alternate/path/to/another/image.jpg";
echo file_exists($path1) ? $path1 : $path2;
?>' alt='' />
</td>
////EDIT OK, here's a JS version:
<table><tr>
<td><img src='' id='myImage' /></td>
</tr></table>
<script type='text/javascript'>
document.getElementById('myImage').src = "newImage.png";
document.getElementById('myImage').onload = function() {
alert("done");
}
document.getElementById('myImage').onerror = function() {
alert("Inserting alternate");
document.getElementById('myImage').src = "alternate.png";
}
</script>
There are different possible cause as discussed would just like to add this for someone who might have the same issue as mine.
In my case I had a missing close div as shown below
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
</head>
<body>
<div> //I am an open div
<div id="hello"></div>
<script type ="text/javascript">
what();
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>
</body>
</html>
Missing a close div can result in disorganization of the transversal from child to parent or parent to child hence resulting in an error when you try to access an element in the DOM
All tables within the bootstrap stretch according to their container, which you can easily do by placing your table inside a .span*
grid element of your choice. If you wish to remove this property you can create your own table class and simply add it to the table you want to expand with the content within:
.table-nonfluid {
width: auto !important;
}
You can add this class inside your own stylesheet and simply add it to the container of your table like so:
<table class="table table-nonfluid"> ... </table>
This way your change won't affect the bootstrap stylesheet itself (you might want to have a fluid table somewhere else in your document).
To Convert BEGIN OPENSSH PRIVATE KEY
to BEGIN RSA PRIVATE KEY
:
ssh-keygen -p -m PEM -f ~/.ssh/id_rsa
It also can happen when you try to UPDATE
a PRIMARY KEY.
The <p>
paragraph tag is meant for specifying paragraphs of text. If you don't want the text to start on a new line, I would suggest you're using the <p>
tag incorrectly. Perhaps the <span>
tag more closely fits what you want to achieve...?
The POSIX standard mandates that multiple /
are treated as a single /
in a file name. Thus
//dir///subdir////file
is the same as /dir/subdir/file
.
As such concatenating a two strings to build a complete path is a simple as:
full_path="$part1/$part2"
You can use Vim in Ex mode:
ex -sc 'a|BRAVO' -cx file
a
append text
x
save and close
Adding display:inline-block
to the labels and giving them padding-top
would fix this, I think. Also, just setting the line-height
on the labels would also.
For kotlin, you can use the below code.
fun isMyServiceRunning(calssObj: Class<SERVICE_CALL_NAME>): Boolean {
val manager = requireActivity().getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
for (service in manager.getRunningServices(Integer.MAX_VALUE)) {
if (calssObj.getName().equals(service.service.getClassName())) {
return true
}
}
return false
}
There is the solution if you need only outline without border. It's not mine. I got if from Bootstrap css file. If you specify outline: 1px auto certain_color
, you'll get thin outer line around div of certain color. In this case the specified width has no matter, even if you specify 10 px width, anyway it will be thin line. The key word in mentioned rule is "auto".
If you need outline with rounded corners and certain width, you may add css rule on border with needed width and same color. It makes outline thicker.
Make sure you have full-text search feature installed.
Create full-text search catalog.
use AdventureWorks
create fulltext catalog FullTextCatalog as default
select *
from sys.fulltext_catalogs
Create full-text search index.
create fulltext index on Production.ProductDescription(Description)
key index PK_ProductDescription_ProductDescriptionID
Before you create the index, make sure:
- you don't already have full-text search index on the table as only one full-text search index allowed on a table
- a unique index exists on the table. The index must be based on single-key column, that does not allow NULL.
- full-text catalog exists. You have to specify full-text catalog name explicitly if there is no default full-text catalog.
You can do step 2 and 3 in SQL Sever Management Studio. In object explorer, right click on a table, select Full-Text index
menu item and then Define Full-Text Index...
sub-menu item. Full-Text indexing wizard will guide you through the process. It will also create a full-text search catalog for you if you don't have any yet.
You can find more info at MSDN
No jQuery Needed
if (str.match(/[a-z]/i)) {
// alphabet letters found
}
First, make sure that the source page and the target page are both served through the file
URI scheme. You can't force an http
page to open a file
page (but it works the other way around).
Next, your script that calls window.open()
should be invoked by a user-initiated event, such as clicks, keypresses and the like. Simply calling window.open()
won't work.
You can test this right here in this question page. Run these in Chrome's JavaScript console:
// Does nothing
window.open('http://google.com');
// Click anywhere within this page and the new window opens
$(document.body).unbind('click').click(function() { window.open('http://google.com'); });
// This will open a new window, but it would be blank
$(document.body).unbind('click').click(function() { window.open('file:///path/to/a/local/html/file.html'); });
You can also test if this works with a local file. Here's a sample HTML file that simply loads jQuery:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
</head>
<body>
<h5>Feel the presha</h5>
<h3>Come play my game, I'll test ya</h3>
<h1>Psycho- somatic- addict- insane!</h1>
</body>
</html>
Then open Chrome's JavaScript console and run the statements above. The 3rd one will now work.
(in answer to the second question) By only using a sign bit (and not 2's complement), you can end up with -0. Not very pretty.
Your best bet is to add logging.level.org.springframework.web.client.RestTemplate=DEBUG
to the application.properties
file.
Other solutions like setting log4j.logger.httpclient.wire
will not always work because they assume you use log4j
and Apache HttpClient
, which is not always true.
Note, however, that this syntax will work only on latest versions of Spring Boot.
I don't know why you would need this but to do this, you could edit your css file:-
<style type="text/css">
body{
...;
...;
}
</style>
You have just added here and saved it as main.php. You can continue with main.css but it is better as .php since it does not remain a css file after you do that edit
Then edit your HTML file like this. NOTE: Make the include statement inside the tag
<html>
<head>
<title>Sample</title>
<?php inculde('css/main.css');>
</head>
<body>
...
...
</body>
</html>
MySQL
SELECT r.name,
GROUP_CONCAT(a.name SEPARATOR ',')
FROM RESOURCES r
JOIN APPLICATIONSRESOURCES ar ON ar.resource_id = r.id
JOIN APPLICATIONS a ON a.id = ar.app_id
GROUP BY r.name
**
MS SQL Server
SELECT r.name,
STUFF((SELECT ','+ a.name
FROM APPLICATIONS a
JOIN APPLICATIONRESOURCES ar ON ar.app_id = a.id
WHERE ar.resource_id = r.id
GROUP BY a.name
FOR XML PATH(''), TYPE).value('.','VARCHAR(max)'), 1, 1, '')
FROM RESOURCES r
GROUP BY deptno;
Oracle
SELECT r.name,
LISTAGG(a.name SEPARATOR ',') WITHIN GROUP (ORDER BY a.name)
FROM RESOURCES r
JOIN APPLICATIONSRESOURCES ar ON ar.resource_id = r.id
JOIN APPLICATIONS a ON a.id = ar.app_id
GROUP BY r.name;
Use:
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
The option you should use is iDisplayLength:
$('#adminProducts').dataTable({
'iDisplayLength': 100
});
$('#table').DataTable({
"lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});
It will Load by default all entries.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
If you want to load by default 25 not all do this.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
});
You are getting the error because $ret
is not an array.
To get rid of the error, at the start of your function, define it with this line: $ret = array();
It appears that the get_tags() call is returning nothing, so the foreach is not run, which means that $ret isn't defined.
In 2019 you can use querySelector for that.
It's supported by most browsers (https://caniuse.com/#search=querySelector)
document.querySelector('body').appendChild(i);
Html.Label
gives you a label for an input whose name matches the specified input text (more specifically, for the model property matching the string expression):
// Model
public string Test { get; set; }
// View
@Html.Label("Test")
// Output
<label for="Test">Test</label>
Html.LabelFor
gives you a label for the property represented by the provided expression (typically a model property):
// Model
public class MyModel
{
[DisplayName("A property")]
public string Test { get; set; }
}
// View
@model MyModel
@Html.LabelFor(m => m.Test)
// Output
<label for="Test">A property</label>
Html.LabelForModel
is a bit trickier. It returns a label whose for
value is that of the parameter represented by the model object. This is useful, in particular, for custom editor templates. For example:
// Model
public class MyModel
{
[DisplayName("A property")]
public string Test { get; set; }
}
// Main view
@Html.EditorFor(m => m.Test)
// Inside editor template
@Html.LabelForModel()
// Output
<label for="Test">A property</label>
Late to the party, but I think it is a useful answer.
flatMap
would be the shortest way to do it.
Stream.of(objects).flatMap(o->(o instanceof Client)?Stream.of((Client)o):Stream.empty())
If o
is a Client
then create a Stream with a single element, otherwise use the empty stream. These streams will then be flattened into a Stream<Client>
.
My humble construction that
.git
subfolder: low chance to emit a git command in a non-git subfolderfind
as follow:
find . \
-maxdepth 2 -type d \
-name ".git" \
-execdir python -c 'import os; print(os.path.abspath("."))' \; \
-execdir git pull \;
Of course, you may add other git commands with additional -execdir
options to find
, displaying the branch for instance:
find . \
-maxdepth 2 -type d \
-name ".git" \
-execdir python -c 'import os; print(os.path.abspath("."))' \; \
-execdir git branch \;
-execdir git pull \;
Adding on to Josh's answer,
SELECT COUNT(CASE WHEN myColumn=1 THEN AD_CurrentView.PrimaryKeyColumn ELSE NULL END)
FROM AD_CurrentView
Worked well for me (in SQL Server 2012) without changing the 'count' to a 'sum' and the same logic is portable to other 'conditional aggregates'. E.g., summing based on a condition:
SELECT SUM(CASE WHEN myColumn=1 THEN AD_CurrentView.NumberColumn ELSE 0 END)
FROM AD_CurrentView
For simple input, like two prompts and two corresponding fixed responses, you could also use a "here document", the syntax of which looks like this:
test.sh <<!
y
pasword
!
The << prefixes a pattern, in this case '!'. Everything up to a line beginning with that pattern is interpreted as standard input. This approach is similar to the suggestion to pipe a multi-line echo into ssh, except that it saves the fork/exec of the echo command and I find it a bit more readable. The other advantage is that it uses built-in shell functionality so it doesn't depend on expect.
Add to your settings.py
:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'debug.log',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}
And it will create a file called debug.log
in the root of your.
https://docs.djangoproject.com/en/1.10/topics/logging/
String1.scan(/<([^>]*)>/).last.first
scan
creates an array which, for each <item>
in String1
contains the text between the <
and the >
in a one-element array (because when used with a regex containing capturing groups, scan creates an array containing the captures for each match). last
gives you the last of those arrays and first
then gives you the string in it.
No need for jQuery! This simple snippet works fine for me. It uses angular.element() to bind window resize event.
/**
* Window resize event handling
*/
angular.element($window).on('resize', function () {
console.log($window.innerWidth);
});
/**
* Window resize unbind event
*/
angular.element($window).off('resize');
Code To Get Today's date in any specific Format
You can define the desired format in SimpleDateFormat instance to get the date in that specific formate
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
String todaysdate = dateFormat.format(date);
System.out.println("Today's date : " + todaysdate);
Follow below links to see the valid date format combination.
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
CODE : To get x days ahead or Previous from Today's date, To get the past date or Future date.
For Example :
Today date : 11/27/2018
xdayFromTodaysDate = 2 to get date as 11/29/2018
xdayFromTodaysDate = -2 to get date as 11/25/2018
public String getAniversaryDate(int xdayFromTodaysDate ){
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH,xdayFromTodaysDate);
date = cal.getTime();
String aniversaryDate = dateFormat.format(date);
LOGGER.info("Today's date : " + todaysdate);
return aniversaryDate;
}
CODE : To get x days ahead or Previous from a Given date
public String getAniversaryDate(String givendate, int xdayFromTodaysDate ){
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
try {
Date date = dateFormat.parse(givendate);
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH,xdayFromTodaysDate);
date = cal.getTime();
String aniversaryDate = dateFormat.format(date);
LOGGER.info("aniversaryDate : " + aniversaryDate);
return aniversaryDate;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
I took what you had, and added another X-Testing
header
var config = {headers: {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose',
"X-Testing" : "testing"
}
};
$http.get("/test", config);
And in the Chrome network tab, I see them being sent.
GET /test HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Accept: application/json;odata=verbose
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22
Authorization: Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==
X-Testing: testing
Referer: http://localhost:3000/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Are you not seeing them from the browser, or on the server? Try the browser tooling or a debug proxy and see what is being sent out.
First of all, shouldn't there be a CustomerId in the Invoices table? As it is, You can't perform this query for Invoices that have no payments on them as yet. If there are no payments on an invoice, that invoice will not even show up in the ouput of the query, even though it's an outer join...
Also, When a customer makes a payment, how do you know what Invoice to attach it to ? If the only way is by the InvoiceId on the stub that arrives with the payment, then you are (perhaps inappropriately) associating Invoices with the customer that paid them, rather than with the customer that ordered them... . (Sometimes an invoice can be paid by someone other than the customer who ordered the services)
And then there is the somewhat older recode program.
I realize the following suggestion doesn't answer your question, but the simplest method I have found to capture a rapidly-changing DirectX view, is to plug a video camera into the S-video port of the video card, and record the images as a movie. Then transfer the video from the camera back to an MPG, WMV, AVI etc. file on the computer.
The problem is that you're putting .name class instead of nameclass
Regan's answer is great, but it's a bit out of date, since the correct way to do this is avoid the lxc execution context as Docker has dropped LXC as the default execution context as of docker 0.9.
Instead it's better to tell docker about the nvidia devices via the --device flag, and just use the native execution context rather than lxc.
These instructions were tested on the following environment:
See CUDA 6.5 on AWS GPU Instance Running Ubuntu 14.04 to get your host machine setup.
$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 36A1D7869245C8950F966E92D8576A8BA88D21E9
$ sudo sh -c "echo deb https://get.docker.com/ubuntu docker main > /etc/apt/sources.list.d/docker.list"
$ sudo apt-get update && sudo apt-get install lxc-docker
ls -la /dev | grep nvidia
crw-rw-rw- 1 root root 195, 0 Oct 25 19:37 nvidia0
crw-rw-rw- 1 root root 195, 255 Oct 25 19:37 nvidiactl
crw-rw-rw- 1 root root 251, 0 Oct 25 19:37 nvidia-uvm
I've created a docker image that has the cuda drivers pre-installed. The dockerfile is available on dockerhub if you want to know how this image was built.
You'll want to customize this command to match your nvidia devices. Here's what worked for me:
$ sudo docker run -ti --device /dev/nvidia0:/dev/nvidia0 --device /dev/nvidiactl:/dev/nvidiactl --device /dev/nvidia-uvm:/dev/nvidia-uvm tleyden5iwx/ubuntu-cuda /bin/bash
This should be run from inside the docker container you just launched.
Install CUDA samples:
$ cd /opt/nvidia_installers
$ ./cuda-samples-linux-6.5.14-18745345.run -noprompt -cudaprefix=/usr/local/cuda-6.5/
Build deviceQuery sample:
$ cd /usr/local/cuda/samples/1_Utilities/deviceQuery
$ make
$ ./deviceQuery
If everything worked, you should see the following output:
deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 6.5, CUDA Runtime Version = 6.5, NumDevs = 1, Device0 = GRID K520
Result = PASS
If the response is in json you could do something like (python3):
import json
import requests as reqs
# Make the HTTP request.
response = reqs.get('http://demo.ckan.org/api/3/action/group_list')
# Use the json module to load CKAN's response into a dictionary.
response_dict = json.loads(response.text)
for i in response_dict:
print("key: ", i, "val: ", response_dict[i])
To see everything in the response you can use .__dict__
:
print(response.__dict__)
Let me make it simple and clear. Lets use the re module in python to escape the special characters.
Python script :
import re
s = "C:\Users\Josh\Desktop"
print s
print re.escape(s)
Output :
C:\Users\Josh\Desktop
C:\\Users\\Josh\\Desktop
Explanation :
Now observe that re.escape function on escaping the special chars in the given string we able to add an other backslash before each backslash, and finally the output results in a double backslash, the desired output.
Hope this helps you.
3 characters before and 4 characters after
$> echo "some123_string_and_another" | grep -o -P '.{0,3}string.{0,4}'
23_string_and
Meet same Issue on one mac, but ok on another mac. I'm sure bundle ID is fine and unique.
I know it is provisioning profile issue, so Try refreshing the provisioning profile on your Local computer. Then It Works!
cd ~/Library/MobileDevice/Provisioning\ Profiles
rm *
Download Manual Profiles
You want to use absolute positioning.
An absolute position element is positioned relative to the first parent element that has a position other than static. If no such element is found, the containing block is html
For instance :
.yourDiv{
position:absolute;
top: 123px;
}
To get it to work, the parent needs to be relative (position:relative
)
In your case this should do the trick:
.suggestionsBox{position:absolute; top:40px;}
#specific_locations_add{position:relative;}
It turns out that Popper.js doesn't provide compiled files on its GitHub repository. Therefore, one has to compile the project on his/her own or download compiled files from CDNs. It cannot be automatically imported.
See the crypto.createHash()
function and the associated hash.update()
and hash.digest()
functions:
var crypto = require('crypto')
var shasum = crypto.createHash('sha1')
shasum.update('foo')
shasum.digest('hex') // => "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"
Ookii folder dialog can be found at Nuget.
PM> Install-Package Ookii.Dialogs.Wpf
And, example code is as below.
var dialog = new Ookii.Dialogs.Wpf.VistaFolderBrowserDialog();
if (dialog.ShowDialog(this).GetValueOrDefault())
{
textBoxFolderPath.Text = dialog.SelectedPath;
}
More information on how to use it: https://github.com/augustoproiete/ookii-dialogs-wpf
$("input:checkbox").click(function(){
if ($("input:checkbox:checked").length > 3){
return false;
}
});
To solve a similar problem, I'm using groupby
:
print(f"Distinct entries: {len(df.groupby(['col1', 'col2']))}")
Whether that's appropriate will depend on what you want to do with the result, though (in my case, I just wanted the equivalent of COUNT DISTINCT
as shown).
I basically add one line which they are
to UsersController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using UserDataAccess;
namespace SBPMS.Controllers
{
public class UsersController : ApiController
{
public IEnumerable<User> Get() {
using (SBPMSystemEntities entities = new SBPMSystemEntities()) {
entities.Configuration.ProxyCreationEnabled = false;
return entities.Users.ToList();
}
}
public User Get(int id) {
using (SBPMSystemEntities entities = new SBPMSystemEntities()) {
entities.Configuration.ProxyCreationEnabled = false;
return entities.Users.FirstOrDefault(e => e.user_ID == id);
}
}
}
}
format
supports a percentage floating point precision type:
>>> print "{0:.0%}".format(1./3)
33%
If you don't want integer division, you can import Python3's division from __future__
:
>>> from __future__ import division
>>> 1 / 3
0.3333333333333333
# The above 33% example would could now be written without the explicit
# float conversion:
>>> print "{0:.0f}%".format(1/3 * 100)
33%
# Or even shorter using the format mini language:
>>> print "{:.0%}".format(1/3)
33%
In addition to making the web.config changes for <assemblies>
and <namespaces>
, I found that GAC'ing the assembly made a big difference. You can apply culture and public key token like any core .NET assembly that is registered globally.
Some may shudder at the mention of the GAC. But as a BizTalk developer I've grown to embrace it.
If you see the dollar sign ($) or double dollar sign ($$), and are curious as to what this means in the Prototype framework, here is your answer:
$$('div');
// -> all DIVs in the document. Same as document.getElementsByTagName('div')!
$$('#contents');
// -> same as $('contents'), only it returns an array anyway (even though IDs must be unique within a document).
$$('li.faux');
// -> all LI elements with class 'faux'
Source:
http://www.prototypejs.org/api/utility/dollar-dollar
If there were no staged changes before the git stash pop
, as in the question, then the following two commands should work.
git diff --name-only --cached | xargs git checkout --ours HEAD
git ls-tree stash@{0}^3 --name-only | xargs rm
The first reverses any merges from the stash, successful or not. The second deletes any untracked files introduced by the stash.
From man git stash
: The working directory must match the index.
Which @DavidG points out, the stash pop
will fail if any currently unstaged modified files conflict. As such, we shouldn't need to worry about unwinding merge conflicts beyond getting back to HEAD
. Any remaining modified files are then unrelated to the stash, and were modified before the stash pop
If there were staged changes, I'm unclear on whether we can rely on the same commands and you may want to try @Ben Jackson's technique. Suggestions appreciated..
Here is a testing setup for all of the various cases https://gist.github.com/here/4f3af6dafdb4ca15e804
# Result:
# Merge succeeded in m (theirs)
# Conflict in b
# Unstaged in a
# Untracked in c and d
# Goal:
# Reverse changes to successful merge m
# Keep our version in merge conflict b
# Keep our unstaged a
# Keep our untracked d
# Delete stashed untracked c
I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"
in my .html
<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">
then in my component.ts
reSearch(newValue: string) {
//this.searchText would equal the new value
//handle my filtering with the new value
}
If you know the text in the combo box that you want to select, just use the setCurrentText() method to select that item.
ui->comboBox->setCurrentText("choice 2");
From the Qt 5.7 documentation
The setter setCurrentText() simply calls setEditText() if the combo box is editable. Otherwise, if there is a matching text in the list, currentIndex is set to the corresponding index.
So as long as the combo box is not editable, the text specified in the function call will be selected in the combo box.
Reference: http://doc.qt.io/qt-5/qcombobox.html#currentText-prop
The code works as best I can tell. I would fire up Sysinternals process explorer and find out what is holding the file open. It might very well be Visual Studio.
Use with:
{% with "shop/"|add:shop_name|add:"/base.html" as template %}
{% include template %}
{% endwith %}
Linux manual said:
EPIPE The local end has been shut down on a connection oriented socket. In this case the process will also receive a SIGPIPE unless MSG_NOSIGNAL is set.
But for Ubuntu 12.04 it isn't right. I wrote a test for that case and I always receive EPIPE withot SIGPIPE. SIGPIPE is genereated if I try to write to the same broken socket second time. So you don't need to ignore SIGPIPE if this signal happens it means logic error in your program.
There are different ways. If you just want to check if one list contains any element from the other list, you can do this..
not set(list1).isdisjoint(list2)
I believe using isdisjoint
is better than intersection
for Python 2.6 and above.
I am the author of the source code at the specified link. While the intention of the source code license is not clear (it will be later today), the code is in fact open and free for use in your free or commercial applications with no strings attached.
for i=1,#target do
game.Players.target[i].Character:BreakJoints()
end
Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:
game.Players.target.1.Character:BreakJoints()
Which is completely incorrect.
c = game.Players:GetChildren()
Never use "Players:GetChildren()", it is not guaranteed to return only players.
Instead use:
c = Game.Players:GetPlayers()
if msg:lower()=="me" then
table.insert(people, source)
return people
Here you add the player's name in the list "people", where you in the other places adds the player object.
Fixed code:
local Admins = {"FakeNameHereSoNoStalkers"}
function Kill(Players)
for i,Player in ipairs(Players) do
if Player.Character then
Player.Character:BreakJoints()
end
end
end
function IsAdmin(Player)
for i,AdminName in ipairs(Admins) do
if Player.Name:lower() == AdminName:lower() then return true end
end
return false
end
function GetPlayers(Player,Msg)
local Targets = {}
local Players = Game.Players:GetPlayers()
if Msg:lower() == "me" then
Targets = { Player }
elseif Msg:lower() == "all" then
Targets = Players
elseif Msg:lower() == "others" then
for i,Plr in ipairs(Players) do
if Plr ~= Player then
table.insert(Targets,Plr)
end
end
else
for i,Plr in ipairs(Players) do
if Plr.Name:lower():sub(1,Msg:len()) == Msg then
table.insert(Targets,Plr)
end
end
end
return Targets
end
Game.Players.PlayerAdded:connect(function(Player)
if IsAdmin(Player) then
Player.Chatted:connect(function(Msg)
if Msg:lower():sub(1,6) == ":kill " then
Kill(GetPlayers(Player,Msg:sub(7)))
end
end)
end
end)
You can try element[0].scrollTop, in my opinion this solution is faster.
Here you have bigger example - http://cvmlrobotics.blogspot.de/2013/03/angularjs-get-element-offset-position.html
Using aggregate
:
aggregate(x$Frequency, by=list(Category=x$Category), FUN=sum)
Category x
1 First 30
2 Second 5
3 Third 34
In the example above, multiple dimensions can be specified in the list
. Multiple aggregated metrics of the same data type can be incorporated via cbind
:
aggregate(cbind(x$Frequency, x$Metric2, x$Metric3) ...
(embedding @thelatemail comment), aggregate
has a formula interface too
aggregate(Frequency ~ Category, x, sum)
Or if you want to aggregate multiple columns, you could use the .
notation (works for one column too)
aggregate(. ~ Category, x, sum)
or tapply
:
tapply(x$Frequency, x$Category, FUN=sum)
First Second Third
30 5 34
Using this data:
x <- data.frame(Category=factor(c("First", "First", "First", "Second",
"Third", "Third", "Second")),
Frequency=c(10,15,5,2,14,20,3))
I created a Bootstrap plugin that incorporates a lot of the ideas posted here.
Demo on Bootply: http://www.bootply.com/cObcYInvpq
Github: https://github.com/jhaygt/bootstrap-multimodal
It also addresses the issue with successive modals causing the backdrop to become darker and darker. This ensures that only one backdrop is visible at any given time:
if(modalIndex > 0)
$('.modal-backdrop').not(':first').addClass('hidden');
The z-index of the visible backdrop is updated on both the show.bs.modal
and hidden.bs.modal
events:
$('.modal-backdrop:first').css('z-index', MultiModal.BASE_ZINDEX + (modalIndex * 20));
public void myfunction(){
try
{
sqlcon.Open();
SqlCommand cmd = new SqlCommand("sp_laba", sqlcon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sqlcon.Close();
}
}
Please note if you are downloading from the FTP to your local, you will need to use the following:
with open( filename, 'wb' ) as file :
ftp.retrbinary('RETR %s' % filename, file.write)
Otherwise, the script will at your local file storage rather than the FTP.
I spent a few hours making the mistake myself.
Script below:
import ftplib
# Open the FTP connection
ftp = ftplib.FTP()
ftp.cwd('/where/files-are/located')
filenames = ftp.nlst()
for filename in filenames:
with open( filename, 'wb' ) as file :
ftp.retrbinary('RETR %s' % filename, file.write)
file.close()
ftp.quit()
The STAThreadAttribute marks a thread to use the Single-Threaded COM Apartment if COM is needed. By default, .NET won't initialize COM at all. It's only when COM is needed, like when a COM object or COM Control is created or when drag 'n' drop is needed, that COM is initialized. When that happens, .NET calls the underlying CoInitializeEx function, which takes a flag indicating whether to join the thread to a multi-threaded or single-threaded apartment.
Read more info here (Archived, June 2009)
and
I had this issue and it took me for a while to figure out how to fix that.
My case is slightly different. My MySQL server is of version 5.1.x. And somehow I upgraded my MySQL-python from 1.2.3 to 1.2.5. And I kept getting this issue since then event I added the following soft link.
libmysqlclient.18.dylib -> /usr/local/mysql/lib/libmysqlclient.18.dylib
It turns out that for MySQL 5.1.x there is no libmysqlclient.18.dylib, but only libmysqlclient.16.dylib. You can fix this issue either by downgrade your MySQL-python to 1.2.3 or upgrade your MySQL server to 5.6.x (I haven't tried 5.5.x.)
I downgraded the library to 1.2.3 since upgrading MySQL is not an option for me.
<form id="upload_form" enctype="multipart/form-data">
jQuery with CodeIgniter file upload:
var formData = new FormData($('#upload_form')[0]);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
url: base_url + "member/upload/",
data: formData,
//use contentType, processData for sure.
contentType: false,
processData: false,
beforeSend: function() {
$('.modal .ajax_data').prepend('<img src="' +
base_url +
'"asset/images/ajax-loader.gif" />');
//$(".modal .ajax_data").html("<pre>Hold on...</pre>");
$(".modal").modal("show");
},
success: function(msg) {
$(".modal .ajax_data").html("<pre>" + msg +
"</pre>");
$('#close').hide();
},
error: function() {
$(".modal .ajax_data").html(
"<pre>Sorry! Couldn't process your request.</pre>"
); //
$('#done').hide();
}
});
you can use.
var form = $('form')[0];
var formData = new FormData(form);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
or
var formData = new FormData($('#upload_form')[0]);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
Both will work.
I faced the issue with my web application based on Spring 3 and deployed on Weblogic 10.3 on Oracle Linux 6. The solution mentioned at the link did not work for me.
I had to take the following steps - 1. Copy the Arial*.ttf font files to JROCKIT_JAVA_HOME/jre/lib/fonts directory 2. Make entries of the fonts in fontconfig.properties.src 3. Restart the cluster from Weblogic console
filename.Arial=Arial.ttf
filename.Arial_Bold=Arial_Bold.ttf
filename.Arial_Italic=Arial_Italic.ttf
filename.Arial_Bold_Italic=Arial_Bold_Italic.ttf
array_pop(explode("/", "http://vimeo.com/1234567"));
will return the last element of the example url
It looks like you're writing PHP, in which case you want:
<?
$arr=array('us'=>'United', 'ca'=>'canada');
$key='ca';
echo $arr[$key];
?>
Notice that the ('us'=>'United', 'ca'=>'canada')
needs to be a parameter to the array function in PHP.
Most programming languages that support associative arrays or dictionaries use arr['key']
to retrieve the item specified by 'key'
For instance:
ruby-1.9.1-p378 > h = {'us' => 'USA', 'ca' => 'Canada' }
=> {"us"=>"USA", "ca"=>"Canada"}
ruby-1.9.1-p378 > h['ca']
=> "Canada"
>>> h = {'us':'USA', 'ca':'Canada'}
>>> h['ca']
'Canada'
#
class P
{
static void Main()
{
var d = new System.Collections.Generic.Dictionary<string, string> { {"us", "USA"}, {"ca", "Canada"}};
System.Console.WriteLine(d["ca"]);
}
}
t = {us='USA', ca='Canada'}
print(t['ca'])
print(t.ca) -- Lua's a little different with tables
My solution:
<style type="text/css" media="print">
@page {
size: landscape;
}
body {
writing-mode: tb-rl;
}
</style>
This works in IE
, Firefox
and Chrome
// Get unique value for table 'add_new_videos' column name 'project_id'
$project_id = DB::table('add_new_videos')->distinct()->get(['project_id']);
Using GhostScript from the command line, I've used the following in the past:
on Windows:
gswin32c -dNOPAUSE -q -g300x300 -sDEVICE=tiffg4 -dBATCH -sOutputFile=output_file_name.tif input_file_name.pdf
on *nix:
gs -dNOPAUSE -q -g300x300 -sDEVICE=tiffg4 -dBATCH -sOutputFile=output_file_name.tif input_file_name.pdf
For a large number of files, a simple batch/shell script could be used to convert an arbitrary number of files...
i'll toss in since none of the present solutions yield a tuple:
temp3 = tuple(set(temp1) - set(temp2))
alternatively:
#edited using @Mark Byers idea. If you accept this one as answer, just accept his instead.
temp3 = tuple(x for x in temp1 if x not in set(temp2))
Like the other non-tuple yielding answers in this direction, it preserves order
Each MAX function is evaluated individually. So MAX(CompletedDate) will return the value of the latest CompletedDate column and MAX(Notes) will return the maximum (i.e. alphabeticaly highest) value.
You need to structure your query differently to get what you want. This question had actually already been asked and answered several times, so I won't repeat it:
How to find the record in a table that contains the maximum value?
JSON is simpler and faster than PHP's serialization format and should be used unless:
json_decode()
: "This function will return false if the JSON encoded data is deeper than 127 elements."The -u flag is specifying that you want to link your local branch to the upstream branch. This will also create an upstream branch if one does not exist. None of these answers cover how i do it (in complete form) so here it is:
git push -u origin <your-local-branch-name>
So if your local branch name is coffee
git push -u origin coffee
This code is working in Swift3:
yourTextFieldName .setValue(UIColor.init(colorLiteralRed: 80/255, green: 80/255, blue: 80/255, alpha: 1.0), forKeyPath: "_placeholderLabel.textColor")
let me know if you have any issue.
Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.
You've got:
//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]
Which translates into:
Get me all the elements that have an ID
that contains ctl00_btnAircraftMapCell
. Out of these elements, get any child elements that have a title
that contains Select Seat
.
What you actually want is:
//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]
Which translates into:
Get me all the anchor elements that have both: an id
that contains ctl00_btnAircraftMapCell
and a title
that contains Select Seat
.
As has been suggested, using the string.format method is nice and simple and very readable.
In vb.net the " + " is used for addition and the " & " is used for string concatenation.
In your example:
MsgBox("Variable = " + variable)
becomes:
MsgBox("Variable = " & variable)
I may have been a bit quick answering this as it appears these operators can both be used for concatenation, but recommended use is the "&", source http://msdn.microsoft.com/en-us/library/te2585xw(v=VS.100).aspx
maybe call
variable.ToString()
update:
Use string interpolation (vs2015 onwards I believe):
MsgBox($"Variable = {variable}")
It is simpler to use a file (req.xml
in my case) with content you want to send -- like this:
curl -H "Content-Type: text/xml" -d @req.xml -X POST http://localhost/asdf
You should consider using type 'application/xml', too (differences explained here)
Alternatively, without needing making curl actually read the file, you can use cat
to spit the file into the stdout and make curl
to read from stdout like this:
cat req.xml | curl -H "Content-Type: text/xml" -d @- -X POST http://localhost/asdf
Both examples should produce identical service output.
If you are using Statement
, go for the following
//MY_NUMBER is the column name in the database
String generatedColumns[] = {"MY_NUMBER"};
Statement stmt = conn.createStatement();
//String sql holds the insert query
stmt.executeUpdate(sql, generatedColumns);
ResultSet rs = stmt.getGeneratedKeys();
// The generated id
if(rs.next())
long key = rs.getLong(1);
If you are using PreparedStatement
, go for the following
String generatedColumns[] = {"MY_NUMBER"};
PreparedStatement pstmt = conn.prepareStatement(sql,generatedColumns);
pstmt.setString(1, "qwerty");
pstmt.execute();
ResultSet rs = pstmt.getGeneratedKeys();
if(rs.next())
long key = rs.getLong(1);
If you use .NET as your middle tier, check the route attribute clearly, for example,
I had issue when it was like this,
[Route("something/{somethingLong: long}")] //Space.
Fixed it by this,
[Route("something/{somethingLong:long}")] //No space
You can create a macro for Ctrl +Shift + S (for example) that do all this things:
Edit > Macros > Start Macro Recording (the recording will start). Click where you need.
For example:
Code > Reformat Code
Code > Auto-Indent Lines
Code > Optimize Imports
Code > Rearrange Code
File > Save All
... (all that you want)
Then, click on red button in bottom-right of the IDE to stop the Macro recording.
Set a macro name.
Go to File > Settings > Macros > YOUR MACRO NAME.
Right Click > Add Keyboard Shortcut, and type Ctrl + Shift + S.
This is working in ASP .NET MVC 4 In any controller action you can write: 1stline gets the whole url+Query String. 2nd line remove local path & query ,last '/' symbol. 3rd line add '/' symbol at last position.
Uri url = System.Web.HttpContext.Current.Request.Url;
string UrlLink = url.OriginalString.Replace(url.PathAndQuery,"");
UrlLink = String.Concat(UrlLink,"/" );
It's a destructor. The function is guaranteed to be called when the object goes out of scope.
Try using below command implemented in Git 1.8.4.
git log -u -L <upperLimit>,<lowerLimit>:<path_to_filename>
So, in your case upperLimit
& lowerLimit
is the touched line_number
More info - https://www.techpurohit.com/list-some-useful-git-commands
Why don't you just right click on the table and then properties -> Storage and it would tell you the row count. You can use the below for row count in a view
SELECT SUM (row_count)
FROM sys.dm_db_partition_stats
WHERE object_id=OBJECT_ID('Transactions')
AND (index_id=0 or index_id=1)`
HTML
<div class="row">
<div class="col-xs-2 pull-bottom"
style="height:100px;background:blue">
</div>
<div class="col-xs-8 pull-bottom"
style="height:50px;background:yellow">
</div>
</div>
CSS
.pull-bottom {
display: inline-block;
vertical-align: bottom;
float: none;
}
Use ==
:
pip install django_modeltranslation==0.4.0-beta2
Simple implementation of BST in Python
class TreeNode:
def __init__(self, value):
self.left = None
self.right = None
self.data = value
class Tree:
def __init__(self):
self.root = None
def addNode(self, node, value):
if(node==None):
self.root = TreeNode(value)
else:
if(value<node.data):
if(node.left==None):
node.left = TreeNode(value)
else:
self.addNode(node.left, value)
else:
if(node.right==None):
node.right = TreeNode(value)
else:
self.addNode(node.right, value)
def printInorder(self, node):
if(node!=None):
self.printInorder(node.left)
print(node.data)
self.printInorder(node.right)
def main():
testTree = Tree()
testTree.addNode(testTree.root, 200)
testTree.addNode(testTree.root, 300)
testTree.addNode(testTree.root, 100)
testTree.addNode(testTree.root, 30)
testTree.printInorder(testTree.root)
This thread helped me a lot with my problem, but I've used $.queue in a different way and thought I would post what I came up with here. What I needed was a sequence of events (frames) to be triggered, but the sequence to be built dynamically. I have a variable number of placeholders, each of which should contain an animated sequence of images. The data is held in an array of arrays, so I loop through the arrays to build each sequence for each of the placeholders like this:
/* create an empty queue */
var theQueue = $({});
/* loop through the data array */
for (var i = 0; i < ph.length; i++) {
for (var l = 0; l < ph[i].length; l++) {
/* create a function which swaps an image, and calls the next function in the queue */
theQueue.queue("anim", new Function("cb", "$('ph_"+i+"' img').attr('src', '/images/"+i+"/"+l+".png');cb();"));
/* set the animation speed */
theQueue.delay(200,'anim');
}
}
/* start the animation */
theQueue.dequeue('anim');
This is a simplified version of the script I have arrived at, but should show the principle - when a function is added to the queue, it is added using the Function constructor - this way the function can be written dynamically using variables from the loop(s). Note the way the function is passed the argument for the next() call, and this is invoked at the end. The function in this case has no time dependency (it doesn't use $.fadeIn or anything like that), so I stagger the frames using $.delay.
For Apache, you can use mod_ssl
to force SSL with the SSLRequireSSL Directive
:
This directive forbids access unless HTTP over SSL (i.e. HTTPS) is enabled for the current connection. This is very handy inside the SSL-enabled virtual host or directories for defending against configuration errors that expose stuff that should be protected. When this directive is present all requests are denied which are not using SSL.
This will not do a redirect to https though. To redirect, try the following with mod_rewrite
in your .htaccess file
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
or any of the various approaches given at
You can also solve this from within PHP in case your provider has disabled .htaccess (which is unlikely since you asked for it, but anyway)
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
if(!headers_sent()) {
header("Status: 301 Moved Permanently");
header(sprintf(
'Location: https://%s%s',
$_SERVER['HTTP_HOST'],
$_SERVER['REQUEST_URI']
));
exit();
}
}
Instead of using valueOf(long)
and parse()
, you can directly use the BigInteger constructor that takes a string argument:
BigInteger numBig = new BigInteger("8599825996872482982482982252524684268426846846846846849848418418414141841841984219848941984218942894298421984286289228927948728929829");
That should give you the desired value.
You have to set ANDROID_HOME
variable to SDK.
Create a new variable by the name and set it to the installation directory.
Make sure SDK is not below 2 subfolders from c drive or any windows root drive.
The most elegant way would be to update the struct fields directly, without having to use the update()
function - but maybe there are good reasons for using it that don't come across in the question.
struct foo* bar = get_foo_ptr();
foo_ref.id = 42;
foo_ref.current_route = new_route;
Or you can, like Pukku suggested, create separate access functions for each field of the struct.
Otherwise the best solution I can think of is treating a value of '0' in a struct field as a 'do not update' flag - so you just create a funciton to return a zeroed out struct, and then use this to update.
struct foo empty_foo(void)
{
struct foo bar;
bzero(&bar, sizeof (struct bar));
return bar;
}
struct foo bar = empty_foo();
bar.id=42;
bar.current_route = new_route;
update(&bar);
However, this might not be very feasible, if 0 is a valid value for fields in the struct.