Here's the answer to all your questions: http://wiki.python.org/moin/PythonEditors
One more point to add.Along with above upvoted answers, please make sure the below line is added to app.py
file:
app = Flask(__name__, static_folder="your path to static")
Otherwise flask will not be able to detect static folder.
As adapted from Erika Ehrli's blog, this should do it:
XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");
// Save the document to a file and auto-indent the output.
using (XmlTextWriter writer = new XmlTextWriter("data.xml", null)) {
writer.Formatting = Formatting.Indented;
doc.Save(writer);
}
I believe this is much simpler;
dynamic obj = JObject.Parse(jsonString);
string results = obj.results;
foreach(string result in result.Split('))
{
//Todo
}
Not answering to your direct questions, since there are already a lot of detailed answers, but it's worth mentioning, that to the contrary of Android documentation, Android Studio is suggesting to use the same version for compileSDKVersion
and targetSDKVersion
.
For arrays where the elements are neither Hashable nor Comparable (e.g. complex objects, dictionaries or structs), this extension provides a generalized way to remove duplicates:
extension Array
{
func filterDuplicate<T:Hashable>(_ keyValue:(Element)->T) -> [Element]
{
var uniqueKeys = Set<T>()
return filter{uniqueKeys.insert(keyValue($0)).inserted}
}
func filterDuplicate<T>(_ keyValue:(Element)->T) -> [Element]
{
return filterDuplicate{"\(keyValue($0))"}
}
}
// example usage: (for a unique combination of attributes):
peopleArray = peopleArray.filterDuplicate{ ($0.name, $0.age, $0.sex) }
or...
peopleArray = peopleArray.filterDuplicate{ "\(($0.name, $0.age, $0.sex))" }
You don't have to bother with making values Hashable and it allows you to use different combinations of fields for uniqueness.
Note: for a more robust approach, please see the solution proposed by Coeur in the comments below.
stackoverflow.com/a/55684308/1033581
[EDIT] Swift 4 alternative
With Swift 4.2 you can use the Hasher class to build a hash much easier. The above extension could be changed to leverage this :
extension Array
{
func filterDuplicate(_ keyValue:((AnyHashable...)->AnyHashable,Element)->AnyHashable) -> [Element]
{
func makeHash(_ params:AnyHashable ...) -> AnyHashable
{
var hash = Hasher()
params.forEach{ hash.combine($0) }
return hash.finalize()
}
var uniqueKeys = Set<AnyHashable>()
return filter{uniqueKeys.insert(keyValue(makeHash,$0)).inserted}
}
}
The calling syntax is a little different because the closure receives an additional parameter containing a function to hash a variable number of values (which must be Hashable individually)
peopleArray = peopleArray.filterDuplicate{ $0($1.name, $1.age, $1.sex) }
It will also work with a single uniqueness value (using $1 and ignoring $0).
peopleArray = peopleArray.filterDuplicate{ $1.name }
I was able to setup a SSL certificated for a domain AND multiple subdomains by using using --cert-name
combined with --expand
options.
See official certbot-auto documentation at https://certbot.eff.org/docs/using.html
Example:
certbot-auto certonly --cert-name mydomain.com.br \
--renew-by-default -a webroot -n --expand \
--webroot-path=/usr/share/nginx/html \
-d mydomain.com.br \
-d www.mydomain.com.br \
-d aaa1.com.br \
-d aaa2.com.br \
-d aaa3.com.br
.str.get
This is the simplest to specify string methods
# Setup
df = pd.DataFrame({'A': ['xyz', 'abc', 'foobar'], 'B': [123, 456, 789]})
df
A B
0 xyz 123
1 abc 456
2 foobar 789
df.dtypes
A object
B int64
dtype: object
For string (read:object
) type columns, use
df['C'] = df['A'].str[0]
# Similar to,
df['C'] = df['A'].str.get(0)
.str
handles NaNs by returning NaN as the output.
For non-numeric columns, an .astype
conversion is required beforehand, as shown in @Ed Chum's answer.
# Note that this won't work well if the data has NaNs.
# It'll return lowercase "n"
df['D'] = df['B'].astype(str).str[0]
df
A B C D
0 xyz 123 x 1
1 abc 456 a 4
2 foobar 789 f 7
There is enough evidence to suggest a simple list comprehension will work well here and probably be faster.
# For string columns
df['C'] = [x[0] for x in df['A']]
# For numeric columns
df['D'] = [str(x)[0] for x in df['B']]
df
A B C D
0 xyz 123 x 1
1 abc 456 a 4
2 foobar 789 f 7
If your data has NaNs, then you will need to handle this appropriately with an if
/else
in the list comprehension,
df2 = pd.DataFrame({'A': ['xyz', np.nan, 'foobar'], 'B': [123, 456, np.nan]})
df2
A B
0 xyz 123.0
1 NaN 456.0
2 foobar NaN
# For string columns
df2['C'] = [x[0] if isinstance(x, str) else np.nan for x in df2['A']]
# For numeric columns
df2['D'] = [str(x)[0] if pd.notna(x) else np.nan for x in df2['B']]
A B C D
0 xyz 123.0 x 1
1 NaN 456.0 NaN 4
2 foobar NaN f NaN
Let's do some timeit tests on some larger data.
df_ = df.copy()
df = pd.concat([df_] * 5000, ignore_index=True)
%timeit df.assign(C=df['A'].str[0])
%timeit df.assign(D=df['B'].astype(str).str[0])
%timeit df.assign(C=[x[0] for x in df['A']])
%timeit df.assign(D=[str(x)[0] for x in df['B']])
12 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
27.1 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
3.77 ms ± 110 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
7.84 ms ± 145 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
List comprehensions are 4x faster.
Don't do it inside the loop. Make a list, then combine them outside the loop.
datalist = list()
for (i in 1:5) {
# ... make some data
dat <- data.frame(x = rnorm(10), y = runif(10))
dat$i <- i # maybe you want to keep track of which iteration produced it?
datalist[[i]] <- dat # add it to your list
}
big_data = do.call(rbind, datalist)
# or big_data <- dplyr::bind_rows(datalist)
# or big_data <- data.table::rbindlist(datalist)
This is a much more R-like way to do things. It can also be substantially faster, especially if you use dplyr::bind_rows
or data.table::rbindlist
for the final combining of data frames.
The -L
merely gives the path where to find the .a
or .so
file. What you're looking for is to add -lmine
to the LIBS
variable.
Make that -static -lmine
to force it to pick the static library (in case both static and dynamic library exist).
Addition: Suppose the path to the file has been conveyed to the linker (or compiler driver) via -L
you can also specifically tell it to link libfoo.a
by giving -l:libfoo.a
. Note that in this case the name includes the conventional lib
-prefix. You can also give a full path this way. Sometimes this is the better method to "guide" the linker to the right location.
The consensus here is to put the global variables in a static class as static members. When you create a new Windows Forms application, it usually comes with a Program class (Program.cs), which is a static class and serves as the main entry point of the application. It lives for the the whole lifetime of the app, so I think it is best to put the global variables there instead of creating a new one.
static class Program
{
public static string globalString = "This is a global string.";
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
And use it as such:
public partial class Form1 : Form
{
public Form1()
{
Program.globalString = "Accessible in Form1.";
InitializeComponent();
}
}
check your DNS settings ...I was facing similar problem ... when I checked my /etc/resolve.config file ,the name server was missing ... after adding it the problem gets resolved
Had same problem with some non-licensed cables. Works fine with Apple's & Belkin's USB cables.
This is a very old question, but I think that a new answer might add some value since, in my opinion, no one directly addressed some of the concerns in the OP.
Despite what the accepted answer suggests, list
objects in R are not hash maps. If you want to make a parallel with python, list
are more like, you guess, python list
s (or tuple
s actually).
It's better to describe how most R objects are stored internally (the C type of an R object is SEXP
). They are made basically of three parts:
NULL
if the object doesn't have attributes).From an internal point of view, there is little difference between a list
and a numeric
vector for instance. The values they store are just different. Let's break two objects into the paradigm we described before:
x <- runif(10)
y <- list(runif(10), runif(3))
For x
:
numeric
(REALSXP
in the C-side), the length is 10 and other stuff.double
values.NULL
, since the object doesn't have any.For y
:
list
(VECSXP
in the C-side), the length is 2 and other stuff.runif(10)
and runif(3)
respectively.NULL
, as for x
.So the only difference between a numeric
vector and a list
is that the numeric
data part is made of double
values, while for the list
the data part is an array of pointers to other R objects.
What happens with names? Well, names are just some of the attributes you can assign to an object. Let's see the object below:
z <- list(a=1:3, b=LETTERS)
list
(VECSXP
in the C-side), the length is 2 and other stuff.1:3
and LETTERS
respectively.names
component which is a character
R object with value c("a","b")
.From the R level, you can retrieve the attributes of an object with the attributes
function.
The key-value typical of an hash map in R is just an illusion. When you say:
z[["a"]]
this is what happens:
[[
subset function is called;"a"
) is of type character
, so the method is instructed to search such value from the names
attribute (if present) of the object z
;names
attribute isn't there, NULL
is returned;"a"
value is searched in it. If "a"
is not a name of the object, NULL
is returned;z[[1]]
.The key-value search is rather indirect and is always positional. Also, useful to keep in mind:
in hash maps the only limit a key must have is that it must be hashable. names
in R must be strings (character
vectors);
in hash maps you cannot have two identical keys. In R, you can assign names
to an object with repeated values. For instance:
names(y) <- c("same", "same")
is perfectly valid in R. When you try y[["same"]]
the first value is retrieved. You should know why at this point.
In conclusion, the ability to give arbitrary attributes to an object gives you the appearance of something different from an external point of view. But R list
s are not hash maps in any way.
var o = { cat : "meow", dog : "woof"};
var x = Object.keys(o);
for (i=0; i<x.length; i++) {
console.log(o[x[i]]);
}
IAB
It is always a good idea to use existing solutions that are being supported by a lot of high-level developers. The most popular one is https://github.com/cocur/slugify. First of all, it supports more than one language, and it is being updated.
If you do not want to use the whole package, you can copy the part that you need.
yes, these are the well-known quantifiers used in math. Another example is ? which reads as "exists".
Try SET GLOBAL slow_query_log = 'ON';
and perhaps FLUSH LOGS;
This assumes you are using MySQL 5.1 or later. If you are using an earlier version, you'll need to restart the server. This is documented in the MySQL Manual. You can configure the log either in the config file or on the command line.
Answers that claim Django model's Meta
and metaclasses are "completely different" are misleading answers.
The construction of Django model class objects, that is to say the object that stands for the class definition itself (yes, classes are also objects), are indeed controlled by a metaclass called ModelBase
, and you can see that code here.
And one of the things that ModelBase
does is to create the _meta
attribute on every Django model which contains validation machinery, field details, save logic and so forth. During this operation, the stuff that is specified in the model's inner Meta
class is read and used within that process.
So, while yes, in a sense Meta
and metaclasses are different 'things', within the mechanics of Django model construction they are intimately related; understanding how they work together will deepen your insight into both at once.
This might be a helpful source of information to better understand how Django models employ metaclasses.
https://code.djangoproject.com/wiki/DevModelCreation
And this might help too if you want to better understand how objects work in general.
My opinion is that selectedIndex
or using objectAtIndex
is not necessarily the best way to switch the tab. If you reorder your tabs, a hard coded index selection might mess with your former app behavior.
If you have the object reference of the view controller you want to switch to, you can do:
tabBarController.selectedViewController = myViewController
Of course you must make sure, that myViewController
really is in the list of tabBarController.viewControllers
.
Resurrecting a thread from stasis.
In 2018 this solution works for Swing/JFrame in NetBeans (should work in any IDE :):
this.getContentPane().setBackground(Color.GREEN);
Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.
If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll
(assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.
If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).
The append()
method adds a single item to the end of the list.
x = [1, 2, 3]
x.append([4, 5])
x.append('abc')
print(x)
# gives you
[1, 2, 3, [4, 5], 'abc']
The extend()
method takes one argument, a list, and appends each of the items of the argument to the original list. (Lists are implemented as classes. “Creating” a list is really instantiating a class. As such, a list has methods that operate on it.)
x = [1, 2, 3]
x.extend([4, 5])
x.extend('abc')
print(x)
# gives you
[1, 2, 3, 4, 5, 'a', 'b', 'c']
From Dive Into Python.
curl.exe
and .crt
to C:\Windows\System32
> curl https://api.stackexchange.com
p.s. If you want another folder to store executable check your paths > echo %PATH%
Make sure USB debugging on your phone is turned on. ADB kill-server and ADB start-server is not the problem.
C:\Documents and Settings\Administrator> adb nodaemon server
- cannot bind 'tcp:5037'
C:\Documents and Settings\Administrator> netstat -aon | findstr "5037"
- TCP 127.0.0.1:1130 127.0.0.1:5037 TIME_WAIT 0
- TCP 127.0.0.1:1269 127.0.0.1:5037 TIME_WAIT 0
- TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 3088
- TCP 127.0.0.1:5037 127.0.0.1:1128 TIME_WAIT 0
- TCP 127.0.0.1:5037 127.0.0.1:1129 TIME_WAIT 0
- TCP 127.0.0.1:5037 127.0.0.1:1270 TIME_WAIT 0
C:\Documents and Settings\Administrator>tasklist -fi "pid eq 3088"
- Image name PID session name session # memory usage
========================= ====== ================ ======== ============
- adb.exe 3088 Console 0 3,816 K
C:\Documents and Settings\Administrator>taskkill /f /pid 3088
- Success: terminate the PID for the process of 3,088.
C:\Documents and Settings\Administrator>adb start-server
- daemon not running. starting it now on port 5037 *
- daemon started successfully *
Reader they show at http://www.webqr.com/index.html works like a charm, but literaly, you need the one on the webpage, the github version it's really hard to make it work, however, it is possible. The best way to go is reverse-engineer the example shown at the webpage.
However, to edit and get the full potential out of it, it's not so easy. At some point I may post the stripped-down reverse-engineered QR reader, but in the meantime have some fun hacking the code.
Happy coding.
go to that path "C:\Program Files (x86)\JetBrains\IntelliJ IDEA 12.1.4\bin\idea.exe.vmoptions" and change size to -Xmx512m
-Xms128m
-Xmx512m
-XX:MaxPermSize=250m
-XX:ReservedCodeCacheSize=64m
-XX:+UseCodeCacheFlushing
-ea
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
hope its will work
return "hello world".toLowerCase().replace(/(?:(^.)|(\s+.))/g, function(match) {
return match.charAt(match.length-1).toUpperCase();
}); // HelloWorld
The answer was very funny for me and my team, and worked like a charm
REASON:
We observed that this happens only for the First View in the View Hierarchy, if this first view is a UITableView. So, all other similar UITableViews do not have this annoying section, except the first. We Tried moving the UITableView out of the first place in the view hierarchy, and everything was working as expected.
Sorry to be the answerer of bad news, but after research and debugging, it's pretty clear that there is no way to customize the styling of the new reCAPTCHA controls. The controls are wrapped in an iframe
, which prevents the use of CSS to style them, and Same-Origin Policy prevents JavaScript from accessing the contents, ruling out even a hacky solution.
Unlike reCAPTCHA API Version 1.0, there are no customize options in API Version 2.0. If we consider how this new API works, it's no surprise why.
While the new reCAPTCHA API may sound simple, there is a high degree of sophistication behind that modest checkbox. CAPTCHAs have long relied on the inability of robots to solve distorted text. However, our research recently showed that today’s Artificial Intelligence technology can solve even the most difficult variant of distorted text at 99.8% accuracy. Thus distorted text, on its own, is no longer a dependable test.
To counter this, last year we developed an Advanced Risk Analysis backend for reCAPTCHA that actively considers a user’s entire engagement with the CAPTCHA—before, during, and after—to determine whether that user is a human. This enables us to rely less on typing distorted text and, in turn, offer a better experience for users. We talked about this in our Valentine’s Day post earlier this year.
If you were able to directly manipulate the styling of the control elements, you could easily interfere with the user-profiling logic that makes the new reCAPTCHA possible.
Now the new API does offer a theme
option, by which you can choose a preset theme such as light
and dark
. However there is not presently a way to create a custom theme. If we inspect the iframe
, we will find the theme
name is passed in the query string of the src
attribute. This URL looks something like the following.
https://www.google.com/recaptcha/api2/anchor?...&theme=dark&...
This parameter determines what CSS class name is used on the wrapper element in the iframe
and determines the preset theme to use.
Digging through the minified source, I found that there are actually 4 valid theme values, which is more than the 2 listed in the documentation, but default
and standard
are the same as light
.
We can see the code that selects the class name from this object here.
There is no code for a custom theme, and if any other theme
value is specified, it will use the standard
theme.
At present, there is no way to fully style the new reCAPTCHA elements, only the wrapper elements around the iframe
can be stylized. This was almost-certainly done intentionally, to prevent users from breaking the user profiling logic that makes the new captcha-free checkbox possible. It is possible that Google could implement a limited custom theme API, perhaps allowing you to choose custom colors for existing elements, but I would not expect Google to implement full CSS styling.
In my case it was very weird (use a storyboard): For some reason it changed from "Main storyboard file base name" to "Main nib file base name" in the plist.
Changing back to "Main storyboard file base name" (UIMainStoryboardFile) solved the issue
Try this:
var alphaExp = /^[a-zA-Z]+$/;
if(document.myForm.name.match(alphaExp))
{
//Your logice will be here.
}
else{
alert("Please enter only alphabets");
}
Thanks.
AF_INET
is an address family that is used to designate the type of addresses that your socket can communicate with (in this case, Internet Protocol v4 addresses). When you create a socket, you have to specify its address family, and then you can only use addresses of that type with the socket. The Linux kernel, for example, supports 29 other address families such as UNIX (AF_UNIX
) sockets and IPX (AF_IPX
), and also communications with IRDA and Bluetooth (AF_IRDA
and AF_BLUETOOTH
, but it is doubtful you'll use these at such a low level).
For the most part, sticking with AF_INET
for socket programming over a network is the safest option. There is also AF_INET6
for Internet Protocol v6 addresses.
Hope this helps,
You can start as Lauritz recommended, with:
except Exception as ex:
and then just to print ex
like so:
try:
#your try code here
except Exception as ex:
print ex
I found a good article about using the WMP with Firefox on MSDN.
Based on MSDN's article and after doing some trials and errors, I found using JavaScript is better than using conditional comments or nested "EMBED/OBJECT" tags.
I made a JS function that generate WMP object based on given arguments:
<script type="text/javascript">
function generateWindowsMediaPlayer(
holderId, // String
height, // Number
width, // Number
videoUrl // String
// you can declare more arguments for more flexibility
) {
var holder = document.getElementById(holderId);
var player = '<object ';
player += 'height="' + height.toString() + '" ';
player += 'width="' + width.toString() + '" ';
videoUrl = encodeURI(videoUrl); // Encode for special characters
if (navigator.userAgent.indexOf("MSIE") < 0) {
// Chrome, Firefox, Opera, Safari
//player += 'type="application/x-ms-wmp" '; //Old Edition
player += 'type="video/x-ms-wmp" '; //New Edition, suggested by MNRSullivan (Read Comments)
player += 'data="' + videoUrl + '" >';
}
else {
// Internet Explorer
player += 'classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6" >';
player += '<param name="url" value="' + videoUrl + '" />';
}
player += '<param name="autoStart" value="false" />';
player += '<param name="playCount" value="1" />';
player += '</object>';
holder.innerHTML = player;
}
</script>
Then I used that function by writing some markups and inline JS like these:
<div id='wmpHolder'></div>
<script type="text/javascript">
window.addEventListener('load', generateWindowsMediaPlayer('wmpHolder', 240, 320, 'http://mysite.com/path/video.ext'));
</script>
You can use jQuery.ready instead of window load event to making the codes more backward-compatible and cross-browser.
I tested the codes over IE 9-10, Chrome 27, Firefox 21, Opera 12 and Safari 5, on Windows 7/8.
Another method utilizing the dplyr package:
library(dplyr)
df <- mtcars %>%
filter(mpg > 25)
Without the chain (%>%) operator:
library(dplyr)
df <- filter(mtcars, mpg > 25)
You can use
x = [1, 2, 3]
disp(sprintf('Answer: (%d, %d, %d)', x))
This results in
Answer: (1, 2, 3)
For vectors of arbitrary size, you can use
disp(strrep(['Answer: (' sprintf(' %d,', x) ')'], ',)', ')'))
An alternative way would be
disp(strrep(['Answer: (' num2str(x, ' %d,') ')'], ',)', ')'))
U can also use :
var query =
from t1 in myTABLE1List
join t2 in myTABLE1List
on new { ColA=t1.ColumnA, ColB=t1.ColumnB } equals new { ColA=t2.ColumnA, ColB=t2.ColumnB }
join t3 in myTABLE1List
on new {ColC=t2.ColumnA, ColD=t2.ColumnB } equals new { ColC=t3.ColumnA, ColD=t3.ColumnB }
You can use linq:
var q = from tag in Week orderby Convert.ToDateTime(tag.date) select tag;
List<cTag> Sorted = q.ToList()
I use the following pattern to make it bulletproof.
Try it out you can't break it without making modifications to the base classes (except if you define an obsolete flag without error flag set to true, but even then you end up with a warning)
public abstract class Base<TSelf, TParameter>
where TSelf : Base<TSelf, TParameter>, new()
{
protected const string FactoryMessage = "Use YourClass.Create(...) instead";
public static TSelf Create(TParameter parameter)
{
var me = new TSelf();
me.Initialize(parameter);
return me;
}
[Obsolete(FactoryMessage, true)]
protected Base()
{
}
protected virtual void Initialize(TParameter parameter)
{
}
}
public abstract class BaseWithConfig<TSelf, TConfig>: Base<TSelf, TConfig>
where TSelf : BaseWithConfig<TSelf, TConfig>, new()
{
public TConfig Config { get; private set; }
[Obsolete(FactoryMessage, true)]
protected BaseWithConfig()
{
}
protected override void Initialize(TConfig parameter)
{
this.Config = parameter;
}
}
public class MyService : BaseWithConfig<MyService, (string UserName, string Password)>
{
[Obsolete(FactoryMessage, true)]
public MyService()
{
}
}
public class Person : Base<Person, (string FirstName, string LastName)>
{
[Obsolete(FactoryMessage,true)]
public Person()
{
}
protected override void Initialize((string FirstName, string LastName) parameter)
{
this.FirstName = parameter.FirstName;
this.LastName = parameter.LastName;
}
public string LastName { get; private set; }
public string FirstName { get; private set; }
}
[Test]
public void FactoryTest()
{
var notInitilaizedPerson = new Person(); // doesn't compile because of the obsolete attribute.
Person max = Person.Create(("Max", "Mustermann"));
Assert.AreEqual("Max",max.FirstName);
var service = MyService.Create(("MyUser", "MyPassword"));
Assert.AreEqual("MyUser", service.Config.UserName);
}
EDIT: And here is an example based on your drawing example that even enforces interface abstraction
public abstract class BaseWithAbstraction<TSelf, TInterface, TParameter>
where TSelf : BaseWithAbstraction<TSelf, TInterface, TParameter>, TInterface, new()
{
[Obsolete(FactoryMessage, true)]
protected BaseWithAbstraction()
{
}
protected const string FactoryMessage = "Use YourClass.Create(...) instead";
public static TInterface Create(TParameter parameter)
{
var me = new TSelf();
me.Initialize(parameter);
return me;
}
protected virtual void Initialize(TParameter parameter)
{
}
}
public abstract class BaseWithParameter<TSelf, TInterface, TParameter> : BaseWithAbstraction<TSelf, TInterface, TParameter>
where TSelf : BaseWithParameter<TSelf, TInterface, TParameter>, TInterface, new()
{
protected TParameter Parameter { get; private set; }
[Obsolete(FactoryMessage, true)]
protected BaseWithParameter()
{
}
protected sealed override void Initialize(TParameter parameter)
{
this.Parameter = parameter;
this.OnAfterInitialize(parameter);
}
protected virtual void OnAfterInitialize(TParameter parameter)
{
}
}
public class GraphicsDeviceManager
{
}
public interface IDrawable
{
void Update();
void Draw();
}
internal abstract class Drawable<TSelf> : BaseWithParameter<TSelf, IDrawable, GraphicsDeviceManager>, IDrawable
where TSelf : Drawable<TSelf>, IDrawable, new()
{
[Obsolete(FactoryMessage, true)]
protected Drawable()
{
}
public abstract void Update();
public abstract void Draw();
}
internal class Rectangle : Drawable<Rectangle>
{
[Obsolete(FactoryMessage, true)]
public Rectangle()
{
}
public override void Update()
{
GraphicsDeviceManager manager = this.Parameter;
// TODo manager
}
public override void Draw()
{
GraphicsDeviceManager manager = this.Parameter;
// TODo manager
}
}
internal class Circle : Drawable<Circle>
{
[Obsolete(FactoryMessage, true)]
public Circle()
{
}
public override void Update()
{
GraphicsDeviceManager manager = this.Parameter;
// TODo manager
}
public override void Draw()
{
GraphicsDeviceManager manager = this.Parameter;
// TODo manager
}
}
[Test]
public void FactoryTest()
{
// doesn't compile because interface abstraction is enforced.
Rectangle rectangle = Rectangle.Create(new GraphicsDeviceManager());
// you get only the IDrawable returned.
IDrawable service = Circle.Create(new GraphicsDeviceManager());
}
As said, the objectForKey:
datatype is :(id)aKey
whereas the valueForKey:
datatype is :(NSString *)key
.
For example:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObject:@"123"],[NSNumber numberWithInteger:5], nil];
NSLog(@"objectForKey : --- %@",[dict objectForKey:[NSNumber numberWithInteger:5]]);
//This will work fine and prints ( 123 )
NSLog(@"valueForKey : --- %@",[dict valueForKey:[NSNumber numberWithInteger:5]]);
//it gives warning "Incompatible pointer types sending 'NSNumber *' to parameter of type 'NSString *'" ---- This will crash on runtime.
So, valueForKey:
will take only a string value and is a KVC method, whereas objectForKey:
will take any type of object.
The value in objectForKey
will be accessed by the same kind of object.
Just to clarify the problem here - the error is in the following bit of code:
<xsl:attribute name="src">
<xsl:copy-of select="/root/Image/node()"/>
</xsl:attribute>
The instruction xsl:copy-of takes a node or node-set and makes a copy of it - outputting a node or node-set. However an attribute cannot contain a node, only a textual value, so xsl:value-of would be a possible solution (as this returns the textual value of a node or nodeset).
A MUCH shorter solution (and perhaps more elegant) would be the following:
<img width="100" height="100" src="{/root/Image/node()}" class="CalloutRightPhoto"/>
The use of the {} in the attribute is called an Attribute Value Template, and can contain any XPATH expression.
Note, the same XPath can be used here as you have used in the xsl_copy-of as it knows to take the textual value when used in a Attribute Value Template.
var str1 = 'abc';
var str2 = str1+' def'; // str2 is now 'abc def'
official Link of DB 2 JDBC Driver from IBM
I have made a program using c++ which is working in joint and disjoint graph too .
#include <queue>
#include "iostream"
#include "vector"
#include "queue"
using namespace std;
struct Edge {
int source,destination;
};
class Graph{
int V;
vector<vector<int>> adjList;
public:
Graph(vector<Edge> edges,int V){
this->V = V;
adjList.resize(V);
for(auto i : edges){
adjList[i.source].push_back(i.destination);
// adjList[i.destination].push_back(i.source);
}
}
void BFSRecursivelyJoinandDisjointtGraphUtil(vector<bool> &discovered, queue<int> &q);
void BFSRecursivelyJointandDisjointGraph(int s);
void printGraph();
};
void Graph :: printGraph()
{
for (int i = 0; i < this->adjList.size(); i++)
{
cout << i << " -- ";
for (int v : this->adjList[i])
cout <<"->"<< v << " ";
cout << endl;
}
}
void Graph ::BFSRecursivelyJoinandDisjointtGraphUtil(vector<bool> &discovered, queue<int> &q) {
if (q.empty())
return;
int v = q.front();
q.pop();
cout << v <<" ";
for (int u : this->adjList[v])
{
if (!discovered[u])
{
discovered[u] = true;
q.push(u);
}
}
BFSRecursivelyJoinandDisjointtGraphUtil(discovered, q);
}
void Graph ::BFSRecursivelyJointandDisjointGraph(int s) {
vector<bool> discovered(V, false);
queue<int> q;
for (int i = s; i < V; i++) {
if (discovered[i] == false)
{
discovered[i] = true;
q.push(i);
BFSRecursivelyJoinandDisjointtGraphUtil(discovered, q);
}
}
}
int main()
{
vector<Edge> edges =
{
{0, 1}, {0, 2}, {1, 2}, {2, 0}, {2,3},{3,3}
};
int V = 4;
Graph graph(edges, V);
// graph.printGraph();
graph.BFSRecursivelyJointandDisjointGraph(2);
cout << "\n";
edges = {
{0,4},{1,2},{1,3},{1,4},{2,3},{3,4}
};
Graph graph2(edges,5);
graph2.BFSRecursivelyJointandDisjointGraph(0);
return 0;
}
I tried to install to VS 2015 using the Web installer. It seemed to work, but there was still no MySQL entry for Data Connections. I ended up going to http://dev.mysql.com/downloads/windows/visualstudio/, using it to uninstall then re-install the connector. Not it works as expected.
I also favor the RegEx solution. The code will be much cleaner. I would hesitate to use toLowerCase() in situations where I knew the strings were going to be large, since strings are immutable and would have to be copied. Also, the matches() solution might be confusing because it takes a regular expression as an argument (searching for "Need$le" cold be problematic).
Building on some of the above examples:
public boolean containsIgnoreCase( String haystack, String needle ) {
if(needle.equals(""))
return true;
if(haystack == null || needle == null || haystack .equals(""))
return false;
Pattern p = Pattern.compile(needle,Pattern.CASE_INSENSITIVE+Pattern.LITERAL);
Matcher m = p.matcher(haystack);
return m.find();
}
example call:
String needle = "Need$le";
String haystack = "This is a haystack that might have a need$le in it.";
if( containsIgnoreCase( haystack, needle) ) {
System.out.println( "Found " + needle + " within " + haystack + "." );
}
(Note: you might want to handle NULL and empty strings differently depending on your needs. I think they way I have it is closer to the Java spec for strings.)
Speed critical solutions could include iterating through the haystack character by character looking for the first character of the needle. When the first character is matched (case insenstively), begin iterating through the needle character by character, looking for the corresponding character in the haystack and returning "true" if all characters get matched. If a non-matched character is encountered, resume iteration through the haystack at the next character, returning "false" if a position > haystack.length() - needle.length() is reached.
This is only somewhat related to the question, but I've just discovered a (to me) obscure bit of perl syntax that you can use with "our" (package) variables that you can't use with "my" (local) variables.
#!/usr/bin/perl
our $foo = "BAR";
print $foo . "\n";
${"foo"} = "BAZ";
print $foo . "\n";
Output:
BAR
BAZ
This won't work if you change 'our' to 'my'.
You can use rake db:reset
when you want to drop the local database and start fresh with data loaded from db/seeds.rb
. This is a useful command when you are still figuring out your schema, and often need to add fields to existing models.
Once the reset command is used it will do the following:
Drop the database: rake db:drop
Load the schema: rake db:schema:load
Seed the data: rake db:seed
But if you want to completely drop your database you can use rake db:drop
. Dropping the database will also remove any schema conflicts or bad data. If you want to keep the data you have, be sure to back it up before running this command.
This is a detailed article about the most important rake database commands.
1)What is the difference between both the way of creating class objects.
First one is a pointer to a constructed object in heap (by new
).
Second one is an object that implicitly constructed. (Default constructor)
2)If i am creating object like Example example; how to use that in an singleton class.
It depends on your goals, easiest is put it as a member in class simply.
A sample of a singleton class which has an object from Example
class:
class Sample
{
Example example;
public:
static inline Sample *getInstance()
{
if (!uniqeInstance)
{
uniqeInstance = new Sample;
}
return uniqeInstance;
}
private:
Sample();
virtual ~Sample();
Sample(const Sample&);
Sample &operator=(const Sample &);
static Sample *uniqeInstance;
};
For chinese Rails developers:
DateTime.strptime('2012-12-09 00:01:36', '%Y-%m-%d %H:%M:%S')
=> Sun, 09 Dec 2012 00:01:36 +0000
every javascript object is a simple hashmap which accepts a string or a Symbol as its key, so you could write your code as:
var map = {};
// add a item
map[key1] = value1;
// or remove it
delete map[key1];
// or determine whether a key exists
key1 in map;
javascript object is a real hashmap on its implementation, so the complexity on search is O(1), but there is no dedicated hashcode()
function for javascript strings, it is implemented internally by javascript engine (V8, SpiderMonkey, JScript.dll, etc...)
2020 Update:
javascript today supports other datatypes as well: Map
and WeakMap
. They behave more closely as hash maps than traditional objects.
If you want the String
composed of the last three characters, you can use substring(int)
:
String new_word = word.substring(word.length() - 3);
If you actually want them as a character array, you should write
char[] buffer = new char[3];
int length = word.length();
word.getChars(length - 3, length, buffer, 0);
The first two arguments to getChars
denote the portion of the string you want to extract. The third argument is the array into which that portion will be put. And the last argument gives the position in the buffer where the operation starts.
If the string has less than three characters, you'll get an exception in either of the above cases, so you might want to check for that.
In Cygwin, you can activate such feature by right-clicking the window. In the pop-up window, select Options... -> Mouse -> activate Clicks place command line cursor -> Apply.
From now on, simply clicking the left mouse button at some position within the command line will place the cursor there.
int intLength(int i) {
int l=0;
for(;i;i/=10) l++;
return l==0 ? 1 : l;
}
Here's a tiny efficient one
If you would like to combine the matrix with some visualisations I can recommend (I am using the built in iris
dataset):
library(psych)
pairs.panels(iris[1:4]) # select columns 1-4
The Performance Analytics basically does the same but includes significance indicators by default.
library(PerformanceAnalytics)
chart.Correlation(iris[1:4])
Or this nice and simple visualisation:
library(corrplot)
x <- cor(iris[1:4])
corrplot(x, type="upper", order="hclust")
It stands for Representational State Transfer and it can mean a lot of things, but usually when you are talking about APIs and applications, you are talking about REST as a way to do web services or get programs to talk over the web.
REST is basically a way of communicating between systems and does much of what SOAP RPC was designed to do, but while SOAP generally makes a connection, authenticates and then does stuff over that connection, REST works pretty much the same way that that the web works. You have a URL and when you request that URL you get something back. This is where things start getting confusing because people describe the web as a the largest REST application and while this is technically correct it doesn't really help explain what it is.
In a nutshell, REST allows you to get two applications talking over the Internet using tools that are similar to what a web browser uses. This is much simpler than SOAP and a lot of what REST does is says, "Hey, things don't have to be so complex."
Worth reading:
run conda navigator, you can upgrade your packages easily in the friendly GUI
Im putting this in an answer because it's too long for a comment:
If you need the VM to be aware when the CheckBox
is changed, you should really bind the CheckBox
to the VM, and not a static value:
public class ViewModel
{
private bool _caseSensitive;
public bool CaseSensitive
{
get { return _caseSensitive; }
set
{
_caseSensitive = value;
NotifyPropertyChange(() => CaseSensitive);
Settings.Default.bSearchCaseSensitive = value;
}
}
}
XAML:
<CheckBox Content="Case Sensitive" IsChecked="{Binding CaseSensitive}"/>
Try this, it works fine for me:
1 . Modify your MainActivity
section in AndroidManifest.xml
, delete from it, line with MAIN
category in intent-filter
section
<activity android:name="ru.quickmessage.pa.MainActivity"
android:configChanges="keyboardHidden|orientation"
android:screenOrientation="portrait"
android:label="@string/app_name"
android:theme="@style/CustomTheme"
android:launchMode="singleTask">
<intent-filter>
==> <action android:name="android.intent.action.MAIN" /> <== Delete this line
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
2 . Create <activity-alias>
, for each of your icons. Like this
<activity-alias android:label="@string/app_name"
android:icon="@drawable/icon"
android:name=".MainActivity-Red"
android:enabled="false"
android:targetActivity=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
3 . Set programmatically: set ENABLE attribute for the appropriate activity-alias
getPackageManager().setComponentEnabledSetting(
new ComponentName("ru.quickmessage.pa", "ru.quickmessage.pa.MainActivity-Red"),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Note, At least one must be enabled at all times.
Option 2 will work. You could also use a Set<Character>
or
char[] myCharSet = new char[] {'A', 'B', 'C', ...};
Arrays.sort(myCharSet);
if (Arrays.binarySearch(myCharSet, symbol) >= 0) { ... }
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
An important point to remember is if you're behind a corporate firewall and you get you're corporate proxy settings from a .pac file, then be sure to use the value for global proxy.
Here's how to apply environment variables to template file (no backup need).
echo "Hello {{FOO}}" > foo.conf.tmpl
FOO="world" && sed -e "s/{{FOO}}/$FOO/g" foo.conf.tmpl > foo.conf
Working both macOS 10.12.4 and Ubuntu 14.04.5
make sure you use the POST to insert the data. Actually you were using GET.
#include <iostrema>
int main(){
int32_t maxSigned = -1U >> 1;
cout << maxSigned << '\n';
return 0;
}
It might be architecture dependent but it does work at least in my setup.
You need to convert the date field to varchar to strip out the time, then convert it back to datetime, this will reset the time to '00:00:00.000'.
SELECT *
FROM [TableName]
WHERE
(
convert(datetime,convert(varchar,GETDATE(),1))
between
convert(datetime,convert(varchar,[StartDate],1))
and
convert(datetime,convert(varchar,[EndDate],1))
)
Another simple way:
Dir.mkdir('tmp/excel') unless Dir.exist?('tmp/excel')
You can use this function:
int arraySize(char array[])
{
int cont = 0;
for (int i = 0; array[i] != 0; i++)
cont++;
return cont;
}
You can get the all record of the date '2016-07-14' by using it
whereDate('date','=','2016-07-14')
Or use the another code for dynamic date
whereDate('date',$date)
Have you tried redirecting all three I/O streams:
nohup ./yourprogram > foo.out 2> foo.err < /dev/null &
I've never done it, but it looks like Reflection provides this. Field
is an AnnotatedElement
and so it has getAnnotation
. This page has an example (copied below); quite straightforward if you know the class of the annotation and if the annotation policy retains the annotation at runtime. Naturally if the retention policy doesn't keep the annotation at runtime, you won't be able to query it at runtime.
An answer that's since been deleted (?) provided a useful link to an annotations tutorial that you may find helpful; I've copied the link here so people can use it.
Example from this page:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
String str();
int val();
}
class Meta {
@MyAnno(str = "Two Parameters", val = 19)
public static void myMeth(String str, int i) {
Meta ob = new Meta();
try {
Class c = ob.getClass();
Method m = c.getMethod("myMeth", String.class, int.class);
MyAnno anno = m.getAnnotation(MyAnno.class);
System.out.println(anno.str() + " " + anno.val());
} catch (NoSuchMethodException exc) {
System.out.println("Method Not Found.");
}
}
public static void main(String args[]) {
myMeth("test", 10);
}
}
I think you could do it by creating parameters in an object maybe?
var myObject = {}; for(var i=0;i<myArray.length;i++) { myObject[ myArray[i] ]; }
If you don't set them to anything, you'll just have an object with some parameters that are undefined. I'd have to write this myself to be sure though.
Use the array list which is actually implement array. It takes initially array of size 4 and when it gets full, a new array is created with its double size and the data of first array get copied into second array, now the new item is inserted into new array. Also the name of second array creates an alias of first so that it can be accessed by the same name as previous and the first array gets disposed
Just give a try using subset
nrow(subset(data,condition))
Example
nrow(subset(myData,sCode == "CA"))
In a similar use case I had to skip annoying lines before the line with my actual column names. This solution worked nicely. Read the file first, then pass the list to csv.DictReader
.
with open('all16.csv') as tmp:
# Skip first line (if any)
next(tmp, None)
# {line_num: row}
data = dict(enumerate(csv.DictReader(tmp)))
Have you looked into ZXING? I've been using it successfully to create barcodes. You can see a full working example in the bitcoin application src
// this is a small sample use of the QRCodeEncoder class from zxing
try {
// generate a 150x150 QR code
Bitmap bm = encodeAsBitmap(barcode_content, BarcodeFormat.QR_CODE, 150, 150);
if(bm != null) {
image_view.setImageBitmap(bm);
}
} catch (WriterException e) { //eek }
I think this is a much more cleaner solution when copying text:
copyToClipboard(item) {
document.addEventListener('copy', (e: ClipboardEvent) => {
e.clipboardData.setData('text/plain', (item));
e.preventDefault();
document.removeEventListener('copy', null);
});
document.execCommand('copy');
}
And then just call copyToClipboard on click event in html. (click)="copyToClipboard('texttocopy')"
You can join your array using the following:
string.Join(",", Client);
Then you can output anyway you want. You can change the comma to what ever you want, a space, a pipe, or whatever.
It's a bug or whatever but the removePersistentDomainForName
is not working while clearing all the NSUserDefaults
values.
So, better option is that to reset the PersistentDomain
and that you can do via following way:
NSUserDefaults.standardUserDefaults().setPersistentDomain(["":""], forName: NSBundle.mainBundle().bundleIdentifier!)
To match pattern
or an empty string, use
^$|pattern
^
and $
are the beginning and end of the string anchors respectively.|
is used to denote alternates, e.g. this|that
.\b
\b
in most flavor is a "word boundary" anchor. It is a zero-width match, i.e. an empty string, but it only matches those strings at very specific places, namely at the boundaries of a word.
That is, \b
is located:
\w
and \W
(either order):
^
and \w
\w
\w
and $
\w
This is not trivial depending on specification.
I like the explanation From EdX (Microsoft: DEV210x Introduction to C++) for a similar problem:
"The enum represents the literal values of days as integers. Referring to the numeric types table, you see that an int takes 4 bytes of memory. 7 days x 4 bytes each would require 28 bytes of memory if the entire enum were stored but the compiler only uses a single element of the enum, therefore the size in memory is actually 4 bytes."
There is no need to know where the files are, because when you launch a bat file the working directory is the directory where it was launched (the "master folder"), so if you have this structure:
.\mydocuments\folder\mybat.bat
.\mydocuments\folder\subfolder\file.txt
And the user starts the "mybat.bat", the working directory is ".\mydocuments\folder", so you only need to write the subfolder name in your script:
@Echo OFF
REM Do anything with ".\Subfolder\File1.txt"
PUSHD ".\Subfolder"
Type "File1.txt"
Pause&Exit
Anyway, the working directory is stored in the "%CD%" variable, and the directory where the bat was launched is stored on the argument 0. Then if you want to know the working directory on any computer you can do:
@Echo OFF
Echo Launch dir: "%~dp0"
Echo Current dir: "%CD%"
Pause&Exit
What did the trick for me was to change the target machine from “ANY CPU” to “x64” or maybe in your case “x86” depending in your target machine’s architecture. I would try this first before moving into a more complex solution which indicates a more complex problem.
Here's another way through the GUI that does exactly what your script does even though it goes through Indexes (not Constraints) in the object explorer.
NodeJS now includes threads (as an experimental feature at time of answering).
The $@
and $<
are called automatic variables. The variable $@
represents the name of the target and $<
represents the first prerequisite required to create the output file.
For example:
hello.o: hello.c hello.h
gcc -c $< -o $@
Here, hello.o
is the output file. This is what $@
expands to. The first dependency is hello.c
. That's what $<
expands to.
The -c
flag generates the .o
file; see man gcc
for a more detailed explanation. The -o
specifies the output file to create.
For further details, you can read this article about Linux Makefiles.
Also, you can check the GNU make
manuals. It will make it easier to make Makefiles and to debug them.
If you run this command, it will output the makefile database:
make -p
After all this, yet another simple solution:
const time = new Date(null);
time.setSeconds(7530);
console.log(time.getHours(), time.getMinutes(), time.getSeconds());
You can continue using WebClient to POST (instead of GET, which is the HTTP verb you're currently using with DownloadString), but I think you'll find it easier to work with the (slightly) lower-level classes WebRequest and WebResponse.
There are two parts to this - the first is to post the login form, the second is recovering the "Set-cookie" header and sending that back to the server as "Cookie" along with your GET request. The server will use this cookie to identify you from now on (assuming it's using cookie-based authentication which I'm fairly confident it is as that page returns a Set-cookie header which includes "PHPSESSID").
POSTing to the login form
Form posts are easy to simulate, it's just a case of formatting your post data as follows:
field1=value1&field2=value2
Using WebRequest and code I adapted from Scott Hanselman, here's how you'd POST form data to your login form:
string formUrl = "http://www.mmoinn.com/index.do?PageModule=UsersAction&Action=UsersLogin"; // NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag
string formParams = string.Format("email_address={0}&password={1}", "your email", "your password");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
Here's an example of what you should see in the Set-cookie header for your login form:
PHPSESSID=c4812cffcf2c45e0357a5a93c137642e; path=/; domain=.mmoinn.com,wowmine_referer=directenter; path=/; domain=.mmoinn.com,lang=en; path=/;domain=.mmoinn.com,adt_usertype=other,adt_host=-
GETting the page behind the login form
Now you can perform your GET request to a page that you need to be logged in for.
string pageSource;
string getUrl = "the url of the page behind the login";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
EDIT:
If you need to view the results of the first POST, you can recover the HTML it returned with:
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
Place this directly below cookieHeader = resp.Headers["Set-cookie"];
and then inspect the string held in pageSource.
You need to alias the subquery.
SELECT name FROM (SELECT name FROM agentinformation) a
or to be more explicit
SELECT a.name FROM (SELECT name FROM agentinformation) a
Objective-C is not Java. In Objective-C exceptions are what they are called. Exceptions! Don’t use them for error handling. It’s not their proposal. Just check the length of the string before using characterAtIndex and everything is fine....
If anybody encounters this with errors like Error: cannot add duplicate collection entry of type ‘mimeMap’ with unique key attribute and/or other scripts stop working when doing this fix, it might help to remove it first like this:
<staticContent>
<remove fileExtension=".woff" />
<mimeMap fileExtension=".woff" mimeType="application/font-woff" />
</staticContent>
At least that solved my problem
You may use clang as well. It used to be faster than GCC, and now it is quite a stable thing. It is much easier to build clang from sources (you can really drink cup of coffee during build process).
In short:
Compile your code:
path/to/clang --target=arm-linux-gnueabihf --sysroot=/some/path/arm-linux-gnueabihf/sysroot my-happy-program.c -fuse-ld=lld
Optionally you may use legacy arm-linux-gnueabihf binutils. Then you may remove "-fuse-ld=lld" flag at the end.
Below is my cmake toolchain file.
toolchain.cmake
set(CMAKE_SYSTEM_VERSION 1)
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm)
# Custom toolchain-specific definitions for your project
set(PLATFORM_ARM "1")
set(PLATFORM_COMPILE_DEFS "COMPILE_GLES")
# There we go!
# Below, we specify toolchain itself!
set(TARGET_TRIPLE arm-linux-gnueabihf)
# Specify your target rootfs mount point on your compiler host machine
set(TARGET_ROOTFS /Volumes/rootfs-${TARGET_TRIPLE})
# Specify clang paths
set(LLVM_DIR /Users/stepan/projects/shared/toolchains/llvm-7.0.darwin-release-x86_64/install)
set(CLANG ${LLVM_DIR}/bin/clang)
set(CLANGXX ${LLVM_DIR}/bin/clang++)
# Specify compiler (which is clang)
set(CMAKE_C_COMPILER ${CLANG})
set(CMAKE_CXX_COMPILER ${CLANGXX})
# Specify binutils
set (CMAKE_AR "${LLVM_DIR}/bin/llvm-ar" CACHE FILEPATH "Archiver")
set (CMAKE_LINKER "${LLVM_DIR}/bin/llvm-ld" CACHE FILEPATH "Linker")
set (CMAKE_NM "${LLVM_DIR}/bin/llvm-nm" CACHE FILEPATH "NM")
set (CMAKE_OBJDUMP "${LLVM_DIR}/bin/llvm-objdump" CACHE FILEPATH "Objdump")
set (CMAKE_RANLIB "${LLVM_DIR}/bin/llvm-ranlib" CACHE FILEPATH "ranlib")
# You may use legacy binutils though.
#set(BINUTILS /usr/local/Cellar/arm-linux-gnueabihf-binutils/2.31.1)
#set (CMAKE_AR "${BINUTILS}/bin/${TARGET_TRIPLE}-ar" CACHE FILEPATH "Archiver")
#set (CMAKE_LINKER "${BINUTILS}/bin/${TARGET_TRIPLE}-ld" CACHE FILEPATH "Linker")
#set (CMAKE_NM "${BINUTILS}/bin/${TARGET_TRIPLE}-nm" CACHE FILEPATH "NM")
#set (CMAKE_OBJDUMP "${BINUTILS}/bin/${TARGET_TRIPLE}-objdump" CACHE FILEPATH "Objdump")
#set (CMAKE_RANLIB "${BINUTILS}/bin/${TARGET_TRIPLE}-ranlib" CACHE FILEPATH "ranlib")
# Specify sysroot (almost same as rootfs)
set(CMAKE_SYSROOT ${TARGET_ROOTFS})
set(CMAKE_FIND_ROOT_PATH ${TARGET_ROOTFS})
# Specify lookup methods for cmake
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
# Sometimes you also need this:
# set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
# Specify raspberry triple
set(CROSS_FLAGS "--target=${TARGET_TRIPLE}")
# Specify other raspberry related flags
set(RASP_FLAGS "-D__STDC_CONSTANT_MACROS -D__STDC_LIMIT_MACROS")
# Gather and distribute flags specified at prev steps.
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CROSS_FLAGS} ${RASP_FLAGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CROSS_FLAGS} ${RASP_FLAGS}")
# Use clang linker. Why?
# Well, you may install custom arm-linux-gnueabihf binutils,
# but then, you also need to recompile clang, with customized triple;
# otherwise clang will try to use host 'ld' for linking,
# so... use clang linker.
set(CMAKE_EXE_LINKER_FLAGS ${CMAKE_EXE_LINKER_FLAGS} -fuse-ld=lld)
It works fine with Salesforce REST API query datetime formats
DateTime now = DateTime.UtcNow;
string startDate = now.AddDays(-5).ToString("yyyy-MM-ddTHH\\:mm\\:ssZ");
string endDate = now.ToString("yyyy-MM-ddTHH\\:mm\\:ssZ");
//REST service Query
string salesforceUrl= https://csxx.salesforce.com//services/data/v33.0/sobjects/Account/updated/?start=" + startDate + "&end=" + endDate;
// https://csxx.salesforce.com/services/data/v33.0/sobjects/Account/updated/?start=2015-03-10T15:15:57Z&end=2015-03-15T15:15:57Z
It returns the results from Salesforce without any issues.
This will give you the desired result
#!/usr/bin/python
import os
# traverse root directory, and list directories as dirs and files as files
for root, dirs, files in os.walk("."):
path = root.split(os.sep)
print((len(path) - 1) * '---', os.path.basename(root))
for file in files:
print(len(path) * '---', file)
You can use the spool
command (SQL*Plus documentation, but one of many such commands SQL Developer also supports) to write results straight to disk. Each spool
can change the file that's being written to, so you can have several queries writing to different files just by putting spool
commands between them:
spool "\path\to\spool1.txt"
select /*csv*/ * from employees;
spool "\path\to\spool2.txt"
select /*csv*/ * from locations;
spool off;
You'd need to run this as a script (F5, or the second button on the command bar above the SQL Worksheet). You might also want to explore some of the formatting options and the set
command, though some of those do not translate to SQL Developer.
Since you mentioned CSV in the title I've included a SQL Developer-specific hint that does that formatting for you.
A downside though is that SQL Developer includes the query in the spool file, which you can avoid by having the commands and queries in a script file that you then run as a script.
If you enabled it as a DHCP client then your router should get an IP address from a DHCP server. If you connect your router on a net with a DHCP server you should reach your router's administrator page on the IP address assigned by the DHCP.
You can also get this error message when you place an inline tag in your html but make the (common for me) typo that you forget to add the slash to the closing-script tag like this:
<script>
alert("I ran!");
<script> <!-- OOPS opened script tag again instead of closing it -->
The JS interpreter tries to "execute" the tag, which looks like an expression beginning with a less-than sign, hence the error: SyntaxError: expected expression, got '<'
Use strpos
. If the string is not found it returns false
, otherwise something that is not false
. Be sure to use a type-safe comparison (===
) as 0
may be returned and it is a falsy value:
if (strpos($string, $substring) === false) {
// substring is not found in string
}
if (strpos($string, $substring2) !== false) {
// substring2 is found in string
}
use this to clear the previous keyboard buffer before scanning the string it will solve your problem scanner.nextLine();//this is to clear the keyboard buffer
I came across this post, and it worked for me:
img {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
margin: auto;_x000D_
}
_x000D_
<div style="border: 1px solid black; position:relative; min-height: 200px">_x000D_
<img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a">_x000D_
_x000D_
</div>
_x000D_
(Vertical and horizontal alignment)
Use ANSI syntax and it will be a lot more clear how you are joining the tables:
SELECT s.name as Student, c.name as Course
FROM student s
INNER JOIN bridge b ON s.id = b.sid
INNER JOIN course c ON b.cid = c.id
ORDER BY s.name
@QueryParam documentation says
" The type T of the annotated parameter, field or property must either:
1) Be a primitive type
2) Have a constructor that accepts a single String argument
3) Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String))
4) Have a registered implementation of javax.ws.rs.ext.ParamConverterProvider JAX-RS extension SPI that returns a javax.ws.rs.ext.ParamConverter instance capable of a "from string" conversion for the type.
5) Be List, Set or SortedSet, where T satisfies 2, 3 or 4 above. The resulting collection is read-only. "
If you want to control what response goes to user when query parameter in String form can't be converted to your type T, you can throw WebApplicationException. Dropwizard comes with following *Param classes you can use for your needs.
BooleanParam, DateTimeParam, IntParam, LongParam, LocalDateParam, NonEmptyStringParam, UUIDParam. See https://github.com/dropwizard/dropwizard/tree/master/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params
If you need Joda DateTime, just use Dropwizard DateTimeParam.
If the above list does not suit your needs, define your own by extending AbstractParam. Override parse method. If you need control over error response body, override error method.
Good article from Coda Hale on this is at http://codahale.com/what-makes-jersey-interesting-parameter-classes/
import io.dropwizard.jersey.params.AbstractParam;
import java.util.Date;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
public class DateParam extends AbstractParam<Date> {
public DateParam(String input) {
super(input);
}
@Override
protected Date parse(String input) throws Exception {
return new Date(input);
}
@Override
protected Response error(String input, Exception e) {
// customize response body if you like here by specifying entity
return Response.status(Status.BAD_REQUEST).build();
}
}
Date(String arg) constructor is deprecated. I would use Java 8 date classes if you are on Java 8. Otherwise joda date time is recommended.
I don't recommend storing passwords in a script, but this is a way to what you indicate:
use 5.010;
my %user_table = ( tom => '123!', frank => '321!' );
say ( $user_table{ $name } eq $password ? 'You have gained access.'
: 'Access denied!'
);
Any time you want to enforce an association like this, it's a good idea to think of a table, and the most common form of table in Perl is the hash.
I have set the vm argument in WAS server as -Dfile.encoding=UTF-8 to change the servers' default character set.
SELECT Computer.Computer_Name, Application1.Name, Max(Soft.[Version]) as Version1
FROM Application1
inner JOIN Software
ON Application1.ID = Software.Application_Id
cross join Computer
Left JOIN Software_Computer
ON Software_Computer.Computer_Id = Computer.ID and Software_Computer.Software_Id = Software.Id
Left JOIN Software as Soft
ON Soft.Id = Software_Computer.Software_Id
WHERE Computer.ID = 1
GROUP BY Computer.Computer_Name, Application1.Name
There is no way in PostgreSQL to deconstruct a scalar JSON object. Thus, as you point out,
select length(to_json('Some "text"'::TEXT) ::TEXT);
is 15,
The trick is to convert the JSON into an array of one JSON element, then extract that element using ->>
.
select length( array_to_json(array[to_json('Some "text"'::TEXT)])->>0 );
will return 11.
Only call time pass-by-reference is removed. So change:
call_user_func($func, &$this, &$client ...
To this:
call_user_func($func, $this, $client ...
&$this
should never be needed after PHP4 anyway period.
If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {
)
EDIT:
See @Simba Answer for valid solution
submodule.<name>.update
is what you want to change, see the docs - defaultcheckout
submodule.<name>.branch
specify remote branch to be tracked - defaultmaster
OLD ANSWER:
Personally I hate answers here which direct to external links which may stop working over time and check my answer here (Unless question is duplicate) - directing to question which does cover subject between the lines of other subject, but overall equals: "I'm not answering, read the documentation."
So back to the question: Why does it happen?
Situation you described
After pulling changes from server, many times my submodule head gets detached from master branch.
This is a common case when one does not use submodules too often or has just started with submodules. I believe that I am correct in stating, that we all have been there at some point where our submodule's HEAD gets detached.
$ cd <submodule-path>
# if the master branch already exists locally:
# (From git docs - branch)
# -u <upstream>
# --set-upstream-to=<upstream>
# Set up <branchname>'s tracking information so <upstream>
# is considered <branchname>'s upstream branch.
# If no <branchname> is specified, then it defaults to the current branch.
$ git branch -u <origin>/<branch> <branch>
# else:
$ git checkout -b <branch> --track <origin>/<branch>
<branch>
. $ git submodule add -b <branch> <repository> [<submodule-path>]
$ git config -f .gitmodules submodule.<submodule-path>.update rebase
$ git submodule update --remote
$ cd <submodule-path>
$ git checkout <branch>
$ cd <parent-repo-path>
# <submodule-path> is here path releative to parent repo root
# without starting path separator
$ git config -f .gitmodules submodule.<submodule-path>.branch <branch>
$ git config -f .gitmodules submodule.<submodule-path>.update <rebase|merge>
In the common cases, you already have fixed by now your DETACHED HEAD since it was related to one of the configuration issues above.
fixing DETACHED HEAD when .update = checkout
$ cd <submodule-path> # and make modification to your submodule
$ git add .
$ git commit -m"Your modification" # Let's say you forgot to push it to remote.
$ cd <parent-repo-path>
$ git status # you will get
Your branch is up-to-date with '<origin>/<branch>'.
Changes not staged for commit:
modified: path/to/submodule (new commits)
# As normally you would commit new commit hash to your parent repo
$ git add -A
$ git commit -m"Updated submodule"
$ git push <origin> <branch>.
$ git status
Your branch is up-to-date with '<origin>/<branch>'.
nothing to commit, working directory clean
# If you now update your submodule
$ git submodule update --remote
Submodule path 'path/to/submodule': checked out 'commit-hash'
$ git status # will show again that (submodule has new commits)
$ cd <submodule-path>
$ git status
HEAD detached at <hash>
# as you see you are DETACHED and you are lucky if you found out now
# since at this point you just asked git to update your submodule
# from remote master which is 1 commit behind your local branch
# since you did not push you submodule chage commit to remote.
# Here you can fix it simply by. (in submodules path)
$ git checkout <branch>
$ git push <origin>/<branch>
# which will fix the states for both submodule and parent since
# you told already parent repo which is the submodules commit hash
# to track so you don't see it anymore as untracked.
But if you managed to make some changes locally already for submodule and commited, pushed these to remote then when you executed 'git checkout ', Git notifies you:
$ git checkout <branch>
Warning: you are leaving 1 commit behind, not connected to any of your branches:
If you want to keep it by creating a new branch, this may be a good time to do so with:
The recommended option to create a temporary branch can be good, and then you can just merge these branches etc. However I personally would use just git cherry-pick <hash>
in this case.
$ git cherry-pick <hash> # hash which git showed you related to DETACHED HEAD
# if you get 'error: could not apply...' run mergetool and fix conflicts
$ git mergetool
$ git status # since your modifications are staged just remove untracked junk files
$ rm -rf <untracked junk file(s)>
$ git commit # without arguments
# which should open for you commit message from DETACHED HEAD
# just save it or modify the message.
$ git push <origin> <branch>
$ cd <parent-repo-path>
$ git add -A # or just the unstaged submodule
$ git commit -m"Updated <submodule>"
$ git push <origin> <branch>
Although there are some more cases you can get your submodules into DETACHED HEAD state, I hope that you understand now a bit more how to debug your particular case.
error 380 windows 7 solution very easy just check your date time & regional setting do them correct.
Turns out there is a shutdown, but this must be initiated from another thread.
This solution worked for me: https://stackoverflow.com/a/22533929/573216
Take a look at this article which shows the registry keys you need to look for and provides a .NET library that will do this for you.
First, you should to determine if .NET 3.5 is installed by looking at HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Install, which is a DWORD value. If that value is present and set to 1, then that version of the Framework is installed.
Look at HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\SP, which is a DWORD value which indicates the Service Pack level (where 0 is no service pack).
To be correct about things, you really need to ensure that .NET Fx 2.0 and .NET Fx 3.0 are installed first and then check to see if .NET 3.5 is installed. If all three are true, then you can check for the service pack level.
This is surely an encoding problem. You have a different encoding in your database and in your website and this fact is the cause of the problem. Also if you ran that command you have to change the records that are already in your tables to convert those character in UTF-8.
Update: Based on your last comment, the core of the problem is that you have a database and a data source (the CSV file) which use different encoding. Hence you can convert your database in UTF-8 or, at least, when you get the data that are in the CSV, you have to convert them from UTF-8 to latin1.
You can do the convertion following this articles:
A one-L NUL, it ends a string.
A two-L NULL points to no thing.
And I will bet a golden bull
That there is no three-L NULLL.
Installing XCode requires:
To install g++ *WITHOUT* having to download the MASSIVE 4.7G xCode install, try this package:
https://github.com/kennethreitz/osx-gcc-installer
The DMG files linked on that page are ~270M and much quicker to install. This was perfect for me, getting homebrew up and running with a minimum of hassle.
The github project itself is basically a script that repackages just the critical chunks of xCode for distribution. In order to run that script and build the DMG files, you'd need to already have an XCode install, which would kind of defeat the point, so the pre-built DMG files are hosted on the project page.
I wanted to comment on @Ionica Bizau, but I don't have enough reputation.
To give a reply to your question about javascript code:
What you need to do is get the parent's element height (minus any elements that take up space) and apply that to the child elements.
function wrapperHeight(){
var height = $(window).outerHeight() - $('#header').outerHeight(true);
$('.wrapper').css({"max-height":height+"px"});
}
Note
window could be replaced by ".container" if that one has no floated children or has a fix to get the correct height calculated. This solution uses jQuery.
Found solution:
In iOS9, ATS enforces best practices during network calls, including the use of HTTPS.
ATS prevents accidental disclosure, provides secure default behavior, and is easy to adopt. You should adopt ATS as soon as possible, regardless of whether you’re creating a new app or updating an existing one. If you’re developing a new app, you should use HTTPS exclusively. If you have an existing app, you should use HTTPS as much as you can right now, and create a plan for migrating the rest of your app as soon as possible.
In beta 1, currently there is no way to define this in info.plist. Solution is to add it manually:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Update1: This is a temporary workaround until you're ready to adopt iOS9 ATS support.
Update2: For more details please refer following link: http://ste.vn/2015/06/10/configuring-app-transport-security-ios-9-osx-10-11/
Update3: If you are trying to connect to a host (YOURHOST.COM) that only has TLS 1.0
Add these to your app's Info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>YOURHOST.COM</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>1.0</string>
<key>NSTemporaryExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
</dict>
</dict>
NB: Should you want the year to be based on some reference date, the code below calculates the dates for the between
statement:
declare @referenceTime datetime = getutcdate()
select *
from myTable
where SomeDate
between dateadd(year, year(@referenceTime) - 1900, '01-01-1900') --1st Jan this year (midnight)
and dateadd(millisecond, -3, dateadd(year, year(@referenceTime) - 1900, '01-01-1901')) --31st Dec end of this year (just before midnight of the new year)
Similarly, if you're using a year value, swapping year(@referenceDate)
for your reference year's value will work
declare @referenceYear int = 2010
select *
from myTable
where SomeDate
between dateadd(year,@referenceYear - 1900, '01-01-1900') --1st Jan this year (midnight)
and dateadd(millisecond, -3, dateadd(year,@referenceYear - 1900, '01-01-1901')) --31st Dec end of this year (just before midnight of the new year)
Because font doesn't have color, you need a panel to make a backgound color and give the foreground color for both JLabel (if you use JLabel) and JPanel to make font color, like example below :
JLabel lblusr = new JLabel("User name : ");
lblusr.setForeground(Color.YELLOW);
JPanel usrPanel = new JPanel();
Color maroon = new Color (128, 0, 0);
usrPanel.setBackground(maroon);
usrPanel.setOpaque(true);
usrPanel.setForeground(Color.YELLOW);
usrPanel.add(lblusr);
The background color of label is maroon with yellow font color.
git push
can push all branches or a single one dependent on this configuration:
Push all branches
git config --global push.default matching
It will push all the branches to the remote branch and would merge them.
If you don't want to push all branches, you can push the current branch if you fully specify its name, but this is much is not different from default
.
Push only the current branch if its named upstream is identical
git config --global push.default simple
So, it's better, in my opinion, to use this option and push your code branch by branch. It's better to push branches manually and individually.
Just type .htaccess. as filename. Notice the dot at the end of htaccess. This will change in Windows to .htaccess without a dot at the end.
To use ProgressDialog
use the below code
ProgressDialog progressdialog = new ProgressDialog(getApplicationContext());
progressdialog.setMessage("Please Wait....");
To start the ProgressDialog
use
progressdialog.show();
progressdialog.setCancelable(false);
is used so that ProgressDialog
cannot be cancelled until the work is done.
To stop the ProgressDialog
use this code (when your work is finished):
progressdialog.dismiss();`
I'd like to expand a little bit on Pavel Minaev's answer, which you should read before reading my answer. Both solutions presented by Pavel won't compile if the member to be compared (such as id
in the question's code) is private. In this case, VS2013 throws the following error for me:
error C2248: 'Class1::id' : cannot access private member declared in class 'Class1'
As mentioned by SkyWalker in the comments on Pavel's answer, using a friend
declaration helps. If you wonder about the correct syntax, here it is:
class Class1
{
public:
Class1(int id) : id(id) {}
private:
int id;
friend struct Class1Compare; // Use this for Pavel's first solution.
friend struct std::less<Class1>; // Use this for Pavel's second solution.
};
However, if you have an access function for your private member, for example getId()
for id
, as follows:
class Class1
{
public:
Class1(int id) : id(id) {}
int getId() const { return id; }
private:
int id;
};
then you can use it instead of a friend
declaration (i.e. you compare lhs.getId() < rhs.getId()
).
Since C++11, you can also use a lambda expression for Pavel's first solution instead of defining a comparator function object class.
Putting everything together, the code could be writtem as follows:
auto comp = [](const Class1& lhs, const Class1& rhs){ return lhs.getId() < rhs.getId(); };
std::map<Class1, int, decltype(comp)> c2int(comp);
I created a working demo of a landscape/portrait layout but the zoom must be disabled for it to work without JavaScript:
http://matthewjamestaylor.com/blog/ipad-layout-with-landscape-portrait-modes
In general you can concatenate a whole sequence of arrays along any axis:
numpy.concatenate( LIST, axis=0 )
but you do have to worry about the shape and dimensionality of each array in the list (for a 2-dimensional 3x5 output, you need to ensure that they are all 2-dimensional n-by-5 arrays already). If you want to concatenate 1-dimensional arrays as the rows of a 2-dimensional output, you need to expand their dimensionality.
As Jorge's answer points out, there is also the function stack
, introduced in numpy 1.10:
numpy.stack( LIST, axis=0 )
This takes the complementary approach: it creates a new view of each input array and adds an extra dimension (in this case, on the left, so each n
-element 1D array becomes a 1-by-n
2D array) before concatenating. It will only work if all the input arrays have the same shape—even along the axis of concatenation.
vstack
(or equivalently row_stack
) is often an easier-to-use solution because it will take a sequence of 1- and/or 2-dimensional arrays and expand the dimensionality automatically where necessary and only where necessary, before concatenating the whole list together. Where a new dimension is required, it is added on the left. Again, you can concatenate a whole list at once without needing to iterate:
numpy.vstack( LIST )
This flexible behavior is also exhibited by the syntactic shortcut numpy.r_[ array1, ...., arrayN ]
(note the square brackets). This is good for concatenating a few explicitly-named arrays but is no good for your situation because this syntax will not accept a sequence of arrays, like your LIST
.
There is also an analogous function column_stack
and shortcut c_[...]
, for horizontal (column-wise) stacking, as well as an almost-analogous function hstack
—although for some reason the latter is less flexible (it is stricter about input arrays' dimensionality, and tries to concatenate 1-D arrays end-to-end instead of treating them as columns).
Finally, in the specific case of vertical stacking of 1-D arrays, the following also works:
numpy.array( LIST )
...because arrays can be constructed out of a sequence of other arrays, adding a new dimension to the beginning.
Jon Skeet is correct. Here is the Nul Device Driver page in the Windows Embedded documentation (I have no idea why it's not somewhere else...).
Here is another:
There is a command line switch for this: --auto-open-devtools-for-tabs
So for the properties on Google Chrome, use something like this:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --auto-open-devtools-for-tabs
Here is a useful link: chromium-command-line-switches
I used this method to clear the image from picturebox. It may help some one
private void btnClear1_Click(object sender, EventArgs e)
{
img1.ImageLocation = null;
}
Looks like this exception message is quite generic and can be received due to a variety of reasons. We ran into this while deploying the client on Windows 8.1 machines. Our WCF client runs inside of a windows service and continuously polls the WCF service. The windows service runs under a non-admin user. The issue was fixed by setting the clientCredentialType to "Windows" in the WCF configuration to allow the authentication to pass-through, as in the following:
<security mode="None">
<transport clientCredentialType="Windows" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
here is direct link for api 17 documentation. Just extract at under docs folder. Hope it helps.
https://dl-ssl.google.com/android/repository/docs-17_r02.zip (129 MB)
Since a ThreadLocal
is a reference to data within a given Thread
, you can end up with classloading leaks when using ThreadLocal
s in application servers using thread pools. You need to be very careful about cleaning up any ThreadLocal
s you get()
or set()
by using the ThreadLocal
's remove()
method.
If you do not clean up when you're done, any references it holds to classes loaded as part of a deployed webapp will remain in the permanent heap and will never get garbage collected. Redeploying/undeploying the webapp will not clean up each Thread
's reference to your webapp's class(es) since the Thread
is not something owned by your webapp. Each successive deployment will create a new instance of the class which will never be garbage collected.
You will end up with out of memory exceptions due to java.lang.OutOfMemoryError: PermGen space
and after some googling will probably just increase -XX:MaxPermSize
instead of fixing the bug.
If you do end up experiencing these problems, you can determine which thread and class is retaining these references by using Eclipse's Memory Analyzer and/or by following Frank Kieviet's guide and followup.
Update: Re-discovered Alex Vasseur's blog entry that helped me track down some ThreadLocal
issues I was having.
As a supplementary to the two previous answers (of user "sudo rm -rf" and "Evan Mulawski"), if you don't want to do anything when your alert view is clicked, you can just allocate, show and release it. You don't have to declare the delegate protocol.
Just place jquery url on the top of your jquery code
like this--
<script src="<%=ResolveUrl("~/Scripts/jquery-1.3.2.js")%>" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('#post').click(function() {
alert("test");
});
});
</script>
To help others who do not have a full disk to troubleshoot this problem, first inspect your error log (for me the path is given in my /etc/mysql/my.cnf
file):
tail /var/log/mysql/error.log
My problem turned out to be a new IP address allocated after some network router reconfiguration, so I needed to change the bind-address
variable.
Maybe this is what you want?
echo foo > test.txt
echo. >> test.txt
echo bar >> test.txt
results in the following within test.txt:
foo
bar
You can create an ExtensionMethod to do that!
public static class StringExtension
{
public static string Repeat(this string str, int count)
{
string ret = "";
for (var x = 0; x < count; x++)
{
ret += str;
}
return ret;
}
}
Or using @Dan Tao solution:
public static class StringExtension
{
public static string Repeat(this string str, int count)
{
if (count == 0)
return "";
return string.Concat(Enumerable.Repeat(indent, N))
}
}
Per Caching SHA-2 Pluggable Authentication
In MySQL 8.0,
caching_sha2_password
is the default authentication plugin rather thanmysql_native_password
.
You're using mysql_native_password
, which is no longer the default. Assuming you're using the correct connector for your version you need to specify the auth_plugin
argument when instantiating your connection object
cnx = mysql.connector.connect(user='lcherukuri', password='password',
host='127.0.0.1', database='test',
auth_plugin='mysql_native_password')
From those same docs:
The
connect()
method supports anauth_plugin
argument that can be used to force use of a particular plugin. For example, if the server is configured to usesha256_password
by default and you want to connect to an account that authenticates usingmysql_native_password
, either connect using SSL or specifyauth_plugin='mysql_native_password'
.
You need to deserialize the JSON once before returning it as response. Please refer below code. This works for me:
JavaScriptSerializer jss = new JavaScriptSerializer();
Object finalData = jss.DeserializeObject(str);
You could fix it with the PHP constant __DIR__
require_once __DIR__ . '/common/configs/config_templates.inc.php';
It is the directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname
__FILE__
. This directory name does not have a trailing slash unless it is the root directory. 1
The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2
package.
An example with your data:
# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")
# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) +
geom_point(size=5) +
labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
theme_bw() +
theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))
this results in:
As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888"))
instead of scale_color_manual()
.
window.onresize = function(){
var img = document.getElementById('fullsize');
img.style.width = "100%";
};
In IE onresize
event gets fired on every pixel change (width or height) so there could be performance issue. Delay image resizing for few milliseconds by using javascript's window.setTimeout().
http://mbccs.blogspot.com/2007/11/fixing-window-resize-event-in-ie.html
Put that file in assets.
For project created in Android Studio project you need to create assets folder under the main folder.
Read that file as:
public String loadJSONFromAsset(Context context) {
String json = null;
try {
InputStream is = context.getAssets().open("file_name.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
and then you can simply read this string
return by this function as
JSONObject obj = new JSONObject(json_return_by_the_function);
For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html
Hope you will get what you want.
I am still a beginner at git, and it was just a stupid mistake I made, long story in one sentence. I was not in a subfolder as @gaoagong reported, but the other way round, in a parent folder. Strange enough, I did not get the idea from that answer, instead, the idea came up when I tested git add --all
, see the long story below.
Example in details. Actual repo:
The Parent folder that I had opened mistakenly on parent level (vscode_git in my case):
I had cloned a repo, but I had a parent folder above this repo which I had opened instead, and then I tried adding a file of the subfolder's repo with git add 'd:\Stack Overflow\vscode_git\vscode-java\.github\ISSUE_TEMPLATE.md'
, which simply did nothing, no warning message, and the git status
afterwards said:
nothing added to commit but untracked files present (use "git add" to track)
Running git add --all
gave me the yellow notes:
warning: adding embedded git repository: vscode-java the embedded repository and will not know how to obtain it.
hint: If you meant to add a submodule, use: git submodule add vscode-java
hint: If you added this path by mistake, you can remove it from the index with git rm --cached vscode-java
See "git help submodule" for more information.git
To fix this, I reverted the git add --all
with git rm --cached -r -f -- "d:\Stack Overflow\vscode_git\vscode-java" rm 'vscode-java'
:
Then, by simply opening the actual repo folder instead,
the git worked as expected again. Of course the ".git" folder of the parent folder could be deleted then:
I wrap connection with the helper class:
public class ConnectionFactory
{
private readonly string _connectionName;
public ConnectionFactory(string connectionName)
{
_connectionName = connectionName;
}
public IDbConnection NewConnection() => new SqlConnection(_connectionName);
#region Connection Scopes
public TResult Scope<TResult>(Func<IDbConnection, TResult> func)
{
using (var connection = NewConnection())
{
connection.Open();
return func(connection);
}
}
public async Task<TResult> ScopeAsync<TResult>(Func<IDbConnection, Task<TResult>> funcAsync)
{
using (var connection = NewConnection())
{
connection.Open();
return await funcAsync(connection);
}
}
public void Scope(Action<IDbConnection> func)
{
using (var connection = NewConnection())
{
connection.Open();
func(connection);
}
}
public async Task ScopeAsync<TResult>(Func<IDbConnection, Task> funcAsync)
{
using (var connection = NewConnection())
{
connection.Open();
await funcAsync(connection);
}
}
#endregion Connection Scopes
}
Examples of usage:
public class PostsService
{
protected IConnectionFactory Connection;
// Initialization here ..
public async Task TestPosts_Async()
{
// Normal way..
var posts = Connection.Scope(cnn =>
{
var state = PostState.Active;
return cnn.Query<Post>("SELECT * FROM [Posts] WHERE [State] = @state;", new { state });
});
// Async way..
posts = await Connection.ScopeAsync(cnn =>
{
var state = PostState.Active;
return cnn.QueryAsync<Post>("SELECT * FROM [Posts] WHERE [State] = @state;", new { state });
});
}
}
So I don't have to explicitly open the connection every time. Additionally, you can use it this way for the convenience' sake of the future refactoring:
var posts = Connection.Scope(cnn =>
{
var state = PostState.Active;
return cnn.Query<Post>($"SELECT * FROM [{TableName<Post>()}] WHERE [{nameof(Post.State)}] = @{nameof(state)};", new { state });
});
What is TableName<T>()
can be found in this answer.
The problem with the recorded macro is the same as the problem with the built-in action: Excel chooses to freeze the top visible row, rather than the actual top row where the header information can be found.
The purpose of a macro in this case is to freeze the actual top row. When I am viewing row #405592 and I need to check the header for the column (because I forgot to freeze rows when I opened the file), I have to scroll to the top, freeze the top row, then find my way back to row #405592 again. Since I believe this is stupid behavior, I want a macro to correct it, but, like I said, the recorded macro just mimics the same stupid behavior.
I am using Office 2011 for Mac OS X Lion
Update (2 minutes later):
I found a solution here: http://www.ozgrid.com/forum/showthread.php?t=19692
Dim r As Range
Set r = ActiveCell
Range("A2").Select
With ActiveWindow
.FreezePanes = False
.ScrollRow = 1
.ScrollColumn = 1
.FreezePanes = True
.ScrollRow = r.Row
End With
r.Select
If your parameter value is not fixed or your value can be null based on business you can try the following approach.
DECLARE @DrugClassstring VARCHAR(MAX);
SET @DrugClassstring = 'C3,C2'; -- You can pass null also
---------------------------------------------
IF @DrugClassstring IS NULL
SET @DrugClassstring = 'C3,C2,C4,C5,RX,OT'; -- If null you can set your all conditional case that will return for all
SELECT dn.drugclass_FK , dn.cdrugname
FROM drugname AS dn
INNER JOIN dbo.SplitString(@DrugClassstring, ',') class ON dn.drugclass_FK = class.[Name] -- SplitString is a a function
SplitString function
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
ALTER FUNCTION [dbo].[SplitString](@stringToSplit VARCHAR(MAX),
@delimeter CHAR(1) = ',')
RETURNS @returnList TABLE([Name] [NVARCHAR](500))
AS
BEGIN
--It's use in report sql, before any change concern to everyone
DECLARE @name NVARCHAR(255);
DECLARE @pos INT;
WHILE CHARINDEX(@delimeter, @stringToSplit) > 0
BEGIN
SELECT @pos = CHARINDEX(@delimeter, @stringToSplit);
SELECT @name = SUBSTRING(@stringToSplit, 1, @pos-1);
INSERT INTO @returnList
SELECT @name;
SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, LEN(@stringToSplit)-@pos);
END;
INSERT INTO @returnList
SELECT @stringToSplit;
RETURN;
END;
$id = $this->db->insert_id();
var a_href = $('div.cpt').find('h2 a').attr('href');
should be
var a_href = $(this).find('div.cpt').find('h2 a').attr('href');
In the first line, your query searches the entire document. In the second, the query starts from your tr
element and only gets the element underneath it. (You can combine the find
s if you like, I left them separate to illustrate the point.)
parent_list = [{'A': 'val1', 'B': 'val2'}, {'C': 'val3', 'D': 'val4'}]
{% for dict_item in parent_list %}
{% for key, value in dict_item.items() %}
<h1>Key: {{key}}</h1>
<h2>Value: {{value}}</h2>
{% endfor %}
{% endfor %}
Make sure you have the list of dict items. If you get UnicodeError
may be the value inside the dict contains unicode format. That issue can be solved in your views.py
.
If the dict is unicode
object, you have to encode into utf-8
.
DELETE
FROM MyTable
WHERE NOT EXISTS (
SELECT min(RowID)
FROM Mytable
WHERE (SELECT RowID
FROM Mytable
GROUP BY Col1, Col2, Col3
))
);
John's answer won't produce .txt files as the OP wants. Use:
split -b=1M -d file.txt file --additional-suffix=.txt
You can't call a non-static method without first creating an instance of its parent class.
So from the static method, you would have to instantiate a new object...
Vehicle myCar = new Vehicle();
... and then call the non-static method.
myCar.Drive();
I had a ton of trouble with this and then found a great solution:
Create a file in a text editor called whoami.php with the below code as it's content, save the file and upload it to public_html (or whatever you root of your webserver directory is named). It should output a useful string that you can use to track down the user the webserver is running as, my output was "php is running as user: nt authority\iusr" which allowed me to track down the permissions I needed to modify to the user "IUSR".
<?php
// outputs the username that owns the running php/httpd process
// (on a system with the "whoami" executable in the path)
echo 'php is running as user: ' . exec('whoami');
?>
Here is a POSIX version that combines many of the previous answers to deliver following features:
Here is the code and some test cases:
import threading
import signal
import os
import time
class TerminateExecution(Exception):
"""
Exception to indicate that execution has exceeded the preset running time.
"""
def quit_function(pid):
# Killing all subprocesses
os.setpgrp()
os.killpg(0, signal.SIGTERM)
# Killing the main thread
os.kill(pid, signal.SIGTERM)
def handle_term(signum, frame):
raise TerminateExecution()
def invoke_with_timeout(timeout, fn, *args, **kwargs):
# Setting a sigterm handler and initiating a timer
old_handler = signal.signal(signal.SIGTERM, handle_term)
timer = threading.Timer(timeout, quit_function, args=[os.getpid()])
terminate = False
# Executing the function
timer.start()
try:
result = fn(*args, **kwargs)
except TerminateExecution:
terminate = True
finally:
# Restoring original handler and cancel timer
signal.signal(signal.SIGTERM, old_handler)
timer.cancel()
if terminate:
raise BaseException("xxx")
return result
### Test cases
def countdown(n):
print('countdown started', flush=True)
for i in range(n, -1, -1):
print(i, end=', ', flush=True)
time.sleep(1)
print('countdown finished')
return 1337
def really_long_function():
time.sleep(10)
def really_long_function2():
os.system("sleep 787")
# Checking that we can run a function as expected.
assert invoke_with_timeout(3, countdown, 1) == 1337
# Testing various scenarios
t1 = time.time()
try:
print(invoke_with_timeout(1, countdown, 3))
assert(False)
except BaseException:
assert(time.time() - t1 < 1.1)
print("All good", time.time() - t1)
t1 = time.time()
try:
print(invoke_with_timeout(1, really_long_function2))
assert(False)
except BaseException:
assert(time.time() - t1 < 1.1)
print("All good", time.time() - t1)
t1 = time.time()
try:
print(invoke_with_timeout(1, really_long_function))
assert(False)
except BaseException:
assert(time.time() - t1 < 1.1)
print("All good", time.time() - t1)
# Checking that classes are referenced and not
# copied (as would be the case with multiprocessing)
class X:
def __init__(self):
self.value = 0
def set(self, v):
self.value = v
x = X()
invoke_with_timeout(2, x.set, 9)
assert x.value == 9
Static method example
class StaticDemo
{
public static void copyArg(String str1, String str2)
{
str2 = str1;
System.out.println("First String arg is: "+str1);
System.out.println("Second String arg is: "+str2);
}
public static void main(String agrs[])
{
//StaticDemo.copyArg("XYZ", "ABC");
copyArg("XYZ", "ABC");
}
}
Output:
First String arg is: XYZ
Second String arg is: XYZ
As you can see in the above example that for calling static method, I didn’t even use an object. It can be directly called in a program or by using class name.
Non-static method example
class Test
{
public void display()
{
System.out.println("I'm non-static method");
}
public static void main(String agrs[])
{
Test obj=new Test();
obj.display();
}
}
Output:
I'm non-static method
A non-static method is always be called by using the object of class as shown in the above example.
Key Points:
How to call static methods: direct or using class name:
StaticDemo.copyArg(s1, s2);
or
copyArg(s1, s2);
How to call a non-static method: using object of the class:
Test obj = new Test();
This Problem is due to Security, Better open Developer Command prompt for VS 2012 in RUN AS ADMINISTRATOR and install your Service, it fix your problem surely.
Try this it will not throw exception and user can try again:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
int choice = 0;
while (!Int32.TryParse(Console.ReadLine(), out choice))
{
Console.WriteLine("Wrong input! Enter choice number again:");
}
Save this little extension:
extension Int {
var seconds: Int {
return self
}
var minutes: Int {
return self.seconds * 60
}
var hours: Int {
return self.minutes * 60
}
var days: Int {
return self.hours * 24
}
var weeks: Int {
return self.days * 7
}
var months: Int {
return self.weeks * 4
}
var years: Int {
return self.months * 12
}
}
Then use it intuitively like:
let threeDaysLater = TimeInterval(3.days)
date.addingTimeInterval(threeDaysLater)
>>> if 'foo' in foo and 'bar' in foo:
... print 'yes'
...
yes
Jason, () aren't necessary in Python.
You would have to open a new window(or navigate to a new page) containing just the information you wish the user to be able to print
Javscript:
function printInfo(ele) {
var openWindow = window.open("", "title", "attributes");
openWindow.document.write(ele.previousSibling.innerHTML);
openWindow.document.close();
openWindow.focus();
openWindow.print();
openWindow.close();
}
HTML:
<div id="....">
<div>
content to print
</div><a href="#" onclick="printInfo(this)">Print</a>
</div>
A few notes here: the anchor must NOT have whitespace between it and the div containing the content to print
Sessions would be the only good way, you could also use GET/POST but that would be potentially insecure.
In linear regression, the outcome (dependent variable) is continuous. It can have any one of an infinite number of possible values. In logistic regression, the outcome (dependent variable) has only a limited number of possible values.
For instance, if X contains the area in square feet of houses, and Y contains the corresponding sale price of those houses, you could use linear regression to predict selling price as a function of house size. While the possible selling price may not actually be any, there are so many possible values that a linear regression model would be chosen.
If, instead, you wanted to predict, based on size, whether a house would sell for more than $200K, you would use logistic regression. The possible outputs are either Yes, the house will sell for more than $200K, or No, the house will not.
Login to Server as Admin
Go To Security > Logins > New Login
Step 1:
Login Name : SomeName
Step 2:
Select SQL Server / Windows Authentication.
More Info on, what is the differences between sql server authentication and windows authentication..?
Choose Default DB and Language of your choice
Click OK
Try to connect with the New User Credentials, It will prompt you to change the password. Change and login
OR
Try with query :
USE [master] -- Default DB
GO
CREATE LOGIN [Username] WITH PASSWORD=N'123456', DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=ON, CHECK_POLICY=ON
GO
--123456 is the Password And Username is Login User
ALTER LOGIN [Username] enable -- Enable or to Disable User
GO
Actually, the difference between hibernate save() and persist() methods depends on generator class we are using.
If our generator class is assigned, then there is no difference between save() and persist() methods. Because generator ‘assigned’ means, as a programmer we need to give the primary key value to save in the database right [ Hope you know this generators concept ]
In case of other than assigned generator class, suppose if our generator class name is Increment means hibernate itself will assign the primary key id value into the database right [other than assigned generator, hibernate only used to take care the primary key id value remember], so in this case if we call save() or persist() method, then it will insert the record into the database normally.
But here, thing is, save() method can return that primary key id value which is generated by hibernate and we can see it by
long s = session.save(k);
In this same case, persist() will never give any value back to the client, return type void.
persist() also guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries.
whereas in save(), INSERT happens immediately, no matter if you are inside or outside of a transaction.
It's called market segmentation or something like that. nVidia produces one very configurable chip and then sells it in different configurations that essentially have the same elements and hence the same bill of materials to different market segments, although one would usually expect to find elements of higher quality on the more expensive Quadro boards.
What differentiates Quadro from GeForce is that GeForce usually has its dual precision floating point performance severely limited, e.g. to 1/4 or 1/8 of that of the Quadro/Tesla GPUs. This limitation is purely artificial and imposed on solely to differentiate the gamer/enthusiast segment from the professional segment. Lower DP performance makes GeForce boards bad candidates for stuff like scientific or engineering computing and those are markets where money streams from. Also Quadros (arguably) have more display channels and faster RAMDACs which allows them to drive more and higher resolution screens, a sort of setup perceived as professional for CAD/CAM work.
As Jason Morgan has pointed out, there are tricks that can unlock some of the disabled features in GeForce to bring them in par with Quadro. Those usually involves soldering and voids the warranty on the card. Since HPC puts lots of stress on the hardware and malfunctions occur more frequently that one would like them to, I would advise against using cheap tricks.
To revert a merge commit, you need to use: git revert -m <parent number>
. So for example, to revert the recent most merge commit using the parent with number 1 you would use:
git revert -m 1 HEAD
To revert a merge commit before the last commit, you would do:
git revert -m 1 HEAD^
Use git show <merge commit SHA1>
to see the parents, the numbering is the order they appear e.g. Merge: e4c54b3 4725ad2
git merge documentation: http://schacon.github.com/git/git-merge.html
git merge discussion (confusing but very detailed): http://schacon.github.com/git/howto/revert-a-faulty-merge.txt
I am promoting my comment to an answer:
The easy way is:
You could draw in the original 'frame' itself instead of using gray image.
The hard way (method you were trying to implement):
backtorgb = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB)
is the correct syntax.
There is no function overloading in Python, meaning that you can't have multiple functions with the same name but different arguments.
In your code example, you're not overloading __init__()
. What happens is that the second definition rebinds the name __init__
to the new method, rendering the first method inaccessible.
As to your general question about constructors, Wikipedia is a good starting point. For Python-specific stuff, I highly recommend the Python docs.
The limit of requests in .Net can be configured from two properties together:
Web.Config/system.web/httpRuntime/maxRequestLength
Web.Config/system.webServer/security/requestFiltering/requestLimits/maxAllowedContentLength
(in bytes)References:
Example:
<location path="upl">
<system.web>
<!--The default size is 4096 kilobytes (4 MB). MaxValue is 2147483647 KB (2 TB)-->
<!-- 100 MB in kilobytes -->
<httpRuntime maxRequestLength="102400" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<!--The default size is 30000000 bytes (28.6 MB). MaxValue is 4294967295 bytes (4 GB)-->
<!-- 100 MB in bytes -->
<requestLimits maxAllowedContentLength="104857600" />
</requestFiltering>
</security>
</system.webServer>
</location>
fname = "feed.txt"
feed = open(fname, 'r')
num_lines = len(feed.splitlines())
num_words = 0
num_chars = 0
for line in lines:
num_words += len(line.split())
paste this code in ur MainActivity
TextView textview=(TextView)findViewById(R.id.textviewid);
Spannable spannable=new SpannableString("Hello my name is sunil");
spannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 5,
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
textview.setText(spannable);
//Note:- the 0,5 is the size of colour which u want to give the strring
//0,5 means it give colour to starting from h and ending with space i.e.(hello), if you want to change size and colour u can easily
Two different characters.
\n
is used as an end-of-line terminator in Unix text files
\r
Was historically (pre-OS X) used as an end-of-line terminator in Mac text files
\r\n
(ie both) are used to terminate lines in Windows and DOS text files.
In case if you have to apply your custom class you can use
@Html.TextBoxFor(m => m.Birthday, new Dictionary<string, object>() { {"readonly", "true"}, {"class", "commonField"} } )
Where are
commonField is CSS class
and Birthday could be string field that you probably can use to keep jQuery Datapicker
date :)
<script>
$(function () {
$("#Birthday").datepicker({
});
});
</script>
That's a real life example.
The stopPropagation()
method stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.
You can use the method event.isPropagationStopped()
to know whether this method was ever called (on that event object).
Syntax:
Here is the simple syntax to use this method:
event.stopPropagation()
Example:
$("div").click(function(event) {
alert("This is : " + $(this).prop('id'));
// Comment the following to see the difference
event.stopPropagation();
});?
simply go to this link
download the dll
copy and paste the dll to the plugins folder at notepad++, \Notepad++\plugins
restart the notepad++, and it should be shown in the list
NOTE: this dll supports 64 bit notepade++
I tried $request->merge($array)
function in Laravel 5.2 and it is working perfectly.
Example:
$request->merge(["key"=>"value"]);
docs: SQL Expression Language Tutorial - Using Text
example:
from sqlalchemy.sql import text
connection = engine.connect()
# recommended
cmd = 'select * from Employees where EmployeeGroup = :group'
employeeGroup = 'Staff'
employees = connection.execute(text(cmd), group = employeeGroup)
# or - wee more difficult to interpret the command
employeeGroup = 'Staff'
employees = connection.execute(
text('select * from Employees where EmployeeGroup = :group'),
group = employeeGroup)
# or - notice the requirement to quote 'Staff'
employees = connection.execute(
text("select * from Employees where EmployeeGroup = 'Staff'"))
for employee in employees: logger.debug(employee)
# output
(0, 'Tim', 'Gurra', 'Staff', '991-509-9284')
(1, 'Jim', 'Carey', 'Staff', '832-252-1910')
(2, 'Lee', 'Asher', 'Staff', '897-747-1564')
(3, 'Ben', 'Hayes', 'Staff', '584-255-2631')
You have to bind your event handlers to correct context (this
):
onChange={this.setAuthorState.bind(this)}
print 'yes' if 0 < x < 0.5 else 'no'
range()
is for generating arrays of consecutive integers
General function to round a datetime at any time lapse in seconds:
def roundTime(dt=None, roundTo=60):
"""Round a datetime object to any time lapse in seconds
dt : datetime.datetime object, default now.
roundTo : Closest number of seconds to round to, default 1 minute.
Author: Thierry Husson 2012 - Use it as you want but don't blame me.
"""
if dt == None : dt = datetime.datetime.now()
seconds = (dt.replace(tzinfo=None) - dt.min).seconds
rounding = (seconds+roundTo/2) // roundTo * roundTo
return dt + datetime.timedelta(0,rounding-seconds,-dt.microsecond)
Samples with 1 hour rounding & 30 minutes rounding:
print roundTime(datetime.datetime(2012,12,31,23,44,59,1234),roundTo=60*60)
2013-01-01 00:00:00
print roundTime(datetime.datetime(2012,12,31,23,44,59,1234),roundTo=30*60)
2012-12-31 23:30:00
In short:
import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)
Many examples on the matplotlib website. The one I most commonly use is here
After you granted the permissions to the specified user you have to do this at filtering:
First step:
Second step:
Now you will be able to display the tables after you changed the default load Alter session to the desire schema (using a Trigger after LOG ON).
This is called Fixed Header Scrolling. There are a number of documented approaches:
http://www.imaputz.com/cssStuff/bigFourVersion.html
You won't effectively pull this off without JavaScript ... especially if you want cross browser support.
There are a number of gotchyas with any approach you take, especially concerning cross browser/version support.
Edit:
Even if it's not the header you want to fix, but the first row of data, the concept is still the same. I wasn't 100% which you were referring to.
Additional thought I was tasked by my company to research a solution for this that could function in IE7+, Firefox, and Chrome.
After many moons of searching, trying, and frustration it really boiled down to a fundamental problem. For the most part, in order to gain the fixed header, you need to implement fixed height/width columns because most solutions involve using two separate tables, one for the header which will float and stay in place over the second table that contains the data.
//float this one right over second table
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</table>
<table>
//Data
</table>
An alternative approach some try is utilize the tbody and thead tags but that is flawed too because IE will not allow you put a scrollbar on the tbody which means you can't limit its height (so stupid IMO).
<table>
<thead style="do some stuff to fix its position">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody style="No scrolling allowed here!">
Data here
</tbody>
</table>
This approach has many issues such as ensures EXACT pixel widths because tables are so cute in that different browsers will allocate pixels differently based on calculations and you simply CANNOT (AFAIK) guarantee that the distribution will be perfect in all cases. It becomes glaringly obvious if you have borders within your table.
I took a different approach and said screw tables since you can't make this guarantee. I used divs to mimic tables. This also has issues of positioning the rows and columns (mainly because floating has issues, using in-line block won't work for IE7, so it really left me with using absolute positioning to put them in their proper places).
There is someone out there that made the Slick Grid which has a very similar approach to mine and you can use and a good (albeit complex) example for achieving this.
The easy solution is to write something like that,
px-lg-1
mb-lg-5
By adding lg, the class will be applied only on large screens
php_uname but I am not sure what hostname you want the hostname of the client or server.
plus you should use cookie based approach
From http://sed.sourceforge.net/sed1line.txt: (Please don't ask me how this works ;-) )
# delete duplicate, consecutive lines from a file (emulates "uniq").
# First line in a set of duplicate lines is kept, rest are deleted.
sed '$!N; /^\(.*\)\n\1$/!P; D'
# delete duplicate, nonconsecutive lines from a file. Beware not to
# overflow the buffer size of the hold space, or else use GNU sed.
sed -n 'G; s/\n/&&/; /^\([ -~]*\n\).*\n\1/d; s/\n//; h; P'
For non-grouped elements, name and id should be same. In this case you gave name as 'sp' and id as 'sp_100'. Don't do that, do it like this:
HTML:
<input type="hidden" id="msg" name="msg" value="" style="display:none"/>
<input type="checkbox" name="sp" value="100" id="sp">
Javascript:
var Msg="abc";
document.getElementById('msg').value = Msg;
document.getElementById('sp').checked = true;
For more details
please visit : http://www.impressivewebs.com/avoiding-problems-with-javascript-getelementbyid-method-in-internet-explorer-7/
You can setup _JAVA_OPTIONS
instead of JAVA_OPTS
. This should work without $_JAVA_OPTIONS
.
Here is a solution to deal with files, which may be used more frequently...
int convert(char *infile, char *outfile) {
char *source = NULL;
FILE *fp = fopen(infile, "r");
long bufsize;
if (fp != NULL) {
/* Go to the end of the file. */
if (fseek(fp, 0L, SEEK_END) == 0) {
/* Get the size of the file. */
bufsize = ftell(fp);
if (bufsize == -1) { /* Error */ }
/* Allocate our buffer to that size. */
source = malloc(sizeof(char) * (bufsize + 1));
/* Go back to the start of the file. */
if (fseek(fp, 0L, SEEK_SET) != 0) { /* Error */ }
/* Read the entire file into memory. */
size_t newLen = fread(source, sizeof(char), bufsize, fp);
if ( ferror( fp ) != 0 ) {
fputs("Error reading file", stderr);
} else {
source[newLen++] = '\0'; /* Just to be safe. */
}
}
fclose(fp);
}
int sourceLen = bufsize - 1;
int destLen = sourceLen/2;
unsigned char* dest = malloc(destLen);
short i;
unsigned char highByte, lowByte;
for (i = 0; i < sourceLen; i += 2)
{
highByte = toupper(source[i]);
lowByte = toupper(source[i + 1]);
if (highByte > 0x39)
highByte -= 0x37;
else
highByte -= 0x30;
if (lowByte > 0x39)
lowByte -= 0x37;
else
lowByte -= 0x30;
dest[i / 2] = (highByte << 4) | lowByte;
}
FILE *fop = fopen(outfile, "w");
if (fop == NULL) return 1;
fwrite(dest, 1, destLen, fop);
fclose(fop);
free(source);
free(dest);
return 0;
}
To invoke the procedure from the SQLPlus command line, try one of these:
CALL test_sp_1();
EXEC test_sp_1
If you commit one file and push your revision, it will not transfer the whole repository, it will push changes.
Just an addition to the answers above.
If you want to execute a SQL with an "IN" statement you could do this:
ids_list = [1,2,3]
query = "SELECT id, name FROM user WHERE id IN %s"
args = [(ids_list,)] # Don't forget the "comma", to force the tuple
conn.execute(query, args)
Two points:
EDIT Watch out that if the length of list is one or zero this will raise an error!
Instead of .First()
change it to .FirstOrDefault()
In Java, integer literals are of type int by default. For some other types, you may suffix the literal with a case-insensitive letter like L
, D
, F
to specify a long, double, or float, respectively. Note it is common practice to use uppercase letters for better readability.
The Java Language Specification does not provide the same syntactic sugar for byte or short types. Instead, you may declare it as such using explicit casting:
byte foo = (byte)0;
short bar = (short)0;
In your setLongValue(100L)
method call, you don't have to necessarily include the L
suffix because in this case the int literal is automatically widened to a long. This is called widening primitive conversion in the Java Language Specification.
use:
opener.document.<id of document>.innerHTML = xmlhttp.responseText;