This is what solved it for me. Originally I went to Google and copied and pasted their suggested snippet for jQuery on their CDN page:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
The snippet does not include the HTTP:
or HTTPS:
in the src
attribute but my browser, FireFox, needed it so I changed it to:
edit: this worked for me with Google Chrome as well
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Then it worked.
When, if you lose your daemon mysql in mac OSx but is present in other path for exemple in private/var do the following command
1)
ln -s /private/var/mysql/mysql.sock /tmp/mysql.sock
2) restart your connexion to mysql with :
mysql -u username -p -h host databasename
lines
is a list of strings, re.findall
doesn't work with that. try:
import re, sys
f = open('findallEX.txt', 'r')
lines = f.read()
match = re.findall('[A-Z]+', lines)
print match
var num = 10;
alert("Binary " + num.toString(2)); //1010
alert("Octal " + num.toString(8)); //12
alert("Hex " + num.toString(16)); //a
alert("Binary to Decimal "+ parseInt("1010", 2)); //10
alert("Octal to Decimal " + parseInt("12", 8)); //10
alert("Hex to Decimal " + parseInt("a", 16)); //10
Use std::to_chars
once your standard library provides it:
std::array<char, 32> buf;
auto result = std::to_chars(buf.data(), buf.data() + buf.size(), val);
if (result.ec == std::errc()) {
auto str = std::string(buf.data(), result.ptr - buf.data());
// use the string
} else {
// handle the error
}
The advantages of this method are:
Unfortunately std::to_string
is of limited utility with floating point because it uses the fixed representation, rounding small values to zero and producing long strings for large values, e.g.
auto s1 = std::to_string(1e+40);
// s1 == 10000000000000000303786028427003666890752.000000
auto s2 = std::to_string(1e-40);
// s2 == 0.000000
C++20 might get a more convenient std::format
API with the same benefits as std::to_chars
if the P0645 standards proposal gets approved.
It could be not a problem with a single line of your code.
On some devices (I don't recall if it is in stock Android) the Permission dialog includes a check box labeled "Never ask again". If you click Deny with the box checked then you won't be prompted again for that permission, it will automatically be denied to the app. To revert this, you have to go into Settings -> App -> Permissions and re--enable that perm for the app. Then turn it off to deny it again. You may have to open the app before turning it off again, not sure.
I don't know if your Nexus has it. Maybe worth a try.
What you are seeing here is not an overloaded +
oparator, but autoboxing behaviour. The Integer
class is immutable and your code:
Integer i = 0;
i = i + 1;
is seen by the compiler (after the autoboxing) as:
Integer i = Integer.valueOf(0);
i = Integer.valueOf(i.intValue() + 1);
so you are correct in your conclusion that the Integer
instance is changed, but not sneakily - it is consistent with the Java language definition :-)
Do you mean these hex values?
.glyphicon-asterisk:before{content:"\2a";}
.glyphicon-plus:before{content:"\2b";}
.glyphicon-euro:before{content:"\20ac";}
...
You can find these in glyphicons.css
here:
http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css
(If you only want to know the Glyphicons classes: http://getbootstrap.com/components/#glyphicons)
You can do this.
When hovering to the .item1
, it will change the .item2
element.
.item1 {
size:100%;
}
.item1:hover
{
.item2 {
border:none;
}
}
.item2{
border: solid 1px blue;
}
For any method in a Spring CrudRepository you should be able to specify the @Query yourself. Something like this should work:
@Query( "select o from MyObject o where inventoryId in :ids" )
List<MyObject> findByInventoryIds(@Param("ids") List<Long> inventoryIdList);
add is a local variable not a global variable try this
var add;_x000D_
var input = document.getElementById("input");_x000D_
_x000D_
function start() {_x000D_
add = setInterval("input.value++", 1000);_x000D_
}_x000D_
start();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="number" id="input" />_x000D_
<input type="button" onclick="clearInterval(add)" value="stop" />_x000D_
<input type="button" onclick="start()" value="start" />
_x000D_
You can do it using only the shell, no need for tr
or sed
$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test
If you are working in PHP version 5.* then you have to install
sudo apt-get install php5-gd
And if you are working in PHP version 7.* then you have to install
sudo apt-get install php7.0-gd
Hope it will work...
And if you are working in PHP version 7.2 then you have to install
sudo apt-get install php7.2-gd... it worked for me
studentType newStudent() // studentType doesn't exist here
{
struct studentType // it only exists within the function
{
string studentID;
string firstName;
string lastName;
string subjectName;
string courseGrade;
int arrayMarks[4];
double avgMarks;
} newStudent;
...
Move it outside the function:
struct studentType
{
string studentID;
string firstName;
string lastName;
string subjectName;
string courseGrade;
int arrayMarks[4];
double avgMarks;
};
studentType newStudent()
{
studentType newStudent
...
return newStudent;
}
Put a call to DoEvents
in the loop.
This will affect performance, so you might want to only call it on each, say, 10th iteration.
However, if you only have 30, that's hardly an issue.
try to empty your innerHtml everytime. just like this:
Element.innerHtml="";
_x000D_
I modified the solution by @Kalyani and so far it's been working beautifully!
$('selector').click(function(event) {
if(!event.detail || event.detail == 1){ return true; }
else { return false; }
});
Because "not ... =" is two operations and "<>" is only one, it is faster to use "<>".
Here is a quick experiment to prove it:
StartTime = Timer
For x = 1 to 100000000
If 4 <> 3 Then
End if
Next
WScript.echo Timer-StartTime
StartTime = Timer
For x = 1 to 100000000
If Not (4 = 3) Then
End if
Next
WScript.echo Timer-StartTime
The results I get on my machine:
4.783203
5.552734
1 - (change)
is bound to the HTML onchange event. The documentation about HTML onchange says the following :
Execute a JavaScript when a user changes the selected option of a
<select>
element
Source : https://www.w3schools.com/jsref/event_onchange.asp
2 - As stated before, (ngModelChange)
is bound to the model variable binded to your input.
So, my interpretation is :
(change)
triggers when the user changes the input(ngModelChange)
triggers when the model changes, whether it's consecutive to a user action or notAs Cody and Brett mentioned, you could reduce VBA slowdown with sensible use of Redim Preserve
. Brett suggested Mod
to do this.
You can also use a user defined Type
and Sub
to do this. Consider my code below:
Public Type dsIntArrayType
eElems() As Integer
eSize As Integer
End Type
Public Sub PushBackIntArray( _
ByRef dsIntArray As dsIntArrayType, _
ByVal intValue As Integer)
With dsIntArray
If UBound(.eElems) < (.eSize + 1) Then
ReDim Preserve .eElems(.eSize * 2 + 1)
End If
.eSize = .eSize + 1
.eElems(.eSize) = intValue
End With
End Sub
This calls ReDim Preserve
only when the size has doubled. The member variable eSize
keeps track of the actual data size of eElems
. This approach has helped me improve performance when final array length is not known until run time.
Hope this helps others too.
Yes you can. In c++, class and struct are kind of similar. We can define not only structure inside a class, but also a class inside one. It is called inner class.
As an example I am adding a simple Trie class.
class Trie {
private:
struct node{
node* alp[26];
bool isend;
};
node* root;
node* createNode(){
node* newnode=new node();
for(int i=0; i<26; i++){
newnode->alp[i]=nullptr;
}
newnode->isend=false;
return newnode;
}
public:
/** Initialize your data structure here. */
Trie() {
root=createNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
node* head=root;
for(int i=0; i<word.length(); i++){
if(head->alp[int(word[i]-'a')]==nullptr){
node* newnode=createNode();
head->alp[int(word[i]-'a')]=newnode;
}
head=head->alp[int(word[i]-'a')];
}
head->isend=true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
node* head=root;
for(int i=0; i<word.length(); i++){
if(head->alp[int(word[i]-'a')]==nullptr){
return false;
}
head=head->alp[int(word[i]-'a')];
}
if(head->isend){return true;}
return false;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
node* head=root;
for(int i=0; i<prefix.length(); i++){
if(head->alp[int(prefix[i]-'a')]==nullptr){
return false;
}
head=head->alp[int(prefix[i]-'a')];
}
return true;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
I had the same problem after upgrading to Ubuntu 14.10. I found this link which describes the steps to be followed in order to apply the patch. It takes a while since you have to start all over again: downloading, building, installing... but it worked for me! Sorry I'm not an expert and I can't provide further details.
Here are the steps described in the link above:
If you want to patch and build mysql-workbench yourself, get the source from for 6.2.3. From the directory you downloaded it to, do:
wget 'http://dev.mysql.com/get/Downloads/MySQLGUITools/mysql-workbench-community-6.2.3-src.tar.gz'
tar xvf mysql-workbench-community-6.2.3-src.tar.gz && cd mysql-workbench-community-6.2.3-src
wget -O patch-glib.diff 'http://bugs.mysql.com/file.php?id=21874&bug_id=74147'
patch -p0 < patch-glib.diff
sudo apt-get build-dep mysql-workbench
sudo apt-get install libgdal-dev
cd build
cmake .. -DBUILD_CONFIG=mysql_release
make
sudo make install
Hope this can be helpful.
You could achieve that simply by wrapping the image by a <div>
and adding overflow: hidden
to that element:
<div class="img-wrapper">
<img src="..." />
</div>
.img-wrapper {
display: inline-block; /* change the default display type to inline-block */
overflow: hidden; /* hide the overflow */
}
Also it's worth noting that <img>
element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px
gap at the bottom of the image.
That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align
property to the image with a value other than baseline
.
Additionally for a better user experience, you could add transition
to the images.
Thus we'll end up with the following:
.img-wrapper img {
transition: all .2s ease;
vertical-align: middle;
}
You might wanna use include method in JS.
var sentence = "This is my line";
console.log(sentence.includes("my"));
//returns true if substring is present.
PS: includes is case sensitive.
Loop over Application.Current.Windows[]
and find the one with IsActive == true
.
This is perhaps the best explanations on why to use lambda expressions -> https://youtu.be/j9nj5dTo54Q
In summary, it's to improve code readability, reduce chances of errors by reusing rather than replicating code, and leverage optimization happening behind the scenes.
Assuming there is a column named business:
SELECT Business, COUNT(*) FROM eventsTable GROUP BY Business
For HttpClient-4.1 using TLSv1.2, code would go something like this:
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, null, new SecureRandom());
SSLSocketFactory sf = new SSLSocketFactory(sslContext);
Scheme httpsScheme = new Scheme("https", 443, sf);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(httpsScheme);
ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
HttpClient client = new DefaultHttpClient(cm);
// Use client to make the connection and get the results.
I agree with Rup. I guess the main reason is to avoid confusion on relative paths. I think wordpress can work from scratch with relative paths but the problem might come when using multiple plugins, how the theme is configured etc.
I've once used this plugin for relative paths, when working on testing servers:
Root Relative URLs
Converts all URLs to root-relative URLs for hosting the same site on multiple IPs, easier production migration and better mobile device testing.
Here's an answer covering the more general question of calling another PS script from a PS script, as you may do if you were composing your scripts of many little, narrow-purpose scripts.
I found it was simply a case of using dot-sourcing. That is, you just do:
# This is Script-A.ps1
. ./Script-B.ps1 -SomeObject $variableFromScriptA -SomeOtherParam 1234;
I found all the Q/A very confusing and complicated and eventually landed upon the simple method above, which is really just like calling another script as if it was a function in the original script, which I seem to find more intuitive.
Dot-sourcing can "import" the other script in its entirety, using:
. ./Script-B.ps1
It's now as if the two files are merged.
Ultimately, what I was really missing is the notion that I should be building a module of reusable functions.
First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.
Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.
Here's how you should do it with all the suggestions above:
public enum States {
...
MASSACHUSETTS("Massachusetts", "MA", true),
MICHIGAN ("Michigan", "MI", false),
...; // all 50 of those
private final String full;
private final String abbr;
private final boolean originalColony;
private States(String full, String abbr, boolean originalColony) {
this.full = full;
this.abbr = abbr;
this.originalColony = originalColony;
}
public String getFullName() {
return full;
}
public String getAbbreviatedName() {
return abbr;
}
public boolean isOriginalColony(){
return originalColony;
}
}
I can suggest you a javascript oriented approach which makes it easy to work with javascript files in your project.
Create a javascript section in your jinja template file and place all variables you want to use in your javascript files in a window object:
Start.html
...
{% block scripts %}
<script type="text/javascript">
window.appConfig = {
debug: {% if env == 'development' %}true{% else %}false{% endif %},
facebook_app_id: {{ facebook_app_id }},
accountkit_api_version: '{{ accountkit_api_version }}',
csrf_token: '{{ csrf_token }}'
}
</script>
<script type="text/javascript" src="{{ url_for('static', filename='app.js') }}"></script>
{% endblock %}
Jinja will replace values and our appConfig object will be reachable from our other script files:
App.js
var AccountKit_OnInteractive = function(){
AccountKit.init({
appId: appConfig.facebook_app_id,
debug: appConfig.debug,
state: appConfig.csrf_token,
version: appConfig.accountkit_api_version
})
}
I have seperated javascript code from html documents with this way which is easier to manage and seo friendly.
JsonNode
is immutable and is intended for parse operation. However, it can be cast into ObjectNode
(and ArrayNode
) that allow mutations:
((ObjectNode)jsonNode).put("value", "NO");
For an array, you can use:
((ObjectNode)jsonNode).putArray("arrayName").add(object.ge??tValue());
Using just try_files
didn't work for me - it caused a rewrite or internal redirection cycle error in my logs.
The Nginx docs had some additional details:
http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files
So I ended up using the following:
root /var/www/mysite;
location / {
try_files $uri /base.html;
}
location = /base.html {
expires 30s;
}
If you want get output only when php fail:
php -r 'echo file_get_contents(http://www.example.com/cronit.php);'
This way you receive an email from cronjob only when the script fails and not whenever the php is called.
I received this exception unrelated to any TLS issues. In my case the Content-Length header value did not match the body length.
If your JSON is without key you can do it like this:
library[library.length] = {"foregrounds" : foregrounds,"backgrounds" : backgrounds};
So, try this:
var library = {[{
"title" : "Gold Rush",
"foregrounds" : ["Slide 1","Slide 2","Slide 3"],
"backgrounds" : ["1.jpg","","2.jpg"]
}, {
"title" : California",
"foregrounds" : ["Slide 1","Slide 2","Slide 3"],
"backgrounds" : ["3.jpg","4.jpg","5.jpg"]
}]
}
Then:
library[library.length] = {"title" : "Gold Rush", "foregrounds" : ["Howdy","Slide 2"], "backgrounds" : ["1.jpg",""]};
Your -vm argument seems ok BUT it's position is wrong. According to this Eclipse Wiki entry :
The -vm option must occur before the -vmargs option, since everything after -vmargs is passed directly to the JVM.
So your -vm argument is not taken into account and it fails over to your default java installation, which is probably 1.6.0_65.
I found an answer now. Thanks for your suggestions!
for e in ./*.cutoff.txt; do
if grep -q -E 'COX1|Cu-oxidase' $e
then
echo xyz >$e.match.txt
else
echo
fi
if grep -q -E 'AMO' $e
then
echo abc >$e.match.txt
else
echo
fi; done
Any comments on that? It seems inefficient to grep twice, but it works...
setTimeout(function(){
},5000);
Place your code inside of the { }
300 = 0.3 seconds
700 = 0.7 seconds
1000 = 1 second
2000= 2 seconds
2200 = 2.2 seconds
3500 = 3.5 seconds
10000 = 10 seconds
etc.
I know this answer has already been accepted, but I thought I'd throw my 2cents in. I like to use the tomb package. It's basically a suped up quit channel, but it does nice things like pass back any errors as well. The routine under control still has the responsibility of checking for remote kill signals. Afaik it's not possible to get an "id" of a goroutine and kill it if it's misbehaving (ie: stuck in an infinite loop).
Here's a simple example which I tested:
package main
import (
"launchpad.net/tomb"
"time"
"fmt"
)
type Proc struct {
Tomb tomb.Tomb
}
func (proc *Proc) Exec() {
defer proc.Tomb.Done() // Must call only once
for {
select {
case <-proc.Tomb.Dying():
return
default:
time.Sleep(300 * time.Millisecond)
fmt.Println("Loop the loop")
}
}
}
func main() {
proc := &Proc{}
go proc.Exec()
time.Sleep(1 * time.Second)
proc.Tomb.Kill(fmt.Errorf("Death from above"))
err := proc.Tomb.Wait() // Will return the error that killed the proc
fmt.Println(err)
}
The output should look like:
# Loop the loop
# Loop the loop
# Loop the loop
# Loop the loop
# Death from above
All answers are OK, depending on how academic you want to be. If you wish to follow the Java specifications accurately, use the following:
private static final Pattern DOUBLE_PATTERN = Pattern.compile(
"[\\x00-\\x20]*[+-]?(NaN|Infinity|((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)" +
"([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|" +
"(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))" +
"[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*");
public static boolean isFloat(String s)
{
return DOUBLE_PATTERN.matcher(s).matches();
}
This code is based on the JavaDocs at Double.
The extended configuration section in a previous response with
...
...
<rollingStyle value="Composite" />
...
...
listed works but I did not have to use
<staticLogFileName value="false" />
. I think the RollingAppender must (logically) ignore that setting since by definition the file gets rebuilt each day when the application restarts/reused. Perhaps it does matter for immediate rollover EVERY time the application starts.
If the database link option is not available, another route you could take is to link the tables via ODBC to something such as MS Access or Crystal reports and do the join there.
It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return
statement. When the code goes down that path, the function ends with no value returned, and so returns None
.
Updated: It sounds like your code looks like this:
def b(self, p, data):
current = p
if current.data == data:
return True
elif current.data == 1:
return False
else:
self.b(current.next, data)
That else clause is your None
path. You need to return the value that the recursive call returns:
else:
return self.b(current.next, data)
BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.
One way to do it (may not be the best) is to create another array with the new elements and do column_stack. i.e.
>>>a = array([[1,3,4],[1,2,3]...[1,2,1]])
[[1 3 4]
[1 2 3]
[1 2 1]]
>>>b = array([1,2,3])
>>>column_stack((a,b))
array([[1, 3, 4, 1],
[1, 2, 3, 2],
[1, 2, 1, 3]])
=VLOOKUP(lookup_value,table_array,col_index_num,range_lookup)
will solve this issue.
This will search for a value in the first column to the left and return the value in the same row from a specific column.
For other circumstances in which you want the number string to be consistent, I made a function.
Someone may find this useful:
idnamer<-function(x,y){#Alphabetical designation and number of integers required
id<-c(1:y)
for (i in 1:length(id)){
if(nchar(id[i])<2){
id[i]<-paste("0",id[i],sep="")
}
}
id<-paste(x,id,sep="")
return(id)
}
idnamer("EF",28)
Sorry about the formatting.
There are 2 differences, unlike r+
, w+
will:
//This Works just fine
DateTime dt = new DateTime();
Log.d("ts",String.valueOf(dt.now()));
dt=dt.plusYears(3);
dt=dt.minusDays(7);
Log.d("JODA DateTime",String.valueOf(dt));
Timestamp ts= new Timestamp(dt.getMillis());
Log.d("Coverted to java.sql.Timestamp",String.valueOf(ts));
I finally solved this myself. If anyone else is having this problem, here is my solution:
I created a new method:
public function curl_del($path)
{
$url = $this->__url.$path;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $result;
}
Update 2
Since this seems to help some people, here is my final curl DELETE method, which returns the HTTP response in JSON decoded object:
/**
* @desc Do a DELETE request with cURL
*
* @param string $path path that goes after the URL fx. "/user/login"
* @param array $json If you need to send some json with your request.
* For me delete requests are always blank
* @return Obj $result HTTP response from REST interface in JSON decoded.
*/
public function curl_del($path, $json = '')
{
$url = $this->__url.$path;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$result = json_decode($result);
curl_close($ch);
return $result;
}
The differences between a class
and a struct
in C++ is:
struct
members and base classes/structs are public
by default.class
members and base classes/struts are private
by default.Both classes and structs can have a mixture of public
, protected
and private
members, can use inheritance and can have member functions.
I would recommend you:
struct
for plain-old-data structures without any class-like features;class
when you make use of features such as private
or protected
members, non-default constructors and operators, etc.You can also use math combination "-=" to move background
$(this).animate( {backgroundPositionX: "-=20px"} ,500);
I think you have created your test classes outside the src folder. You can solve above problem by two way:
Add your package name in java build path->source
Move your package/class
in src
folder
I have the same problem and solved in this way both solutions working fine.
Place this dependency, and dont forget to select : Include dependencies with "provided" scope
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
Use the S3FileSystem.rm
function in s3fs
.
You can delete a single file or several at once:
import s3fs
file_system = s3fs.S3FileSystem()
file_system.rm('s3://my-bucket/foo.txt') # single file
files = ['s3://my-bucket/bar.txt', 's3://my-bucket/baz.txt']
file_system.rm(files) # several files
You might also consider using Amazon S3 Lifecycle to create an expiration for files with the prefix foo/bar1
.
Open the S3 browser console and click a bucket. Then click Properties and then LifeCycle.
Create an expiration rule for all files with the prefix foo/bar1
and set the date to 1 day since file was created.
Save and all matching files will be gone within 24 hours.
Just don't forget to remove the rule after you're done!
No API calls, no third party libraries, apps or scripts.
I just deleted several million files this way.
A screenshot showing the Lifecycle Rule window (note in this shot the Prefix has been left blank, affecting all keys in the bucket):
1)Right Click On drawable directory then go to new then go to vector assets 2)change asset type from clip art to local 3)browse your file 4)give size 5)then click next then done Your usable svg will be generated in drawable directory
open android sdk->click on tools tab->about and u get the entire details!
Select ID, IsNull(Cast(ParentID as varchar(max)),'') from Patients
This is needed because field ParentID is not varchar/nvarchar type. This will do the trick:
Select ID, IsNull(ParentID,'') from Patients
This is my Save Attachments script. You select all the messages that you want the attachments saved from, and it will save a copy there. It also adds text to the message body indicating where the attachment is saved. You could easily change the folder name to include the date, but you would need to make sure the folder existed before starting to save files.
Public Sub SaveAttachments()
Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem 'Object
Dim objAttachments As Outlook.Attachments
Dim objSelection As Outlook.Selection
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strDeletedFiles As String
' Get the path to your My Documents folder
strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
On Error Resume Next
' Instantiate an Outlook Application object.
Set objOL = CreateObject("Outlook.Application")
' Get the collection of selected objects.
Set objSelection = objOL.ActiveExplorer.Selection
' Set the Attachment folder.
strFolderpath = strFolderpath & "\Attachments\"
' Check each selected item for attachments. If attachments exist,
' save them to the strFolderPath folder and strip them from the item.
For Each objMsg In objSelection
' This code only strips attachments from mail items.
' If objMsg.class=olMail Then
' Get the Attachments collection of the item.
Set objAttachments = objMsg.Attachments
lngCount = objAttachments.Count
strDeletedFiles = ""
If lngCount > 0 Then
' We need to use a count down loop for removing items
' from a collection. Otherwise, the loop counter gets
' confused and only every other item is removed.
For i = lngCount To 1 Step -1
' Save attachment before deleting from item.
' Get the file name.
strFile = objAttachments.Item(i).FileName
' Combine with the path to the Temp folder.
strFile = strFolderpath & strFile
' Save the attachment as a file.
objAttachments.Item(i).SaveAsFile strFile
' Delete the attachment.
objAttachments.Item(i).Delete
'write the save as path to a string to add to the message
'check for html and use html tags in link
If objMsg.BodyFormat <> olFormatHTML Then
strDeletedFiles = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
Else
strDeletedFiles = strDeletedFiles & "<br>" & "<a href='file://" & _
strFile & "'>" & strFile & "</a>"
End If
'Use the MsgBox command to troubleshoot. Remove it from the final code.
'MsgBox strDeletedFiles
Next i
' Adds the filename string to the message body and save it
' Check for HTML body
If objMsg.BodyFormat <> olFormatHTML Then
objMsg.Body = vbCrLf & "The file(s) were saved to " & strDeletedFiles & vbCrLf & objMsg.Body
Else
objMsg.HTMLBody = "<p>" & "The file(s) were saved to " & strDeletedFiles & "</p>" & objMsg.HTMLBody
End If
objMsg.Save
End If
Next
ExitSub:
Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub
I have tried so many approches! the only useful thing is:
if var topController = UIApplication.shared.keyWindow?.rootViewController
{
while (topController.presentedViewController != nil)
{
topController = topController.presentedViewController!
}
}
Best practice: one form per product is definitely the way to go.
Benefits:
In your specific situation
If you only ever intend to have one form element, in this case a submit
button, one form for all should work just fine.
My recommendation Do one form per product, and change your markup to something like:
<form method="post" action="">
<input type="hidden" name="product_id" value="123">
<button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>
This will give you a much cleaner and usable POST
. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).
Note: There's no technical benefit to using
<button>
vs.<input>
, but as a programmer I find it cooler to work withaction=='add_to_cart'
thanaction=='Add to Cart'
. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.
If a GPU device has, for example, 4 multiprocessing units, and they can run 768 threads each: then at a given moment no more than 4*768 threads will be really running in parallel (if you planned more threads, they will be waiting their turn).
threads are organized in blocks. A block is executed by a multiprocessing unit. The threads of a block can be indentified (indexed) using 1Dimension(x), 2Dimensions (x,y) or 3Dim indexes (x,y,z) but in any case xyz <= 768 for our example (other restrictions apply to x,y,z, see the guide and your device capability).
Obviously, if you need more than those 4*768 threads you need more than 4 blocks. Blocks may be also indexed 1D, 2D or 3D. There is a queue of blocks waiting to enter the GPU (because, in our example, the GPU has 4 multiprocessors and only 4 blocks are being executed simultaneously).
Suppose we want one thread to process one pixel (i,j).
We can use blocks of 64 threads each. Then we need 512*512/64 = 4096 blocks (so to have 512x512 threads = 4096*64)
It's common to organize (to make indexing the image easier) the threads in 2D blocks having blockDim = 8 x 8 (the 64 threads per block). I prefer to call it threadsPerBlock.
dim3 threadsPerBlock(8, 8); // 64 threads
and 2D gridDim = 64 x 64 blocks (the 4096 blocks needed). I prefer to call it numBlocks.
dim3 numBlocks(imageWidth/threadsPerBlock.x, /* for instance 512/8 = 64*/
imageHeight/threadsPerBlock.y);
The kernel is launched like this:
myKernel <<<numBlocks,threadsPerBlock>>>( /* params for the kernel function */ );
Finally: there will be something like "a queue of 4096 blocks", where a block is waiting to be assigned one of the multiprocessors of the GPU to get its 64 threads executed.
In the kernel the pixel (i,j) to be processed by a thread is calculated this way:
uint i = (blockIdx.x * blockDim.x) + threadIdx.x;
uint j = (blockIdx.y * blockDim.y) + threadIdx.y;
Single-source Python 2/3 compatible version based on @pts' answer:
#!/usr/bin/env python
import binascii
def int2bytes(i):
hex_string = '%x' % i
n = len(hex_string)
return binascii.unhexlify(hex_string.zfill(n + (n & 1)))
print(int2bytes(1245427))
# -> b'\x13\x00\xf3'
One quick & dirty solution:
// makes a number from two ascii hexa characters
int ahex2int(char a, char b){
a = (a <= '9') ? a - '0' : (a & 0x7) + 9;
b = (b <= '9') ? b - '0' : (b & 0x7) + 9;
return (a << 4) + b;
}
You have to be sure your input is correct, no validation included (one could say it is C). Good thing it is quite compact, it works with both 'A' to 'F' and 'a' to 'f'.
The approach relies on the position of alphabet characters in the ASCII table, let's peek e.g. to Wikipedia (https://en.wikipedia.org/wiki/ASCII#/media/File:USASCII_code_chart.png). Long story short, the numbers are below the characters, so the numeric characters (0 to 9) are easily converted by subtracting the code for zero. The alphabetic characters (A to F) are read by zeroing other than last three bits (effectively making it work with either upper- or lowercase), subtracting one (because after the bit masking, the alphabet starts on position one) and adding ten (because A to F represent 10th to 15th value in hexadecimal code). Finally, we need to combine the two digits that form the lower and upper nibble of the encoded number.
Here we go with same approach (with minor variations):
#include <stdio.h>
// takes a null-terminated string of hexa characters and tries to
// convert it to numbers
long ahex2num(unsigned char *in){
unsigned char *pin = in; // lets use pointer to loop through the string
long out = 0; // here we accumulate the result
while(*pin != 0){
out <<= 4; // we have one more input character, so
// we shift the accumulated interim-result one order up
out += (*pin < 'A') ? *pin & 0xF : (*pin & 0x7) + 9; // add the new nibble
pin++; // go ahead
}
return out;
}
// main function will test our conversion fn
int main(void) {
unsigned char str[] = "1800785"; // no 0x prefix, please
long num;
num = ahex2num(str); // call the function
printf("Input: %s\n",str); // print input string
printf("Output: %x\n",num); // print the converted number back as hexa
printf("Check: %ld = %ld \n",num,0x1800785); // check the numeric values matches
return 0;
}
GET parameters are cached by the web browser, POST is not. So with a POST you don't have to worry about caching, so that is why it is usually prefered.
If you happen to use LuaSocket in your project, or just have it installed and don't mind to use it, you can use the socket.sleep(time)
function which sleeps for a given amount of time (in seconds).
This works both on Windows and Unix, and you do not have to compile additional modules.
I should add that the function supports fractional seconds as a parameter, i.e. socket.sleep(0.5)
will sleep half a second. It uses Sleep()
on Windows and nanosleep()
elsewhere, so you may have issues with Windows accuracy when time
gets too low.
Simply \newpage
or \pagebreak
will work, e.g.
hello world
\newpage
```{r, echo=FALSE}
1+1
```
\pagebreak
```{r, echo=FALSE}
plot(1:10)
```
This solution assumes you are knitting PDF. For HTML, you can achieve a similar effect by adding a tag <P style="page-break-before: always">
. Note that you likely won't see a page break in your browser (HTMLs don't have pages per se), but the printing layout will have it.
FrostWire Team over here.
All the selector crap api doesn't work as expected. After trying all the solutions presented in this thread to no good, we just solved the problem at the moment of inflating the ListView Item.
Make sure your item keeps it's state, we did it as a member variable of the MenuItem (boolean selected)
When you inflate, ask if the underlying item is selected, if so, just set the drawable resource that you want as the background (be it a 9patch or whatever). Make sure your adapter is aware of this and that it calls notifyDataChanged() when something has been selected.
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = act.getLayoutInflater();
rowView = inflater.inflate(R.layout.slidemenu_listitem, null);
MenuItemHolder viewHolder = new MenuItemHolder();
viewHolder.label = (TextView) rowView.findViewById(R.id.slidemenu_item_label);
viewHolder.icon = (ImageView) rowView.findViewById(R.id.slidemenu_item_icon);
rowView.setTag(viewHolder);
}
MenuItemHolder holder = (MenuItemHolder) rowView.getTag();
String s = items[position].label;
holder.label.setText(s);
holder.icon.setImageDrawable(items[position].icon);
//Here comes the magic
rowView.setSelected(items[position].selected);
rowView.setBackgroundResource((rowView.isSelected()) ? R.drawable.slidemenu_item_background_selected : R.drawable.slidemenu_item_background);
return rowView;
}
It'd be really nice if the selectors would actually work, in theory it's a nice and elegant solution, but it seems like it's broken. KISS.
you could also use rsync. It seems to work better for multiple files than scp IMHO.
rsync -avzh /path/to/dir/ user@remote:/path/to/remote/dir/
Update
You can use rsync via ssh by adding the '-e' switch:
rsync -avzh -e ssh /path/do/dir/ user@remote:/path/to/remote/dir/
Pass an array to the function, instead of individual parameters and use null coalescing operator (PHP 7+).
Below, I'm passing an array with 2 items. Inside the function, I'm checking if value for item1 is set, if not assigned default vault.
$args = ['item2' => 'item2',
'item3' => 'value3'];
function function_name ($args) {
isset($args['item1']) ? $args['item1'] : 'default value';
}
Remove your script, and change the HTML:
<a id="closemodal" href="https://www.google.com" class="btn btn-primary close" data-dismiss="modal" target="_blank">Launch google.com</a>
EDIT: Please note that currently this will not work as this functionality does not yet exist in bootstrap. See issue here.
Try not to go
MAMP > conf > [your PHP version] > php.ini
but
MAMP > bin > php > [your PHP version] > conf > php.ini
and change it there, it worked for me...
Project > Generate Javadoc....
In the Javadoc command: field, browse to find javadoc.exe (usually at [path_to_jdk_directory]\bin\javadoc.exe).
Check the box next to the project/package/file for which you are creating the Javadoc.
In the Destination: field, browse to find the desired destination (for example, the root directory of the current project).
Click Finish.
You should now be able to find the newly generated Javadoc in the destination folder. Open index.html.
This is how I do it in TypeScript:
const index = this.array.indexOf(this.objectToReplace);
this.array[index] = newObject;
While working in a big project which has complex build system and where it is hard to get (or modify) the gcc/g++ command directly there is another way to see the result of macro expansion. Simply redefine the macro, and you will get output similiar to following:
file.h: note: this is the location of the previous definition
#define MACRO current_value
The plus sign is the historic encoding for a space character in URL parameters, as documented in the help for the urlencode()
function.
That same page contains the answer you need - use rawurlencode()
instead to get RFC 3986 compatible encoding.
Redirection/Piping the output of the file to wc -l
should suffice, like the following:
cat /etc/fstab | wc -l
which then would provide the no. of lines only.
How about:
public static T Min<T>(params T[] values)
{
if (values == null) throw new ArgumentNullException("values");
var comparer = Comparer<T>.Default;
switch(values.Length) {
case 0: throw new ArgumentException();
case 1: return values[0];
case 2: return comparer.Compare(values[0],values[1]) < 0
? values[0] : values[1];
default:
T best = values[0];
for (int i = 1; i < values.Length; i++)
{
if (comparer.Compare(values[i], best) < 0)
{
best = values[i];
}
}
return best;
}
}
// overload for the common "2" case...
public static T Min<T>(T x, T y)
{
return Comparer<T>.Default.Compare(x, y) < 0 ? x : y;
}
Works with any type that supports IComparable<T>
or IComparable
.
Actually, with LINQ, another alternative is:
var min = new[] {x,y,z}.Min();
In some environments, NSLog() will be unresponsive. But there are other ways to get output...
NSString* url = @"someurlstring";
printf("%s", [url UTF8String]);
By using printf
with the appropriate parameters, we can display things this way. This is the only way I have found to work on online Objective-C sandbox environments.
In my case after running IE as an administrator, i had to add the url of the report manager to the Local Internet Zones in Internet Explorer, not Trusted Sites.
The following will produce, in the output directory,
But it does not contain all .NET Core runtime assemblies.
<PropertyGroup>
<Temp>$(SolutionDir)\packaging\</Temp>
</PropertyGroup>
<ItemGroup>
<BootStrapFiles Include="$(Temp)hostpolicy.dll;$(Temp)$(ProjectName).exe;$(Temp)hostfxr.dll;"/>
</ItemGroup>
<Target Name="GenerateNetcoreExe"
AfterTargets="Build"
Condition="'$(IsNestedBuild)' != 'true'">
<RemoveDir Directories="$(Temp)" />
<Exec
ConsoleToMSBuild="true"
Command="dotnet build $(ProjectPath) -r win-x64 /p:CopyLocalLockFileAssemblies=false;IsNestedBuild=true --output $(Temp)" >
<Output TaskParameter="ConsoleOutput" PropertyName="OutputOfExec" />
</Exec>
<Copy
SourceFiles="@(BootStrapFiles)"
DestinationFolder="$(OutputPath)"
/>
</Target>
I wrapped it up in a sample here: https://github.com/SimonCropp/NetCoreConsole
Doing Project
-> Clean...
fixed it for me.
My eclipse had stopped working so I cleaned workspace
directory and after I run eclipse when I import the project I had this problem. Other solutions suggested here didn't work.
One option would be to put all the code in the loop inside a Sub
and then just return from that Sub
when you want to "continue".
Not perfect, but I think it would be less confusing that the extra loop.
This is how I usually get current logged in user and their id in my templates.
<p>Your Username is : {{user|default: Unknown}} </p>
<p>Your User Id is : {{user.id|default: Unknown}} </p>
Because at least one value is a string the + operator is being interpreted as a string concatenation operator. The simplest fix for this is to indicate that you intend for the values to be interpreted as numbers.
var total = +a + +b;
and
$('#total_price').val(+a + +b);
Or, better, just pull them out as numbers to begin with:
var a = +$('input[name=service_price]').val();
var b = +$('input[name=modem_price]').val();
var total = a+b;
$('#total_price').val(a+b);
See Mozilla's Unary + documentation.
Note that this is only a good idea if you know the value is going to be a number anyway. If this is user input you must be more careful and probably want to use parseInt
and other validation as other answers suggest.
If anyone is looking for a simple solution in Laravel 5.3:
timestamps()
be saved as is i.e. '2016-11-14 12:19:49'In your views, format the field as below (or as required):
date('F d, Y', strtotime($list->created_at))
It worked for me very well for me.
@S-Lott gives the right procedure, but expanding on the Unicode issues, the Python interpreter can provide more insights.
Jon Skeet is right (unusual) about the codecs
module - it contains byte strings:
>>> import codecs
>>> codecs.BOM
'\xff\xfe'
>>> codecs.BOM_UTF8
'\xef\xbb\xbf'
>>>
Picking another nit, the BOM
has a standard Unicode name, and it can be entered as:
>>> bom= u"\N{ZERO WIDTH NO-BREAK SPACE}"
>>> bom
u'\ufeff'
It is also accessible via unicodedata
:
>>> import unicodedata
>>> unicodedata.lookup('ZERO WIDTH NO-BREAK SPACE')
u'\ufeff'
>>>
I saw this error when I wanted to edit a page usnig ASP.Net MVC. I had no problem while Creating but Updating Database made my DateCreated property out of range!
When you don't want your DateTime
Property be Nullable and do not want to check if its value is in the sql DateTime range (and @Html.HiddenFor
doesn't help!), simply add a static DateTime
field inside related class (Controller) and give it the value when GET is operating then use it when POST is doing it's job:
public class PagesController : Controller
{
static DateTime dateTimeField;
UnitOfWork db = new UnitOfWork();
// GET:
public ActionResult Edit(int? id)
{
Page page = db.pageRepository.GetById(id);
dateTimeField = page.DateCreated;
return View(page);
}
// POST:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Page page)
{
page.DateCreated = dateTimeField;
db.pageRepository.Update(page);
db.Save();
return RedirectToAction("Index");
}
}
if your interested you can also create string extension methods like so:
public static int Search(this string yourString, string yourMarker, int yourInst = 1, bool caseSensitive = true)
{
//returns the placement of a string in another string
int num = 0;
int currentInst = 0;
//if optional argument, case sensitive is false convert string and marker to lowercase
if (!caseSensitive) { yourString = yourString.ToLower(); yourMarker = yourMarker.ToLower(); }
int myReturnValue = -1; //if nothing is found the returned integer is negative 1
while ((num + yourMarker.Length) <= yourString.Length)
{
string testString = yourString.Substring(num, yourMarker.Length);
if (testString == yourMarker)
{
currentInst++;
if (currentInst == yourInst)
{
myReturnValue = num;
break;
}
}
num++;
}
return myReturnValue;
}
public static int Search(this string yourString, char yourMarker, int yourInst = 1, bool caseSensitive = true)
{
//returns the placement of a string in another string
int num = 0;
int currentInst = 0;
var charArray = yourString.ToArray<char>();
int myReturnValue = -1;
if (!caseSensitive)
{
yourString = yourString.ToLower();
yourMarker = Char.ToLower(yourMarker);
}
while (num <= charArray.Length)
{
if (charArray[num] == yourMarker)
{
currentInst++;
if (currentInst == yourInst)
{
myReturnValue = num;
break;
}
}
num++;
}
return myReturnValue;
}
This will do it:
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': my_url,
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
The main issue being that $.getJSON
will run asynchronously, thus your Javascript will progress past the expression which invokes it even before its success
callback fires, so there are no guarantees that your variable will capture any data.
Note in particular the 'async': false
option in the above ajax call. The manual says:
By default, all requests are sent asynchronous (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
Try:
123-(?:(apple|banana|)-|)456
That will match apple
, banana
, or a blank string, and following it there will be a 0 or 1 hyphens. I was wrong about not having a need for a capturing group. Silly me.
I would try:
self.wordList = list(wordList)
to force it to make a copy instead of referencing the same object.
JQuery and PHP
In PHP file "contenido.php":
<?php
$mURL = $_GET['url'];
echo file_get_contents($mURL);
?>
In html:
<script type="text/javascript" src="js/jquery/jquery.min.js"></script>
<script type="text/javascript">
function getContent(pUrl, pDivDestino){
var mDivDestino = $('#'+pDivDestino);
$.ajax({
type : 'GET',
url : 'contenido.php',
dataType : 'html',
data: {
url : pUrl
},
success : function(data){
mDivDestino.html(data);
}
});
}
</script>
<a href="#" onclick="javascript:getContent('http://www.google.com/', 'contenido')">Get Google</a>
<div id="contenido"></div>
I figured out what it was! When I cleared the fields using the each() method, it also cleared the hidden field which the php needed to run:
if ($_POST['action'] == 'addRunner')
I used the :not() on the selection to stop it from clearing the hidden field.
==
is the correct operator to compare strings in Go. However, the strings that you read from STDIN with reader.ReadString
do not contain "a"
, but "a\n"
(if you look closely, you'll see the extra line break in your example output).
You can use the strings.TrimRight
function to remove trailing whitespaces from your input:
if strings.TrimRight(input, "\n") == "a" {
// ...
}
LEXEME - Sequence of characters matched by PATTERN forming the TOKEN
PATTERN - The set of rule that define a TOKEN
TOKEN - The meaningful collection of characters over the character set of the programming language ex:ID, Constant, Keywords, Operators, Punctuation, Literal String
I found it on this page: http://eslint.org/docs/user-guide/configuring
In package.json, this works:
"eslintConfig": {
"globals": {
"window": true
}
}
This will work in all browsers
#circle {
background: #f00;
width: 200px;
height: 200px;
border-radius: 50%;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
}
I had same problem with UnicodeDecodeError
and i solved it with this line.
Don't know if is the best way but it worked for me.
str = str.decode('unicode_escape').encode('utf-8')
As scoota269 says, you should use onSubmit
instead, cause pressing enter on a textbox will most likey trigger a form submit (if inside a form)
<form action="#" onsubmit="handle">
<input type="text" name="txt" />
</form>
<script>
function handle(e){
e.preventDefault(); // Otherwise the form will be submitted
alert("FORM WAS SUBMITTED");
}
</script>
If you want to have an event on the input-field then you need to make sure your handle()
will return false, otherwise the form will get submitted.
<form action="#">
<input type="text" name="txt" onkeypress="handle(event)" />
</form>
<script>
function handle(e){
if(e.keyCode === 13){
e.preventDefault(); // Ensure it is only this code that runs
alert("Enter was pressed was presses");
}
}
</script>
Get focused child, and use it to get position in adapter.
mRecyclerView.getChildAdapterPosition(mRecyclerView.getFocusedChild())
Try following command;
ALTER TABLE Person11
ADD CONSTRAINT col_1_def
DEFAULT 'This is not NULL' FOR Address
// TypeScript
const today = new Date();
const firstDayOfYear = new Date(today.getFullYear(), 0, 1);
// Explicitly convert Date to Number
const pastDaysOfYear = ( Number(today) - Number(firstDayOfYear) );
Consider the following example,
import import { AfterViewInit, ViewChild } from '@angular/core';
import { Component } from '@angular/core';
import { CountdownTimerComponent } from './countdown-timer.component';
@Component({
selector: 'app-countdown-parent-vc',
templateUrl: 'app-countdown-parent-vc.html',
styleUrl: [app-countdown-parent-vc.css]
export class CreateCategoryComponent implements OnInit {
@ViewChild(CountdownTimerComponent, {static: false})
private timerComponent: CountdownTimerComponent;
ngAfterViewInit() {
this.timerComponent.startTimer();
}
submitNewCategory(){
this.ngAfterViewInit();
}
Read more about @ViewChild here.
SETUSER could work, having a user, even an orphaned user in the DB with the default schema needed. But SETUSER is on the legacy not supported for ever list. So a similar alternative would be to setup an application role with the needed default schema, as long as no cross DB access is needed, this should work like a treat.
I found the problem to this... due to a incorrect/failed reference in .rdl to data conns etc. Also found that BIDS wasn't happy about having spaces in some of the project/report filenames... so anyone facing this issue make sure you have no spaces in your naming and check your rdl files, connections, everything for failed/out of date references! Visual Studio seems crap at keeping all of it's references up to date... god forbid you have to rename anything!
The <hr>
should be placed inside a <div>
for proper functioning.
Place it like this to get desired width `
<div class='row'>
<div class='col-lg-8 col-lg-offset-2'>
<hr>
</div>
</div>
`
Hope this helps a future reader!
Coming from the Mozilla Documentation, "You can use the delete operator to delete variables declared implicitly but not those declared with the var statement. "
Here is the link: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Operators:Special_Operators:delete_Operator
As previously stated check for and use built in timer. But if you want or need to write your own here is my two cents:
//=-=|Source|=-=//
/**
* JavaScript Timer Object
*
* var now=timer['elapsed']();
* timer['stop']();
* timer['start']();
* timer['reset']();
*
* @expose
* @method timer
* @return {number}
*/
timer=function(){
var a=Date.now();
b=0;
return{
/** @expose */
elapsed:function(){return b=Date.now()-a},
start:function(){return a=Date.now()},
stop:function(){return Date.now()},
reset:function(){return a=0}
}
}();
//=-=|Google Advanced Optimized|=-=//
timer=function(){var a=Date.now();b=0;return{a:function(){return b=Date.now()-a},start:function(){return a=Date.now()},stop:function(){return Date.now()},reset:function(){return a=0}}}();
It is the directory from where you run the command to execute your batch file.
As mentioned in the above answers you can add the below command to your script to verify:
> set current_dir=%cd%
> echo %current_dir%
You can't put a div
directly inside a table
, like this:
<!-- INVALID -->
<table>
<div>
Hello World
</div>
</table>
Putting a div
inside a td
or th
element is fine, however:
<!-- VALID -->
<table>
<tr>
<td>
<div>
Hello World
</div>
</td>
</tr>
</table>
If you are talking about the issue where multiple and non-space whitespace characters are stripped specifically from attribute values, then yes, encoding them as character references such as 	 will fix it.
try this:
$('form').submit(function(){
// this function will be raised when submit button is clicked.
// perform submit operations here
});
I was having the same exception with node v12.13.1,
Downgraded node to v10.15.3 and it works fine now.
The @Transactional
annotation takes a timeout parameter where you can specify timeout in seconds for a specific method in the @RestController
@RequestMapping(value = "/method",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@Transactional(timeout = 120)
/*This code will use gridview sum inside data list*/
SumOFdata(grd_DataDetail);
private void SumOFEPFWages(GridView grd)
{
Label lbl_TotAmt = (Label)grd.FooterRow.FindControl("lblTotGrossW");
/*Sum of the total Amount of the day*/
foreach (GridViewRow gvr in grd.Rows)
{
Label lbl_Amount = (Label)gvr.FindControl("lblGrossS");
lbl_TotAmt.Text = (Convert.ToDouble(lbl_Amount.Text) + Convert.ToDouble(lbl_TotAmt.Text)).ToString();
}
}
Here's an updated version with Kotlin I used assuming phone is higher than Honeycomb:
val actionBarHeight = with(TypedValue().also {context.theme.resolveAttribute(android.R.attr.actionBarSize, it, true)}) {
TypedValue.complexToDimensionPixelSize(this.data, resources.displayMetrics)
}
public table2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 485, 218);
setTitle("jtable");
getContentPane().setLayout(null);
String data[][] = { { "Row1/1", "Row1/2", "Row1/3" },
{ "Row2/1", "Row2/2", "Row2/3" },
{ "Row3/1", "Row3/2", "Row3/3" },
{ "Row4/1", "Row4/2", "Row4/3" }, };
String header[] = { "Column 1", "Column 2", "Column 3" };
// Table
JTable table = new JTable(data,header);
// ScrollPane
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(36, 37, 407, 79);
getContentPane().add(scrollPane);
}
}
try this!!
You can use String.Replace which basically removes all occurrences
line.Replace(@"\", "");
The (A==B).all()
solution is very neat, but there are some built-in functions for this task. Namely array_equal
, allclose
and array_equiv
.
(Although, some quick testing with timeit
seems to indicate that the (A==B).all()
method is the fastest, which is a little peculiar, given it has to allocate a whole new array.)
Trying to do the same thing. If you want it to be aligned on the right side then set the value of right
to 0
. In case you need some padding from the right, set the value to the size of the padding you need.
Example:
.test {
position: fixed;
right: 20px; /* Padding from the right side */
}
A way to do this without Linq & Lambdas
string source = "a,b, b, c";
string[] items = source.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
After trying all of these answers, to no avail, I managed to get it up by first running the device from Vbox, leaving it open, and then running the device from Genymotion... In my case this was the ONLY way after trying several different devices (Samsung S4/S6 etc), network/DHCP settings and modes and so on...
The PDB file is a Visual Studio specific file that has the debugging symbols for your project. You can ignore those messages, unless you're hoping to step into the code for those dlls with the debugger (which is doubtful, as those are system dlls). In other words, you can and should ignore them, as you won't have the PDB files for any of those dlls (by default at least, it turns out you can actually obtain them when debugging via the Microsoft Symbol Server). All it means is that when you set a breakpoint and are stepping through the code, you won't be able to step into any of those dlls (which you wouldn't want to do anyways).
Just for completeness, here's the official PDB description from MSDN:
A program database (PDB) file holds debugging and project state information that allows incremental linking of a Debug configuration of your program. A PDB file is created when you compile a C/C++ program with /ZI or /Zi
Also for future reference, if you want to have PDB files for your own code, you would would have to build your project with either the /ZI or /Zi options enabled (you can set them via project properties --> C/C++ --> General, then set the field for "Debug Information Format"). Not relevant to your situation, but I figured it might be useful in the future
That's what I came to:
function uncheck_radio_before_click(radio) {
if(radio.prop('checked'))
radio.one('click', function(){ radio.prop('checked', false); } );
}
$('body').on('mouseup', 'input[type="radio"]', function(){
var radio=$(this);
uncheck_radio_before_click(radio);
})
$('body').on('mouseup', 'label', function(){
var label=$(this);
var radio;
if(label.attr('for'))
radio=$('#'+label.attr('for')).filter('input[type="radio"]');
else
radio=label.children('input[type="radio"]');
if(radio.length)
uncheck_radio_before_click(radio);
})
try with this simple line... add this line in your xml code in image view tag with out adding any dependency android:scaleType="fitXY"
Here's a function that will return the content of any meta tag and will memoize the result, avoiding unnecessary querying of the DOM.
var getMetaContent = (function(){
var metas = {};
var metaGetter = function(metaName){
var theMetaContent, wasDOMQueried = true;;
if (metas[metaName]) {
theMetaContent = metas[metaName];
wasDOMQueried = false;
}
else {
Array.prototype.forEach.call(document.getElementsByTagName("meta"), function(el) {
if (el.name === metaName) theMetaContent = el.content;
metas[metaName] = theMetaContent;
});
}
console.log("Q:wasDOMQueried? A:" + wasDOMQueried);
return theMetaContent;
}
return metaGetter;
})();
getMetaContent("description"); /* getMetaContent console.logs the content of the description metatag. If invoked a second time it confirms that the DOM was only queried once */
And here's an extended version that also queries for open graph tags, and uses Array#some:
var getMetaContent = (function(){
var metas = {};
var metaGetter = function(metaName){
wasDOMQueried = true;
if (metas[metaName]) {
wasDOMQueried = false;
}
else {
Array.prototype.some.call(document.getElementsByTagName("meta"), function(el) {
if(el.name === metaName){
metas[metaName] = el.content;
return true;
}
if(el.getAttribute("property") === metaName){
metas[metaName] = el.content;
return true;
}
else{
metas[metaName] = "meta tag not found";
}
});
}
console.info("Q:wasDOMQueried? A:" + wasDOMQueried);
console.info(metas);
return metas[metaName];
}
return metaGetter;
})();
getMetaContent("video"); // "http://video.com/video33353.mp4"
Be aware that np.array_split(df, 3)
splits the dataframe into 3 sub-dataframes, while the split_dataframe
function defined in @elixir's answer, when called as split_dataframe(df, chunk_size=3)
, splits the dataframe every chunk_size
rows.
Example:
With np.array_split
:
df = pd.DataFrame([1,2,3,4,5,6,7,8,9,10,11], columns=['TEST'])
df_split = np.array_split(df, 3)
...you get 3 sub-dataframes:
df_split[0] # 1, 2, 3, 4
df_split[1] # 5, 6, 7, 8
df_split[2] # 9, 10, 11
With split_dataframe
:
df_split2 = split_dataframe(df, chunk_size=3)
...you get 4 sub-dataframes:
df_split2[0] # 1, 2, 3
df_split2[1] # 4, 5, 6
df_split2[2] # 7, 8, 9
df_split2[3] # 10, 11
Hope I'm right, and that this is useful.
I like the trick presented by Peter N Lewis on this thread: "If n has a limited range, then you can get the result you want simply by adding a known constant multiple of [the divisor] that is greater that the absolute value of the minimum."
So if I have a value d that is in degrees and I want to take
d % 180f
and I want to avoid the problems if d is negative, then instead I just do this:
(d + 720f) % 180f
This assumes that although d may be negative, it is known that it will never be more negative than -720.
If you want to follow all the "best practices," there's a few things I'd recommend, some of which are touched on in other answers and comments to this question.
First, while it doesn't have too much of an affect on the specific question you asked, you did mention efficiency, and the best way to handle shared data in your application is to factor it out into a service.
I would personally recommend embracing AngularJS's promise system, which will make your asynchronous services more composable compared to raw callbacks. Luckily, Angular's $http
service already uses them under the hood. Here's a service that will return a promise that resolves to the data from the JSON file; calling the service more than once will not cause a second HTTP request.
app.factory('locations', function($http) {
var promise = null;
return function() {
if (promise) {
// If we've already asked for this data once,
// return the promise that already exists.
return promise;
} else {
promise = $http.get('locations/locations.json');
return promise;
}
};
});
As far as getting the data into your directive, it's important to remember that directives are designed to abstract generic DOM manipulation; you should not inject them with application-specific services. In this case, it would be tempting to simply inject the locations
service into the directive, but this couples the directive to that service.
A brief aside on code modularity: a directive’s functions should almost never be responsible for getting or formatting their own data. There’s nothing to stop you from using the $http service from within a directive, but this is almost always the wrong thing to do. Writing a controller to use $http is the right way to do it. A directive already touches a DOM element, which is a very complex object and is difficult to stub out for testing. Adding network I/O to the mix makes your code that much more difficult to understand and that much more difficult to test. In addition, network I/O locks in the way that your directive will get its data – maybe in some other place you’ll want to have this directive receive data from a socket or take in preloaded data. Your directive should either take data in as an attribute through scope.$eval and/or have a controller to handle acquiring and storing the data.
In this specific case, you should place the appropriate data on your controller's scope and share it with the directive via an attribute.
app.controller('SomeController', function($scope, locations) {
locations().success(function(data) {
$scope.locations = data;
});
});
<ul class="list">
<li ng-repeat="location in locations">
<a href="#">{{location.id}}. {{location.name}}</a>
</li>
</ul>
<map locations='locations'></map>
app.directive('map', function() {
return {
restrict: 'E',
replace: true,
template: '<div></div>',
scope: {
// creates a scope variable in your directive
// called `locations` bound to whatever was passed
// in via the `locations` attribute in the DOM
locations: '=locations'
},
link: function(scope, element, attrs) {
scope.$watch('locations', function(locations) {
angular.forEach(locations, function(location, key) {
// do something
});
});
}
};
});
In this way, the map
directive can be used with any set of location data--the directive is not hard-coded to use a specific set of data, and simply linking the directive by including it in the DOM will not fire off random HTTP requests.
package main
import "encoding/json"
func main() {
in := []byte(`{ "votes": { "option_A": "3" } }`)
var raw map[string]interface{}
if err := json.Unmarshal(in, &raw); err != nil {
panic(err)
}
raw["count"] = 1
out, err := json.Marshal(raw)
if err != nil {
panic(err)
}
println(string(out))
}
Using sessionStorage
for this is not possible.
From the MDN Docs
Opening a page in a new tab or window will cause a new session to be initiated.
That means that you can't share between tabs, for this you should use localStorage
One of the way would be using NumberFormat.
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(4.0));
Output:
4.00
If ajax request is not fired, please check the select2 class in the select element. Removing the select2 class will fix that issue.
simply do the select
:
Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date) AND
((@day = 'Monday' AND (Monday = 1))
OR (@day = 'Tuesday' AND (Tuesday = 1))
OR (Wednesday = 1))
Check out ActiveModel::Dirty (available on all models by default). The documentation is really good, but it lets you do things such as:
@user.street1_changed? # => true/false
Adding an answer that's completely based on and indebted to divestoclimb with a hint from Shaun Stone. Just wanted to spell it out in detail since it's a common problem and the solution is a bit confusing.
This is using Hibernate 4.1.4.Final, though I suspect anything after 3.6 will work.
First, create divestoclimb's UtcTimestampTypeDescriptor
public class UtcTimestampTypeDescriptor extends TimestampTypeDescriptor {
public static final UtcTimestampTypeDescriptor INSTANCE = new UtcTimestampTypeDescriptor();
private static final TimeZone UTC = TimeZone.getTimeZone("UTC");
public <X> ValueBinder<X> getBinder(final JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicBinder<X>( javaTypeDescriptor, this ) {
@Override
protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException {
st.setTimestamp( index, javaTypeDescriptor.unwrap( value, Timestamp.class, options ), Calendar.getInstance(UTC) );
}
};
}
public <X> ValueExtractor<X> getExtractor(final JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicExtractor<X>( javaTypeDescriptor, this ) {
@Override
protected X doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException {
return javaTypeDescriptor.wrap( rs.getTimestamp( name, Calendar.getInstance(UTC) ), options );
}
};
}
}
Then create UtcTimestampType, which uses UtcTimestampTypeDescriptor instead of TimestampTypeDescriptor as the SqlTypeDescriptor in the super constructor call but otherwise delegates everything to TimestampType:
public class UtcTimestampType
extends AbstractSingleColumnStandardBasicType<Date>
implements VersionType<Date>, LiteralType<Date> {
public static final UtcTimestampType INSTANCE = new UtcTimestampType();
public UtcTimestampType() {
super( UtcTimestampTypeDescriptor.INSTANCE, JdbcTimestampTypeDescriptor.INSTANCE );
}
public String getName() {
return TimestampType.INSTANCE.getName();
}
@Override
public String[] getRegistrationKeys() {
return TimestampType.INSTANCE.getRegistrationKeys();
}
public Date next(Date current, SessionImplementor session) {
return TimestampType.INSTANCE.next(current, session);
}
public Date seed(SessionImplementor session) {
return TimestampType.INSTANCE.seed(session);
}
public Comparator<Date> getComparator() {
return TimestampType.INSTANCE.getComparator();
}
public String objectToSQLString(Date value, Dialect dialect) throws Exception {
return TimestampType.INSTANCE.objectToSQLString(value, dialect);
}
public Date fromStringValue(String xml) throws HibernateException {
return TimestampType.INSTANCE.fromStringValue(xml);
}
}
Finally, when you initialize your Hibernate configuration, register UtcTimestampType as a type override:
configuration.registerTypeOverride(new UtcTimestampType());
Now timestamps shouldn't be concerned with the JVM's time zone on their way to and from the database. HTH.
If you are starting your Tomcat from Eclipse ("Servers" view) then you should have a "Run/Run Configuration" (menu) entry called "Apache Tomcat / Tomcat …". When you select this entry in the list of run configurations you get a window with several tabs, one of which is labeled "Environment". There you can configure environment variables for your Tomcat. Be sure to restart Tomcat afterwards.
Assuming the C++ API is C-compatible (no classes, templates, etc.), you can wrap it in extern "C" { ... }
, just as you did when going the other way.
If you want to expose objects and other cute C++ stuff, you'll have to write a wrapper API.
The r
makes the string a raw string, which doesn't process escape characters (however, since there are none in the string, it is actually not needed here).
Also, re.match
matches from the beginning of the string. In other words, it looks for an exact match between the string and the pattern. To match stuff that could be anywhere in the string, use re.search
. See a demonstration below:
>>> import re
>>> line = 'This,is,a,sample,string'
>>> re.match("sample", line)
>>> re.search("sample", line)
<_sre.SRE_Match object at 0x021D32C0>
>>>
In case anyone is still struggling with this, as I was all morning today, I have found a solution that works for me:
Installation instructions:
git clone https://github.com/gstarnberger/uncompyle.git
cd uncompyle/
sudo ./setup.py install
Once the program is installed (note: it will be installed to your system-wide-accessible Python packages, so it should be in your $PATH
), you can recover your Python files like so:
uncompyler.py thank_goodness_this_still_exists.pyc > recovered_file.py
The decompiler adds some noise mostly in the form of comments, however I've found it to be surprisingly clean and faithful to my original code. You will have to remove a little line of text beginning with +++ near the end of the recovered file to be able to run your code.
The Java Packager tool compiles, packages, and prepares Java and JavaFX applications for distribution. The javapackager command is the command-line version.
– Oracle's documentation
The javapackager
utility ships with the JDK. It can generate .exe files with the -native exe
flag, among many other things.
WinRun4j is a java launcher for windows. It is an alternative to javaw.exe and provides the following benefits:
- Uses an INI file for specifying classpath, main class, vm args, program args.
- Custom executable name that appears in task manager.
- Additional JVM args for more flexible memory use.
- Built-in icon replacer for custom icon.
- [more bullet points follow]
– WinRun4J's webpage
WinRun4J is an open source utility. It has many features.
Packages your JAR, assets and a JVM for distribution on Windows, Linux and Mac OS X, adding a native executable file to make it appear like a native app. Packr is most suitable for GUI applications.
– packr README
packr is another open source tool.
JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself.
– JSmooth's website
JSmooth is open source and has features, but it is very old. The last release was in 2007.
JexePack is a command line tool (great for automated scripting) that allows you to package your Java application (class files), optionally along with its resources (like GIF/JPG/TXT/etc), into a single compressed 32-bit Windows EXE, which runs using Sun's Java Runtime Environment. Both console and windowed applications are supported.
– JexePack's website
JexePack is trialware. Payment is required for production use, and exe files created with this tool will display "reminders" without payment. Also, the last release was in 2013.
InstallAnywhere makes it easy for developers to create professional installation software for any platform. With InstallAnywhere, you’ll adapt to industry changes quickly, get to market faster and deliver an engaging customer experience. And know the vulnerability of your project’s OSS components before you ship.
– InstallAnywhere's website
InstallAnywhere is a commercial/enterprise package that generates installers for Java-based programs. It's probably capable of creating .exe files.
As an alternative to .exe files, you can create a JAR file that automatically runs when double-clicked, by adding an entry point to the JAR manifest.
An excellent source of information on this topic is Excelsior's article "Convert Java to EXE – Why, When, When Not and How".
See also the companion article "Best JAR to EXE Conversion Tools, Free and Commercial".
Assuming you're using WinForms, as it was the first thing I did when I was starting C# you need to create an event to close this form.
Lets say you've got a button called myNewButton. If you double click it on WinForms designer you will create an event. After that you just have to use this.Close
private void myNewButton_Click(object sender, EventArgs e) {
this.Close();
}
And that should be it.
The only reason for this not working is that your Event is detached from button. But it should create new event if old one is no longer attached when you double click on the button in WinForms designer.
In Go, there is a general rule that syntax should not hide complex/costly operations. Converting a string
to an interface{}
is done in O(1) time. Converting a []string
to an interface{}
is also done in O(1) time since a slice is still one value. However, converting a []string
to an []interface{}
is O(n) time because each element of the slice must be converted to an interface{}
.
The one exception to this rule is converting strings. When converting a string
to and from a []byte
or a []rune
, Go does O(n) work even though conversions are "syntax".
There is no standard library function that will do this conversion for you. You could make one with reflect, but it would be slower than the three line option.
Example with reflection:
func InterfaceSlice(slice interface{}) []interface{} {
s := reflect.ValueOf(slice)
if s.Kind() != reflect.Slice {
panic("InterfaceSlice() given a non-slice type")
}
// Keep the distinction between nil and empty slice input
if s.IsNil() {
return nil
}
ret := make([]interface{}, s.Len())
for i:=0; i<s.Len(); i++ {
ret[i] = s.Index(i).Interface()
}
return ret
}
Your best option though is just to use the lines of code you gave in your question:
b := make([]interface{}, len(a))
for i := range a {
b[i] = a[i]
}
I had the same problem. I'm using this solution I found: React Native display SVG from a file
It's not perfect, and i'm revisiting today, because it performs a lot worse on Android.
Is it possible to get this above example:
jQuery.fn.highlight = function (str, className)
{
var regex = new RegExp(str, "g");
return this.each(function ()
{
this.innerHTML = this.innerHTML.replace(
regex,
"<span class=\"" + className + "\">" + str + "</span>"
);
});
};
not to replace text inside html-tags like , this otherwise breakes the page.
Tried different solutions to solve the problem for several weeks without success.
The problem I was facing was caused by upgrading from laravel 5.0 to 5.5 and forgot to update config/session.php
If anyone is facing the problem, try to update the config/session.php to match the version on Laravel you are running
The three possible solutions suggested here have different use cases.
Use .equals when comparing ObjectID on two mongoDocuments like this
results.userId.equals(AnotherMongoDocument._id)
Use .toString() when comparing a string representation of ObjectID to an ObjectID of a mongoDocument. like this
results.userId === AnotherMongoDocument._id.toString()
This solution worked for me
var ar = [];
$('#id option:selected').each(function(index,valor){
ar.push(valor.value);
});
console.log(ar);
be sure to have your <option>
tags with they correspondant value
attribute.
Hope it helps.
The main differences between github and gists are in terms of number of features and user interface:
One is designed with a great number of features and flexibility in mind, which is a good fit for both small and very big projects, while gists are only a good fit for very small projects.
For example, gists do support multi-files, but the interface is very simple, and they're limited in features, so they don't even have a file browser, nor issues, pull requests or wiki. If you dont need to have that, gists are very nice and more discrete. Like the comments, instead of answers, in SO.
Note: Thanks to @Qwerty for the suggestion of making my comment a real answer.
const string ua = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
Request.Headers["User-Agent"] = ua;
var httpWorkerRequestField = Request.GetType().GetField("_wr", BindingFlags.Instance | BindingFlags.NonPublic);
if (httpWorkerRequestField != null)
{
var httpWorkerRequest = httpWorkerRequestField.GetValue(Request);
var knownRequestHeadersField = httpWorkerRequest.GetType().GetField("_knownRequestHeaders", BindingFlags.Instance | BindingFlags.NonPublic);
if (knownRequestHeadersField != null)
{
string[] knownRequestHeaders = (string[])knownRequestHeadersField.GetValue(httpWorkerRequest);
knownRequestHeaders[39] = ua;
}
}
Just simply.. #sometime when larger table we can't add the id to each tr
<table>
<tr>
<td>some text</td>
<td>something</td>
</tr>
<tr>
<td>Hello</td>
<td>Hel</td>
</tr>
</table>
<script>
var cell = document.getElementsByTagName("td");
var i = 0;
while(cell[i] != undefined){
alert(cell[i].innerHTML); //do some alert for test
i++;
}//end while
</script>
The color and window sizing are defined by the shortcut LNK file. I think I found a way that will do what you need, try this:
explorer.exe "Windows PowerShell.lnk"
The LNK file is in the all user start menu which is located in different places depending whether your on XP or Windows 7. In 7 the LNK file is here:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell
I basically do like this, create new element and attach that to <head>
var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);
You may also use onload
event to each script you attach, but please test it out, I am not so sure it works cross-browser or not.
x.onload=callback_function;
Disclaimer: use a parser if you have the option. That said...
This is the regex I use (!) to match HTML tags:
<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>
It may not be perfect, but I ran this code through a lot of HTML. Note that it even catches strange things like <a name="badgenerator"">
, which show up on the web.
I guess to make it not match self contained tags, you'd either want to use Kobi's negative look-behind:
<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+(?<!/\s*)>
or just combine if and if not.
To downvoters: This is working code from an actual product. I doubt anyone reading this page will get the impression that it is socially acceptable to use regexes on HTML.
Caveat: I should note that this regex still breaks down in the presence of CDATA blocks, comments, and script and style elements. Good news is, you can get rid of those using a regex...
for (Map.Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
System.out.println( entry.getKey());
System.out.println( entry.getValue());//Returns the list of values
}
For Swift 3, the below code scales the image keeping the aspect ratio. You can read more about the ImageContext in Apple's documentation:
extension UIImage {
class func resizeImage(image: UIImage, newHeight: CGFloat) -> UIImage {
let scale = newHeight / image.size.height
let newWidth = image.size.width * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
To use it, call resizeImage()
method:
UIImage.resizeImage(image: yourImageName, newHeight: yourImageNewHeight)
on macOS (/ OS X), if someone else is having trouble with the OS apparently leaking memory:
Just use Map#get(key)
?
Object value = map.get(myCode);
Here's a tutorial about maps, you may find it useful: http://java.sun.com/docs/books/tutorial/collections/interfaces/map.html.
Edit: you edited your question with the following:
I'm expecting to see a String, such as "ABC" or "DEF" as that is what I put in there initially, but if I do a System.out.println() I get something like java.lang.string#F0454
Sorry, I'm not too familiar with maps as you can probably guess ;)
You're seeing the outcome of Object#toString()
. But the java.lang.String
should already have one implemented, unless you created a custom implementation with a lowercase s
in the name: java.lang.string
. If it is actually a custom object, then you need to override Object#toString()
to get a "human readable string" whenever you do a System.out.println()
or toString()
on the desired object. For example:
@Override
public String toString() {
return "This is Object X with a property value " + value;
}
No, the only thing that needs to be modified for an Anaconda environment is the PATH (so that it gets the right Python from the environment bin/
directory, or Scripts\
on Windows).
The way Anaconda environments work is that they hard link everything that is installed into the environment. For all intents and purposes, this means that each environment is a completely separate installation of Python and all the packages. By using hard links, this is done efficiently. Thus, there's no need to mess with PYTHONPATH because the Python binary in the environment already searches the site-packages in the environment, and the lib of the environment, and so on.
If the list of acceptable characters is pretty small, you can use a regular expression like this:
Regex.IsMatch(items, "[a-z0-9 ]+", RegexOptions.IgnoreCase);
The regular expression used here looks for any character from a-z and 0-9 including a space (what's inside the square brackets []), that there is one or more of these characters (the + sign--you can use a * for 0 or more). The final option tells the regex parser to ignore case.
This will fail on anything that is not a letter, number, or space. To add more characters to the blessed list, add it inside the square brackets.
The 'best' way to do this would be to set a property on a view object once the update is successful. You can then access this property in the view and inform the user accordingly.
Having said that it would be possible to trigger an alert from the controller code by doing something like this -
public ActionResult ActionName(PostBackData postbackdata)
{
//your DB code
return new JavascriptResult { Script = "alert('Successfully registered');" };
}
You can find further info in this question - How to display "Message box" using MVC3 controller
In your Ruby on Rails controller you can use:
private
before_filter :safari_cookie_fix
def safari_cookie_fix
user_agent = UserAgent.parse(request.user_agent) # Uses useragent gem!
if user_agent.browser == 'Safari' # we apply the fix..
return if session[:safari_cookie_fixed] # it is already fixed.. continue
if params[:safari_cookie_fix].present? # we should be top window and able to set cookies.. so fix the issue :)
session[:safari_cookie_fixed] = true
redirect_to params[:return_to]
else
# Redirect the top frame to your server..
render :text => "<script>alert('start redirect');top.window.location='?safari_cookie_fix=true&return_to=#{set_your_return_url}';</script>"
end
end
end
The way I build CMake projects cross platform is the following:
/project-root> mkdir build
/project-root> cd build
/project-root/build> cmake -G "<generator>" -DCMAKE_INSTALL_PREFIX=stage ..
/project-root/build> cmake --build . --target=install --config=Release
./project-root/build/stage
- the path is always considered relative to the current directory if it is not absolute).
with the buildsystem configured in the line before. It will execute the install
target which also builds all necessary dependent targets if they need to be built and then copies the files into the CMAKE_INSTALL_PREFIX
(which in this case is ./project-root/build/stage
. For multi-configuration builds, like in Visual Studio, you can also specify the configuration with the optional --config <config>
flag.cmake --build
command is that it works for all generators (i.e. makefiles and Visual Studio) without needing different commands.Afterwards I use the installed files to create packages or include them in other projects...
bash doesn't know boolean variables, nor does test
(which is what gets called when you use [
).
A solution would be:
if $myVar ; then ... ; fi
because true
and false
are commands that return 0
or 1
respectively which is what if
expects.
Note that the values are "swapped". The command after if
must return 0
on success while 0
means "false" in most programming languages.
SECURITY WARNING: This works because BASH expands the variable, then tries to execute the result as a command! Make sure the variable can't contain malicious code like rm -rf /
From GNU Make error appendix, as you see this is not a Make error but an error coming from gcc.
‘[foo] Error NN’ ‘[foo] signal description’ These errors are not really make errors at all. They mean that a program that make invoked as part of a recipe returned a non-0 error code (‘Error NN’), which make interprets as failure, or it exited in some other abnormal fashion (with a signal of some type). See Errors in Recipes. If no *** is attached to the message, then the subprocess failed but the rule in the makefile was prefixed with the - special character, so make ignored the error.
So in order to attack the problem, the error message from gcc is required. Paste the command in the Makefile directly to the command line and see what gcc says. For more details on Make errors click here.
I know it's silly, but in my case I just tried with sudo
and it worked like a charm.
in your case, just try: $ sudo docker-compose up
Base64 overhead is 33%.
BaseXML for XML1.0 overhead is only 20%. But it's not a standard and only have a C implementation yet. Check it out if you're concerned with data size. Note that however browsers tends to implement compression so that it is less needed.
I developed it after the discussion in this thread: Encoding binary data within XML : alternatives to base64.
Django 1.10 (release notes) added the is
and is not
comparison operators to the if
tag. This change makes identity testing in a template pretty straightforward.
In[2]: from django.template import Context, Template
In[3]: context = Context({"somevar": False, "zero": 0})
In[4]: compare_false = Template("{% if somevar is False %}is false{% endif %}")
In[5]: compare_false.render(context)
Out[5]: u'is false'
In[6]: compare_zero = Template("{% if zero is not False %}not false{% endif %}")
In[7]: compare_zero.render(context)
Out[7]: u'not false'
If You are using an older Django then as of version 1.5 (release notes) the template engine interprets True
, False
and None
as the corresponding Python objects.
In[2]: from django.template import Context, Template
In[3]: context = Context({"is_true": True, "is_false": False,
"is_none": None, "zero": 0})
In[4]: compare_true = Template("{% if is_true == True %}true{% endif %}")
In[5]: compare_true.render(context)
Out[5]: u'true'
In[6]: compare_false = Template("{% if is_false == False %}false{% endif %}")
In[7]: compare_false.render(context)
Out[7]: u'false'
In[8]: compare_none = Template("{% if is_none == None %}none{% endif %}")
In[9]: compare_none.render(context)
Out[9]: u'none'
Although it does not work the way one might expect.
In[10]: compare_zero = Template("{% if zero == False %}0 == False{% endif %}")
In[11]: compare_zero.render(context)
Out[11]: u'0 == False'
You can follow this, more readable, not expectation raise due to key not found :
data.map((datum)=>{
return {
'id':datum.id,
'title':datum.login,
}
Use this method Collections.sort(List,Comparator) . Implement a Comparator and pass it to Collections.sort().
class RecipeCompare implements Comparator<Recipe> {
@Override
public int compare(Recipe o1, Recipe o2) {
// write comparison logic here like below , it's just a sample
return o1.getID().compareTo(o2.getID());
}
}
Then use the Comparator
as
Collections.sort(recipes,new RecipeCompare());
It depends on what you are intending to do with it.
Sets are significantly faster when it comes to determining if an object is present in the set (as in x in s
), but are slower than lists when it comes to iterating over their contents.
You can use the timeit module to see which is faster for your situation.
In simple words
$.ajax("info.txt").done(function(data) {
alert(data);
}).fail(function(data){
alert("Try again champ!");
});
if its get the info.text then it will alert and whatever function you add or if any how unable to retrieve info.text from the server then alert or error function.
this will work:
DECLARE @IndexInfo TABLE (index_name varchar(250)
,index_description varchar(250)
,index_keys varchar(250)
)
INSERT INTO @IndexInfo
exec sp_msforeachtable 'sp_helpindex ''?'''
select * from @IndexInfo
this does not reurn the table name and you will get warnings for all tables without an index, if that is a problem, you can create a loop over the tables that have indexes like this:
DECLARE @IndexInfoTemp TABLE (index_name varchar(250)
,index_description varchar(250)
,index_keys varchar(250)
)
DECLARE @IndexInfo TABLE (table_name sysname
,index_name varchar(250)
,index_description varchar(250)
,index_keys varchar(250)
)
DECLARE @Tables Table (RowID int not null identity(1,1)
,TableName sysname
)
DECLARE @MaxRow int
DECLARE @CurrentRow int
DECLARE @CurrentTable sysname
INSERT INTO @Tables
SELECT
DISTINCT t.name
FROM sys.indexes i
INNER JOIN sys.tables t ON i.object_id = t.object_id
WHERE i.Name IS NOT NULL
SELECT @MaxRow=@@ROWCOUNT,@CurrentRow=1
WHILE @CurrentRow<=@MaxRow
BEGIN
SELECT @CurrentTable=TableName FROM @Tables WHERE RowID=@CurrentRow
INSERT INTO @IndexInfoTemp
exec sp_helpindex @CurrentTable
INSERT INTO @IndexInfo
(table_name , index_name , index_description , index_keys)
SELECT
@CurrentTable , index_name , index_description , index_keys
FROM @IndexInfoTemp
DELETE FROM @IndexInfoTemp
SET @CurrentRow=@CurrentRow+1
END --WHILE
SELECT * from @IndexInfo
EDIT
if you want, you can filter the data, here are some examples (these work for either method):
SELECT * FROM @IndexInfo WHERE index_description NOT LIKE '%primary key%'
SELECT * FROM @IndexInfo WHERE index_description NOT LIKE '%nonclustered%' AND index_description LIKE '%clustered%'
SELECT * FROM @IndexInfo WHERE index_description LIKE '%unique%'
copied from: https://android.stackexchange.com/questions/12962/flush-clear-dns-cache
Addresses are cached for 600 seconds (10 minutes) by default. Failed lookups are cached for 10 seconds. From everything I've seen, there's nothing built in to flush the cache. This is apparently a reported bug http://code.google.com/p/android/issues/detail?id=7904 in Android because of the way it stores DNS cache. Clearing the browser cache doesn't touch the DNS, the "hard reset" clears it.
The error message says it all: strs[sum-1]
is a tuple, not a string. If you show more of your code someone will probably be able to help you. Without that we can only guess.
Using intent.setType("message/rfc822");
does work but it shows extra apps that not necessarily handling emails (e.g. GDrive). Using Intent.ACTION_SENDTO
with setType("text/plain")
is the best but you have to add setData(Uri.parse("mailto:"))
to get the best results (only email apps). The full code is as follows:
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setType("text/plain");
intent.setData(Uri.parse("mailto:[email protected]"));
intent.putExtra(Intent.EXTRA_SUBJECT, "Email from My app");
intent.putExtra(Intent.EXTRA_TEXT, "Place your email message here ...");
startActivity(Intent.createChooser(intent, "Send Email"));
After poking around it looks like Kelsey is correct.
Just use a comma or something and split it when you want to consume it.
Good question... I find that coders typically use the declaration to declare defaults. I've been held to one way (or warned) or the other too based on the compiler
void testFunct(int nVal1, int nVal2=500);
void testFunct(int nVal1, int nVal2)
{
using namespace std;
cout << nVal1 << << nVal2 << endl;
}
A "C-program" is not supposed to be run. It is meant to be compiled into an "executable" program which then can be run from your terminal. You need a compiler for that.
Oh, and the answer to your last question ("Why?") is that the file you are trying to execute doesn't have the executable rights set (which a compiler usually does automatically with the binary, which let's infer that you were trying to run the source code as a script, hence the hint at compiling.)
I spent more time on this than I should have, and haven't tested in IE for obvious reasons. That being said, it's pretty much identical.
a.boxclose{
float:right;
margin-top:-30px;
margin-right:-30px;
cursor:pointer;
color: #fff;
border: 1px solid #AEAEAE;
border-radius: 30px;
background: #605F61;
font-size: 31px;
font-weight: bold;
display: inline-block;
line-height: 0px;
padding: 11px 3px;
}
.boxclose:before {
content: "×";
}
It's doubtful you can change it on click with the default myLocation Marker. However, if you would like the app to automatically zoom in on your location once it is found, I would check out my answer to this question
Note that the answer I provided does not zoom in, but if you modify the onLocationChanged method to be like the one below, you can choose whatever zoom level you like:
@Override
public void onLocationChanged(Location location)
{
if( mListener != null )
{
mListener.onLocationChanged( location );
//Move the camera to the user's location and zoom in!
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 12.0f));
}
}
Recursively delete all children of the file ...
public static void DeleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory()) {
for (File child : fileOrDirectory.listFiles()) {
DeleteRecursive(child);
}
}
fileOrDirectory.delete();
}
UDP is mailing a letter at the post office.
TCP is mailing a letter with a return receipt at the post office, except that the post master will organize the letters in-order-of mailing and only deliver them in-order.
Well, it was an attempt anyway.
Hello Try this code below
public class RemoveCharacter {
public static void main(String[] args){
String str = "MXy nameX iXs farXazX";
char x = 'X';
System.out.println(removeChr(str,x));
}
public static String removeChr(String str, char x){
StringBuilder strBuilder = new StringBuilder();
char[] rmString = str.toCharArray();
for(int i=0; i<rmString.length; i++){
if(rmString[i] == x){
} else {
strBuilder.append(rmString[i]);
}
}
return strBuilder.toString();
}
}
Here is the focus listener example.
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (hasFocus) {
Toast.makeText(getApplicationContext(), "Got the focus", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Lost the focus", Toast.LENGTH_LONG).show();
}
}
});
Alright, the problem is easy. Tensorflow require python 3.4 - 3.7 and 64bit. I see than you're using python 2.7.
Read the tensorflow install instructions here: https://www.tensorflow.org/install/pip
This simple function works for me:
public static String leftPad(String string, int length, String pad) {
return pad.repeat(length - string.length()) + string;
}
Invocation:
String s = leftPad(myString, 10, "0");
SQL Server uses Julian dates so your 30 means "30 calendar days". getdate() - 0.02083 means "30 minutes ago".
Well, I use this method on my site:
<a class="share-btn" href="https://www.facebook.com/sharer/sharer.php?app_id=[your_app_id]&sdk=joey&u=[full_article_url]&display=popup&ref=plugin&src=share_button" onclick="return !window.open(this.href, 'Facebook', 'width=640,height=580')">
Works perfectly.
If you're having this after installing Visual Studio 2015 and you can see Error messages in System event log such as this: Unable to bind to the underlying transport for [::]:{your_port}. . The IP Listen-Only list may contain a reference ...
then you might be missing a registry entry.
Run this under administrative command prompt: netsh http add iplisten ipaddress=::
to fix it.
I found the solution described in detail here
I needed a multilevel dropdown menu in css. I couldn't find an error-free menu that I searched. Then I created a menu instance using the Css hover transition effect.I hope it will be useful for users.
#AnaMenu {
width: 920px; /* Menu width */
height: 30px; /* Menu height */
position: relative;
background: #0080ff;
margin:0 0 0 -30px;
padding: 10px 0 0 15px;
border: 0;
}
#nav { display:block;background:transparent;
margin:0;padding: 0;border: 0 }
#nav ul { float: none; display:block;
height:35px;
margin:16px 0 0 0;border:0;
padding: 15px 0 3px 0;
overflow: visible;
}
#nav ul li{border:0;}
#nav li a, #nav li a:link, #nav li a:visited {height:23px;
-webkit-transition: background-color 1s ease-out;
-moz-transition: background-color 1s ease-out;
-o-transition: background-color 1s ease-out;
transition: background-color 1s ease-out;
color: #fff; /* Change colour of link */
display: block;border:0;border-right:1px solid #efefef;text-decoration:none;
margin: 0;letter-spacing:0.6px;
padding: 2px 10px 2px 10px;
}
#nav li a:hover, #nav li a:active {
color: #fff;
margin: 0;background:#6ab5ff;border:0;
padding: 2px 10px 2px 10px;
}
#nav li li a, #nav li li a:link, #nav li li a:visited {
background: #fafafa;
width: 200px;
color: #05429b; /* Link text color */
float: none;
margin: 0;border-bottom:1px solid #9be6e9;
padding: 8px 15px;
}
#nav li li a:hover, #nav li li a:active {
background: #2793ff; /* Mouse hover color */
color: #fff;
padding: 8px 15px;border:0 ;text-decoration:none}
#nav li {float: none; display: inline-block;margin: 0; padding: 0; border: 0 }
#nav li ul { z-index: 9999; position: absolute; left: -999em; height: auto; width: 200px; margin: 0; padding: 0;background:transparent}
#nav li ul a { width: 170px;border:0;text-decoration:none;font-size:14px }
#nav li ul ul { margin: -40px 0 0 230px }
#nav li:hover ul ul, #nav li:hover ul ul ul, #nav li.sfhover ul ul, #nav li.sfhover ul ul ul {left: -999em; }
#nav li:hover ul, #nav li li:hover ul, #nav li li li:hover ul, #nav li.sfhover ul, #nav li li.sfhover ul, #nav li li li.sfhover ul { left: auto; }
#nav li:hover, #nav li.sfhover {position: static;}
Multilevel dropdown menu can be used in Blogger blogs. Details at : Css multilevel dropdown menu
I was looking for it earlier and I made it in very easiest way, I hope you would like this.
//crete this method into your Utils class and call this method wherever you want to use.
//you can set these placeHolder() and error() image static as well. I made it as comment inside this method, then no need to use [placeHolderUrl and errorImageUrl] parameters. remove it from this method.
public static void loadImage(final Activity context, ImageView imageView, String url, int placeHolderUrl, int errorImageUrl) {
if (context == null || context.isDestroyed()) return;
//placeHolderUrl=R.drawable.ic_user;
//errorImageUrl=R.drawable.ic_error;
Glide.with(context) //passing context
.load(getFullUrl(url)) //passing your url to load image.
.placeholder(placeHolderUrl) //this would be your default image (like default profile or logo etc). it would be loaded at initial time and it will replace with your loaded image once glide successfully load image using url.
.error(errorImageUrl)//in case of any glide exception or not able to download then this image will be appear . if you won't mention this error() then nothing to worry placeHolder image would be remain as it is.
.diskCacheStrategy(DiskCacheStrategy.ALL) //using to load into cache then second time it will load fast.
.transform(new CircleTransform(context))//this CircleTransform class help to crop an image as circle.
.animate(R.anim.fade_in) // when image (url) will be loaded by glide then this face in animation help to replace url image in the place of placeHolder (default) image.
.fitCenter()//this method help to fit image into center of your ImageView
.into(imageView); //pass imageView reference to appear the image.
}
CircleTransform.java
public class CircleTransform extends BitmapTransformation {
public CircleTransform(Context context) {
super(context);
if(context==null)
return;
}
private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
if (source == null) return null;
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
if (result == null) {
result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
return result;
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return circleCrop(pool, toTransform);
}
@Override
public String getId() {
return getClass().getName();
}
}
fade_in.xml for fade in animation .
<set xmlns:android="http://schemas.android.com/apk/res/android">
<!--THIS ANIMATION IS USING FOR FADE IN -->
<alpha
android:duration="800"
android:fromAlpha="0.0"
android:interpolator="@android:anim/decelerate_interpolator"
android:toAlpha="1.0" />
finally to call this method.
Utils.loadImage(YourClassName.this,mImageView,url,R.drawable.ic_user,R.drawable.ic_error);
If you prefer to use a step by step approach you could consider a solution like follows
import numpy as np
import matplotlib.pyplot as plt
mean = 0; std = 1; variance = np.square(std)
x = np.arange(-5,5,.01)
f = np.exp(-np.square(x-mean)/2*variance)/(np.sqrt(2*np.pi*variance))
plt.plot(x,f)
plt.ylabel('gaussian distribution')
plt.show()
For Visual Studio Express 2013 to get rid of these problem you have to do the following.
Right click on your project click Properties. In properties window from left menus select Configuration Properties->C/C++->General
In right side select
Treat Warning As Errors NO
and
SDL Checks NO
Typescript with Hooks
Note: I'm using React version 16.3, with React.createRef. For other versions use the ref callback.
Dropdown component:
interface DropdownProps {
...
};
export const Dropdown: React.FC<DropdownProps> () {
const ref: React.RefObject<HTMLDivElement> = React.createRef();
const handleClickOutside = (event: MouseEvent) => {
if (ref && ref !== null) {
const cur = ref.current;
if (cur && !cur.contains(event.target as Node)) {
// close all dropdowns
}
}
}
useEffect(() => {
// Bind the event listener
document.addEventListener("mousedown", handleClickOutside);
return () => {
// Unbind the event listener on clean up
document.removeEventListener("mousedown", handleClickOutside);
};
});
return (
<div ref={ref}>
...
</div>
);
}
This should be equivalent to your current code, only a lot faster:
output <- matrix(unlist(z), ncol = 10, byrow = TRUE)