If you have multiple source files, you probably actually want to use link-time-optimization to output one bitcode file for the entire program. The other answers given will cause you to end up with a bitcode file for every source file.
Instead, you want to compile with link-time-optimization
clang -flto -c program1.c -o program1.o
clang -flto -c program2.c -o program2.o
and for the final linking step, add the argument -Wl,-plugin-opt=also-emit-llvm
clang -flto -Wl,-plugin-opt=also-emit-llvm program1.o program2.o -o program
This gives you both a compiled program and the bitcode corresponding to it (program.bc). You can then modify program.bc in any way you like, and recompile the modified program at any time by doing
clang program.bc -o program
although be aware that you need to include any necessary linker flags (for external libraries, etc) at this step again.
Note that you need to be using the gold linker for this to work. If you want to force clang to use a specific linker, create a symlink to that linker named "ld" in a special directory called "fakebin" somewhere on your computer, and add the option
-B/home/jeremy/fakebin
to any linking steps above.
System wide C++ change on Ubuntu:
sudo apt-get install clang
sudo update-alternatives --config c++
Will print something like this:
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/bin/g++ 20 auto mode
1 /usr/bin/clang++ 10 manual mode
2 /usr/bin/g++ 20 manual mode
Then just select clang++.
A good summary of LLVM is this:
At the frontend you have Perl, and many other high level languages. At the backend, you have the natives code that run directly on the machine.
At the centre is your intermediate code representation. If every high level language can be represented in this LLVM IR format, then analysis tools based on this IR can be easily reused - that is the basic rationale.
Sometimes when we do these steps:
alter table my_table drop constraint my_pk;
alter table my_table add constraint my_pk primary key (city_id, buildtime, time);
The last statement fails with
ORA-00955 "name is already used by an existing object"
Oracle usually creates an unique index with the same name my_pk. In such a case you can drop the unique index or rename it based on whether the constraint is still relevant.
You can combine the dropping of primary key constraint and unique index into a single sql statement:
alter table my_table drop constraint my_pk drop index;
check this: ORA-00955 "name is already used by an existing object"
The list variable (which I would recommend to rename to something more sensible) is a reference to a list object, which can be changed.
On the line
listoflists.append((list, list[0]))
You actually are only adding a reference to the object reference by the list variable. You've got multiple possibilities to create a copy of the list, so listoflists contains the values as you seem to expect:
Use the copy library
import copy
listoflists.append((copy.copy(list), list[0]))
use the slice notation
listoflists.append((list[:], list[0]))
This worked for me.
.alert:not(:first-child){
margin: 30px;
}
I am also phase these error and i am little bit change in modelClass which are implemented Serializable interface like:
At that Model class also implement Parcelable interface with writeToParcel() override method
Then just got error to "create creator" so CREATOR is write and also create with modelclass contructor with arguments & without arguments..
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(name);
}
protected ArtistTrackClass(Parcel in) {
id = in.readString();
name = in.readString();
}
public ArtistTrackClass() {
}
public static final Creator<ArtistTrackClass> CREATOR = new Creator<ArtistTrackClass>() {
@Override
public ArtistTrackClass createFromParcel(Parcel in) {
return new ArtistTrackClass(in);
}
@Override
public ArtistTrackClass[] newArray(int size) {
return new ArtistTrackClass[size];
}
};
Here,
ArtistTrackClass -> ModelClass
Constructor with Parcel arguments "read our attributes" and writeToParcel() is "write our attributes"
A .o object file file (also .obj on Windows) contains compiled object code (that is, machine code produced by your C or C++ compiler), together with the names of the functions and other objects the file contains. Object files are processed by the linker to produce the final executable. If your build process has not produced these files, there is probably something wrong with your makefile/project files.
you can use undocumented wm_concat
function.
select col1, wm_concat(distinct col2) col2_list
from tab1
group by col1;
this function returns clob column, if you want you can use dbms_lob.substr
to convert clob to varchar2.
web.py is probably the simplest web framework out there. "Bare" CGI is simpler, but you're completely on your own when it comes to making a service that actually does something.
"Hello, World!" according to web.py isn't much longer than an bare CGI version, but it adds URL mapping, HTTP command distinction, and query parameter parsing for free:
import web
urls = (
'/(.*)', 'hello'
)
app = web.application(urls, globals())
class hello:
def GET(self, name):
if not name:
name = 'world'
return 'Hello, ' + name + '!'
if __name__ == "__main__":
app.run()
Since the previous answers were written, requests have changed. Have a look at the bug thread at Github for more detail and this comment for an example.
In short, the files parameter takes a dict
with the key being the name of the form field and the value being either a string or a 2, 3 or 4-length tuple, as described in the section POST a Multipart-Encoded File in the requests quickstart:
>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
In the above, the tuple is composed as follows:
(filename, data, content_type, headers)
If the value is just a string, the filename will be the same as the key, as in the following:
>>> files = {'obvius_session_id': '72c2b6f406cdabd578c5fd7598557c52'}
Content-Disposition: form-data; name="obvius_session_id"; filename="obvius_session_id"
Content-Type: application/octet-stream
72c2b6f406cdabd578c5fd7598557c52
If the value is a tuple and the first entry is None
the filename property will not be included:
>>> files = {'obvius_session_id': (None, '72c2b6f406cdabd578c5fd7598557c52')}
Content-Disposition: form-data; name="obvius_session_id"
Content-Type: application/octet-stream
72c2b6f406cdabd578c5fd7598557c52
Using the Drag and Drop method
cmd
to pull up the windows bar operation.Open File Location
.Copy to Desktop
while dragging and before dropping, then push down and hold the Control key until you see the message. If you have iAds in your binary you will not be able to run it on anything before iOS 4.0 and it will be rejected if you try and submit a binary like this.
You can still run the simulator from 3.2 onwards after upgrading.
In the iPhone Simulator try selecting Hardware -> Version -> 3.2
The answer is on the example link you provided:
http://getbootstrap.com/javascript/#modals-usage
i.e.
Call a modal with id myModal with a single line of JavaScript:
$('#myModal').modal('show');
Where is this list of products that you're trying to determine the existence of? If that list exists within another table you could do this
declare @are_equal bit
declare @products int
SELECT @products =
count(pl.id)
FROM ProductList pl
JOIN Products p
ON pl.productId = p.productId
select @are_equal = @products == select count(id) from ProductList
Edit:
Then do ALL the work in C#. Cache the actual list of products in your application somewhere, and do a LINQ query.
var compareProducts = new List<Product>(){p1,p2,p3,p4,p5};
var found = From p in GetAllProducts()
Join cp in compareProducts on cp.Id equals p.Id
select p;
return compareProducts.Count == found.Count;
This prevents constructing SQL queries by hand, and keeps all your application logic in the application.
I'm sure this is a duplicate, but I can't find a question with the same answer.
Add HorizontalContentAlignment="Stretch"
to your ListBox. That should do the trick. Just be careful with auto-complete because it is so easy to get HorizontalAlignment
by mistake.
Instead of merge, as others suggested, you can rebase one branch onto another:
git checkout BranchB
git rebase BranchA
This takes BranchB
and rebases it onto BranchA
, which effectively looks like BranchB
was branched from BranchA
, not master
.
There is definitly a problem with the destination folder path.
Your above error message says, it wants to put the contents to a file in the directory /files/grantapps/
, which would be beyond your vhost
, but somewhere in the system (see the leading absolute slash )
You should double check:
/home/username/public_html/files/grantapps/
really present./home/username/public_html/files/grantapps/
class stack
{ private int top;
private int[] element;
stack()
{element=new int[10];
top=-1;
}
void push(int item)
{top++;
if(top==9)
System.out.println("Overflow");
else
{
top++;
element[top]=item;
}
void pop()
{if(top==-1)
System.out.println("Underflow");
else
top--;
}
void display()
{
System.out.println("\nTop="+top+"\nElement="+element[top]);
}
public static void main(String args[])
{
stack s1=new stack();
s1.push(10);
s1.display();
s1.push(20);
s1.display();
s1.push(30);
s1.display();
s1.pop();
s1.display();
}
}
Output
Top=0
Element=10
Top=1
Element=20
Top=2
Element=30
Top=1
Element=20
Additionally, if you want to set multiple variables at once by one query, you can use the other syntax for setting variables which goes like this: SELECT @varname:=value
.
A practical example:
SELECT @total_count:=COUNT(*), @total_price:=SUM(quantity*price) FROM items ...
The real question is do you need to use historical data and active data together for reporting? If so keep them in one table, partition and create a view for active records to use in active queries. If you only need to look at them occasionally (to research leagal issues or some such) then put them in a separate table.
When the session expires the data is no longer present, so something like
if (!isset($_SESSION['id'])) {
header("Location: destination.php");
exit;
}
will redirect whenever the session is no longer active.
You can set how long the session cookie is alive using session.cookie_lifetime
ini_set("session.cookie_lifetime","3600"); //an hour
EDIT: If you are timing sessions out due to security concern (instead of convenience,) use the accepted answer, as the comments below show, this is controlled by the client and thus not secure. I never thought of this as a security measure.
I think what he is trying to say is to use the
getContentPane().setBackground(Color.the_Color_you_want_here)
but if u want to set the color to any other then the JFrame, you use the object.setBackground(Color.the_Color_you_want_here)
Eg:
jPanel.setbackground(Color.BLUE)
Create new Maven file with path as classpath and goal as class name
I am getting this issue when using owl carousal and scrolling the images.
So get solved just adding below CSS in your page.
.owl-carousel {
-ms-touch-action: pan-y;
touch-action: pan-y;
}
or
.owl-carousel {
-ms-touch-action: none;
touch-action: none;
}
Having a table like this (with a header and a body)
<table id="myTableId">
<thead>
</thead>
<tbody>
</tbody>
</table>
remove every tr having a parent called tbody inside the #tableId
$('#tableId tbody > tr').remove();
and in reverse if you want to add to your table
$('#tableId tbody').append("<tr><td></td>....</tr>");
UPDATE : 2020
Instead of using Redirect, Simply add multiple route in the path
Example:
<Route exact path={["/","/defaultPath"]} component={searchDashboard} />
Instead of using "", use 0. Then use conditional formating to color 0 to the backgrounds color, so that it appears blank.
Since blank cells and 0 will have the same behavior in most situations, this may solve the issue.
To store values in shared preferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();
To retrieve values from shared preferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", "");
After you write to the MemoryStream
and before you read it back, you need to Seek
back to the beginning of the MemoryStream
so you're not reading from the end.
UPDATE
After seeing your update, I think there's a more reliable way to build the stream:
UnicodeEncoding uniEncoding = new UnicodeEncoding();
String message = "Message";
// You might not want to use the outer using statement that I have
// I wasn't sure how long you would need the MemoryStream object
using(MemoryStream ms = new MemoryStream())
{
var sw = new StreamWriter(ms, uniEncoding);
try
{
sw.Write(message);
sw.Flush();//otherwise you are risking empty stream
ms.Seek(0, SeekOrigin.Begin);
// Test and work with the stream here.
// If you need to start back at the beginning, be sure to Seek again.
}
finally
{
sw.Dispose();
}
}
As you can see, this code uses a StreamWriter to write the entire string (with proper encoding) out to the MemoryStream
. This takes the hassle out of ensuring the entire byte array for the string is written.
Update: I stepped into issue with empty stream several time. It's enough to call Flush right after you've finished writing.
For the question
How can i run a jar file in command prompt but with arguments
.
To pass arguments to the jar file at the time of execution
java -jar myjar.jar arg1 arg2
In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:
String arg1 = args[0];
String arg2 = args[1];
If you need to set the credentials on the fly, have a look at this source:
http://spc3.codeplex.com/SourceControl/changeset/view/57957#1015709
private ICredentials BuildCredentials(string siteurl, string username, string password, string authtype) {
NetworkCredential cred;
if (username.Contains(@"\")) {
string domain = username.Substring(0, username.IndexOf(@"\"));
username = username.Substring(username.IndexOf(@"\") + 1);
cred = new System.Net.NetworkCredential(username, password, domain);
} else {
cred = new System.Net.NetworkCredential(username, password);
}
CredentialCache cache = new CredentialCache();
if (authtype.Contains(":")) {
authtype = authtype.Substring(authtype.IndexOf(":") + 1); //remove the TMG: prefix
}
cache.Add(new Uri(siteurl), authtype, cred);
return cache;
}
Just type java -version
in your console.
If a 64 bit version is running, you'll get a message like:
java version "1.6.0_18"
Java(TM) SE Runtime Environment (build 1.6.0_18-b07)
Java HotSpot(TM) 64-Bit Server VM (build 16.0-b13, mixed mode)
A 32 bit version will show something similar to:
java version "1.6.0_41"
Java(TM) SE Runtime Environment (build 1.6.0_41-b02)
Java HotSpot(TM) Client VM (build 20.14-b01, mixed mode, sharing)
Note Client
instead of 64-Bit Server
in the third line. The Client/Server
part is irrelevant, it's the absence of the 64-Bit
that matters.
If multiple Java versions are installed on your system, navigate to the /bin folder of the Java version you want to check, and type java -version
there.
Finding the first occurrence
There's a recipe for that in itertools
:
def first_true(iterable, default=False, pred=None):
"""Returns the first true value in the iterable.
If no true value is found, returns *default*
If *pred* is not None, returns the first item
for which pred(item) is true.
"""
# first_true([a,b,c], x) --> a or b or c or x
# first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
return next(filter(pred, iterable), default)
For example, the following code finds the first odd number in a list:
>>> first_true([2,3,4,5], None, lambda x: x%2==1)
3
You can just use the Select()
extension method:
IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<string> strings = integers.Select(i => i.ToString());
Or in LINQ syntax:
IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
var strings = from i in integers
select i.ToString();
curl --head https://www.example.net
I was pointed to this by curl itself; when I issued the command with -X HEAD
, it printed:
Warning: Setting custom HTTP method to HEAD with -X/--request may not work the
Warning: way you want. Consider using -I/--head instead.
just .idea/
works fine for me
Running after the page load should partially be satisfied by setting an event listener to the window load event
window.addEventListener("load",function()...)
Inside the module.run(function()...)
of angular you will have all access to the module structure and dependencies.
You can broadcast
and emit
events for communications bridges.
For example:
In my pretty standard setup I've been seeing the following work well when passed in as VM Option (commandline before class in Java, or VM Option in an IDE):
-Droot.log.level=TRACE
var onlyFileName = System.IO.Path.GetFileName(ofd.FileName);
IDE: The MS Office of Programming. It's where you type your code, plus some added features to make you a happier programmer. (e.g. Eclipse, Netbeans). Car body: It's what you really touch, see and work on.
Library: A library is a collection of functions, often grouped into multiple program files, but packaged into a single archive file. This contains programs created by other folks, so that you don't have to reinvent the wheel. (e.g. junit.jar, log4j.jar). A library generally has a key role, but does all of its work behind the scenes, it doesn't have a GUI. Car's engine.
API: The library publisher's documentation. This is how you should use my library. (e.g. log4j API, junit API). Car's user manual - yes, cars do come with one too!
What is a kit? It's a collection of many related items that work together to provide a specific service. When someone says medicine kit, you get everything you need for an emergency: plasters, aspirin, gauze and antiseptic, etc.
SDK: McDonald's Happy Meal. You have everything you need (and don't need) boxed neatly: main course, drink, dessert and a bonus toy. An SDK is a bunch of different software components assembled into a package, such that they're "ready-for-action" right out of the box. It often includes multiple libraries and can, but may not necessarily include plugins, API documentation, even an IDE itself. (e.g. iOS Development Kit).
Toolkit: GUI. GUI. GUI. When you hear 'toolkit' in a programming context, it will often refer to a set of libraries intended for GUI development. Since toolkits are UI-centric, they often come with plugins (or standalone IDE's) that provide screen-painting utilities. (e.g. GWT)
Framework: While not the prevalent notion, a framework can be viewed as a kit. It also has a library (or a collection of libraries that work together) that provides a specific coding structure & pattern (thus the word, framework). (e.g. Spring Framework)
Regex won't help much. First of all, you will want to take into account the operators precedence, and second, you need to work with parentheses which is impossible with regex.
Depending on what exactly kind of expression you need to parse, you may try either Python AST or (more likely) pyparsing. But, first of all, I'd recommend to read something about syntax analysis in general and the Shunting yard algorithm in particular.
And fight the temptation of using eval
, that's not safe.
If you would like to auto format on save just with Javascript source, add this one into Users Setting
(press Cmd, or Ctrl,):
"[javascript]": { "editor.formatOnSave": true }
I don't think all the other answerers understood the question correctly. The question requires disabling editing part of the text. One solution I can think of is simulating a textbox with a fixed prefix which is not part of the textarea or input.
An example of this approach is:
<div style="border:1px solid gray; color:#999999; font-family:arial; font-size:10pt; width:200px; white-space:nowrap;">Default Notes<br/>
<textarea style="border:0px solid black;" cols="39" rows="5"></textarea></div>
The other approach, which I end up using is using JS and JQuery to simulate "Disable" feature. Example with pseudo-code (cannot be specific cause of legal issue):
// disable existing notes by preventing keystroke
document.getElementById("txtNotes").addEventListener('keydown', function (e) {
if (cursorLocation < defaultNoteLength ) {
e.preventDefault();
});
// disable existing notes by preventing right click
document.addEventListener('contextmenu', function (e) {
if (cursorLocation < defaultNoteLength )
e.preventDefault();
});
Thanks, Carsten, for mentioning that this question is old, but I found that the solution might help other people in the future.
I know this is an ancient thread, but it was my first hit on Google, and I wanted to share the following resub
that I put together, which adds support for multiple $1, $2, etc. backreferences...
#!/usr/bin/env bash
############################################
### resub - regex substitution in bash ###
############################################
resub() {
local match="$1" subst="$2" tmp
if [[ -z $match ]]; then
echo "Usage: echo \"some text\" | resub '(.*) (.*)' '\$2 me \${1}time'" >&2
return 1
fi
### First, convert "$1" to "$BASH_REMATCH[1]" and 'single-quote' for later eval-ing...
### Utility function to 'single-quote' a list of strings
squot() { local a=(); for i in "$@"; do a+=( $(echo \'${i//\'/\'\"\'\"\'}\' )); done; echo "${a[@]}"; }
tmp=""
while [[ $subst =~ (.*)\${([0-9]+)}(.*) ]] || [[ $subst =~ (.*)\$([0-9]+)(.*) ]]; do
tmp="\${BASH_REMATCH[${BASH_REMATCH[2]}]}$(squot "${BASH_REMATCH[3]}")${tmp}"
subst="${BASH_REMATCH[1]}"
done
subst="$(squot "${subst}")${tmp}"
### Now start (globally) substituting
tmp=""
while read line; do
counter=0
while [[ $line =~ $match(.*) ]]; do
eval tmp='"${tmp}${line%${BASH_REMATCH[0]}}"'"${subst}"
line="${BASH_REMATCH[$(( ${#BASH_REMATCH[@]} - 1 ))]}"
done
echo "${tmp}${line}"
done
}
resub "$@"
##################
### EXAMPLES ###
##################
### % echo "The quick brown fox jumps quickly over the lazy dog" | resub quick slow
### The slow brown fox jumps slowly over the lazy dog
### % echo "The quick brown fox jumps quickly over the lazy dog" | resub 'quick ([^ ]+) fox' 'slow $1 sheep'
### The slow brown sheep jumps quickly over the lazy dog
### % animal="sheep"
### % echo "The quick brown fox 'jumps' quickly over the \"lazy\" \$dog" | resub 'quick ([^ ]+) fox' "\"\$low\" \${1} '$animal'"
### The "$low" brown 'sheep' 'jumps' quickly over the "lazy" $dog
### % echo "one two three four five" | resub "one ([^ ]+) three ([^ ]+) five" 'one $2 three $1 five'
### one four three two five
### % echo "one two one four five" | resub "one ([^ ]+) " 'XXX $1 '
### XXX two XXX four five
### % echo "one two three four five one six three seven eight" | resub "one ([^ ]+) three ([^ ]+) " 'XXX $1 YYY $2 '
### XXX two YYY four five XXX six YYY seven eight
H/T to @Charles Duffy re: (.*)$match(.*)
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
DTO
should only contain private fields for your data, getters, setters, and constructors.DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.
You can use the extension method AsEnumerable in Assembly System.Core and System.Linq namespace :
List<Book> list = new List<Book>();
return list.AsEnumerable();
This will, as said on this MSDN link change the type of the List in compile-time. This will give you the benefits also to only enumerate your collection we needed (see MSDN example for this).
String[] split = data.split("\\|",-1);
This is not the actual requirement in all the time. The Drawback of above is show below:
Scenerio 1:
When all data are present:
String data = "5|6|7||8|9|10|";
String[] split = data.split("\\|");
String[] splt = data.split("\\|",-1);
System.out.println(split.length); //output: 7
System.out.println(splt.length); //output: 8
When data is missing:
Scenerio 2: Data Missing
String data = "5|6|7||8|||";
String[] split = data.split("\\|");
String[] splt = data.split("\\|",-1);
System.out.println(split.length); //output: 5
System.out.println(splt.length); //output: 8
Real requirement is length should be 7 although there is data missing. Because there are cases such as when I need to insert in database or something else. We can achieve this by using below approach.
String data = "5|6|7||8|||";
String[] split = data.split("\\|");
String[] splt = data.replaceAll("\\|$","").split("\\|",-1);
System.out.println(split.length); //output: 5
System.out.println(splt.length); //output:7
What I've done here is, I'm removing "|" pipe at the end and then splitting the String. If you have "," as a seperator then you need to add ",$" inside replaceAll.
Full Document height calculation:
To be more generic and find the height of any document you could just find the highest DOM Node on current page with a simple recursion:
;(function() {
var pageHeight = 0;
function findHighestNode(nodesList) {
for (var i = nodesList.length - 1; i >= 0; i--) {
if (nodesList[i].scrollHeight && nodesList[i].clientHeight) {
var elHeight = Math.max(nodesList[i].scrollHeight, nodesList[i].clientHeight);
pageHeight = Math.max(elHeight, pageHeight);
}
if (nodesList[i].childNodes.length) findHighestNode(nodesList[i].childNodes);
}
}
findHighestNode(document.documentElement.childNodes);
// The entire page height is found
console.log('Page height is', pageHeight);
})();
You can Test it on your sample sites (http://fandango.com/ or http://paperbackswap.com/) with pasting this script to a DevTools Console.
NOTE: it is working with Iframes
.
Enjoy!
According to my interpretation of the implementation of unicode-escape
and the unicode repr
in the CPython 2.6.5 source, yes; the only difference between repr(unicode_string)
and unicode_string.encode('unicode-escape')
is the inclusion of wrapping quotes and escaping whichever quote was used.
They are both driven by the same function, unicodeescape_string
. This function takes a parameter whose sole function is to toggle the addition of the wrapping quotes and escaping of that quote.
I think you want Any
:
if (myList.Any(str => str.Contains("Mdd LH")))
It's well worth becoming familiar with the LINQ standard query operators; I would usually use those rather than implementation-specific methods (such as List<T>.ConvertAll
) unless I was really bothered by the performance of a specific operator. (The implementation-specific methods can sometimes be more efficient by knowing the size of the result etc.)
The preffered answer can be even smaller if you make use of Java 1.8 Lambdas
textfield.textProperty().addListener((observable, oldValue, newValue) -> {
if (newValue.matches("\\d*")) return;
textfield.setText(newValue.replaceAll("[^\\d]", ""));
});
If I understand your question correctly, it appears you want to know the following:
How do I check if my
String
array containsusercode
, theString
that was just inputted?
See here for a similar question. It quotes solutions that have been pointed out by previous answers. I hope this helps.
If your goal is to have
str = "Hello\nWorld";
and output what it contains in string literal form, you can use JSON.stringify
:
console.log(JSON.stringify(str)); // ""Hello\nWorld""
const str = "Hello\nWorld";_x000D_
const json = JSON.stringify(str);_x000D_
console.log(json); // ""Hello\nWorld""_x000D_
for (let i = 0; i < json.length; ++i) {_x000D_
console.log(`${i}: ${json.charAt(i)}`);_x000D_
}
_x000D_
.as-console-wrapper {_x000D_
max-height: 100% !important;_x000D_
}
_x000D_
console.log
adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal (yes, that's somewhat confusing).
JSON.stringify
takes what you give it (in this case, a string) and returns a string containing valid JSON for that value. So for the above, it returns an opening quote ("
), the word Hello
, a backslash (\
), the letter n
, the word World
, and the closing quote ("
). The linefeed in the string is escaped in the output as a \
and an n
because that's how you encode a linefeed in JSON. Other escape sequences are similarly encoded.
Your syntax is incorrect. The var
keyword in your for
loop must be followed by a variable name, in this case its propName
var propValue;
for(var propName in nyc) {
propValue = nyc[propName]
console.log(propName,propValue);
}
I suggest you have a look here for some basics:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
To answer the question that is asked in the beginning:
Why can't the container component call the async API, and then dispatch the actions?
Keep in mind that those docs are for Redux, not Redux plus React. Redux stores hooked up to React components can do exactly what you say, but a Plain Jane Redux store with no middleware doesn't accept arguments to dispatch
except plain ol' objects.
Without middleware you could of course still do
const store = createStore(reducer);
MyAPI.doThing().then(resp => store.dispatch(...));
But it's a similar case where the asynchrony is wrapped around Redux rather than handled by Redux. So, middleware allows for asynchrony by modifying what can be passed directly to dispatch
.
That said, the spirit of your suggestion is, I think, valid. There are certainly other ways you could handle asynchrony in a Redux + React application.
One benefit of using middleware is that you can continue to use action creators as normal without worrying about exactly how they're hooked up. For example, using redux-thunk
, the code you wrote would look a lot like
function updateThing() {
return dispatch => {
dispatch({
type: ActionTypes.STARTED_UPDATING
});
AsyncApi.getFieldValue()
.then(result => dispatch({
type: ActionTypes.UPDATED,
payload: result
}));
}
}
const ConnectedApp = connect(
(state) => { ...state },
{ update: updateThing }
)(App);
which doesn't look all that different from the original — it's just shuffled a bit — and connect
doesn't know that updateThing
is (or needs to be) asynchronous.
If you also wanted to support promises, observables, sagas, or crazy custom and highly declarative action creators, then Redux can do it just by changing what you pass to dispatch
(aka, what you return from action creators). No mucking with the React components (or connect
calls) necessary.
For someone using Android Studio 4.0 or above on MacOS 10.15.1 or above. Using command line blow:
# Deletes the Android Studio application
# Note that this may be different depending on what you named the application as, or whether you downloaded the preview version
rm -Rf /Applications/Android\ Studio.app
# Delete All Android Studio related preferences
# The asterisk here should target all folders/files beginning with the string before it
rm -Rf ~/Library/Preferences/Google/AndroidStudio*
# Deletes the Android Studio's plist file
rm -Rf ~/Library/Preferences/com.google.android.*
# Deletes the Android Emulator's plist file
rm -Rf ~/Library/Preferences/com.android.*
# Deletes mainly plugins (or at least according to what mine (Edric) contains)
rm -Rf ~/Library/Application\ Support/Google/AndroidStudio*
# Deletes all logs that Android Studio outputs
rm -Rf ~/Library/Logs/Google/AndroidStudio*
# Deletes Android Studio's caches
rm -Rf ~/Library/Caches/Google/AndroidStudio*
# Deletes older versions of Android Studio
rm -Rf ~/.AndroidStudio*
Difference
Library/Preferences/Google/AndroidStudio*
Library/Logs/Google/AndroidStudio*
Library/Caches/Google/AndroidStudio*
(Update: If I could delete this answer I would, although since it's accepted, I can't. I'm updating the description to provide better guidance and discourage folks from using the poor practice I outlined in the original answer).
You can specify these parameters via context or environment parameters, such as in context.xml. See the sections titled "Context Parameters" and "Environment Entries" on this page:
http://tomcat.apache.org/tomcat-5.5-doc/config/context.html
As @netjeff points out, these values will be available via the Context.lookup(String) method and not as System parameters.
Another way to do specify these values is to define variables inside of the web.xml file of the web application you're deploying (see below). As @Roberto Lo Giacco points out, this is generally considered a poor practice since a deployed artifact should not be environment specific. However, below is the configuration snippet if you really want to do this:
<env-entry>
<env-entry-name>SMTP_PASSWORD</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>abc123ftw</env-entry-value>
</env-entry>
LinearLayout
means you can align views one by one (vertically/ horizontally).
RelativeLayout
means based on relation of views from its parents and other views.
ConstraintLayout
is similar to a RelativeLayout in that it uses relations to position and size widgets, but has additional flexibility and is easier to use in the Layout Editor.
WebView
to load html, static or dynamic pages.
FrameLayout
to load child one above another, like cards inside a frame, we can place one above another or anywhere inside the frame.
deprecated - AbsoluteLayout
means you have to give exact position where the view should be.
For more information, please check this address https://developer.android.com/guide/topics/ui/declaring-layout#CommonLayouts
If the request if GET and we passed some query parameters then,
fro`enter code here`m flask import request
@app.route('/')
@app.route('/data')
def data():
if request.method == 'GET':
# Get the parameters by key
arg1 = request.args.get('arg1')
arg2 = request.args.get('arg2')
# Generate the query string
query_string="?arg1={0}&arg2={1}".format(arg1, arg2)
return render_template("data.html", query_string=query_string)
I'm not really too clear what you are asking, but using the -f
command line option just specifies a file - it doesn't tell make to change directories. If you want to do the work in another directory, you need to cd
to the directory:
clean:
cd gtest-1.4.0 && $(MAKE) clean
Note that each line in Makefile
runs in a separate shell, so there is no need to change the directory back.
Try invoking your command with Invoke-Expression
:
Invoke-Expression $cmd1
Here is a working example on my machine:
$cmd = "& 'C:\Program Files\7-zip\7z.exe' a -tzip c:\temp\test.zip c:\temp\test.txt"
Invoke-Expression $cmd
iex
is an alias for Invoke-Expression
so you could do:
iex $cmd1
For a full list :
Visit https://ss64.com/ps/ for more Powershell
stuff.
Good Luck...
If you want to check for local files first do:
@font-face {
font-family: 'Green Sans Web';
src:
local('Green Web'),
local('GreenWeb-Regular'),
url('GreenWeb.ttf');
}
There is a more elaborate description of what to do here.
You are getting this error because you are not giving full path. (C:\Users...\file.exe) If you want to remove this error then either give full path or copy that application (you want to open) to the folder where your project(.exe) is present/saved.
#include <windows.h>
using namespace std;
int main()
{
system ("start C:\\Users\\Folder\\chrome.exe https://www.stackoverflow.com"); //for opening stackoverflow through google chrome , if chorme.exe is in that folder..
return 0;
}
To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm.dll
, please install or use the JRE or JDK that contains these missing components.
Follow these steps:
Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)
After that, go to C:/Program files/java/jre7/bin
Here, create an folder called Server
Now go into the C:/Program files/java/jre7/bin/client
folder
Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server
folder
This is a really interesting question, and you'll get it done in Multiple ways:
Here, In general, we have a public
schema by default. So, I'm using it as an instance.
DROP SCHEMA `public` CASCADE;
CREATE SCHEMA `public`;
GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO public;
If you are using PostgreSQL 9.3 or greater, you may also need to restore the default grants.
Pros:
This will clean an entire Schema and re-create it as a new one.
Cons:
You'll lose other entities too like Functions
, Views
, Materialized views
, etc.
pg_tables
table.PostgreSQL stores all the tables on its record table named pg_table
.
SELECT
'DROP TABLE IF EXISTS "' || tablename || '" CASCADE;'
from
pg_tables WHERE schemaname = 'public';
As you can see, By the use of subquery, We can remove the entire tables from the schema.
Pros:
When the other data entities are Important and you just want to delete only tables from the schema, this approach will really helpful to you.
$ sudo -u postgres psql
$ \c mydatabase
Paste these commands:
DROP SCHEMA public CASCADE;
CREATE SCHEMA public;
GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO public;
Note: This bunch of commands are similar to the first point, so the Pros and cons will remain the same.
As Chris suggests, you can do it like this:
public string GetXMLAsString(XmlDocument myxml)
{
return myxml.OuterXml;
}
Or like this:
public string GetXMLAsString(XmlDocument myxml)
{
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
myxml.WriteTo(tx);
string str = sw.ToString();//
return str;
}
and if you really want to create a new XmlDocument
then do this
XmlDocument newxmlDoc= myxml
body
{
width:80%;
margin-left:auto;
margin-right:auto;
}
This will work on most browsers, including IE.
As Andrew Brower says, but adding a trim
ALTER PROCEDURE <Name>
(
@PartialName VARCHAR(50) = NULL
)
SELECT Name
FROM <table>
WHERE Name LIKE '%' + LTRIM(RTRIM(@PartialName)) + '%'
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "scr", "javascript:test();", true);
You can put them into a list and then sort them using their natural ordering, like so:
final List<Integer> list = Arrays.asList(11367, 11358, 11421, 11530, 11491, 11218, 11789);
Collections.sort( list );
// Use the sorted list
If the numbers are stored in the same variable, then you'll have to somehow put them into a List
and then call sort
, like so:
final List<Integer> list = new ArrayList<Integer>();
list.add( myVariable );
// Change myVariable to another number...
list.add( myVariable );
// etc...
Collections.sort( list );
// Use the sorted list
on the server side in node.js I just added this and it worked. reactjs front end on my local machine can access api backend hosted on azure:
// Enables CORS
const cors = require('cors');
app.use(cors({ origin: true }));
if (Application.OpenForms["Form_NAME"] == null)
{
new Form_NAME().Show();
}
If the form instance is not open it will enter the IF loop.
You can access any DGV cell as follows :
dataGridView1.Rows[rowIndex].Cells[columnIndex].Value = value;
But usually it's better to use databinding : you bind the DGV to a data source (DataTable
, collection...) through the DataSource
property, and only work on the data source itself. The DataGridView
will automatically reflect the changes, and changes made on the DataGridView
will be reflected on the data source
Here is the code (but not in C#):
Private m_CurUser As String
Public ReadOnly Property CurrentUser As String
Get
If String.IsNullOrEmpty(m_CurUser) Then
Dim who As System.Security.Principal.IIdentity = System.Security.Principal.WindowsIdentity.GetCurrent()
If who Is Nothing Then
m_CurUser = Environment.UserDomainName & "\" & Environment.UserName
Else
m_CurUser = who.Name
End If
End If
Return m_CurUser
End Get
End Property
Here is the code (now also in C#):
private string m_CurUser;
public string CurrentUser
{
get
{
if(string.IsNullOrEmpty(m_CurUser))
{
var who = System.Security.Principal.WindowsIdentity.GetCurrent();
if (who == null)
m_CurUser = System.Environment.UserDomainName + @"\" + System.Environment.UserName;
else
m_CurUser = who.Name;
}
return m_CurUser;
}
}
/* Author: Siken Dongol */
#include <stdio.h>
int strLength(char *input) {
int i = 0;
while(input[i++]!='\0');
return --i;
}
int main()
{
char input[] = "Siken Man Singh Dongol";
int len = strLength(input);
char output[len];
int index = 0;
while(len >= 0) {
output[index++] = input[--len];
}
printf("%s\n",input);
printf("%s\n",output);
return 0;
}
Actually there is a simpler way to do this, just:
if ($("#input").is(':empty')) {
console.log('empty');
} else {
console.log('not empty');
}
src: https://www.geeksforgeeks.org/how-to-check-an-html-element-is-empty-using-jquery/
I did some things different and it works for me.
With no changes in code, I did config my .plist file like this:
I hope it helps.
For each view controller I change the "status bar"'s Simulated Metrics property, in storyboard, from "inferred" to "Light Content"
by this function:
ALTER FUNCTION [dbo].[isnull](@input nvarchar(50),@ret int = 0)
RETURNS int
AS
BEGIN
return (case when @input='' then @ret when @input is null then @ret else @input end)
END
and use this:
dbo.isnull(value,0)
Depending on how secure you need the configuration files or how reliable your application is, http://activemq.apache.org/encrypted-passwords.html may be a good solution for you.
If you are not too afraid of the password being decrypted and it can be really simple to configure using a bean to store the password key. However, if you need more security you can set an environment variable with the secret and remove it after launch. With this you have to worry about the application / server going down and not application not automatically relaunching.
I have been using a pattern like this to program complex multi inheritance things:
var mammal = {
lungCapacity: 200,
breath() {return 'Breathing with ' + this.lungCapacity + ' capacity.'}
}
var dog = {
catchTime: 2,
bark() {return 'woof'},
playCatch() {return 'Catched the ball in ' + this.catchTime + ' seconds!'}
}
var robot = {
beep() {return 'Boop'}
}
var robotDogProto = Object.assign({}, robot, dog, {catchTime: 0.1})
var robotDog = Object.create(robotDogProto)
var livingDogProto = Object.assign({}, mammal, dog)
var livingDog = Object.create(livingDogProto)
This method uses very little code, and allows for things like overwriting default properties (like I do with a custom catchTime in robotDogProto)
Already restarted your Webserver?
This will force php to reload the php.ini
Just run command adb logcat | grep hash
and look for something like Key hash ABCDEFGH1234= does not match any stored key
. Now save this hash on your fb developer console.
In C if you implement count line it will never fail. Yes you can get one extra line if there is stray "ENTER KEY" generally at the end of the file.
File might look some thing like this:
"hello 1
"Hello 2
"
Code below
#include <stdio.h>
#include <stdlib.h>
#define FILE_NAME "file1.txt"
int main() {
FILE *fd = NULL;
int cnt, ch;
fd = fopen(FILE_NAME,"r");
if (fd == NULL) {
perror(FILE_NAME);
exit(-1);
}
while(EOF != (ch = fgetc(fd))) {
/*
* int fgetc(FILE *) returns unsigned char cast to int
* Because it has to return EOF or error also.
*/
if (ch == '\n')
++cnt;
}
printf("cnt line in %s is %d\n", FILE_NAME, cnt);
fclose(fd);
return 0;
}
This is how it worked for me:
Make sure composer is installed without no errors.
Open "System Properties" on windows and go to the "Advanced" tab. (You can just press the windows button on your keyboard and type in "Edit the system environment variables`
"Environment variables"
Under "System variables" Edit "PATH"
Click on "New".
Type in: C:\ProgramData\ComposerSetup\bin\composer.phar
Close all folders & CMDs + restart you WAMP server.
Go to whatever directory you want to install a package in and type in
composer.phar create-project slim/slim-skeleton
for example.
Modify the WebApiConfig and add at the end another Routes.MapHttpRoute like this:
config.Routes.MapHttpRoute(
name: "ServiceApi",
routeTemplate: "api/Service/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Then create a controller like this:
public class ServiceController : ApiController
{
[HttpGet]
public string Get(int id)
{
return "object of id id";
}
[HttpGet]
public IQueryable<DropDownModel> DropDowEmpresa()
{
return db.Empresa.Where(x => x.Activo == true).Select(y =>
new DropDownModel
{
Id = y.Id,
Value = y.Nombre,
});
}
[HttpGet]
public IQueryable<DropDownModel> DropDowTipoContacto()
{
return db.TipoContacto.Select(y =>
new DropDownModel
{
Id = y.Id,
Value = y.Nombre,
});
}
[HttpGet]
public string FindProductsByName()
{
return "FindProductsByName";
}
}
This is how I solved it. I hope it will help someone.
I know this is a bit old but the answer in short would be <load-on-startup> both occurrences have given the same id which is 1 twice. This may confuse loading sequence.
I think the best approach is using reduce and Map object. This is a single line solution.
const data = [
{id: 1, name: 'David'},
{id: 2, name: 'Mark'},
{id: 2, name: 'Lora'},
{id: 4, name: 'Tyler'},
{id: 4, name: 'Donald'},
{id: 5, name: 'Adrian'},
{id: 6, name: 'Michael'}
]
const uniqueData = [...data.reduce((map, obj) => map.set(obj.id, obj), new Map()).values()];
console.log(uniqueData)
/*
in `map.set(obj.id, obj)`
'obj.id' is key. (don't worry. we'll get only values using the .values() method)
'obj' is whole object.
*/
_x000D_
There are 3 different things we are using here :
So lets understand how spring data jpa and spring + hibernate works-
Let's say you are using spring + hibernate for your application. Now you need to have dao interface and implementation where you will be writing crud operation using SessionFactory of hibernate. Let say you are writing dao class for Employee class, tomorrow in your application you might need to write similiar crud operation for any other entity. So there is lot of boilerplate code we can see here.
Now Spring data jpa allow us to define dao interfaces by extending its repositories(crudrepository, jparepository) so it provide you dao implementation at runtime. You don't need to write dao implementation anymore.Thats how spring data jpa makes your life easy.
I had the same problem and Andrew is correct. Check your classpath variable "M2_REPO". It probably points to an invalid location of your local maven repo.
In my case I was using mvn eclipse:eclipse
on the command line and this plugin was setting the M2_REPO classpath variable. Eclipse couldn't find my maven settings.xml in my home directory and as a result was incorrectly the M2_REPO classpath variable. My solution was to restart eclipse and it picked up my settings.xml and removed the red exclamation on my projects.
I got some more information from this guy: http://www.mkyong.com/maven/how-to-configure-m2_repo-variable-in-eclipse-ide/
Use npm/bower to install bootstrap if you want to recompile it/change less files/test. With grunt it would be easier to do this, as shown on http://getbootstrap.com/getting-started/#grunt. If you only want to add precompiled libraries feel free to manually include files to project.
No, you have to do this by yourself or use separate grunt tool. For example 'grunt-contrib-concat' How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)
Create simple ajax combo with de initial seleted value for select2 4.0.3
<select name="mycombo" id="mycombo""></select>
<script>
document.addEventListener("DOMContentLoaded", function (event) {
selectMaker.create('table', 'idname', '1', $("#mycombo"), 2, 'type');
});
</script>
library .js
var selectMaker = {
create: function (table, fieldname, initialSelected, input, minimumInputLength = 3, type ='',placeholder = 'Select a element') {
if (input.data('select2')) {
input.select2("destroy");
}
input.select2({
placeholder: placeholder,
width: '100%',
minimumInputLength: minimumInputLength,
containerCssClass: type,
dropdownCssClass: type,
ajax: {
url: 'ajaxValues.php?getQuery=true&table=' + table + '&fieldname=' + fieldname + '&type=' + type,
type: 'post',
dataType: 'json',
contentType: "application/json",
delay: 250,
data: function (params) {
return {
term: params.term, // search term
page: params.page
};
},
processResults: function (data) {
return {
results: $.map(data.items, function (item) {
return {
text: item.name,
id: item.id
}
})
};
}
}
});
if (initialSelected>0) {
var $option = $('<option selected>Cargando...</option>').val(0);
input.append($option).trigger('change'); // append the option and update Select2
$.ajax({// make the request for the selected data object
type: 'GET',
url: 'ajaxValues.php?getQuery=true&table=' + table + '&fieldname=' + fieldname + '&type=' + type + '&initialSelected=' + initialSelected,
dataType: 'json'
}).then(function (data) {
// Here we should have the data object
$option.text(data.items[0].name).val(data.items[0].id); // update the text that is displayed (and maybe even the value)
$option.removeData(); // remove any caching data that might be associated
input.trigger('change'); // notify JavaScript components of possible changes
});
}
}
};
and the php server side
<?php
if (isset($_GET['getQuery']) && isset($_GET['table']) && isset($_GET['fieldname'])) {
//parametros carga de petición
parse_str(file_get_contents("php://input"), $data);
$data = (object) $data;
if (isset($data->term)) {
$term = pSQL($data->term);
}else{
$term = '';
}
if (isset($_GET['initialSelected'])){
$id =pSQL($_GET['initialSelected']);
}else{
$id = '';
}
if ($_GET['table'] == 'mytable' && $_GET['fieldname'] == 'mycolname' && $_GET['type'] == 'mytype') {
if (empty($id)){
$where = "and name like '%" . $term . "%'";
}else{
$where = "and id= ".$id;
}
$rows = yourarrayfunctionfromsql("SELECT id, name
FROM yourtable
WHERE 1 " . $where . "
ORDER BY name ");
}
$items = array("items" => $rows);
$var = json_encode($items);
echo $var;
?>
If you are windows user and using command line to check following versions then:
Check node version
node -v
Check npm version
npm -v
Do not depend on ADB shell, just treat it (the adb logcat) a normal linux output and then pip it:
$ adb shell logcat | grep YouTag
# just like:
$ ps -ef | grep your_proc
576 is the minimum maximum reassembly buffer size, i.e. each implementation must be able to reassemble packets of at least that size. See IETF RFC 1122 for details.
just use this as a middleware
<?php
namespace App\Http\Middleware;
use Closure;
class CorsMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Allow-Methods', '*');
return $response;
}
}
and register the middleware in your kernel file on this path app/Http/Kernel.php
in which group that you prefer and everything will be fine
Package Explorer / View Menu / Package Presentation... / Hierarchical
The "View Menu" can be opened with Ctrl + F10, or the small arrow-down icon in the top-right corner of the Package Explorer.
Sample code to render system time in a specific time zone and a specific format.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class TimZoneTest {
public static void main (String[] args){
//<GMT><+/-><hour>:<minutes>
// Any screw up in this format, timezone defaults to GMT QUIETLY. So test your format a few times.
System.out.println(my_time_in("GMT-5:00", "MM/dd/yyyy HH:mm:ss") );
System.out.println(my_time_in("GMT+5:30", "'at' HH:mm a z 'on' MM/dd/yyyy"));
System.out.println("---------------------------------------------");
// Alternate format
System.out.println(my_time_in("America/Los_Angeles", "'at' HH:mm a z 'on' MM/dd/yyyy") );
System.out.println(my_time_in("America/Buenos_Aires", "'at' HH:mm a z 'on' MM/dd/yyyy") );
}
public static String my_time_in(String target_time_zone, String format){
TimeZone tz = TimeZone.getTimeZone(target_time_zone);
Date date = Calendar.getInstance().getTime();
SimpleDateFormat date_format_gmt = new SimpleDateFormat(format);
date_format_gmt.setTimeZone(tz);
return date_format_gmt.format(date);
}
}
Output
10/08/2011 21:07:21
at 07:37 AM GMT+05:30 on 10/09/2011
at 19:07 PM PDT on 10/08/2011
at 23:07 PM ART on 10/08/2011
This is what i have created for Material Design. May it will helpful you.
Have a look for MultipleThemeMaterialDesign
Does this do what you want?
p <- ggplot(myData, aes(foo, bar)) + geom_whateverGeomYouWant(more = options) +
p + scale_x_continuous(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0)) +
opts(legend.position = "none")
If you want the last 5 rows, ordered in ascending order, you need a subquery:
SELECT *
FROM
( SELECT id, name, form_id, DATE(updated_at) AS updated_date, updated_at
FROM wp_frm_items
WHERE user_id = 11
AND form_id=9
ORDER BY updated_at DESC
LIMIT 5
) AS tmp
ORDER BY updated_at
After reading the question for 10th time, this may be (just maybe) what you want. Order by Date descending and then order by time (on same date) ascending:
SELECT id, name, form_id, DATE(updated_at) AS updated_date
FROM wp_frm_items
WHERE user_id = 11
AND form_id=9
ORDER BY DATE(updated_at) DESC
, updated_at ASC
You can use two enums. One for the database and the other for readability.
You just need to make sure they stay in sync, which seems like a small cost. You don't have to set the values, just set the positions the same, but setting the values makes it very clear the two enums are related and prevents errors from rearranging the enum members. And a comment lets the maintenance crew know these are related and must be kept in sync.
// keep in sync with GroupTypes
public enum GroupTypeCodes
{
OEM,
CMB
}
// keep in sync with GroupTypesCodes
public enum GroupTypes
{
TheGroup = GroupTypeCodes.OEM,
TheOtherGroup = GroupTypeCodes.CMB
}
To use it you just convert to the code first:
GroupTypes myGroupType = GroupTypes.TheGroup;
string valueToSaveIntoDatabase = ((GroupTypeCodes)myGroupType).ToString();
Then if you want to make it even more convenient you can add an extension function that only works for this type of enum:
public static string ToString(this GroupTypes source)
{
return ((GroupTypeCodes)source).ToString();
}
and you can then just do:
GroupTypes myGroupType = GroupTypes.TheGroup;
string valueToSaveIntoDatabase = myGroupType.ToString();
Yeah, eclipse sees the top directory as the working/root directory, for the purposes of paths.
...just thought I'd add some extra info. I'm new here! I'd like to help.
No, it is not possible.
Consider a scenario where an ACBus is a derived class of base class Bus. ACBus has features like TurnOnAC and TurnOffAC which operate on a field named ACState. TurnOnAC sets ACState to on and TurnOffAC sets ACState to off. If you try to use TurnOnAC and TurnOffAC features on Bus, it makes no sense.
if (A || B) { do something }
Solution:
Instead of using setHeader
method I have used addHeader
.
response.addHeader("Access-Control-Allow-Origin", "*");
*
in above line will allow access to all domains, For allowing access to specific domain only:
response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");
For issues related to IE<=9, Please see here.
You probably forgot to set the form's KeyPreview property to True. Overriding the ProcessCmdKey() method is the generic solution:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == (Keys.Control | Keys.F)) {
MessageBox.Show("What the Ctrl+F?");
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
Yes. You can throw anything you want: integers, strings, objects, whatever. If you want to throw an object, then simply create a new object, just as you would create one under other circumstances, and then throw it. Mozilla's Javascript reference has several examples.
For a GOOD and definite solution see the Setting up Permissions
section in Installing and Configuring Symfony
section :
Setting up Permissions
One common issue when installing Symfony is that the app/cache and app/logs directories must be writable both by the web server and the command line user. On a UNIX system, if your web server user is different from your command line user, you can try one of the following solutions.
- Use the same user for the CLI and the web server
In development environments, it is a common practice to use the same UNIX user for the CLI and the web server because it avoids any of these permissions issues when setting up new projects. This can be done by editing your web server configuration (e.g. commonly httpd.conf or apache2.conf for Apache) and setting its user to be the same as your CLI user (e.g. for Apache, update the User and Group values).
- Using ACL on a system that supports chmod +a
Many systems allow you to use the chmod +a command. Try this first, and if you get an error - try the next method. This uses a command to try to determine your web server user and set it as HTTPDUSER:
$ rm -rf app/cache/* $ rm -rf app/logs/* $ HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\ -f1` $ sudo chmod +a "$HTTPDUSER allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs $ sudo chmod +a "`whoami` allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs
- Using ACL on a system that does not support chmod +a
Some systems don't support chmod +a, but do support another utility called setfacl. You may need to enable ACL support on your partition and install setfacl before using it (as is the case with Ubuntu). This uses a command to try to determine your web server user and set it as HTTPDUSER:
$ HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\ -f1` $ sudo setfacl -R -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX app/cache app/logs $ sudo setfacl -dR -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX app/cache app/logs
For Symfony 3 it would be:
$ HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\ -f1` $ sudo setfacl -R -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX var/cache var/logs $ sudo setfacl -dR -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX var/cache var/logs
If this doesn't work, try adding -n option.
- Without using ACL
If none of the previous methods work for you, change the umask so that the cache and log directories will be group-writable or world-writable (depending if the web server user and the command line user are in the same group or not). To achieve this, put the following line at the beginning of the app/console, web/app.php and web/app_dev.php files:
umask(0002); // This will let the permissions be 0775 // or umask(0000); // This will let the permissions be 0777
Note that using the ACL is recommended when you have access to them on your server because changing the umask is not thread-safe.
source : Failed to write cache file "/var/www/myapp/app/cache/dev/classes.php" when clearing the cache
I tried a lot to get the shortest code to get the weeknumber ISO-conform.
Date.prototype.getWeek=function(){
var date=new Date(this);
date.setHours(0,0,0,0);
return Math.round(((date.setDate(this.getDate()+2-(this.getDay()||7))-date.setMonth(0,4))/8.64e7+3+(date.getDay()||7))/7)+"/"+date.getFullYear();}
The variable date
is necessary to avoid to alter the original this
. I used the return values of setDate()
and setMonth()
to dispense with getTime()
to save code length and I used an expontial number for milliseconds of a day instead of a multiplication of single elements or a number with five zeros. this
is Date or Number of milliseconds, return value is String
e.g. "49/2017".
When you use a code like this:
using (var rsa = new RSACryptoServiceProvider(1024))
{
// Do something with the key...
// Encrypt, export, etc.
}
.NET (actually Windows) stores your key in a persistent key container forever. The container is randomly generated by .NET
This means:
Any random RSA/DSA key you have EVER generated for the purpose of protecting data, creating custom X.509 certificate, etc. may have been exposed without your awareness in the Windows file system. Accessible by anyone who has access to your account.
Your disk is being slowly filled with data. Normally not a big concern but it depends on your application (e.g. it might generates hundreds of keys every minute).
To resolve these issues:
using (var rsa = new RSACryptoServiceProvider(1024))
{
try
{
// Do something with the key...
// Encrypt, export, etc.
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
ALWAYS
Here is a useful solution that works for various operating systems, including Linux, Windows, etc.:
import os, psutil
process = psutil.Process(os.getpid())
print(process.memory_info().rss) # in bytes
With Python 2.7 and psutil 5.6.3, the last line should be
print(process.memory_info()[0])
instead (there was a change in the API later).
Note:
do pip install psutil
if it is not installed yet
handy one-liner if you quickly want to know how many MB your process takes:
import os, psutil; print(psutil.Process(os.getpid()).memory_info().rss / 1024 ** 2)
There are numerous ways to do this, but if you want a simple example, this will do. It just needs to be enhanced with necessary defensive coding to check for type safety and invalid parsing, etc.
/// <summary>
/// Extension method to return an enum value of type T for the given string.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static T ToEnum<T>(this string value)
{
return (T) Enum.Parse(typeof(T), value, true);
}
/// <summary>
/// Extension method to return an enum value of type T for the given int.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static T ToEnum<T>(this int value)
{
var name = Enum.GetName(typeof(T), value);
return name.ToEnum<T>();
}
You need more than a regex
, for example "9999-99-00" isn't a valid date. There's a SimpleDateFormat
class that's built to do this. More heavyweight, but more comprehensive.
e.g.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
boolean isValidDate(string input) {
try {
format.parse(input);
return true;
}
catch(ParseException e){
return false;
}
}
Unfortunately, SimpleDateFormat
is both heavyweight and not thread-safe.
In .Net 2.0 I`m pretty sure about this solution:
public IEnumerable<T> Distinct<T>(IEnumerable<T> source)
{
List<T> uniques = new List<T>();
foreach (T item in source)
{
if (!uniques.Contains(item)) uniques.Add(item);
}
return uniques;
}
ASCII has 128 code points, 0 through 127. It can fit in a single 8-bit byte, the values 128 through 255 tended to be used for other characters. With incompatible choices, causing the code page disaster. Text encoded in one code page cannot be read correctly by a program that assumes or guessed at another code page.
Unicode came about to solve this disaster. Version 1 started out with 65536 code points, commonly encoded in 16 bits. Later extended in version 2 to 1.1 million code points. The current version is 6.3, using 110,187 of the available 1.1 million code points. That doesn't fit in 16 bits anymore.
Encoding in 16-bits was common when v2 came around, used by Microsoft and Apple operating systems for example. And language runtimes like Java. The v2 spec came up with a way to map those 1.1 million code points into 16-bits. An encoding called UTF-16, a variable length encoding where one code point can take either 2 or 4 bytes. The original v1 code points take 2 bytes, added ones take 4.
Another variable length encoding that's very common, used in *nix operating systems and tools is UTF-8, a code point can take between 1 and 4 bytes, the original ASCII codes take 1 byte the rest take more. The only non-variable length encoding is UTF-32, takes 4 bytes for a code point. Not often used since it is pretty wasteful. There are other ones, like UTF-1 and UTF-7, widely ignored.
An issue with the UTF-16/32 encodings is that the order of the bytes will depend on the endian-ness of the machine that created the text stream. So add to the mix UTF-16BE, UTF-16LE, UTF-32BE and UTF-32LE.
Having these different encoding choices brings back the code page disaster to some degree, along with heated debates among programmers which UTF choice is "best". Their association with operating system defaults pretty much draws the lines. One counter-measure is the definition of a BOM, the Byte Order Mark, a special codepoint (U+FEFF, zero width space) at the beginning of a text stream that indicates how the rest of the stream is encoded. It indicates both the UTF encoding and the endianess and is neutral to a text rendering engine. Unfortunately it is optional and many programmers claim their right to omit it so accidents are still pretty common.
Alternative to @Peter Monks.
If the number in the 'in' statement is small and fixed.
DECLARE @var1 varchar(30), @var2 varchar(30), @var3 varchar(30);
SET @var1 = 'james';
SET @var2 = 'same';
SET @var3 = 'dogcat';
Select * FROM Database Where x in (@var1,@var2,@var3);
I followed approach as shown in code below to return a dictionary. Created a class and declared dictionary as global and created a function to add value corresponding to some keys in dictionary.
**Note have used Python 2.7 so some minor modification might be required for Python 3+
class a:
global d
d={}
def get_config(self,x):
if x=='GENESYS':
d['host'] = 'host name'
d['port'] = '15222'
return d
Calling get_config method using class instance in a separate python file:
from constant import a
class b:
a().get_config('GENESYS')
print a().get_config('GENESYS').get('host')
print a().get_config('GENESYS').get('port')
value = (value) ? false : true;
Try this if you are on ubuntu:
sudo apt-get update
sudo apt-get install build-essential libpq-dev libssl-dev openssl libffi-dev zlib1g-dev
sudo apt-get install python3-pip python3.7-dev
sudo apt-get install python3.7
In case you don't have the repository and so it fires a not-found package you first have to install this:
sudo apt-get install -y software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
more info here: http://devopspy.com/python/install-python-3-6-ubuntu-lts/
2017 Update - since WooCommerce 3:
global $product;
$id = $product->get_id();
Woocommerce doesn't like you accessing those variables directly. This will get rid of any warnings from woocommerce if your wp_debug is true.
To click the "ok" button in an alert box:
driver.switchTo().alert().accept();
If your Object represents a number, eg, such as an Integer, you can cast it to a Number then call the doubleValue() method.
Double asDouble(Object o) {
Double val = null;
if (o instanceof Number) {
val = ((Number) o).doubleValue();
}
return val;
}
Your percentage divided by 100 (to get the percentage between 0 and 1) times by the number
35.8/100*10000
I am New to Jackson API, when i got the "org.codehaus.jackson.map.JsonMappingException: No serializer found for class com.company.project.yourclass" , I added the getter and setter to com.company.project.yourclass, that helped me to use the ObjectMapper's mapper object to write the java object into a flat file.
You could use Fiddler which is a good free tool.
// Create a DataTable and add two Columns to it
DataTable dt=new DataTable();
dt.Columns.Add("Name",typeof(string));
dt.Columns.Add("Age",typeof(int));
// Create a DataRow, add Name and Age data, and add to the DataTable
DataRow dr=dt.NewRow();
dr["Name"]="Mohammad"; // or dr[0]="Mohammad";
dr["Age"]=24; // or dr[1]=24;
dt.Rows.Add(dr);
// Create another DataRow, add Name and Age data, and add to the DataTable
dr=dt.NewRow();
dr["Name"]="Shahnawaz"; // or dr[0]="Shahnawaz";
dr["Age"]=24; // or dr[1]=24;
dt.Rows.Add(dr);
// DataBind to your UI control, if necessary (a GridView, in this example)
GridView1.DataSource=dt;
GridView1.DataBind();
Pretty sure this solves what you're looking for:
HTML:
<table>
<tr><td><button class="editbtn">edit</button></td></tr>
<tr><td><button class="editbtn">edit</button></td></tr>
<tr><td><button class="editbtn">edit</button></td></tr>
<tr><td><button class="editbtn">edit</button></td></tr>
</table>
Javascript (using jQuery):
$(document).ready(function(){
$('.editbtn').click(function(){
$(this).html($(this).html() == 'edit' ? 'modify' : 'edit');
});
});
Edit:
Apparently I should have looked at your sample code first ;)
You need to change (at least) the ID attribute of each element. The ID is the unique identifier for each element on the page, meaning that if you have multiple items with the same ID, you'll get conflicts.
By using classes, you can apply the same logic to multiple elements without any conflicts.
You can USE PyPDF2 package
#install pyDF2
pip install PyPDF2
# importing all the required modules
import PyPDF2
# creating an object
file = open('example.pdf', 'rb')
# creating a pdf reader object
fileReader = PyPDF2.PdfFileReader(file)
# print the number of pages in pdf file
print(fileReader.numPages)
Follow this Documentation http://pythonhosted.org/PyPDF2/
Surprisingly, all 10 answers here say the same thing. The '::' is a namespace resolution operator, and yes it is true. But there is one gotcha that you have to realize about the namespace resolution operator when it comes to the constant lookup algorithm. As Matz delineates in his book, 'The Ruby Programming Language', constant lookup has multiple steps. First, it searches a constant in the lexical scope where the constant is referenced. If it does not find the constant within the lexical scope, it then searches the inheritance hierarchy. Because of this constant lookup algorithm, below we get the expected results:
module A
module B
PI = 3.14
module C
class E
PI = 3.15
end
class F < E
def get_pi
puts PI
end
end
end
end
end
f = A::B::C::F.new
f.get_pi
> 3.14
While F inherits from E, the B module is within the lexical scope of F. Consequently, F instances will refer to the constant PI defined in the module B. Now if module B did not define PI, then F instances will refer to the PI constant defined in the superclass E.
But what if we were to use '::' rather than nesting modules? Would we get the same result? No!
By using the namespace resolution operator when defining nested modules, the nested modules and classes are no longer within the lexical scope of their outer modules. As you can see below, PI defined in A::B is not in the lexical scope of A::B::C::D and thus we get uninitialized constant when trying to refer to PI in the get_pi instance method:
module A
end
module A::B
PI = 3.14
end
module A::B::C
class D
def get_pi
puts PI
end
end
end
d = A::B::C::D.new
d.get_pi
NameError: uninitialized constant A::B::C::D::PI
Did you mean? A::B::PI
The usual way to handle this scenario is by setting the alt
tag to something meaningful.
If you want a default image instead, then I suggest using a server-side technology to serve up your images, called using a similar format to:
<img src="ImageHandler.aspx?Img=Blue.jpg" alt="I am a picture" />
In the ImageHandler.aspx
code, catch any file-not-found errors and serve up your default.jpg
instead.
I think you need to add some context to your question. However, basic information about these things can be found here:
window.opener
https://developer.mozilla.org/en-US/docs/Web/API/Window.opener
I've used window.opener mostly when opening a new window that acted as a dialog which required user input, and needed to pass information back to the main window. However this is restricted by origin policy, so you need to ensure both the content from the dialog and the opener window are loaded from the same origin.
window.parent
https://developer.mozilla.org/en-US/docs/Web/API/Window.parent
I've used this mostly when working with IFrames that need to communicate with the window object that contains them.
window.top
https://developer.mozilla.org/en-US/docs/Web/API/Window.top
This is useful for ensuring you are interacting with the top level browser window. You can use it for preventing another site from iframing your website, among other things.
If you add some more detail to your question, I can supply other more relevant examples.
UPDATE:
There are a few ways you can handle your situation.
You have the following structure:
When Dialog 1 runs the code to open Dialog 2, after creating Dialog 2, have dialog 1 set a property on Dialog 2 that references the Dialog1 opener.
So if "childwindow" is you variable for the dialog 2 window object, and "window" is the variable for the Dialog 1 window object. After opening dialog 2, but before closing dialog 1 make an assignment similar to this:
childwindow.appMainWindow = window.opener
After making the assignment above, close dialog 1.
Then from the code running inside dialog2, you should be able to use
window.appMainWindow
to reference the main window, window object.
Hope this helps.
The size_t
type is meant to specify the size of something so it's natural to use it, for example, getting the length of a string and then processing each character:
for (size_t i = 0, max = strlen (str); i < max; i++)
doSomethingWith (str[i]);
You do have to watch out for boundary conditions of course, since it's an unsigned type. The boundary at the top end is not usually that important since the maximum is usually large (though it is possible to get there). Most people just use an int
for that sort of thing because they rarely have structures or arrays that get big enough to exceed the capacity of that int
.
But watch out for things like:
for (size_t i = strlen (str) - 1; i >= 0; i--)
which will cause an infinite loop due to the wrapping behaviour of unsigned values (although I've seen compilers warn against this). This can also be alleviated by the (slightly harder to understand but at least immune to wrapping problems):
for (size_t i = strlen (str); i-- > 0; )
By shifting the decrement into a post-check side-effect of the continuation condition, this does the check for continuation on the value before decrement, but still uses the decremented value inside the loop (which is why the loop runs from len .. 1
rather than len-1 .. 0
).
I am using Windows 7 Professional and I was having same problem @Bayu Mohammad Lufty not worked for me.
I simply delete .AndroidStudio1.2 from my C:\Users\UserName\ and restart my Android studio again. It open Android Studio perfectly! It configured everything again in next start :)
My problem was that I needed to have the ""
outside the expression since I have a dynamic variable inside the sed expression itself. So than the actual solution is that one from lenn jackman that you replace the "
inside the sed regex with [\"]
.
So my complete bash is:
RELEASE_VERSION="0.6.6"
sed -i -e "s#value=[\"]trunk[\"]#value=\"tags/$RELEASE_VERSION\"#g" myfile.xml
Here is:
#
is the sed separator
[\"]
= "
in regex
value = \"tags/$RELEASE_VERSION\"
= my replacement string, important it has just the \"
for the quotes
Also note that .equals()
normally contains ==
for testing as this is the first thing you would wish to test for if you wanted to test if two objects are equal.
And ==
actually does look at values for primitive types, for objects it checks the reference.
This analyze pretty much what is available out there: http://www.slideshare.net/SlexAxton/breaking-the-cross-domain-barrier
For postMessage solution take a look to:
https://github.com/chrissrogers/jquery-postmessage/blob/master/jquery.ba-postmessage.js
and a slightly different version:
https://github.com/thomassturm/ender-postmessage/blob/master/ender-postmessage.js
If someone interested in pseudo code(for university home works) here is one.
GETLCA(BINARYTREE BT, NODE A, NODE B)
IF Root==NIL
return NIL
ENDIF
IF Root==A OR root==B
return Root
ENDIF
Left = GETLCA (Root.Left, A, B)
Right = GETLCA (Root.Right, A, B)
IF Left! = NIL AND Right! = NIL
return root
ELSEIF Left! = NIL
Return Left
ELSE
Return Right
ENDIF
You can do this using dataset property of the element, using with or without jquery it work... i'm not aware of old browser
Note: that when you use dash ('-') sign, you need to use capital case. Eg. a-b => aB
function onContentLoad() {_x000D_
var item = document.getElementById("id1");_x000D_
var x = item.dataset.x;_x000D_
var data = item.dataset.myData;_x000D_
_x000D_
var resX = document.getElementById("resX");_x000D_
var resData = document.getElementById("resData");_x000D_
_x000D_
resX.innerText = x;_x000D_
resData.innerText = data;_x000D_
_x000D_
console.log(x);_x000D_
console.log(data);_x000D_
}
_x000D_
<body onload="onContentLoad()">_x000D_
<div id="id1" data-x="a" data-my-data="b"></div>_x000D_
_x000D_
Read 'x':_x000D_
<label id="resX"></label>_x000D_
<br/>Read 'my-data':_x000D_
<label id="resData"></label>_x000D_
</body>
_x000D_
check this code:
CREATE TRIGGER trig_Update_Employee ON [EmployeeResult] FOR INSERT AS Begin
Insert into Employee (Name, Department)
Select Distinct i.Name, i.Department
from Inserted i
Left Join Employee e on i.Name = e.Name and i.Department = e.Department
where e.Name is null
End
Very annoying, no cookie file exmpale on the official website https://ec.haxx.se/http/http-cookies.
Finnaly, I find it does not work, if your file content is just copyied like this
foo1=bar;foo2=bar2
I gusess the format must looks the style said by @Agustí Sánchez . You can test it by -c to create a cookie file on a website.
So try this way, it works
curl -H "Cookie:`cat ./my.cookie`" http://xxxx.com
You can just copy the cookie from chrome console network tab.
conn = sqlite3.connect('/path/to/your/sqlite_file.db')
c = conn.cursor()
for item in my_list:
c.execute('insert into tablename values (?,?,?)', item)
From grep --help
, but also see man grep:
Exit status is 0 if any line was selected, 1 otherwise; if any error occurs and -q was not given, the exit status is 2.
if grep --quiet MYSQL_ROLE=master /etc/aws/hosts.conf; then
echo exists
else
echo not found
fi
You may want to use a more specific regex, such as ^MYSQL_ROLE=master$
, to avoid that string in comments, names that merely start with "master", etc.
This works because the if takes a command and runs it, and uses the return value of that command to decide how to proceed, with zero meaning true and non-zero meaning false—the same as how other return codes are interpreted by the shell, and the opposite of a language like C.
There is both window.onbeforeunload
and window.onunload
, which are used differently depending on the browser. You can assign them either by setting the window properties to functions, or using the .addEventListener
:
window.onbeforeunload = function(){
// Do something
}
// OR
window.addEventListener("beforeunload", function(e){
// Do something
}, false);
Usually, onbeforeunload
is used if you need to stop the user from leaving the page (ex. the user is working on some unsaved data, so he/she should save before leaving). onunload
isn't supported by Opera, as far as I know, but you could always set both.
The elements of a sequence need to be indented at the same level. Assuming you want two jobs (A and B) each with an ordered list of key value pairs, you should use:
jobs:
- - name: A
- schedule: "0 0/5 * 1/1 * ? *"
- - type: mongodb.cluster
- config:
- host: mongodb://localhost:27017/admin?replicaSet=rs
- minSecondaries: 2
- minOplogHours: 100
- maxSecondaryDelay: 120
- - name: B
- schedule: "0 0/5 * 1/1 * ? *"
- - type: mongodb.cluster
- config:
- host: mongodb://localhost:27017/admin?replicaSet=rs
- minSecondaries: 2
- minOplogHours: 100
- maxSecondaryDelay: 120
Converting the sequences of (single entry) mappings to a mapping as @Tsyvarrev does is also possible, but makes you lose the ordering.
OQ asked about static string
vs const
. Both have different use cases (although both are treated as static).
Use const only for truly constant values (e.g. speed of light - but even this varies depending on medium). The reason for this strict guideline is that the const value is substituted into the uses of the const in assemblies that reference it, meaning you can have versioning issues should the const change in its place of definition (i.e. it shouldn't have been a constant after all). Note this even affects private const
fields because you might have base and subclass in different assemblies and private fields are inherited.
Static fields are tied to the type they are declared within. They are used for representing values that need to be the same for all instances of a given type. These fields can be written to as many times as you like (unless specified readonly).
If you meant static readonly
vs const
, then I'd recommend static readonly
for almost all cases because it is more future proof.
In case you are using zsh you can use for example the -E
or -i
switch:
history -E
If you do a man zshoptions
or man zshbuiltins
you can find out more information about these switches as well as other info related to history:
Also when listing,
-d prints timestamps for each event
-f prints full time-date stamps in the US `MM/DD/YY hh:mm' format
-E prints full time-date stamps in the European `dd.mm.yyyy hh:mm' format
-i prints full time-date stamps in ISO8601 `yyyy-mm-dd hh:mm' format
-t fmt prints time and date stamps in the given format; fmt is formatted with the strftime function with the zsh extensions described for the %D{string} prompt format in the section EXPANSION OF PROMPT SEQUENCES in zshmisc(1). The resulting formatted string must be no more than 256 characters or will not be printed
-D prints elapsed times; may be combined with one of the options above
This is all generally covered by Section 23.3.2 of SystemVerilog IEEE Std 1800-2012.
The simplest way is to instantiate in the main section of top, creating a named instance and wiring the ports up in order:
module top(
input clk,
input rst_n,
input enable,
input [9:0] data_rx_1,
input [9:0] data_rx_2,
output [9:0] data_tx_2
);
subcomponent subcomponent_instance_name (
clk, rst_n, data_rx_1, data_tx );
endmodule
This is described in Section 23.3.2.1 of SystemVerilog IEEE Std 1800-2012.
This has a few draw backs especially regarding the port order of the subcomponent code. simple refactoring here can break connectivity or change behaviour. for example if some one else fixs a bug and reorders the ports for some reason, switching the clk and reset order. There will be no connectivity issue from your compiler but will not work as intended.
module subcomponent(
input rst_n,
input clk,
...
It is therefore recommended to connect using named ports, this also helps tracing connectivity of wires in the code.
module top(
input clk,
input rst_n,
input enable,
input [9:0] data_rx_1,
input [9:0] data_rx_2,
output [9:0] data_tx_2
);
subcomponent subcomponent_instance_name (
.clk(clk), .rst_n(rst_n), .data_rx(data_rx_1), .data_tx(data_tx) );
endmodule
This is described in Section 23.3.2.2 of SystemVerilog IEEE Std 1800-2012.
Giving each port its own line and indenting correctly adds to the readability and code quality.
subcomponent subcomponent_instance_name (
.clk ( clk ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
So far all the connections that have been made have reused inputs and output to the sub module and no connectivity wires have been created. What happens if we are to take outputs from one component to another:
clk_gen(
.clk ( clk_sub ), // output
.en ( enable ) // input
subcomponent subcomponent_instance_name (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
This nominally works as a wire for clk_sub is automatically created, there is a danger to relying on this. it will only ever create a 1 bit wire by default. An example where this is a problem would be for the data:
Note that the instance name for the second component has been changed
subcomponent subcomponent_instance_name (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_temp ) // output [9:0]
);
subcomponent subcomponent_instance_name2 (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_temp ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
The issue with the above code is that data_temp is only 1 bit wide, there would be a compile warning about port width mismatch. The connectivity wire needs to be created and a width specified. I would recommend that all connectivity wires be explicitly written out.
wire [9:0] data_temp
subcomponent subcomponent_instance_name (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_temp ) // output [9:0]
);
subcomponent subcomponent_instance_name2 (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_temp ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
Moving to SystemVerilog there are a few tricks available that save typing a handful of characters. I believe that they hinder the code readability and can make it harder to find bugs.
Use .port
with no brackets to connect to a wire/reg of the same name. This can look neat especially with lots of clk and resets but at some levels you may generate different clocks or resets or you actually do not want to connect to the signal of the same name but a modified one and this can lead to wiring bugs that are not obvious to the eye.
module top(
input clk,
input rst_n,
input enable,
input [9:0] data_rx_1,
input [9:0] data_rx_2,
output [9:0] data_tx_2
);
subcomponent subcomponent_instance_name (
.clk, // input **Auto connect**
.rst_n, // input **Auto connect**
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
endmodule
This is described in Section 23.3.2.3 of SystemVerilog IEEE Std 1800-2012.
Another trick that I think is even worse than the one above is .*
which connects unmentioned ports to signals of the same wire. I consider this to be quite dangerous in production code. It is not obvious when new ports have been added and are missing or that they might accidentally get connected if the new port name had a counter part in the instancing level, they get auto connected and no warning would be generated.
subcomponent subcomponent_instance_name (
.*, // **Auto connect**
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
This is described in Section 23.3.2.4 of SystemVerilog IEEE Std 1800-2012.
1) Add any remote repositories you want to compare:
git remote add foobar git://github.com/user/foobar.git
2) Update your local copy of a remote:
git fetch foobar
Fetch won't change your working copy.
3) Compare any branch from your local repository to any remote you've added:
git diff master foobar/master
You can find the Team ID via this link: https://developer.apple.com/membercenter/index.action#accountSummary
If one is wanting to iterate through an array (Array
or more generally any SequenceType
) in reverse. You have a few additional options.
First you can reverse()
the array and loop through it as normal. However I prefer to use enumerate()
much of the time since it outputs a tuple containing the object and it's index.
The one thing to note here is that it is important to call these in the right order:
for (index, element) in array.enumerate().reverse()
yields indexes in descending order (which is what I generally expect). whereas:
for (index, element) in array.reverse().enumerate()
(which is a closer match to NSArray's reverseEnumerator
)
walks the array backward but outputs ascending indexes.
If I understood you right, you mean that if you have a function 'func', you want to check for each item in list if func(item) returns true; if you get true for all, then do something.
You can use 'all'.
For example: I want to get all prime numbers in range 0-10 in a list:
from math import sqrt
primes = [x for x in range(10) if x > 2 and all(x % i !=0 for i in range(2, int(sqrt(x)) + 1))]
To see a list of HTTP request headers, you can use :
console.log(JSON.stringify(req.headers));
to return a list in JSON format.
{
"host":"localhost:8081",
"connection":"keep-alive",
"cache-control":"max-age=0",
"accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"upgrade-insecure-requests":"1",
"user-agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36",
"accept-encoding":"gzip, deflate, sdch",
"accept-language":"en-US,en;q=0.8,et;q=0.6"
}
For those who don't want to resort to JavaScript, here's an image slicing example:
http://codepen.io/anon/pen/cbzrK
As you scale the window, the clown image will scale accordingly, and when it does, the nose of the clown remains hyperlinked.
Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.
printf("She said \"time flies like an arrow, but fruit flies like a banana\".");
Becomes:
printf(R"(She said "time flies like an arrow, but fruit flies like a banana".)");
With respect to the addition of brackets after the opening quote, and before the closing quote, note that they can be almost any combination of up to 16 characters, helping avoid the situation where the combination is present in the string itself. Specifically:
any member of the basic source character set except: space, the left parenthesis (, the right parenthesis ), the backslash , and the control characters representing horizontal tab, vertical tab, form feed, and newline" (N3936 §2.14.5 [lex.string] grammar) and "at most 16 characters" (§2.14.5/2)
How much clearer it makes this short strings might be debatable, but when used on longer formatted strings like HTML or JSON, it's unquestionably far clearer.
If nobody has pulled it, you can probably do something like
git push remote +branch^1:remotebranch
which will forcibly update the remote branch to the last but one commit of your branch.
The course contains a logical error:
assertTrue("Book check in failed", ml.checkIn(b1));
assertFalse("Book was aleready checked in", ml.checkIn(b1));
In the first assert we expect the checkIn to return True (because checkin is succesful). If this would fail we would print a message like "book check in failed. Now in the second assert we expect the checkIn to fail, because the book was checked in already in the first line. So we expect a checkIn to return a False. If for some reason checkin returns a True (which we don't expect) than the message should never be "Book was already checked in", because the checkin was succesful.
Assuming you want to get the value if the key does exist, use Dictionary<TKey, TValue>.TryGetValue
:
int value;
if (dictionary.TryGetValue(key, out value))
{
// Key was in dictionary; "value" contains corresponding value
}
else
{
// Key wasn't in dictionary; "value" is now 0
}
(Using ContainsKey
and then the the indexer makes it look the key up twice, which is pretty pointless.)
Note that even if you were using reference types, checking for null wouldn't work - the indexer for Dictionary<,>
will throw an exception if you request a missing key, rather than returning null. (This is a big difference between Dictionary<,>
and Hashtable
.)
Hariprasad didupe suggested a solution provided by Batchography, but it could be improved a bit. Unlike with other cases getting into default case will set ERRORLEVEL to 1 and, if that is not desired, you should manually set ERRORLEVEL to 0:
goto :switch-case-N-%N% 2>nul || (
rem Default case
rem Manually set ERRORLEVEL to 0
type nul>nul
echo Something else
)
...
The readability could be improved for the price of a call
overhead:
call:Switch SwitchLabel %N% || (
:SwitchLabel-1
echo One
goto:EOF
:SwitchLabel-2
echo Two
goto:EOF
:SwitchLabel-3
echo Three
goto:EOF
:SwitchLabel-
echo Default case
)
:Switch
goto:%1-%2 2>nul || (
type nul>nul
goto:%1-
)
exit /b
Few things to note:
call
overhead;rem
inside to
avoid parenthesis error;goto:EOF
will exit parent
context). This could be circumvented by replacing goto:%1-
in
subroutine with call:%1-
for the price of additional call
overhead;:-
prefix (which are valid) and
not passing a control variable will lead to default case.IF YOU REALLY NEED TO USE AJAX...
I came accross usecases where the onload handlers were not the right choice. In my case when printing via javascript. So there are actually two options to use AJAX style for this:
Solution 1
Use Base64 image data and a REST image service. If you have your own webservice, you can add a JSP/PHP REST script that offers images in Base64 encoding. Now how is that useful? I came across a cool new syntax for image encoding:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhE..."/>
So you can load the Image Base64 data using Ajax and then on completion you build the Base64 data string to the image! Great fun :). I recommend to use this site http://www.freeformatter.com/base64-encoder.html for image encoding.
$.ajax({
url : 'BASE64_IMAGE_REST_URL',
processData : false,
}).always(function(b64data){
$("#IMAGE_ID").attr("src", "data:image/png;base64,"+b64data);
});
Solution2:
Trick the browser to use its cache. This gives you a nice fadeIn() when the resource is in the browsers cache:
var url = 'IMAGE_URL';
$.ajax({
url : url,
cache: true,
processData : false,
}).always(function(){
$("#IMAGE_ID").attr("src", url).fadeIn();
});
However, both methods have its drawbacks: The first one only works on modern browsers. The second one has performance glitches and relies on assumption how the cache will be used.
cheers, will
I don't use this in production, just some test runners. And to reiterate the urllib3 documentation
If you know what you are doing and would like to disable this and other warnings
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()
Edit / Update:
The following should also work:
import logging
import requests
# turn down requests log verbosity
logging.getLogger('requests').setLevel(logging.CRITICAL)
We use Maven (Ant's big brother) for all our java projects, and it has a very nifty WAR plugin. Tutorials and usage can be found there.
It's a lot easier than Ant, fully compatible with Eclipse (use maven eclipse:eclipse to create Eclipse projects) and easy to configure.
Sample Configuration:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1-alpha-2</version>
<configuration>
<outputDirectory>${project.build.directory}/tmp/</outputDirectory>
<workDirectory>${project.build.directory}/tmp/war/work</workDirectory>
<webappDirectory>${project.build.webappDirectory}</webappDirectory>
<cacheFile>${project.build.directory}/tmp/war/work/webapp-cache.xml</cacheFile>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>pdf</nonFilteredFileExtension>
<nonFilteredFileExtension>png</nonFilteredFileExtension>
<nonFilteredFileExtension>gif</nonFilteredFileExtension>
<nonFilteredFileExtension>jsp</nonFilteredFileExtension>
</nonFilteredFileExtensions>
<webResources>
<resource>
<directory>src/main/webapp/</directory>
<targetPath>WEB-INF</targetPath>
<filtering>true</filtering>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</webResources>
<warName>Application</warName>
</configuration>
</plugin>
Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
Details: To enable the details of this specific error message to be viewable on remote machines, please create a tag within a "web.config" configuration file located in the root directory of the current web application. This tag should then have its "mode" attribute set to "Off".
The answer from @gunn is correct, target="_blank
makes the link open in a new tab.
But this can be a security risk for you page; you can read about it here. There is a simple solution for that: adding rel="noopener noreferrer"
.
<a style={{display: "table-cell"}} href = "someLink" target = "_blank"
rel = "noopener noreferrer">text</a>
If you just want to remove the first two characters and the last two, then you can use negative indexes on the string:
s = "((String1))"
s = s[2...-2]
p s # => "String1"
If you want to remove all parentheses from the string you can use the delete method on the string class:
s = "((String1))"
s.delete! '()'
p s # => "String1"
Let me explain with an example
create emp DataFrame
import spark.sqlContext.implicits._ val emp = Seq((1,"Smith",-1,"2018","10","M",3000), (2,"Rose",1,"2010","20","M",4000), (3,"Williams",1,"2010","10","M",1000), (4,"Jones",2,"2005","10","F",2000), (5,"Brown",2,"2010","40","",-1), (6,"Brown",2,"2010","50","",-1) ) val empColumns = Seq("emp_id","name","superior_emp_id","year_joined", "emp_dept_id","gender","salary")
val empDF = emp.toDF(empColumns:_*)
Create dept DataFrame
val dept = Seq(("Finance",10), ("Marketing",20), ("Sales",30), ("IT",40) )
val deptColumns = Seq("dept_name","dept_id") val deptDF = dept.toDF(deptColumns:_*)
Now let's join emp.emp_dept_id with dept.dept_id
empDF.join(deptDF,empDF("emp_dept_id") === deptDF("dept_id"),"inner")
.show(false)
This results below
+------+--------+---------------+-----------+-----------+------+------+---------+-------+
|emp_id|name |superior_emp_id|year_joined|emp_dept_id|gender|salary|dept_name|dept_id|
+------+--------+---------------+-----------+-----------+------+------+---------+-------+
|1 |Smith |-1 |2018 |10 |M |3000 |Finance |10 |
|2 |Rose |1 |2010 |20 |M |4000 |Marketing|20 |
|3 |Williams|1 |2010 |10 |M |1000 |Finance |10 |
|4 |Jones |2 |2005 |10 |F |2000 |Finance |10 |
|5 |Brown |2 |2010 |40 | |-1 |IT |40 |
+------+--------+---------------+-----------+-----------+------+------+---------+-------+
If you are looking in python PySpark Join with example and also find the complete Scala example at Spark Join
Here is another way to visualize your tree: save the nodes as an xml file and then let your browser show you the hierarchy:
class treeNode{
int key;
treeNode left;
treeNode right;
public treeNode(int key){
this.key = key;
left = right = null;
}
public void printNode(StringBuilder output, String dir){
output.append("<node key='" + key + "' dir='" + dir + "'>");
if(left != null)
left.printNode(output, "l");
if(right != null)
right.printNode(output, "r");
output.append("</node>");
}
}
class tree{
private treeNode treeRoot;
public tree(int key){
treeRoot = new treeNode(key);
}
public void insert(int key){
insert(treeRoot, key);
}
private treeNode insert(treeNode root, int key){
if(root == null){
treeNode child = new treeNode(key);
return child;
}
if(key < root.key)
root.left = insert(root.left, key);
else if(key > root.key)
root.right = insert(root.right, key);
return root;
}
public void saveTreeAsXml(){
StringBuilder strOutput = new StringBuilder();
strOutput.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
treeRoot.printNode(strOutput, "root");
try {
PrintWriter writer = new PrintWriter("C:/tree.xml", "UTF-8");
writer.write(strOutput.toString());
writer.close();
}
catch (FileNotFoundException e){
}
catch(UnsupportedEncodingException e){
}
}
}
Here is code to test it:
tree t = new tree(1);
t.insert(10);
t.insert(5);
t.insert(4);
t.insert(20);
t.insert(40);
t.insert(30);
t.insert(80);
t.insert(60);
t.insert(50);
t.saveTreeAsXml();
And the output looks like this:
I have found @givanse brilliant answer to be the most reliable and compatible across multiple mobile browsers for registering swipe actions.
However, there's a change in his code required to make it work in modern day mobile browsers that are using jQuery
.
event.touches
won't exist if jQuery
is used and results in undefined
and should be replaced by event.originalEvent.touches
. Without jQuery
, event.touches
should work fine.
So the solution becomes,
document.addEventListener('touchstart', handleTouchStart, false);
document.addEventListener('touchmove', handleTouchMove, false);
var xDown = null;
var yDown = null;
function handleTouchStart(evt) {
xDown = evt.originalEvent.touches[0].clientX;
yDown = evt.originalEvent.touches[0].clientY;
};
function handleTouchMove(evt) {
if ( ! xDown || ! yDown ) {
return;
}
var xUp = evt.originalEvent.touches[0].clientX;
var yUp = evt.originalEvent.touches[0].clientY;
var xDiff = xDown - xUp;
var yDiff = yDown - yUp;
if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
if ( xDiff > 0 ) {
/* left swipe */
} else {
/* right swipe */
}
} else {
if ( yDiff > 0 ) {
/* up swipe */
} else {
/* down swipe */
}
}
/* reset values */
xDown = null;
yDown = null;
};
Tested on:
I agree with Chris, checking the extension is not validation of the type of file any way you look at it. Telerik's radUpload is probably your best option, it provides a ContentType property of the file being uploaded, which you can compare to known mime types. You should check for:
application/vnd.ms-excel,
application/excel,
application/x-msexcel
and for the new 2k7 format:
application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet
Telerik used to sell radUpload as an individual component, but now its wrapped into the controls suite, which makes it a little more expensive, but by far its the easiest way to check for the true type
Have both buttons submit to the current page and then add this code at the top:
<?php
if(isset($_GET['firstButtonName'])
header("Location: first-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
if(isset($_GET['secondButtonName'])
header("Location: second-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
?>
It could also be done using $_SESSION if you don't want them to see the variables.
You can't wrap that text as it's unbroken without any spaces. You need a JavaScript or server side solution which splits the string after a few characters.
EDIT
You need to add this property in CSS.
word-wrap: break-word;
Use a FrameLayout with two children. The two children will be overlapped. This is recommended in one of the tutorials from Android actually, it's not a hack...
Here is an example where a TextView is displayed on top of an ImageView:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="center"
android:src="@drawable/golden_gate" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dip"
android:layout_gravity="center_horizontal|bottom"
android:padding="12dip"
android:background="#AA000000"
android:textColor="#ffffffff"
android:text="Golden Gate" />
</FrameLayout>
in VB 2008 (VB 9.0) and later, prefix Right() as Microsoft.VisualBasic.Right(string, number of characters)
Dim str as String = "Hello World"
Msgbox(Microsoft.VisualBasic.Right(str,5))
'World"
Same goes for Left() too.
This answer is for those of you looking to Install Bootstrap 3 in your Rails app without using a gem. There are two simple ways to do this that take less than 10 minutes. Pick the one that suites your needs best. Glyphicons and Javascript work and I've tested them with the latest beta of Rails 4.1.0 as well.
Using Bootstrap 3 with Rails 4 - The Bootstrap 3 files are copied into the vendor directory of your application.
Adding Bootstrap from a CDN to your Rails application - The Bootstrap 3 files are served from the Bootstrap CDN.
Number 2 above is the most flexible. All you need to do is change the version number that is stored in a layout helper. So you can run the Bootstrap version of your choice, whether that is 3.0.0, 3.0.3 or even older Bootstrap 2 releases.
header('Content-type: text/plain; charset=utf-8');
Make sure that your config file (web.config if web, or app.config if windows) in your project starts as:
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings"
type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="YourProjectName.Properties.Settings"
type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</sectionGroup>
</configSections>
</configuration>
Note that inside the configuration
element, the first child must be the configSections
element.
In the name
property on section
element, make sure you replace YourProjectName
with your actual project's name.
It happened to me that I created a webservice in a class library project, then I copied (overwriting) the config file (in order to bring the endpoints configuration) to my windows app and I started to have the same problem. I had inadvertently removed configSections
.
it worked for me, hope it helps
Use the open graph API. Here is a live example querying how many likes "Coca Cola" has.
https://developers.facebook.com/tools/explorer/?method=GET&path=cocacola%3Ffields%3Dlikes
Which boils down to:
https://graph.facebook.com/cocacola?fields=likes
Which you could do in an AJAX GET
The result is:
{
"likes": 71717854,
"id": "40796308305"
}
pip3 install --upgrade pip
worked for me
Just open a command shell and type (saying your port is 123456):
netstat -a -n -o | find "123456"
You will see everything you need.
The headers are:
Proto Local Address Foreign Address State PID
TCP 0.0.0.0:37 0.0.0.0:0 LISTENING 1111
public static final String tryClob2String(final Object value)
{
final Clob clobValue = (Clob) value;
String result = null;
try
{
final long clobLength = clobValue.length();
if (clobLength < Integer.MIN_VALUE || clobLength > Integer.MAX_VALUE)
{
log.debug("CLOB size too big for String!");
}
else
{
result = clobValue.getSubString(1, (int) clobValue.length());
}
}
catch (SQLException e)
{
log.error("tryClob2String ERROR: {}", e);
}
finally
{
if (clobValue != null)
{
try
{
clobValue.free();
}
catch (SQLException e)
{
log.error("CLOB FREE ERROR: {}", e);
}
}
}
return result;
}
This was a fresh linux Mint xfce machine
I have been battling this for a about a week. I'm trying to learn Java on Netbeans IDE and so naturally I get the combo file straight from Oracle. Which is a package of the JDK and the Netbeans IDE together in a tar file located here.
located http://www.oracle.com/technetwork/java/javase/downloads/index.html file name JDK 8u25 with NetBeans 8.0.1
after installing them (or so I thought) I would make/compile a simple program like "hello world" and that would spit out a jar file that you would be able to run in a terminal. Keep in mind that the program ran in the Netbeans IDE.
I would end up with this error: java.lang.UnsupportedClassVersionError:
Even though I ran the file from oracle website I still had the old version of the Java runtime which was not compatible to run my jar file which was compiled with the new java runtime.
After messing with stuff that was mostly over my head from setting Paths to editing .bashrc with no remedy.
I came across a solution that was easy enough for even me. I have come across something that auto installs java and configures it on your system and it works with the latest 1.8.*
One of the steps is adding a PPA wasn't sure about this at first but seems ok as it has worked for me
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer
domenic@domenic-AO532h ~ $ java -version java version "1.8.0_25" Java(TM) SE Runtime Environment (build 1.8.0_25-b17) Java HotSpot(TM) Server VM (build 25.25-b02, mixed mode)
I think it also configures the browser java as well.
I hope this helps others.
Let's say alice
is a github.com user, with 2 or more private repositories repoN
.
For this example we'll work with just two repositories named repo1
and repo2
https://github.com/alice/repo1
https://github.com/alice/repo2
You need to be to pull from these repositories without entering a passwords probably on a server, or on multiple servers.
You want to perform git pull origin master
for example, and you want this to happen without asking for a password.
You don't like dealing with ssh-agent, you have discovered (or you're discovering now) about ~/.ssh/config
a file that let's your ssh client know what private key to use depending on Hostname and username, with a simple configuration entry that looks like this:
Host github.com
HostName github.com
User git
IdentityFile /home/alice/.ssh/alice_github.id_rsa
IdentitiesOnly yes
So you went ahead and created your (alice_github.id_rsa, alice_github.id_rsa.pub)
keypair, you then also went to your repository's .git/config
file and you modified the url of your remote origin
to be something like this:
[remote "origin"]
url = "ssh://[email protected]/alice/repo1.git"
And finally you went to the repository Settings > Deploy keys
section and added the contents of alice_github.id_rsa.pub
At this point you could do your git pull origin master
without entering a password without issue.
So your instinct will be to grab that key and add it to repo2
's Deploy keys, but github.com will error out and tell you that the key is already being used.
Now you go and generate another key (using ssh-keygen -t rsa -C "[email protected]"
without passwords of course), and so that this doesn't become a mess, you will now name your keys like this:
repo1
keypair: (repo1.alice_github.id_rsa, repo1.alice_github.id_rsa.pub)
repo2
keypair: (repo2.alice_github.id_rsa, repo2.alice_github.id_rsa.pub)
You will now put the new public key on repo2
's Deploy keys configuration at github.com, but now you have an ssh problem to deal with.
github.com
domain?Your .ssh/config
file points to github.com
and it doesn't know which key to use when it's time to do the pull.
So I found a trick with github.com. You can tell your ssh client that each repository lives in a different github.com subdomain, in these cases, they will be repo1.github.com
and repo2.github.com
So first thing is editing the .git/config
files on your repo clones, so they look like this instead:
For repo1
[remote "origin"]
url = "ssh://[email protected]/alice/repo1.git"
For repo2
[remote "origin"]
url = "ssh://[email protected]/alice/repo2.git"
And then, on your .ssh/config
file, now you will be able to enter a configuration for each subdomain :)
Host repo1.github.com
HostName github.com
User git
IdentityFile /home/alice/.ssh/repo1.alice_github.id_rsa
IdentitiesOnly yes
Host repo2.github.com
HostName github.com
User git
IdentityFile /home/alice/.ssh/repo2.alice_github.id_rsa
IdentitiesOnly yes
Now you are able to git pull origin master
without entering any passwords from both repositories.
If you have multiple machines, you could copy the keys to each of the machines and reuse them, but I'd advise doing the leg work to generate 1 key per machine and repo. You will have a lot more keys to handle, but you will be less vulnerable if one gets compromised.
To check for ssl support in Python 2.6+:
try:
import ssl
except ImportError:
print "error: no ssl support"
To connect via https:
import urllib2
try:
response = urllib2.urlopen('https://example.com')
print 'response headers: "%s"' % response.info()
except IOError, e:
if hasattr(e, 'code'): # HTTPError
print 'http error code: ', e.code
elif hasattr(e, 'reason'): # URLError
print "can't connect, reason: ", e.reason
else:
raise
Set the html tag, too. This way no weird position hacks are required.
html, body {height: 100%}
When you set keys (primary or foreign) you are setting constraints on how they can be used, which in turn limits what you can do with them. If you really want to alter the column, you could re-create the table without the constraints, although I'd recommend against it. Generally speaking, if you have a situation in which you want to do something, but it is blocked by a constraint, it's best resolved by changing what you want to do rather than the constraint.
{% url 'polls:create' poll.id %}
I was looking for something similar and came across this. It looks like in the first option you mentioned
r = requests.get('<MY_URI>', auth=('<MY_TOKEN>'))
"auth" takes two parameters: username and password, so the actual statement should be
r=requests.get('<MY_URI>', auth=('<YOUR_USERNAME>', '<YOUR_PASSWORD>'))
In my case, there was no password, so I left the second parameter in auth field empty as shown below:
r=requests.get('<MY_URI', auth=('MY_USERNAME', ''))
Hope this helps somebody :)
When working with 4 large Db2 tables I have not only found the limit but it caused me to look really bad to a boss who thought that I could append all four tables (each with over 900,000 rows) to one large table. the real life result was that regardless of how many times I tried the Table (which had exactly 34 columns - 30 text and 3 integer) would spit out some cryptic message "Cannot open database unrecognized format or the file may be corrupted". Bottom Line is Less than 1,500,000 records and just a bit more than 1,252,000 with 34 rows.
To create these constraints through the GUI you need the "indexes and keys" dialogue not the check constraints one.
But in your case you just need to run the piece of code you already have. It doesn't need to be entered into the expression dialogue at all.
Short answer -
Deleted .m2 folder in {user.home}
. E.g. in windows 10 user home is C:\Users\user1
. Re-build your project using mvn clean package
. Only those dependencies would remain, which are required by the projects.
Long Answer - .m2 folder is just like a normal folder and the content of the folder is built from different projects. I think there is no way to figure out automatically that which library is "old". In fact old is a vague word. There could be so many reasons when a previous version of a library is used in a project, hence determining which one is unused is not possible.
All you could do, is to delete the .m2 folder and re-build all of your projects and then the folder would automatically build with all the required library.
If you are concern about only a particular version of a library to be used in all the projects; it is important that the project's pom should also update to latest version. i.e. if different POMs refer different versions of the library, all will get downloaded in .m2.
Yes, you can do that, but only if #b
is after #a
in the HTML.
If #b
comes immediately after #a
: http://jsfiddle.net/u7tYE/
#a:hover + #b {
background: #ccc
}
<div id="a">Div A</div>
<div id="b">Div B</div>
That's using the adjacent sibling combinator (+
).
If there are other elements between #a
and #b
, you can use this: http://jsfiddle.net/u7tYE/1/
#a:hover ~ #b {
background: #ccc
}
<div id="a">Div A</div>
<div>random other elements</div>
<div>random other elements</div>
<div>random other elements</div>
<div id="b">Div B</div>
That's using the general sibling combinator (~
).
Both +
and ~
work in all modern browsers and IE7+
If #b
is a descendant of #a
, you can simply use #a:hover #b
.
ALTERNATIVE: You can use pure CSS to do this by positioning the second element before the first. The first div is first in markup, but positioned to the right or below the second. It will work as if it were a previous sibling.
The same thing happened to me. I wanted to open the Bootstrap modal by clicking on the table rows and get more details about each row. I used a trick to do this, Which I call the virtual button! Compatible with the latest version of Bootstrap (v5.0.0-alpha2). It might be useful for others as well.
See this code snippet with preview: https://gist.github.com/alireza-rezaee/c60da1429c36351ef4f071dec0ea9aba
Summary:
let exampleButton = document.createElement("button");
exampleButton.classList.add("d-none");
document.body.appendChild(exampleButton);
exampleButton.dataset.toggle = "modal";
exampleButton.dataset.target = "#exampleModal";
//AddEventListener to all rows
document.querySelectorAll('#exampleTable tr').forEach(row => {
row.addEventListener('click', e => {
//Set parameteres (clone row dataset)
exampleButton.dataset.whatever = e.target.closest('tr').dataset.whatever;
//Button click simulation
//Now we can use relatedTarget
exampleButton.click();
})
});
All this is to use the relatedTarget
property. (See Bootstrap docs)
Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:
GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/
A simple and flexible offline recognition on Android is implemented by CMUSphinx, an open source speech recognition toolkit. It works purely offline, fast and configurable It can listen continuously for keyword, for example.
You can find latest code and tutorial here.
Update in 2019: Time goes fast, CMUSphinx is not that accurate anymore. I recommend to try Kaldi toolkit instead. The demo is here.
You are having a controlled component where input
value is determined by this.state.city
. So once you submit you have to clear your state which will clear your input automatically.
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.setState({
city: ''
});
}
In case you don't know in advance how many elements you will have to handle it might be a better solution to use collections instead (https://en.wikipedia.org/wiki/Java_collections_framework). It would be possible also to create a new bigger 2-dimensional array, copy the old data over and insert the new items there, but the collection framework handles this for you automatically.
In this case you could use a Map of Strings to Lists of Strings:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MyClass {
public static void main(String args[]) {
Map<String, List<String>> shades = new HashMap<>();
ArrayList<String> shadesOfGrey = new ArrayList<>();
shadesOfGrey.add("lightgrey");
shadesOfGrey.add("dimgray");
shadesOfGrey.add("sgi gray 92");
ArrayList<String> shadesOfBlue = new ArrayList<>();
shadesOfBlue.add("dodgerblue 2");
shadesOfBlue.add("steelblue 2");
shadesOfBlue.add("powderblue");
ArrayList<String> shadesOfYellow = new ArrayList<>();
shadesOfYellow.add("yellow 1");
shadesOfYellow.add("gold 1");
shadesOfYellow.add("darkgoldenrod 1");
ArrayList<String> shadesOfRed = new ArrayList<>();
shadesOfRed.add("indianred 1");
shadesOfRed.add("firebrick 1");
shadesOfRed.add("maroon 1");
shades.put("greys", shadesOfGrey);
shades.put("blues", shadesOfBlue);
shades.put("yellows", shadesOfYellow);
shades.put("reds", shadesOfRed);
System.out.println(shades.get("greys").get(0)); // prints "lightgrey"
}
}
Everything in one line:
get-aduser -filter * -Properties memberof | select name, @{ l="GroupMembership"; e={$_.memberof -join ";" } } | export-csv membership.csv
To make a text default in a select box use the $form->select()
method. Here is how you do it.
$options = array('m'=>'Male','f'=>'Female','n'=>'neutral');
$form->select('Model.name',$options,'f');
The above code will select Female
in the list box by default.
Keep baking...