ActiveX
is supported by Chrome.
Chrome check parameters defined in : control panel/Internet option/Security
.
Nevertheless,if it's possible to define four different area with IE
, Chrome
only check "Internet
" area.
Late reading this, but.. The way I read your question, you only need to change two lines of code:
Accept user input, function writes back on screen.
<input type="text" id="userInput"=> give me input</input>
<button onclick="test()">Submit</button>
<!-- add this line for function to write into -->
<p id="demo"></p>
<script type="text/javascript">
function test(){
var userInput = document.getElementById("userInput").value;
document.getElementById("demo").innerHTML = userInput;
}
</script>
In my case the issue revealed to be chrome blocking the CORS request from localhost:4200 to facebook api website. Running Chrome with this setting: "YOUR_PATH_TO_CHROME\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="c:/chrome worked like a charm while developing. Even with no localhost added to facebook app's settings.
This took me ages to figure out once, you need this:
log4j.logger.httpclient.wire=ERROR
I guess HttpClient uses "httpclient.wire" as its logger name, not "org.apache.commons.httpclient".
Sneaky buggers.
To define Optional
Protocol
in swift you should use @objc
keyword before Protocol
declaration and attribute
/method
declaration inside that protocol.
Below is a sample of Optional Property of a protocol.
@objc protocol Protocol {
@objc optional var name:String?
}
class MyClass: Protocol {
// No error
}
WinObjC? Windows Bridge for iOS (previously known as ‘Project Islandwood’).
Windows Bridge for iOS (also referred to as WinObjC) is a Microsoft open source project that provides an Objective-C development environment for Visual Studio/Windows. In addition, WinObjC provides support for iOS API compatibility. While the final release will happen later this fall (allowing the bridge to take advantage of new tooling capabilities that will ship with the upcoming Visual Studio 2015 Update),
The bridge is available to the open-source community now in its current state. Between now and the fall. The iOS bridge as an open-source project under the MIT license. Given the ambition of the project, making it easy for iOS developers to build and run apps on Windows.
Salmaan Ahmed has an in-depth post on the Windows Bridge for iOS http://blogs.windows.com/buildingapps/2015/08/06/windows-bridge-for-ios-lets-open-this-up/ discussing the compiler, runtime, IDE integration, and what the bridge is and isn’t. Best of all, the source code for the iOS bridge is live on GitHub right now.
The iOS bridge supports both Windows 8.1 and Windows 10 apps built for x86 and x64 processor architectures, and soon we will add compiler optimizations and support for ARM, which adds mobile support.
If anyone comes looking for first day of previous month and last day of previous month:
public static LocalDate firstDayOfPreviousMonth(LocalDate date) {
return date.minusMonths(1).withDayOfMonth(1);
}
public static LocalDate lastDayOfPreviousMonth(LocalDate date) {
return date.withDayOfMonth(1).minusDays(1);
}
Configuring a working email client from localhost
is quite a chore, I have spent hours of frustration attempting it. At last I have found this way to send mails (using WAMP, XAMPP, etc.):
Configure this hMailServer setting:
Configure your Gmail account, perform following modification:
If you want to send email from another computer you need to allow deliveries from External to External accounts by following steps:
OK, i just fixed this error.
This happens when there is an error in query or table doesn't exist.
Try debugging the query buy running it directly on phpmyadmin to confirm the validity of the mysql Query
Go and look at the printf()
implementation with "%f"
in some C library.
You can use this code:
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.setConnectTimeout(TIME_OUT);
conection.connect();
// Getting file length
int lenghtOfFile = conection.getContentLength();
// Create a Input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream to write file
OutputStream output = new FileOutputStream(
"/sdcard/9androidnet.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (SocketTimeoutException e) {
connectionTimeout=true;
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
You can't modify the collection, not even the values. You could save these cases and remove them later. It would end up like this:
Dictionary<string, int> colStates = new Dictionary<string, int>();
// ...
// Some code to populate colStates dictionary
// ...
int OtherCount = 0;
List<string> notRelevantKeys = new List<string>();
foreach (string key in colStates.Keys)
{
double Percent = colStates[key] / colStates.Count;
if (Percent < 0.05)
{
OtherCount += colStates[key];
notRelevantKeys.Add(key);
}
}
foreach (string key in notRelevantKeys)
{
colStates[key] = 0;
}
colStates.Add("Other", OtherCount);
Figured it out. The VM's in cloud engine don't come with a root password setup by default so you'll first need to change the password using
sudo passwd
If you do everything correctly, it should do something like this:
user@server[~]# sudo passwd
Changing password for user root.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
This code worked for me.
After clicking on the link, it will ask you to choose the contact to share a message.
<a href="https://api.whatsapp.com/send?text=enter message here">Click here to share on Whatsapp</a>
_x000D_
You can add target="_blank" attribute to open it in a new window or tab.
I don't think the phone number is needed when someone wants to share a particular message or article.
I have found it best to add viewBox
and preserveAspectRatio
attributes to my SVGs. The viewbox should describe the full width and height of the SVG in the form 0 0 w h
:
<svg preserveAspectRatio="xMidYMid meet" viewBox="0 0 700 550"></svg>
In case something modifies the location that you're trying to serve, e.g. try_files
, this preserves the request for the back-end:
location / {
proxy_pass http://127.0.0.1:8080$request_uri;
}
You can do this by thinking of it a little bit differently. Detect when the body is clicked (document.body.onclick
- i.e. anything on the page) and then check if the element clicked (event.srcElement
/ e.target
) has a class and that that class name is the one you want:
document.body.onclick = function(e) { //when the document body is clicked
if (window.event) {
e = event.srcElement; //assign the element clicked to e (IE 6-8)
}
else {
e = e.target; //assign the element clicked to e
}
if (e.className && e.className.indexOf('someclass') != -1) {
//if the element has a class name, and that is 'someclass' then...
alert('hohoho');
}
}
Or a more concise version of the above:
document.body.onclick= function(e){
e=window.event? event.srcElement: e.target;
if(e.className && e.className.indexOf('someclass')!=-1)alert('hohoho');
}
You have a few options, all varying in "correctness" and ease of use. As always, the right design depends on your needs.
You could simply create two columns in Ticket, OwnedByUserId and OwnedByGroupId, and have nullable Foreign Keys to each table.
You could create M:M reference tables enabling both ticket:user and ticket:group relationships. Perhaps in future you will want to allow a single ticket to be owned by multiple users or groups? This design does not enforce that a ticket must be owned by a single entity only.
You could create a default group for every user and have tickets simply owned by either a true Group or a User's default Group.
Or (my choice) model an entity that acts as a base for both Users and Groups, and have tickets owned by that entity.
Heres a rough example using your posted schema:
create table dbo.PartyType
(
PartyTypeId tinyint primary key,
PartyTypeName varchar(10)
)
insert into dbo.PartyType
values(1, 'User'), (2, 'Group');
create table dbo.Party
(
PartyId int identity(1,1) primary key,
PartyTypeId tinyint references dbo.PartyType(PartyTypeId),
unique (PartyId, PartyTypeId)
)
CREATE TABLE dbo.[Group]
(
ID int primary key,
Name varchar(50) NOT NULL,
PartyTypeId as cast(2 as tinyint) persisted,
foreign key (ID, PartyTypeId) references Party(PartyId, PartyTypeID)
)
CREATE TABLE dbo.[User]
(
ID int primary key,
Name varchar(50) NOT NULL,
PartyTypeId as cast(1 as tinyint) persisted,
foreign key (ID, PartyTypeId) references Party(PartyID, PartyTypeID)
)
CREATE TABLE dbo.Ticket
(
ID int primary key,
[Owner] int NOT NULL references dbo.Party(PartyId),
[Subject] varchar(50) NULL
)
When generating mapping files using doctrine I ran into same issue. I fixed it by removing all comments that some fields had in the database.
Learn them and slowly you'll be able to reconize and figure out when to use them. Start with something simple as the singleton pattern :)
if you want to create one instance of an object and just ONE. You use the singleton pattern. Let's say you're making a program with an options object. You don't want several of those, that would be silly. Singleton makes sure that there will never be more than one. Singleton pattern is simple, used a lot, and really effective.
Thou shalt always encode URLs.
Here is how Ruby encodes your URL:
irb(main):008:0> CGI.escape "a.com/a+b"
=> "a.com%2Fa%2Bb"
While there are no "official guidelines" I follow the principle of KISS and DRY. Make the overloaded constructors as simple as possible, and the simplest way is that they only call this(...). That way you only need to check and handle the parameters once and only once.
public class Simple {
public Simple() {
this(null);
}
public Simple(Resource r) {
this(r, null);
}
public Simple(Resource r1, Resource r2) {
// Guard statements, initialize resources or throw exceptions if
// the resources are wrong
if (r1 == null) {
r1 = new Resource();
}
if (r2 == null) {
r2 = new Resource();
}
// do whatever with resources
}
}
From a unit testing standpoint, it'll become easy to test the class since you can put in the resources into it. If the class has many resources (or collaborators as some OO-geeks call it), consider one of these two things:
public class SimpleParams {
Resource r1;
Resource r2;
// Imagine there are setters and getters here but I'm too lazy
// to write it out. you can make it the parameter class
// "immutable" if you don't have setters and only set the
// resources through the SimpleParams constructor
}
The constructor in Simple only either needs to split the SimpleParams
parameter:
public Simple(SimpleParams params) {
this(params.getR1(), params.getR2());
}
…or make SimpleParams
an attribute:
public Simple(Resource r1, Resource r2) {
this(new SimpleParams(r1, r2));
}
public Simple(SimpleParams params) {
this.params = params;
}
Make a factory class that initializes the resources for you, which is favorable if initializing the resources is a bit difficult:
public interface ResourceFactory {
public Resource createR1();
public Resource createR2();
}
The constructor is then done in the same manner as with the parameter class:
public Simple(ResourceFactory factory) {
this(factory.createR1(), factory.createR2());
}
Yeah... you can mix and match both ways depending on what is easier for you at the time. Parameter classes and simple factory classes are pretty much the same thing considering the Simple
class that they're used the same way.
TLDR; The formula is n(n-1)/2
where n
is the number of items in the set.
To find the number of unique pairs in a set, where the pairs are subject to the commutative property (AB = BA)
, you can calculate the summation of 1 + 2 + ... + (n-1)
where n
is the number of items in the set.
The reasoning is as follows, say you have 4 items:
A
B
C
D
The number of items that can be paired with A
is 3, or n-1
:
AB
AC
AD
It follows that the number of items that can be paired with B
is n-2
(because B
has already been paired with A
):
BC
BD
and so on...
(n-1) + (n-2) + ... + (n-(n-1))
which is the same as
1 + 2 + ... + (n-1)
or
n(n-1)/2
quick and dirty manual hour changer and return:
return new Date(new Date().setHours(new Date().getHours()+3)).getHours()
Just in case someone still struggles with this, I had similar problem when trying to keep track of user session/userid on multipage form
Ive fixed that by adding
.when("/q2/:uid" in the routing:
.when("/q2/:uid", {
templateUrl: "partials/q2.html",
controller: 'formController',
paramExample: uid
})
And added this as a hidden field to pass params between webform pages
<< input type="hidden" required ng-model="formData.userid" ng-init="formData.userid=uid" />
Im new to Angular so not sure its the best possible solution but it seems to work ok for me now
Since $http.get
returns a 'promise' with the extra convenience methods success
and error
(which just wrap the result of then
) you should be able to use (regardless of your Angular version):
$http.get('/someUrl')
.then(function success(response) {
console.log('succeeded', response); // supposed to have: data, status, headers, config, statusText
}, function error(response) {
console.log('failed', response); // supposed to have: data, status, headers, config, statusText
})
Not strictly an answer to the question, but if you're getting bitten by the "my version of Angular is different than the docs" issue you can always dump all of the arguments
, even if you don't know the appropriate method signature:
$http.get('/someUrl')
.success(function(data, foo, bar) {
console.log(arguments); // includes data, status, etc including unlisted ones if present
})
.error(function(baz, foo, bar, idontknow) {
console.log(arguments); // includes data, status, etc including unlisted ones if present
});
Then, based on whatever you find, you can 'fix' the function arguments to match.
Edit: I just noticed that you said you had already created some commits. In that case, use git merge --squash
to make a single commit:
git checkout cleanchanges
git merge --squash master
git commit -m "nice commit comment for all my changes"
(Edit: The following answer applies if you have uncommitted changes.)
Just switch branches with git checkout cleanchanges
. If the branches refer to the same ref, then all your uncommitted changes will be preserved in your working directory when you switch.
The only time you would have a conflict is if some file in the repository is different between origin/master
and cleanchanges
. If you just created the branch, then no problem.
As always, if you're at all concerned about losing work, make a backup copy first. Git is designed to not throw away work without asking you first.
Eclipse forgets to copy the default apps (ROOT, examples, etc.) when it creates a Tomcat folder inside the Eclipse workspace. Go to C:\apache-tomcat-7.0.34\webapps, R-click on the ROOT folder and copy it. Then go to your Eclipse workspace, go to the .metadata folder, and search for "wtpwebapps". You should find something like your-eclipse-workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps (or .../tmp1/wtpwebapps if you already had another server registered in Eclipse). Go to the wtpwebapps folder, R-click, and paste ROOT (say "yes" if asked if you want to merge/replace folders/files). Then reload http://localhost/ to see the Tomcat welcome page.
You can use textContent attribute to retrieve data from a label.
<script>
var datas = document.getElementById("excel-data-div").textContent;
</script>
<label id="excel-data-div" style="display: none;">
Sample text
</label>
my telepathic abilities are not particularly great, but here is what I think you want:
def merge(list_of_strings, indices):
list_of_strings[indices[0]] = ''.join(list_of_strings[i] for i in indices)
list_of_strings = [s for i, s in enumerate(list_of_strings) if i not in indices[1:]]
return list_of_strings
I should note, since it might be not obvious, that it's not the same as what is proposed in other answers.
The ErrorDocument
directive, when supplied a local URL path, expects the path to be fully qualified from the DocumentRoot
. In your case, this means that the actual path to the ErrorDocument
is
ErrorDocument 404 /hellothere/error/404page.html
You need to CAST
the ParentId
as an nvarchar
, so that the output is always the same data type.
SELECT Id 'PatientId',
ISNULL(CAST(ParentId as nvarchar(100)),'') 'ParentId'
FROM Patients
sed ':a;/^\n*$/{$d;N;};/\n$/ba' file
This is not how you do things in Java. There are no dynamic variables in Java. Java variables have to be declared in the source code1.
Depending on what you are trying to achieve, you should use an array, a List
or a Map
; e.g.
int n[] = new int[3];
for (int i = 0; i < 3; i++) {
n[i] = 5;
}
List<Integer> n = new ArrayList<Integer>();
for (int i = 1; i < 4; i++) {
n.add(5);
}
Map<String, Integer> n = new HashMap<String, Integer>();
for (int i = 1; i < 4; i++) {
n.put("n" + i, 5);
}
It is possible to use reflection to dynamically refer to variables that have been declared in the source code. However, this only works for variables that are class members (i.e. static and instance fields). It doesn't work for local variables. See @fyr's "quick and dirty" example.
However doing this kind of thing unnecessarily in Java is a bad idea. It is inefficient, the code is more complicated, and since you are relying on runtime checking it is more fragile. And this is not "variables with dynamic names". It is better described as dynamic access to variables with static names.
1 - That statement is slightly inaccurate. If you use BCEL or ASM, you can "declare" the variables in the bytecode file. But don't do it! That way lies madness!
For CSS, I found that max height of 180 is better for mobile phones landscape 320 when showing browser chrome.
.scrollable-menu {
height: auto;
max-height: 180px;
overflow-x: hidden;
}
Also, to add visible scrollbars, this CSS should do the trick:
.scrollable-menu::-webkit-scrollbar {
-webkit-appearance: none;
width: 4px;
}
.scrollable-menu::-webkit-scrollbar-thumb {
border-radius: 3px;
background-color: lightgray;
-webkit-box-shadow: 0 0 1px rgba(255,255,255,.75);
}
The changes are reflected here: https://www.bootply.com/BhkCKFEELL
I created JS performance test for it http://jsperf.com/split-and-join-vs-replace2
Yes the culprit is definitely word-wrapping. When I tested your two programs, NetBeans IDE 8.2 gave me the following result.
Looking at your code closely you have used a line break at the end of first loop. But you didn't use any line break in second loop. So you are going to print a word with 1000 characters in the second loop. That causes a word-wrapping problem. If we use a non-word character " " after B, it takes only 5.35 seconds to compile the program. And If we use a line break in the second loop after passing 100 values or 50 values, it takes only 8.56 seconds and 7.05 seconds respectively.
Random r = new Random();
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if(r.nextInt(4) == 0) {
System.out.print("O");
} else {
System.out.print("B");
}
if(j%100==0){ //Adding a line break in second loop
System.out.println();
}
}
System.out.println("");
}
Another advice is that to change settings of NetBeans IDE. First of all, go to NetBeans Tools and click Options. After that click Editor and go to Formatting tab. Then select Anywhere in Line Wrap Option. It will take almost 6.24% less time to compile the program.
You can use fetch to do that:
fetch('some_url')
.then(function (response) {
switch (response.status) {
// status "OK"
case 200:
return response.text();
// status "Not Found"
case 404:
throw response;
}
})
.then(function (template) {
console.log(template);
})
.catch(function (response) {
// "Not Found"
console.log(response.statusText);
});
Asynchronous with arrow function version:
(async () => {
var response = await fetch('some_url');
switch (response.status) {
// status "OK"
case 200:
var template = await response.text();
console.log(template);
break;
// status "Not Found"
case 404:
console.log('Not Found');
break;
}
})();
Seems like you might want a treemap.
http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html
You can pass in a custom comparator to it if that applies.
concat()
function because this function only applies to a string, not on a integer. but we can concatenate a string to a number(integer) using + operator.<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<p>The concat() method joins two or more strings</p>_x000D_
_x000D_
_x000D_
<p id="demo"></p>_x000D_
<p id="demo1"></p>_x000D_
_x000D_
<script>_x000D_
var text1 = 4;_x000D_
var text2 = "World!";_x000D_
document.getElementById("demo").innerHTML = text1 + text2;_x000D_
//Below Line can't produce result_x000D_
document.getElementById("demo1").innerHTML = text1.concat(text2);_x000D_
</script>_x000D_
<p><strong>The Concat() method can't concatenate a string with a integer </strong></p>_x000D_
</body>_x000D_
</html>
_x000D_
You can parse the existing XML file into DOM and append new elements to the DOM. Very similar to what you did with creating brand new XML. I am assuming you do not have to worry about duplicate server. If you do have to worry about that, you will have to go through the elements in the DOM to check for duplicates.
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
/* parse existing file to DOM */
Document document = documentBuilder.parse(new File("exisgint/xml/file"));
Element root = document.getDocumentElement();
for (Server newServer : Collection<Server> bunchOfNewServers){
Element server = Document.createElement("server");
/* create and setup the server node...*/
root.appendChild(server);
}
/* use whatever method to output DOM to XML (for example, using transformer like you did).*/
git diff branch_1..branch_2
That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:
git diff branch_1...branch_2
These steps worked for me when the error showed that the Filter class was missing (as reported in this false-diplicated question: JUnit: NoClassDefFoundError: org/junit/runner/manipulation/Filter ):
Thanks to these answers for giving me the hint for this solution: https://stackoverflow.com/a/34067333/5538923 and https://stackoverflow.com/a/39987979/5538923).
Google Mobile Ads SDK FAQ states that:
I keep getting the error 'The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.'
You can safely ignore this message. Your app will still fetch and serve banner ads.
So if you included the google-play-services_lib correctly, and you're getting ads, you have nothing to worry about (I guess...)
I found that I was getting an error "cannot provide arguments when creating an instance of type parameter T" so I needed to do this:
var x = Activator.CreateInstance(typeof(T), args) as T;
In a case where you may be storing true / false as strings, such as in localStorage where the protocol flipped to multi object storage in 2009 & then flipped back to string only in 2011 - you can use JSON.parse to interpret to boolean on the fly:
this.sidebar = !JSON.parse(this.sidebar);
if (dr[dc.ColumnName].GetType().ToString() == "System.DateTime")
If you are working on PC of a company that uses a proxy you must turn on your VPN
Imagine you are developing a web-application and you decide to decouple the functionality from the presentation of the application, because it affords greater freedom.
You create an API and let others implement their own front-ends over it as well. What you just did here is implement an SOA methodology, i.e. using web-services.
Web services make functional building-blocks accessible over standard Internet protocols independent of platforms and programming languages.
So, you design an interchange mechanism between the back-end (web-service) that does the processing and generation of something useful, and the front-end (which consumes the data), which could be anything. (A web, mobile, or desktop application, or another web-service). The only limitation here is that the front-end and back-end must "speak" the same "language".
That's where SOAP and REST come in. They are standard ways you'd pick communicate with the web-service.
SOAP:
SOAP internally uses XML to send data back and forth. SOAP messages have rigid structure and the response XML then needs to be parsed. WSDL is a specification of what requests can be made, with which parameters, and what they will return. It is a complete specification of your API.
REST:
REST is a design concept.
The World Wide Web represents the largest implementation of a system conforming to the REST architectural style.
It isn't as rigid as SOAP. RESTful web-services use standard URIs and methods to make calls to the webservice. When you request a URI, it returns the representation of an object, that you can then perform operations upon (e.g. GET, PUT, POST, DELETE). You are not limited to picking XML to represent data, you could pick anything really (JSON included)
Flickr's REST API goes further and lets you return images as well.
JSON and XML, are functionally equivalent, and common choices. There are also RPC-based frameworks like GRPC based on Protobufs, and Apache Thrift that can be used for communication between the API producers and consumers. The most common format used by web APIs is JSON because of it is easy to use and parse in every language.
With Github's official new command line interface:
gh repo create
See additional details and options and installation instructions.
For instance, to complete your git workflow:
mkdir project
cd project
git init
touch file
git add file
git commit -m 'Initial commit'
gh repo create
git push -u origin master
As the only reliable source for domain suffixes are the domain registrars, you can't find the subdomain without their knowledge. There is a list with all domain suffixes at https://publicsuffix.org. This site also links to a PHP library: https://github.com/jeremykendall/php-domain-parser.
Please find an example below. I also added the sample for en.test.co.uk which is a domain with a multi suffix (co.uk).
<?php
require_once 'vendor/autoload.php';
$pslManager = new Pdp\PublicSuffixListManager();
$parser = new Pdp\Parser($pslManager->getList());
$host = 'http://en.example.com';
$url = $parser->parseUrl($host);
echo $url->host->subdomain;
$host = 'http://en.test.co.uk';
$url = $parser->parseUrl($host);
echo $url->host->subdomain;
To use a MySQL AUTO_INCREMENT
column, you are supposed to use an IDENTITY
strategy:
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
Which is what you'd get when using AUTO
with MySQL:
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
Which is actually equivalent to
@Id @GeneratedValue
private Long id;
In other words, your mapping should work. But Hibernate should omit the id
column in the SQL insert statement, and it is not. There must be a kind of mismatch somewhere.
Did you specify a MySQL dialect in your Hibernate configuration (probably MySQL5InnoDBDialect
or MySQL5Dialect
depending on the engine you're using)?
Also, who created the table? Can you show the corresponding DDL?
Follow-up: I can't reproduce your problem. Using the code of your entity and your DDL, Hibernate generates the following (expected) SQL with MySQL:
insert
into
Operator
(active, password, username)
values
(?, ?, ?)
Note that the id
column is absent from the above statement, as expected.
To sum up, your code, the table definition and the dialect are correct and coherent, it should work. If it doesn't for you, maybe something is out of sync (do a clean build, double check the build directory, etc) or something else is just wrong (check the logs for anything suspicious).
Regarding the dialect, the only difference between MySQL5Dialect
or MySQL5InnoDBDialect
is that the later adds ENGINE=InnoDB
to the table objects when generating the DDL. Using one or the other doesn't change the generated SQL.
JavaType javaType = objectMapper.getTypeFactory().constructParameterizedType(Map.class, Key.class, Value.class);
Map<Key, Value> map=objectMapper.readValue(jsonStr, javaType);
i think this will solve your problem.
By default, Windows associates .js
files with the Windows Script Host, Microsoft's stand-alone JS runtime engine. If you type script.js at a command prompt (or double-click a .js
file in Explorer), the script is executed by wscript.exe
.
This may be solving a local problem with a global setting, but you could associate .js
files with node.exe
instead, so that typing script.js at a command prompt or double-clicking/dragging items onto scripts will launch them with Node.
Of course, if—like me—you've associated .js
files with an editor so that double-clicking them opens up your favorite text editor, this suggestion won't do much good. You could also add a right-click menu entry of "Execute with Node" to .js
files, although this alternative doesn't solve your command-line needs.
The simplest solution is probably to just use a batch file – you don't have to have a copy of Node in the folder your script resides in. Just reference the Node executable absolutely:
"C:\Program Files (x86)\nodejs\node.exe" app.js %*
Another alternative is this very simple C# app which will start Node using its own filename + .js
as the script to run, and pass along any command line arguments.
class Program
{
static void Main(string[] args)
{
var info = System.Diagnostics.Process.GetCurrentProcess();
var proc = new System.Diagnostics.ProcessStartInfo(@"C:\Program Files (x86)\nodejs\node.exe", "\"" + info.ProcessName + ".js\" " + String.Join(" ", args));
proc.UseShellExecute = false;
System.Diagnostics.Process.Start(proc);
}
}
So if you name the resulting EXE "app.exe", you can type app arg1 ...
and Node will be started with the command line "app.js" arg1 ...
. Note the C# bootstrapper app will immediately exit, leaving Node in charge of the console window.
Since this is probably of relatively wide interest, I went ahead and made this available on GitHub, including the compiled exe if getting in to vans with strangers is your thing.
While sizeof
works for this specific type of string:
char str[] = "content";
int charcount = sizeof str - 1; // -1 to exclude terminating '\0'
It does not work if str
is pointer (sizeof
returns size of pointer, usually 4 or 8) or array with specified length (sizeof
will return the byte count matching specified length, which for char type are same).
Just use strlen()
.
I worked out on Xcode 7.3.1 on Swift 2.2. See below.
func addTapGesture() {
let tap = UITapGestureRecognizer(target: self, action: #selector(MyViewController.handleTap))
tap.numberOfTapsRequired = 1
self.myView.addGestureRecognizer(tap)
}
func handleTap() {
// Your code here...
}
All of todays browsers use at least version 1.5
:
http://en.wikipedia.org/wiki/ECMAScript#Dialect
Concerning your tutorial site, the information there seems to be extremely outdated, I beg you to head over to MDC and read their Guide:
https://developer.mozilla.org/en/JavaScript/Guide
You may still want to watch out for features which require version 1.6
or above, as this might give Internet Explorer some troubles.
1 and 2 are SAML 1.1 because those URIs were part of the OASIS SAML 1.1 standard. Section 8.3 of the linked PDF for the OASIS SAML 2.0 standard explains this:
Where possible an existing URN is used to specify a protocol. In the case of IETF protocols, the URN of the most current RFC that specifies the protocol is used. URI references created specifically for SAML have one of the following stems, according to the specification set version in which they were first introduced:
urn:oasis:names:tc:SAML:1.0: urn:oasis:names:tc:SAML:1.1: urn:oasis:names:tc:SAML:2.0:
A little note to the SeanJA answer.
Interestingly, if you use KnockoutJS and jQuery together the following inputs with different IDs, but with the same data-bind observable:
<data-bind="value: first_dt" id="date_1" class="datepick" />
<data-bind="value: first_dt" id="date_2" class="datepick" />
will bind one (the same) datepicker to both of the inputs (even though they have different ids or names).
Use separate observables in your ViewModel to bind a separate datepicker to each input:
<data-bind="value: first_dt" id="date_1" class="datepick" />
<data-bind="value: second_dt" id="date_2" class="datepick" />
Initialization:
$('.datepick').each(function(){
$(this).datepicker();
});
I have followed instructions found here and tried to fix my old Eclipse + SDK + ADT, but with no luck. The basic problem keeps beeing the same; I still get the error message:
This Android SDK requires Android Developer Toolkit version 23.0.0 or above. Current version is 22.6.3.v201404151837-1123206. Please update ADT to the latest version.
But my eclipse can't find updates and can't install ADT 23 as new software. So I can't compile my old project in my workspace.
I tested a fresh eclipode bundle for Windows 8, followed instructions found from Android's developers page, step by step, and it worked fine. So it seems that the Windows Eclipse build is not broken. But I wan't use my Linux installation, my old Ubuntu 10. It seems obvious, that to getting the Linux Eclipse environment working again, I must install a new Eclipse bundle, my old Eclipse won't ever see updates for ADT 23 to get things working. Again, these intructions are for Linux developers that wan't to get their old workspace projects working again without changes in the developing environment, except you must install a new Eclipse bundle, but after that your projects will work as well as before the version 23 SDK/ADT-mess.
~/Development
and unzip bundle there. You get Eclipse and SDK directories.annotations.jar
from your old SDK, from, the backup you made, or from the older sdk.zip
explained in this thread to <new SDK>/tools/support/annotations.jarAfter that I could use my old workspace in Ubuntu and compile and launch applications to Android devices. It was that simple. Thanks Google ;-(
Something like:
if exists (select top 1 * from Sites S where S.Id IS NOT NULL AND S.Status = 1 AND (S.WebUserId = @WebUserId OR S.AllowUploads = 1))
select 1
else
select 0
change import cv
to import cv2.cv as cv
See also the post here.
I think it's to prevent you from mixing declarations and definitions. (Think about the problems that could occur if you include the file in multiple places.)
Hope this helps.
let number = 7;
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
Here is a complete function that will log to the console the parity of your input.
const checkNumber = (x) => {
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
}
Number((6.688689).toFixed(1)); // 6.7
var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;
Use toFixed()
function.
(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"
Probably something like:
ArrayList<DataPoint> myList = new ArrayList<DataPoint>();
//Fill up myList with your Data Points
//Traversal
for(DataPoint myPoint : myList) {
if(myPoint.getName() != null && myPoint.getName().equals("Michael Hoffmann")) {
//Process data do whatever you want
System.out.println("Found it!");
}
}
You can also use Ticks. I'm coding for Windows Mobile so don't have the full set of methods. TotalSeconds is not available to me.
long epochTicks = new DateTime(1970, 1, 1).Ticks;
long unixTime = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond);
or
TimeSpan epochTicks = new TimeSpan(new DateTime(1970, 1, 1).Ticks);
TimeSpan unixTicks = new TimeSpan(DateTime.UtcNow.Ticks) - epochTicks;
double unixTime = unixTicks.TotalSeconds;
If your code is placed in a class you could use a decorator for that. You have such decorator in the utils-decorators (npm install --save utils-decorators
). It will cancel the previous invocation of the decorated method if before the resolving of the previous call there was made another call for that specific method.
import {cancelPrevious} from 'utils-decorators';
class SomeService {
@cancelPrevious()
doSomeAsync(): Promise<any> {
....
}
}
or you could use a wrapper function:
import {cancelPreviousify} from 'utils-decorators';
const cancelable = cancelPreviousify(originalMethod)
https://github.com/vlio20/utils-decorators#cancelprevious-method
Try changing it to.
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "text/plain";
Response.Flush();
Response.TransmitFile(file.FullName);
Response.End();
When using Java 7+
use the following method to download a file from the Internet and save it to some directory:
private static Path download(String sourceURL, String targetDirectory) throws IOException
{
URL url = new URL(sourceURL);
String fileName = sourceURL.substring(sourceURL.lastIndexOf('/') + 1, sourceURL.length());
Path targetPath = new File(targetDirectory + File.separator + fileName).toPath();
Files.copy(url.openStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
return targetPath;
}
Documentation here.
Another option is to use a multi-stage docker build to ensure that your SSH keys are not included in the final image.
As described in my post you can prepare your intermediate image with the required dependencies to git clone and then COPY
the required files into your final image.
Additionally if we LABEL
our intermediate layers, we can even delete them from the machine when finished.
# Choose and name our temporary image.
FROM alpine as intermediate
# Add metadata identifying these images as our build containers (this will be useful later!)
LABEL stage=intermediate
# Take an SSH key as a build argument.
ARG SSH_KEY
# Install dependencies required to git clone.
RUN apk update && \
apk add --update git && \
apk add --update openssh
# 1. Create the SSH directory.
# 2. Populate the private key file.
# 3. Set the required permissions.
# 4. Add github to our list of known hosts for ssh.
RUN mkdir -p /root/.ssh/ && \
echo "$SSH_KEY" > /root/.ssh/id_rsa && \
chmod -R 600 /root/.ssh/ && \
ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts
# Clone a repository (my website in this case)
RUN git clone [email protected]:janakerman/janakerman.git
# Choose the base image for our final image
FROM alpine
# Copy across the files from our `intermediate` container
RUN mkdir files
COPY --from=intermediate /janakerman/README.md /files/README.md
We can then build:
MY_KEY=$(cat ~/.ssh/id_rsa)
docker build --build-arg SSH_KEY="$MY_KEY" --tag clone-example .
Prove our SSH keys are gone:
docker run -ti --rm clone-example cat /root/.ssh/id_rsa
Clean intermediate images from the build machine:
docker rmi -f $(docker images -q --filter label=stage=intermediate)
Updated Method:
As of March 2016, recent versions of Chrome and Firefox now support using FormData.entries()
to inspect FormData. Source.
// Create a test FormData object
var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');
// Display the key/value pairs
for (var pair of formData.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
Thanks to Ghost Echo and rloth for pointing this out!
Old Answer:
After looking at these Mozilla articles, it looks like there is no way to get data out of a FormData object. You can only use them for building FormData to send via an AJAX request.
I also just found this question that states the same thing: FormData.append("key", "value") is not working.
One way around this would be to build up a regular dictionary and then convert it to FormData:
var myFormData = {
key1: 300,
key2: 'hello world'
};
var fd = new FormData();
for (var key in myFormData) {
console.log(key, myFormData[key]);
fd.append(key, myFormData[key]);
}
If you want to debug a plain FormData object, you could also send it in order to examine it in the network request console:
var xhr = new XMLHttpRequest;
xhr.open('POST', '/', true);
xhr.send(fd);
it seems it works after I commented this line in web.config
<compilation debug="true" targetFramework="4.5.2" />
SELECT * FROM myTable WHERE DATE(myDate) = DATE(NOW())
Read more: http://www.tomjepson.co.uk/tutorials/36/mysql-select-where-date-today.html
using System;
using System.Data;
using System.Data.SqlClient;
namespace InsertingData
{
class sqlinsertdata
{
static void Main(string[] args)
{
try
{
SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into <Table Name>values(1,'nagendra',10000);",conn);
cmd.ExecuteNonQuery();
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch(Exception e)
{
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}
Console.ReadKey();
}
}
}
You can install gems into a specific folder (example vendor/) in your Rails app using :
bundle install --path vendor
Here is what i can suggest. Use another variable to derive the if clause and assign it to num1.
Code:
num2 =20 if someBoolValue else num1
num1=num2
Find the second largest number:
public class SecondMaxNumbers {
public void printTwoMaxNumbers(int[] nums){
int maxOne = 0;
int maxTwo = 0;
for(int n:nums){
if(maxOne < n){
maxTwo = maxOne;
maxOne =n;
} else if(maxTwo < n){
maxTwo = n;
}
}
System.out.println("Second Max Number: "+maxTwo);
}
public static void main(String a[]){
int num[] = {10,20,30,40,50,60,70};
SecondMaxNumbers sec = new SecondMaxNumbers();
tmn.printTwoMaxNumbers(num);
}
}
You can track by $index
if your data source has duplicate identifiers
e.g.: $scope.dataSource: [{id:1,name:'one'}, {id:1,name:'one too'}, {id:2,name:'two'}]
You can't iterate this collection while using 'id' as identifier (duplicate id:1).
WON'T WORK:
<element ng-repeat="item.id as item.name for item in dataSource">
// something with item ...
</element>
but you can, if using track by $index
:
<element ng-repeat="item in dataSource track by $index">
// something with item ...
</element>
When searching with [data-x=...], watch out, it doesn't work with jQuery.data(..) setter:
$('<b data-x="1">' ).is('[data-x=1]') // this works
> true
$('<b>').data('x', 1).is('[data-x=1]') // this doesn't
> false
$('<b>').attr('data-x', 1).is('[data-x=1]') // this is the workaround
> true
You can use this instead:
$.fn.filterByData = function(prop, val) {
return this.filter(
function() { return $(this).data(prop)==val; }
);
}
$('<b>').data('x', 1).filterByData('x', 1).length
> 1
This is how the if
behaves.
if(turnedOn) // This turnedOn should be a boolean or you could have a condition here which would give a boolean result.
{
// It will come here if turnedOn is true (i.e) the condition in the "if" evaluates to true
}
else
{
// It will come here if turnedOn is false (i.e) the condition in the "if" evaluates to false
}
Depends on a lot of factors... List implementation, CPU architecture, JVM, loop semantics, complexity of equals method, etc... By the time the list gets big enough to effectively benchmark (1000+ elements), Hash-based binary lookups beat linear searches hands-down, and the difference only scales up from there.
Hope this helps!
string s2 = s1.Replace(",", ",\r\n");
Events can be retrieved using:
jQuery(elem).data('events');
or jQuery 1.8+:
jQuery._data(elem, 'events');
Note:
Events bounded using $('selector').live('event', handler)
can be retrieved using:
jQuery(document).data('events')
Just adding on top of Jacob's answer, for img
in td
,
body {line-height: 0;}
img {display: block; vertical-align: bottom;}
This works for most email clients, including Gmail. But not Outlook. For outlook, you need to do two steps more:
table {border-collapse: collapse;}
and set every td
elements to have the same height
and width
as its contained images. For example,
<td width="600" height="80" style="line-height: 80px;">
<img height="80" src="http://www.website.com/images/Nature_01.jpg" width="600" />
</td>
Not sure if this is still relevant, but I use this way
Public bEnableEvents As Boolean
Public bclickok As Boolean
Public booRestoreErrorChecking As Boolean 'put this at the top of the module
Private Declare Function apiGetComputerName Lib "kernel32" Alias _
"GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function apiGetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Function GetUserID() As String
' Returns the network login name
On Error Resume Next
Dim lngLen As Long, lngX As Long
Dim strUserName As String
strUserName = String$(254, 0)
lngLen = 255
lngX = apiGetUserName(strUserName, lngLen)
If lngX <> 0 Then
GetUserID = Left$(strUserName, lngLen - 1)
Else
GetUserID = ""
End If
Exit Function
End Function
This next bit I save file as PDF, but can change to suit
Public Sub SaveToDesktop()
Dim LoginName As String
LoginName = UCase(GetUserID)
ChDir "C:\Users\" & LoginName & "\Desktop\"
Debug.Print LoginName
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\" & LoginName & "\Desktop\MyFileName.pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
True
End Sub
Inside a code you if you use a variable without using var, then what happens is the automatically var var_name is placed in the global scope eg:
someFunction() {
var a = some_value; /*a has local scope and it cannot be accessed when this
function is not active*/
b = a; /*here it places "var b" at top of script i.e. gives b global scope or
uses already defined global variable b */
}
I will give you steps to writing and compiling code. Use this example:
public class Paycheck {
public static void main(String args[]) {
double amountInAccount;
amountInAccount = 128.57;
System.out.print("You earned $");
System.out.print(amountInAccount);
System.out.println(" at work today.");
}
}
Paycheck.java
cd Desktop
javac Paycheck.java
java Paycheck
You can achieve this with the following code:
$("input").change(function(e) {
for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
var file = e.originalEvent.srcElement.files[i];
var img = document.createElement("img");
var reader = new FileReader();
reader.onloadend = function() {
img.src = reader.result;
}
reader.readAsDataURL(file);
$("input").after(img);
}
});
Put the default value in single quote and it will work as intended. An example of migration:
$table->increments('id');
$table->string('name');
$table->string('url');
$table->string('country');
$table->tinyInteger('status')->default('1');
$table->timestamps();
EDIT : in your case ->default('100.0');
Also, it`s interesting to set your PATH to reflect the JDK. After adding JAVA_HOME (which can be done with the example cited by 'mipadi'):
export JAVA_HOME=$(/usr/libexec/java_home)
Add also in ~/.profile:
export PATH=${JAVA_HOME}/bin:$PATH
P.S.: For OSX, I generally use .profile in the HOME dir instead of .bashrc
Finally in SQLalchemy1.2 version, this new implementation is added to use psycopg2.extras.execute_batch() instead of executemany when you initialize your engine with use_batch_mode=True like:
engine = create_engine(
"postgresql+psycopg2://scott:tiger@host/dbname",
use_batch_mode=True)
http://docs.sqlalchemy.org/en/latest/changelog/migration_12.html#change-4109
Then someone would have to use SQLalchmey won't bother to try different combinations of sqla and psycopg2 and direct SQL together..
You need to use the option -f
:
$ grep -f A B
The option -F
does a fixed string search where as -f
is for specifying a file of patterns. You may want both if the file only contains fixed strings and not regexps.
$ grep -Ff A B
You may also want the -w
option for matching whole words only:
$ grep -wFf A B
Read man grep
for a description of all the possible arguments and what they do.
overflow: auto
(or overflow-y: auto
) is the correct way to go.
The problem is that your text area is taller than your div. The div ends up cutting off the textbox, so even though it looks like it should start scrolling when the text is taller than 159px
it won't start scrolling until the text is taller than 400px
which is the height of the textbox.
Try this: http://jsfiddle.net/G9rfq/1/
I set overflow:auto on the text box, and made the textbox the same size as the div.
Also I don't believe it's valid to have a div
inside a label
, the browser will render it, but it might cause some funky stuff to happen. Also your div
isn't closed.
While you use .on(), it's basically a live query that you are using.
On the other hand, .ready (as in your case) is a static query. While using it, you can dynamically update data and do not have to wait for the page to load. You can simply pass on the values into your database (if required) when a particular value is entered.
The use of live queries is common in forms where we enter data (account or posts or even comments).
At least in Node v8.9.1, you can just do
var json_data = require('/path/to/local/file.json');
and access all the elements of the JSON object.
The .equalsIgnoreCase() method should help with that.
Here is the end-to-end workflow showing the various commands and their associated inputs and outputs. That should clarify the relationship between an image and a container.
+------------+ docker build +--------------+ docker run -dt +-----------+ docker exec -it +------+
| Dockerfile | --------------> | Image | ---------------> | Container | -----------------> | Bash |
+------------+ +--------------+ +-----------+ +------+
^
| docker pull
|
+--------------+
| Registry |
+--------------+
To list the images you could run, execute:
docker image ls
To list the containers you could execute commands on:
docker ps
You can create an ExpandoObject like this:
IDictionary<string,object> expando = new ExpandoObject();
expando["Name"] = value;
And after casting it to dynamic, those values will look like properties:
dynamic d = expando;
Console.WriteLine(d.Name);
However, they are not actual properties and cannot be accessed using Reflection. So the following statement will return a null:
d.GetType().GetProperty("Name")
Get range of dates between specified start and end date (Optimized for time & space complexity):
import datetime
start = datetime.datetime.strptime("21-06-2014", "%d-%m-%Y")
end = datetime.datetime.strptime("07-07-2014", "%d-%m-%Y")
date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]
for date in date_generated:
print date.strftime("%d-%m-%Y")
import os
import sys
Assuming test.sh is the shell script that you would want to execute
os.system("sh test.sh")
For Mac, using Safari is a good alternate option for local development purpose and the feature is built into the browser (so no need to add browser extension or launch Chrome using bash command like [open -a Google\ Chrome --args --disable-web-security --user-data-dir=""].
To disable cross origin restriction using Safari (v11+): From menu click “Develop > Disable Cross Origin Restriction”.
This does not require relaunching the browser and since its a toggle you can easily switch to secure mode.
del *.*
will only delete files, but not subdirectories. To nuke the contents of a directory, you can use this script:
@echo off
setlocal enableextensions
if {%1}=={} goto :HELP
if {%1}=={/?} goto :HELP
goto :START
:HELP
echo Usage: %~n0 directory-name
echo.
echo Empties the contents of the specified directory,
echo WITHOUT CONFIRMATION. USE EXTREME CAUTION!
goto :DONE
:START
pushd %1 || goto :DONE
rd /q /s . 2> NUL
popd
:DONE
endlocal
The pushd
changes into the directory of which you want to delete the children. Then when rd
asks to delete the current directory and all sub directories, the deletion of the sub directories succeed, but the deletion of the current directory fails - because we are in it. This produces an error which 2> NUL
swallows. (2 being the error stream).
Just for completeness, since MySQL and Postgres have already been mentioned: With SQLite, use "pragma table_info()
"
sqlite> pragma table_info('table_name');
cid name type notnull dflt_value pk
---------- ---------- ---------- ---------- ---------- ----------
0 id integer 99 1
1 name 0 0
"div" tag can not be used above "tr" tag. Instead you can use "tbody" tag to do your work. If you are planning to give id attribute to div tag and doing some processing, same purpose you can achieve through "tbody" tag. Div and Table are both block level elements. so they can not be nested. For further information visit this page
For example:
<table>
<tbody class="green">
<tr>
<td>Data</td>
</tr>
</tbody>
<tbody class="blue">
<tr>
<td>Data</td>
</tr>
</tbody>
</table>
secondly, you can put "div" tag inside "td" tag.
<table>
<tr>
<td>
<div></div>
</td>
</tr>
</table>
Further questions are always welcome.
sed
is the Stream EDitor. It can do a whole pile of really cool things, but the most common is text replacement.
The s,%,$,g
part of the command line is the sed
command to execute. The s
stands for substitute, the ,
characters are delimiters (other characters can be used; /
, :
and @
are popular). The %
is the pattern to match (here a literal percent sign) and the $
is the second pattern to match (here a literal dollar sign). The g
at the end means to g
lobally replace on each line (otherwise it would only update the first match).
GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH
. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:
export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH
Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).
From your terminal do:
git config credential.username "prefered username"
OR
git config --global user.name "Firstname Lastname"
That should work, you may need a space after the commas.
Also, the function you call afterwards must support an array of objects, and not just a singleton object.
If you're not using a remote repository (like artifactory), use plain old:
mvn clean install
Pretty old topic but AFAIK, if you run your own repository (eg: with artifactory) to share jar among your team(s), you might want to use
mvn clean deploy
instead.
This way, your continuous integration server can be sure that all dependencies are correctly pushed into your remote repository. If you missed one, mvn will not be able to find it into your CI local m2 repository.
'ProgramFiles(x86)' is an environment variable automatically defined by cmd.exe (both 32-bit and 64-bit versions) on Windows 64-bit machines only, so try this:
@ECHO OFF
echo Check operating system ...
if defined PROGRAMFILES(X86) (
echo 64-bit sytem detected
) else (
echo 32-bit sytem detected
)
pause
Get simple name instead of path.
String onlyClassName = this.getLocalClassName();
call above method in onCreate
Just go to nodejs.org and download the latest installer. It couldn't be any simpler honestly, and without involvement of any third-party stuff. It only takes a minute and does not require you to restart anything or clean out caches, etc.
I've done it via npm a few times before and have run into a few issues. Like for example with the n-package not using the latest stable release.
I just solve this error while using capybara in ror project by adding:
Capybara.ignore_elements = true
to features/support/env.rb
.
These code lines can help you quickly enable log setting in your magento site.
INSERT INTO `core_config_data` (`config_id`, `scope`, `scope_id`, `path`, `value`) VALUES
('', 'default', 0, 'dev/log/active', '1'),
('', 'default', 0, 'dev/log/file', 'system.log'),
('', 'default', 0, 'dev/log/exception_file', 'exception.log');
Then you can see them inside the folder: /var/log
under root installation.
You'd obviously figure it out after a while but just posting this so that it might help someone. This could also happen when your file path contains any whitespace appended or prepended to it.
You could use flatMap. It can filter and map in one.
$scope.appIds = $scope.applicationsHere.flatMap(obj => obj.selected ? obj.id : [])
**Simple solution**
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size;
System.out.println("Enter the number of size of array");
size = sc.nextInt();
int[] a = new int[size];
System.out.println("Enter the array element");
//For reading the element
for(int i=0;i<size;i++) {
a[i] = sc.nextInt();
}
//For print the array element
for(int i : a) {
System.out.print(i+" ,");
}
}
The right way to do this, starting with Spring 4.1, is to use a @TestPropertySource
annotation.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
@TestPropertySource(properties = {"myproperty = foo"})
public class TestWarSpringContext {
...
}
See @TestPropertySource in the Spring docs and Javadocs.
Here is another seamless approach to convert JSON to Datatable using Cinchoo ETL - an open source library
Sample below shows how to convert
string json = @"[
{""id"":""10"",""name"":""User"",""add"":false,""edit"":true,""authorize"":true,""view"":true},
{ ""id"":""11"",""name"":""Group"",""add"":true,""edit"":false,""authorize"":false,""view"":true},
{ ""id"":""12"",""name"":""Permission"",""add"":true,""edit"":true,""authorize"":true,""view"":true}
]";
using (var r = ChoJSONReader.LoadText(json))
{
var dt = r.AsDataTable();
}
Hope it helps.
I had this edge case, where I checked out a previous version of the code in which my file directory structure was different:
git checkout 1.87.1
warning: unable to unlink web/sites/default/default.settings.php: Permission denied
... other warnings ...
Note: checking out '1.87.1'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again.
Example:
git checkout -b <new-branch-name>
HEAD is now at 50a7153d7... Merge branch 'hotfix/1.87.1'
In a case like this you may need to use --force (when you know that going back to the original branch and discarding changes is a safe thing to do).
git checkout master
did not work:
$ git checkout master
error: The following untracked working tree files would be overwritten by checkout:
web/sites/default/default.settings.php
... other files ...
git checkout master --force
(or git checkout master -f
) worked:
git checkout master -f
Previous HEAD position was 50a7153d7... Merge branch 'hotfix/1.87.1'
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.
Phonegap Cordova Installation on Windows
Requirements
Supported Android Devices
Android 2.2 Android 2.3 Android 4.x Phonegap Cordova Installation
Set PATH environment variable for android
From desktop, right click My Computer and click Properties.
Click Advance System Settings link in the left column.
In the system properties window click the environment variables button.
Select the PATH variable from the System variables section. Select the Edit button. You need to add the path to your Android SDK platform-tools and tools directory. For Example: D:\adt-bundle-windows-x86_64-20130219\sdk\platform-tools;D:\adt-bundle-windows-x86_64-20130219\sdk\tools Save your Edit. Close the Environment Variable dialog.
Open Command Prompt, navigate to bin directory within the android sub-folder of the Cordova distribution.
Type in: ./create
Then press Enter.Launch Eclipse. In File Menu Item and select to Import…
Import Select “Existing Android Code into Workspace” and click ‘Next >’.
Browse the project created through command prompt. And click ‘Finish’. Deploy to Emulator From within Eclipse, press this toolbar icon.
Once open, the Android SDK Manager displays various runtime libraries Install the APIs as per requirement from here. From within Eclipse, press this toolbar icon.
Choose and device definition from the list which comes. (There is only one item in the current list.) Press New… in the above window to create new Android Virtual Device(AVD) and use it to run your project.
To open the emulator as a separate application, Select the AVD and press Start. It launches much as it would on device, with additional controls available for hardware buttons:
Deploy to Device:
Make sure USB debugging is enabled on your device and plug it into your system. Right Click the Project and go to Run As > Android Application.
In C++ you can declare a string like this:
#include <string>
using namespace std;
int main()
{
string str1("argue2000"); //define a string and Initialize str1 with "argue2000"
string str2 = "argue2000"; // define a string and assign str2 with "argue2000"
string str3; //just declare a string, it has no value
return 1;
}
If svn add whatever/directory/*
doesn't work, you can do it the tough way:
svn st | grep ^\? | cut -c 2- | xargs svn add
There are many different ways:
sed -n 1p file
head -n 1 file
awk 'NR==1' file
On your solution explorer window, right click to References, select Add Reference, go to .NET tab, find and add Microsoft.CSharp.
Alternatively add the Microsoft.CSharp NuGet package.
Install-Package Microsoft.CSharp
To add to this - it seems important to define the width & height of the drawable as per this post:
(his code works)
I don't think that you need to use each()
, you can use standard for loop
var children = $element.children().not(".pb-sortable-placeholder");
for (var i = 0; i < children.length; i++) {
var currentChild = children.eq(i);
// whatever logic you want
var oldPosition = currentChild.data("position");
}
this way you can have the standard for loop features like break
and continue
works by default
also, the debugging will be easier
From the Sublime Text docs for Windows/Linux:
Keypress Command
Ctrl + K, Ctrl + U Transform to Uppercase
Ctrl + K, Ctrl + L Transform to Lowercase
and for Mac:
Keypress Command
cmd + KU Transform to Uppercase
cmd + KL Transform to Lowercase
Also note that Ctrl + Shift + p in Windows (? + Shift + p in a Mac) brings up the Command Palette where you can search for these and other commands. It looks like this:
I've run into this with a couple virtual environments.
pip uninstall MySQL-python
pip install -U MySQL-python
Worked both times.
Right click on the breakpoint works fine for me (though mostly I am using it for conditional breakpoints on specific variable values. Even breaking on expressions involving a thread name works which is very useful if you're trying to spot threading issues).
Their names can be a bit confusing :). Here's a summary:
The SelectedItem property returns the entire object that your list is bound to. So say you've bound a list to a collection of Category
objects (with each Category object having Name and ID properties). eg. ObservableCollection<Category>
. The SelectedItem
property will return you the currently selected Category
object. For binding purposes however, this is not always what you want, as this only enables you to bind an entire Category object to the property that the list is bound to, not the value of a single property on that Category object (such as its ID
property).
Therefore we have the SelectedValuePath property and the SelectedValue property as an alternative means of binding (you use them in conjunction with one another). Let's say you have a Product
object, that your view is bound to (with properties for things like ProductName, Weight, etc). Let's also say you have a CategoryID
property on that Product object, and you want the user to be able to select a category for the product from a list of categories. You need the ID property of the Category object to be assigned to the CategoryID
property on the Product object. This is where the SelectedValuePath
and the SelectedValue
properties come in. You specify that the ID property on the Category object should be assigned to the property on the Product object that the list is bound to using SelectedValuePath='ID'
, and then bind the SelectedValue
property to the property on the DataContext (ie. the Product).
The example below demonstrates this. We have a ComboBox bound to a list of Categories (via ItemsSource). We're binding the CategoryID property on the Product as the selected value (using the SelectedValue property). We're relating this to the Category's ID property via the SelectedValuePath property. And we're saying only display the Name property in the ComboBox, with the DisplayMemberPath property).
<ComboBox ItemsSource="{Binding Categories}"
SelectedValue="{Binding CategoryID, Mode=TwoWay}"
SelectedValuePath="ID"
DisplayMemberPath="Name" />
public class Category
{
public int ID { get; set; }
public string Name { get; set; }
}
public class Product
{
public int CategoryID { get; set; }
}
It's a little confusing initially, but hopefully this makes it a bit clearer... :)
Chris
You're misunderstanding the meaning of the merge here.
The --no-commit
prevents the MERGE COMMIT from occuring, and that only happens when you merge two divergent branch histories; in your example that's not the case since Git indicates that it was a "fast-forward" merge and then Git only applies the commits already present on the branch sequentially.
It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:
openssl sha1 [put the full path to the file here without brackets]
For example:
openssl sha1 /Users/me/Desktop/myFile.dmg
If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.
I had the same issue, and it turned out to be due to permission of the catalina.out
file not being correct. It was not writable by the tomcat user. Once I fixed the permissions, the issue got resolved. I got to know that it is a permissions issue from the logs in the tomcat8-initd.log
file:
/usr/sbin/tomcat8: line 40: /usr/share/tomcat8/logs/catalina.out: Permission denied
Firstly, your "messy way" is ok, there's nothing wrong with using indices into the dataframe, and this will not be too slow. iterrows() itself isn't terribly fast.
A version of your first idea that would work would be:
row_iterator = df.iterrows()
_, last = row_iterator.next() # take first item from row_iterator
for i, row in row_iterator:
print(row['value'])
print(last['value'])
last = row
The second method could do something similar, to save one index into the dataframe:
last = df.irow(0)
for i in range(1, df.shape[0]):
print(last)
print(df.irow(i))
last = df.irow(i)
When speed is critical you can always try both and time the code.
Combining the input from everyone else (use not, no parens, use os.mkdir
) you'd get...
special_path_for_john = "/usr/share/sounds/blues"
if not os.path.exists(special_path_for_john):
os.mkdir(special_path_for_john)
var element = document.getElementById('sample_id');
element.style.removeProperty("width");
element.style.removeProperty("height");
Unfortunately you can't use transition on background-image
, see the w3c list of animatable properties.
You may want to do some tricks with background-position
.
Websockets use sockets in their implementation. Websockets are based on a standard protocol (now in final call, but not yet final) that defines a connection "handshake" and message "frame." The two sides go through the handshake procedure to mutually accept a connection and then use the standard message format ("frame") to pass messages back and forth.
I'm developing a framework that will allow you to communicate directly machine to machine with installed software. It might suit your purpose. You can follow my blog if you wish: http://highlevellogic.blogspot.com/2011/09/websocket-server-demonstration_26.html
The SubSink package, an easy and consistent solution for unsubscribing
As nobody else has mentioned it, I want to recommend the Subsink package created by Ward Bell: https://github.com/wardbell/subsink#readme.
I have been using it on a project were we are several developers all using it. It helps a lot to have a consistent way that works in every situation.
As of C++17, you can use Structured Bindings:
#include <iostream>
#include <tuple>
int main ()
{
auto [hello, world] = std::make_tuple("Hello ", "world!");
std::cout << hello << world << std::endl;
return 0;
}
This works on AIX korn shell.
find *.cbl *.dms -prune -type f -mtime -1
This is looking for *.cbl
or *.dms
which are 1 day old, in current directory only, skipping the sub-directories.
Try this!
import java.util.*;
class arrProduct
{
public static void main(String args[])
{
//getting the size of the array
Scanner s = new Scanner(System.in);
int noe = s.nextInt();
int out[]=new int[noe];
int arr[] = new int[noe];
// getting the input array
for(int k=0;k<noe;k++)
{
arr[k]=s.nextInt();
}
int val1 = 1,val2=1;
for(int i=0;i<noe;i++)
{
int res=1;
for(int j=1;j<noe;j++)
{
if((i+j)>(noe-1))
{
int diff = (i+j)-(noe);
if(arr[diff]!=0)
{
res = res * arr[diff];
}
}
else
{
if(arr[i+j]!=0)
{
res= res*arr[i+j];
}
}
out[i]=res;
}
}
//printing result
System.out.print("Array of Product: [");
for(int l=0;l<out.length;l++)
{
if(l!=out.length-1)
{
System.out.print(out[l]+",");
}
else
{
System.out.print(out[l]);
}
}
System.out.print("]");
}
}
This is works for me
<textarea_x000D_
type='text'_x000D_
style="resize: none"_x000D_
>_x000D_
Some text_x000D_
</textarea>
_x000D_
function is_mobile_valid(string_or_number){
var mobile=string_or_number;
if(mobile.length!=10){
return false;
}
intRegex = /[0-9 -()+]+$/;
is_mobile=true;
for ( var i=0; i < 10; i++) {
if(intRegex.test(mobile[i]))
{
continue;
}
else{
is_mobile=false;
break;
}
}
return is_mobile;
}
You can just check by calling the function is_mobile_valid(your_string_of_mobile_number);
This is how I did it in React:
import MyPDF from '../path/to/file.pdf';
<a href={myPDF} download="My_File.pdf"> Download Here </a>
It's important to override the default file name with download="name_of_file_you_want.pdf"
or else the file will get a hash number attached to it when you download.
Unfortunately, threads do exist. A thread is something tangible. You can kill one, and the others will still be running. You can spawn new threads.... although each thread is not it's own process, they are running separately inside the process. On multi-core machines, 2 threads could run at the same time.
The quickest method would be using binary tree. Its worst case is also only O(logn).
What happens in reality in case you pass string as a first parameter of function
setTimeout(
'string'
,number
)
is value of first param got evaluated when it is time to run (after number
of miliseconds passed).
Basically it is equal to
setTimeout(
eval('string')
,number
)
This is
an alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is not recommended for the same reasons that make using eval() a security risk.
So samples which you refer are not good samples, and may be given in different context or just simple typo.
If you invoke like this setTimeout(something, number)
, first parameter is not string, but pointer to a something called something
. And again if something
is string - then it will be evaluated. But if it is function, then function will be executed.
jsbin sample
You should always use following syntax to rethrow an exception, else you'll stomp the stack trace:
throw;
If you print the trace resulting from "throw ex", you'll see that it ends on that statement and not at the real source of the exception.
Basically, it should be deemed a criminal offense to use "throw ex".
I'm late to this party but I'd like to add one bit to user756519's thorough, excellent answer. I don't believe the "RetainSameConnection on the Connection Manager" property is relevant in this instance based on my recent experience. In my case, the relevant point was their advice to set "ValidateExternalMetadata" to False.
I'm using a temp table to facilitate copying data from one database (and server) to another, hence the reason "RetainSameConnection" was not relevant in my particular case. And I don't believe it is important to accomplish what is happening in this example either, as thorough as it is.
Shallow copy:
Some members of the copy may reference the same objects as the original:
class X
{
private:
int i;
int *pi;
public:
X()
: pi(new int)
{ }
X(const X& copy) // <-- copy ctor
: i(copy.i), pi(copy.pi)
{ }
};
Here, the pi
member of the original and copied X
object will both point to the same int
.
Deep copy:
All members of the original are cloned (recursively, if necessary). There are no shared objects:
class X
{
private:
int i;
int *pi;
public:
X()
: pi(new int)
{ }
X(const X& copy) // <-- copy ctor
: i(copy.i), pi(new int(*copy.pi)) // <-- note this line in particular!
{ }
};
Here, the pi
member of the original and copied X
object will point to different int
objects, but both of these have the same value.
The default copy constructor (which is automatically provided if you don't provide one yourself) creates only shallow copies.
Correction: Several comments below have correctly pointed out that it is wrong to say that the default copy constructor always performs a shallow copy (or a deep copy, for that matter). Whether a type's copy constructor creates a shallow copy, or deep copy, or something in-between the two, depends on the combination of each member's copy behaviour; a member's type's copy constructor can be made to do whatever it wants, after all.
Here's what section 12.8, paragraph 8 of the 1998 C++ standard says about the above code examples:
The implicitly defined copy constructor for class
X
performs a memberwise copy of its subobjects. [...] Each subobject is copied in the manner appropriate to its type: [...] [I]f the subobject is of scalar type, the builtin assignment operator is used.
With copy con
command:
cd
to your git repositorycopy con .gitignore
and press Ctrl+Z.
With start notepad .gitignore
command:
cd
to your git repositorystart notepad .gitignore
and press Yes button in opened notepad dialog box.
With edit .gitignore
command (Windows x86 only):
cd
to your git repositoryedit .gitignore
and close opened edit editor.A similar approach to @Peter Coppins answer. This, I think, is a bit easier and doesn't require the use of the Orca utility:
Check the "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Common\FilesPaths" registry key and make sure the value "mso.dll" is NOT present. If it is present, then Office 64-bit seems to be installed and you should not need this workaround.
Download the Microsoft Access Database Engine 2010 Redistributable.
From the command line, run: AccessDatabaseEngine_x64.exe /passive
(Note: this installer silently crashed or failed for me, so I unzipped the components and ran: AceRedist.msi /passive and that installed fine. Maybe a Windows 10 thing.)
Source: How to install 64-bit Microsoft Database Drivers alongside 32-bit Microsoft Office
I was wondering, why they didnt provide in jquery itself, so i made a few changes in jquery file ,,, here are the changed code block:
original Code block:
post: function( url, data, callback, type ) {
// shift arguments if data argument was omited
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
Changed Code block:
post: function (url, data, callback, failcallback, type) {
if (type === undefined || type === null) {
if (!jQuery.isFunction(failcallback)) {
type=failcallback
}
else if (!jQuery.isFunction(callback)) {
type = callback
}
}
if (jQuery.isFunction(data) && jQuery.isFunction(callback)) {
failcallback = callback;
}
// shift arguments if data argument was omited
if (jQuery.isFunction(data)) {
type = type || callback;
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
error:failcallback,
dataType: type
});
},
This should help the one trying to catch error on $.Post in jquery.
Updated: Or there is another way to do this is :
$.post(url,{},function(res){
//To do write if call is successful
}).error(function(p1,p2,p3){
//To do Write if call is failed
});
We can find the length of Object by using:
const myObject = {};
console.log(Object.values(myObject).length);
_x000D_
I just had the exact same problem and it turned out to be caused by the fact that 2 projects in the same solution were referencing a different version of the 3rd party library.
Once I corrected all the references everything worked perfectly.
Use microtime(true)
in PHP 5, or the following modification in PHP 4:
array_sum(explode(' ', microtime()));
A portable way to write that code would be:
function getMicrotime()
{
if (version_compare(PHP_VERSION, '5.0.0', '<'))
{
return array_sum(explode(' ', microtime()));
}
return microtime(true);
}
Try this:
diff -rq /path/to/folder1 /path/to/folder2
you must enable X11 forwarding in you PuTTy
to do so open PuTTy, go to Connection => SSH => Tunnels and check mark the Enable X11 forwarding
Also sudo to server and export the below variable here IP is your local machine's IP
export DISPLAY=10.75.75.75:0.0
Thanks, Bendin. I like your solution very much.
I changed it to work in reverse order, showing most recent changes first. Which is important with long standing code, maintained over several years. I usually pipe it into more.
svnhistory elements.py |more
I added -r to the sort. I removed spec. handling for 'first record'. It is it will error out on the last entry, as there is nothing to diff it with. Though I am living with it because I never get down that far.
#!/bin/bash
# history_of_file
#
# Bendin on Stack Overflow: http://stackoverflow.com/questions/282802
# Outputs the full history of a given file as a sequence of
# logentry/diff pairs. The first revision of the file is emitted as
# full text since there's not previous version to compare it to.
#
# Dlink
# Made to work in reverse order
function history_of_file() {
url=$1 # current url of file
svn log -q $url | grep -E -e "^r[[:digit:]]+" -o | cut -c2- | sort -nr | {
while read r
do
echo
svn log -r$r $url@HEAD
svn diff -c$r $url@HEAD
echo
done
}
}
history_of_file $1
Add timestamps
to your Schema
like this then createdAt
and updatedAt
will automatic generate for you
var UserSchema = new Schema({
email: String,
views: { type: Number, default: 0 },
status: Boolean
}, { timestamps: {} });
Also you can change createdAt -> created_at
by
timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }
I think you shouldn't prepend themesDir
. You only pass the filename of the template to flask, it will then look in a folder called templates
relative to your python file.
In Windows I have made the mistake of using
system("clear")
but that is actually for Linux
The Windows type is
system("cls")
without #include conio.h
Shadow using UIView Extension Swift 4
I would like to add one more line with selected answer!
When we rasterizing the layer, It needs to be set to 2.0 for retina displays. Otherwise label text or images on that view will be blurry. So we need to add rasterizationScale
also.
extension UIView {
func dropShadow() {
layer.masksToBounds = false
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 0.5
layer.shadowOffset = CGSize(width: -1, height: 1)
layer.shadowRadius = 1
layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
}
}
My workmates and I have different Gemfile.lock, because we use different platforms, windows and mac, and our server is linux.
We decide to remove Gemfile.lock in repo and create Gemfile.lock.server in git repo, just like database.yml. Then before deploy it on server, we copy Gemfile.lock.server to Gemfile.lock on server using cap deploy hook
you dont insert into identity fields. You need to specify the field names and use the Values clause
insert into #tmp (AssignedTo, field2, field3) values (value, value, value)
If you use do a insert into... select field field field
it will insert the first field into that identity field and will bomb
On Android >=6.0, We have to request permission runtime.
Step1: add in AndroidManifest.xml file
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Step2: Request permission.
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE);
} else {
//TODO
}
Step3: Handle callback when you request permission.
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_READ_PHONE_STATE:
if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
//TODO
}
break;
default:
break;
}
}
Edit: Read official guide here Requesting Permissions at Run Time
Null
means "nothing". The var has not been initialized.
False
means "not true in a boolean context". Used to explicitly show you are dealing with logical issues.
0
is an int
. Nothing to do with the rest above, used for mathematics.
Now, what is tricky, it's that in dynamic languages like PHP, all of them have a value in a boolean context, which (in PHP) is False
.
If you test it with ==
, it's testing the boolean value, so you will get equality. If you test it with ===
, it will test the type, and you will get inequality.
Well, look at the strrpos()
function. It returns False if it did not found anything, but 0 if it has found something at the beginning of the string !
<?php
// pitfall :
if (strrpos("Hello World", "Hello")) {
// never exectuted
}
// smart move :
if (strrpos("Hello World", "Hello") !== False) {
// that works !
}
?>
And of course, if you deal with states:
You want to make a difference between DebugMode = False
(set to off), DebugMode = True
(set to on) and DebugMode = Null
(not set at all, will lead to hard debugging ;-)).
If you are using API 11 or higher you can try this: FLAG_ACTIVITY_CLEAR_TASK
--it seems to be addressing exactly the issue you're having. Obviously the pre-API 11 crowd would have to use some combination of having all activities check an extra, as @doreamon suggests, or some other trickery.
(Also note: to use this you have to pass in FLAG_ACTIVITY_NEW_TASK
)
Intent intent = new Intent(this, LoginActivity.class);
intent.putExtra("finish", true); // if you are checking for this in your other Activities
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TASK |
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
After doing that don't forget to change your href
in,
<a href="{the chosen redirected name}"> home</a>
Example:
.htaccess
file
RewriteEngine On
RewriteRule ^about/$ /about.php
PHP file:
<a href="about/"> about</a>
With the WebClient class:
using System.Net;
//...
WebClient Client = new WebClient ();
Client.DownloadFile("http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png", @"C:\folder\stackoverflowlogo.png");
You can use lynx with -stdin and -dump options to achieve that:
<?php
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("file", "/tmp/htmp2txt.log", "a") // stderr is a file to write to
);
$process = proc_open('lynx -stdin -dump 2>&1', $descriptorspec, $pipes, '/tmp', NULL);
if (is_resource($process)) {
// $pipes now looks like this:
// 0 => writeable handle connected to child stdin
// 1 => readable handle connected to child stdout
// Any error output will be appended to htmp2txt.log
$stdin = $pipes[0];
fwrite($stdin, <<<'EOT'
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>TEST</title>
</head>
<body>
<h1><span>Lorem Ipsum</span></h1>
<h4>"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."</h4>
<h5>"There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain..."</h5>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque et sapien ut erat porttitor suscipit id nec dui. Nam rhoncus mauris ac dui tristique bibendum. Aliquam molestie placerat gravida. Duis vitae tortor gravida libero semper cursus eu ut tortor. Nunc id orci orci. Suspendisse potenti. Phasellus vehicula leo sed erat rutrum sed blandit purus convallis.
</p>
<p>
Aliquam feugiat, neque a tempus rhoncus, neque dolor vulputate eros, non pellentesque elit lacus ut nunc. Pellentesque vel purus libero, ultrices condimentum lorem. Nam dictum faucibus mollis. Praesent adipiscing nunc sed dui ultricies molestie. Quisque facilisis purus quis felis molestie ut accumsan felis ultricies. Curabitur euismod est id est pretium accumsan. Praesent a mi in dolor feugiat vehicula quis at elit. Mauris lacus mauris, laoreet non molestie nec, adipiscing a nulla. Nullam rutrum, libero id pellentesque tempus, erat nibh ornare dolor, id accumsan est risus at leo. In convallis felis at eros condimentum adipiscing aliquam nisi faucibus. Integer arcu ligula, porttitor in fermentum vitae, lacinia nec dui.
</p>
</body>
</html>
EOT
);
fclose($stdin);
echo stream_get_contents($pipes[1]);
fclose($pipes[1]);
// It is important that you close any pipes before calling
// proc_close in order to avoid a deadlock
$return_value = proc_close($process);
echo "command returned $return_value\n";
}
It's critical to emphasize the comma (,
) in a when
clause. It acts as an ||
of an if
statement, that is, it does an OR comparison and not an AND comparison between the delimited expressions of the when
clause. See the following case statement:
x = 3
case x
when 3, x < 2 then 'apple'
when 3, x > 2 then 'orange'
end
=> "apple"
x
is not less than 2, yet the return value is "apple"
. Why? Because x
was 3 and since ',`` acts as an
||, it did not bother to evaluate the expression
x < 2'.
You might think that to perform an AND, you can do something like this below, but it doesn't work:
case x
when (3 && x < 2) then 'apple'
when (3 && x > 2) then 'orange'
end
=> nil
It doesn't work because (3 && x > 2)
evaluates to true, and Ruby takes the True value and compares it to x
with ===
, which is not true, since x
is 3.
To do an &&
comparison, you will have to treat case
like an if
/else
block:
case
when x == 3 && x < 2 then 'apple'
when x == 3 && x > 2 then 'orange'
end
In the Ruby Programming Language book, Matz says this latter form is the simple (and infrequently used) form, which is nothing more than an alternative syntax for if
/elsif
/else
. However, whether it is infrequently used or not, I do not see any other way to attach multiple &&
expressions for a given when
clause.
Well, if you would like to catch all exception to create a minidump for example...
Somebody did the work on Windows.
See http://www.codeproject.com/Articles/207464/Exception-Handling-in-Visual-Cplusplus In the article, he explains how he found out how to catch all kind of exceptions and he provides code that works.
Here is the list you can catch:
SEH exception
terminate
unexpected
pure virtual method call
invalid parameter
new operator fault
SIGABR
SIGFPE
SIGILL
SIGINT
SIGSEGV
SIGTERM
Raised exception
C++ typed exception
And the usage: CCrashHandler ch; ch.SetProcessExceptionHandlers(); // do this for one thread ch.SetThreadExceptionHandlers(); // for each thred
By default, this creates a minidump in the current directory (crashdump.dmp)
GetLogicalDrives() enumerates all mounted disk partitions, not physical drives.
You can enumerate the drive letters with (or without) GetLogicalDrives, then call QueryDosDevice() to find out which physical drive the letter is mapped to.
Alternatively, you can decode the information in the registry at HKEY_LOCAL_MACHINE\SYSTEM\MountedDevices. The binary data encodings there are not obvious, however. If you have a copy of Russinovich and Solomon's book Microsoft Windows Internals, this registry hive is discussed in Chapter 10.
This worked for me on Swift 5
let blurredView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
blurredView.frame = self.view.bounds
backgroundimage.addSubview(blurredView)
only tab
rm -rvf /usr/local/go/
not works well, but
sudo rm -rvf /usr/local/go/
do.
in my case problem was build tools version which was 23.0.0 rc3 and i changed to 22.0.1 and my problem fixed.
By the looks of it you need to actually pass drawImage an image object like so
var canvas = document.getElementById("c");_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
var image = new Image();_x000D_
image.onload = function() {_x000D_
ctx.drawImage(image, 0, 0);_x000D_
};_x000D_
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
_x000D_
<canvas id="c"></canvas>
_x000D_
I've tried it in chrome and it works fine.
If you don't want to open Android Studio just to modify your path...
${HOME}/Library/Android/sdk/tools
${HOME}/Library/Android/sdk/platform-tools
.bashwhatever
export PATH="${HOME}/Library/Android/sdk/tools:${HOME}/Library/Android/sdk/platform-tools:${PATH}"
Just listen to what the warning is telling you:
Reshape your data either X.reshape(-1, 1) if your data has a single feature/column and X.reshape(1, -1) if it contains a single sample.
For your example type(if you have more than one feature/column):
temp = temp.reshape(1,-1)
For one feature/column:
temp = temp.reshape(-1,1)
Maybe the problem only in your IDE encoding settings. Try to set UTF-8 everywhere:
Select * from emp where joindate between date1 and date2;
But this query not show proper data.
Eg
1-jan-2013 to 12-jan-2013.
But it's show data
1-jan-2013 to 11-jan-2013.
I just threw this together, inspired by .NET LINQ
<?php
// callable type hint may be "closure" type hint instead, depending on php version
function array_group_by(array $arr, callable $key_selector) {
$result = array();
foreach ($arr as $i) {
$key = call_user_func($key_selector, $i);
$result[$key][] = $i;
}
return $result;
}
$data = array(
array(1, "Andy", "PHP"),
array(1, "Andy", "C#"),
array(2, "Josh", "C#"),
array(2, "Josh", "ASP"),
array(1, "Andy", "SQL"),
array(3, "Steve", "SQL"),
);
$grouped = array_group_by($data, function($i){ return $i[0]; });
var_dump($grouped);
?>
And voila you get
array(3) {
[1]=>
array(3) {
[0]=>
array(3) {
[0]=>
int(1)
[1]=>
string(4) "Andy"
[2]=>
string(3) "PHP"
}
[1]=>
array(3) {
[0]=>
int(1)
[1]=>
string(4) "Andy"
[2]=>
string(2) "C#"
}
[2]=>
array(3) {
[0]=>
int(1)
[1]=>
string(4) "Andy"
[2]=>
string(3) "SQL"
}
}
[2]=>
array(2) {
[0]=>
array(3) {
[0]=>
int(2)
[1]=>
string(4) "Josh"
[2]=>
string(2) "C#"
}
[1]=>
array(3) {
[0]=>
int(2)
[1]=>
string(4) "Josh"
[2]=>
string(3) "ASP"
}
}
[3]=>
array(1) {
[0]=>
array(3) {
[0]=>
int(3)
[1]=>
string(5) "Steve"
[2]=>
string(3) "SQL"
}
}
}
You can always write it like this
String[] errorSoon = {"Hello","World"};
For (int x=0;x<errorSoon.length;x++) // in this way u create a for loop that would like display the elements which are inside the array errorSoon.oh errorSoon.length is the same as errorSoon<2
{
System.out.println(" "+errorSoon[x]); // this will output those two words, at the top hello and world at the bottom of hello.
}
I depends on what is the regexp language you use, but informally, it would be:
[:alpha:][:alpha:][:digit:][:digit:][:digit:][:digit:][:digit:][:digit:]
where [:alpha:] = [a-zA-Z]
and [:digit:] = [0-9]
If you use a regexp language that allows finite repetitions, that would look like:
[:alpha:]{2}[:digit:]{6}
The correct syntax depends on the particular language you're using, but that is the idea.
Defining r as a dictionary should do the trick:
>>> r: dict = {'is_claimed': 'True', 'rating': 3.5}
>>> print(r['rating'])
3.5
>>> type(r)
<class 'dict'>
Use delegate
and event.target
. delegate
takes advantage of the event bubbling by letting one element listen for, and handle, events on child elements. target
is the jQ-normalized property of the event
object representing the object from which the event originated.
$(document).delegate('*', 'click', function (event) {
// event.target is the element
// $(event.target).text() gets its text
});
'''
If the python version you installed is 3.6.1, you can print strings and a variable through
a single line of code.
For example the first string is "I have", the second string is "US
Dollars" and the variable, **card.price** is equal to 300, we can write
the code this way:
'''
print("I have", card.price, "US Dollars")
#The print() function outputs strings to the screen.
#The comma lets you concatenate and print strings and variables together in a single line of code.
You can deal multipleViewTypes RecyclerAdapter
by making getItemViewType()
return the expected viewType
value for that position
I prepared an MultipleViewTypeAdapter
for constructing MCQ list for examinations which may throw a question that may have 2 or more valid answers (checkbox options) and a single answer questions (radiobutton options).
For this i get the type of Question from API response and i used that for deciding which view i have to show for that question .
public class MultiViewTypeAdapter extends RecyclerView.Adapter {
Context mContext;
ArrayList<Question> dataSet;
ArrayList<String> questions;
private Object radiobuttontype1;
//Viewholder to display Questions with checkboxes
public static class Checkboxtype2 extends RecyclerView.ViewHolder {
ImageView imgclockcheck;
CheckBox checkbox;
public Checkboxtype2(@NonNull View itemView) {
super(itemView);
imgclockcheck = (ImageView) itemView.findViewById(R.id.clockout_cbox_image);
checkbox = (CheckBox) itemView.findViewById(R.id.clockout_cbox);
}
}
//Viewholder to display Questions with radiobuttons
public static class Radiobuttontype1 extends RecyclerView.ViewHolder {
ImageView clockout_imageradiobutton;
RadioButton clockout_radiobutton;
TextView sample;
public radiobuttontype1(View itemView) {
super(itemView);
clockout_imageradiobutton = (ImageView) itemView.findViewById(R.id.clockout_imageradiobutton);
clockout_radiobutton = (RadioButton) itemView.findViewById(R.id.clockout_radiobutton);
sample = (TextView) itemView.findViewById(R.id.sample);
}
}
public MultiViewTypeAdapter(ArrayList<QueDatum> data, Context context) {
this.dataSet = data;
this.mContext = context;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
if (viewType.equalsIgnoreCase("1")) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.clockout_radio_list_row, viewGroup, false);
return new radiobuttontype1(view);
} else if (viewType.equalsIgnoreCase("2")) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.clockout_cbox_list_row, viewGroup, false);
view.setHorizontalFadingEdgeEnabled(true);
return new Checkboxtype2(view);
} else if (viewType.equalsIgnoreCase("3")) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.clockout_radio_list_row, viewGroup, false);
return new Radiobuttontype1(view);
} else if (viewType.equalsIgnoreCase("4")) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.clockout_radio_list_row, viewGroup, false);
return new Radiobuttontype1(view);
} else if (viewType.equalsIgnoreCase("5")) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.clockout_radio_list_row, viewGroup, false);
return new Radiobuttontype1(view);
}
return null;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int viewType) {
if (viewType.equalsIgnoreCase("1")) {
options = dataSet.get(i).getOptions();
question = dataSet.get(i).getQuestion();
image = options.get(i).getValue();
((radiobuttontype1) viewHolder).clockout_radiobutton.setChecked(false);
((radiobuttontype1) viewHolder).sample.setText(question);
//loading image bitmap in the ViewHolder's View
Picasso.with(mContext)
.load(image)
.into(((radiobuttontype1) viewHolder).clockout_imageradiobutton);
} else if (viewType.equalsIgnoreCase("2")) {
options = (ArrayList<Clockout_questions_Option>) dataSet.get(i).getOptions();
question = dataSet.get(i).getQuestion();
image = options.get(i).getValue();
//loading image bitmap in the ViewHolder's View
Picasso.with(mContext)
.load(image)
.into(((Checkboxtype2) viewHolder).imgclockcheck);
} else if (viewType.equalsIgnoreCase("3")) {
//fit data to viewHolder for ViewType 3
} else if (viewType.equalsIgnoreCase("4")) {
//fit data to viewHolder for ViewType 4
} else if (viewType.equalsIgnoreCase("5")) {
//fit data to viewHolder for ViewType 5
}
}
@Override
public int getItemCount() {
return dataSet.size();
}
/**
* returns viewType for that position by picking the viewType value from the
* dataset
*/
@Override
public int getItemViewType(int position) {
return dataSet.get(position).getViewType();
}
}
You can avoid multiple conditional based viewHolder data fillings in onBindViewHolder()
by assigning same ids for the similar views across viewHolders which differ in their positioning.
Function for check number is Decimal or whole number
function IsDecimalExist(p_decimalNumber) {
var l_boolIsExist = true;
if (p_decimalNumber % 1 == 0)
l_boolIsExist = false;
return l_boolIsExist;
}
Do you mean byte size or string length?
Byte size is measured with strlen()
, whereas string length is queried using mb_strlen()
. You can use substr()
to trim a string to X bytes (note that this will break the string if it has a multi-byte encoding - as pointed out by Darhazer in the comments) and mb_substr()
to trim it to X characters in the encoding of the string.
I got the same problem. I just tried to rebuild, clean and restart but no luck. Then I just remove
compile 'com.google.android.gms:play-services:8.3.0'
from build.gradle and resync. After that I put it again and resync. Next to that, I clean the project and the problem is gone!!
I hope it will help any of you facing the same.
I'm also facing this type of problem. After trying all solutions I got final solution on this problem. Reasons for this type of problem is per-defined global fonts. Use !important keyword for each line in @font-face is the solution for this problem.
Full description and example for Solution of this problem is here :- http://answerdone.blogspot.com/2017/06/font-face-not-working-solution.html
do this
sudo apt-get install php-curl
and restart server
sudo service apache2 restart