If you can look ahead but back, you could reverse the string first and then do a lookahead. Some more work will need to be done, of course.
The only way not to capture something is using look-around assertions:
(?<=123-)((apple|banana)(?=-456)|(?=456))
Because even with non-capturing groups (?:…)
the whole regular expression captures their matched contents. But this regular expression matches only apple
or banana
if it’s preceded by 123-
and followed by -456
, or it matches the empty string if it’s preceded by 123-
and followed by 456
.
|Lookaround | Name | What it Does |
-----------------------------------------------------------------------
|(?=foo) | Lookahead | Asserts that what immediately FOLLOWS the |
| | | current position in the string is foo |
-------------------------------------------------------------------------
|(?<=foo) | Lookbehind | Asserts that what immediately PRECEDES the|
| | | current position in the string is foo |
-------------------------------------------------------------------------
|(?!foo) | Negative | Asserts that what immediately FOLLOWS the |
| | Lookahead | current position in the string is NOT foo|
-------------------------------------------------------------------------
|(?<!foo) | Negative | Asserts that what immediately PRECEDES the|
| | Lookbehind | current position in the string is NOT foo|
-------------------------------------------------------------------------
Given the string foobarbarfoo
:
bar(?=bar) finds the 1st bar ("bar" which has "bar" after it)
bar(?!bar) finds the 2nd bar ("bar" which does not have "bar" after it)
(?<=foo)bar finds the 1st bar ("bar" which has "foo" before it)
(?<!foo)bar finds the 2nd bar ("bar" which does not have "foo" before it)
You can also combine them:
(?<=foo)bar(?=bar) finds the 1st bar ("bar" with "foo" before it and "bar" after it)
(?=)
Find expression A where expression B follows:
A(?=B)
(?!)
Find expression A where expression B does not follow:
A(?!B)
(?<=)
Find expression A where expression B precedes:
(?<=B)A
(?<!)
Find expression A where expression B does not precede:
(?<!B)A
(?>)
An atomic group exits a group and throws away alternative patterns after the first matched pattern inside the group (backtracking is disabled).
(?>foo|foot)s
applied to foots
will match its 1st alternative foo
, then fail as s
does not immediately follow, and stop as backtracking is disabledA non-atomic group will allow backtracking; if subsequent matching ahead fails, it will backtrack and use alternative patterns until a match for the entire expression is found or all possibilities are exhausted.
(foo|foot)s
applied to foots
will:
foo
, then fail as s
does not immediately follow in foots
, and backtrack to its 2nd alternative;foot
, then succeed as s
immediately follows in foots
, and stop.<a onclick="jsfunction()" href="#">
or
<a onclick="jsfunction()" href="javascript:void(0);">
Edit:
The above response is really not a good solution, having learned a lot about JS since I initially posted. See EndangeredMassa's answer below for the better approach to solving this problem.
If you are using Qt, try rerunning qmake. If this error is in the widget's class, qmake might have failed to notice that the ui class vtable should be regenerated. This fixed the issue for me.
You can directly run the following command on terminal of your remote server to run tensorboard:
tensorboard --logdir {tf_log directory path} --host "0.0.0.0" --port 6006
Or you can also start the tensorboard within your ipython notebook:
%load_ext tensorboard
%tensorboard --logdir {tf_log directory path} --host "0.0.0.0" --port 6006
Update 2
This method is no longer available in rxjs v6
I'm solved it by using the isNumeric operator from rxjs library (importing rxjs/util/isNumeric
Update
import { isNumeric } from 'rxjs/util/isNumeric';
. . .
var val = "5700";
if (isNumeric(val)){
alert("it is number !");
}
I actually got fed up by the lack of standard MIME sniffing methods in PHP. Install fileinfo... Use deprecated functions... Oh these work, but only for images! I got fed up of it, so I did some research and found the WHATWG Mimesniffing spec - I believe this is still a draft spec though.
Anyway, using this specification, I was able to implement a mimesniffer in PHP. Performance is not an issue. In fact on my humble machine, I was able to open and sniff thousands of files before PHP timed out.
Here is the MimeReader class.
require_once("MimeReader.php");
$mime = new MimeReader(<YOUR FILE PATH>);
$mime_type_string = $mime->getType(); // "image/jpeg" etc.
How about creating two dataframes, each with different data types for their columns, and then appending them together?
d1 = pd.DataFrame(columns=[ 'float_column' ], dtype=float)
d1 = d1.append(pd.DataFrame(columns=[ 'string_column' ], dtype=str))
Results
In[8}: d1.dtypes
Out[8]:
float_column float64
string_column object
dtype: object
After the dataframe is created, you can populate it with floating point variables in the 1st column, and strings (or any data type you desire) in the 2nd column.
Here's an answer that gives the switch-or-launch behaviour of Start, without the Command Prompt window. It does have the drawback that it can be fooled by an Explorer window that has a folder of the same name elsewhere opened. I might fix that by diving into the child windows and looking for the actual path, I need to figure out how to navigate that.
Usage (requires "Windows Script Host Object Model" in your project's References):
Dim mShell As wshShell
mDocPath = whatever_path & "\" & lastfoldername
mExplorerPath = mShell.ExpandEnvironmentStrings("%SystemRoot%") & "\Explorer.exe"
If Not SwitchToFolder(lastfoldername) Then
Shell PathName:=mExplorerPath & " """ & mDocPath & """", WindowStyle:=vbNormalFocus
End If
Module:
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
(ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" _
(ByVal hWnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" _
(ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare Function BringWindowToTop Lib "user32" _
(ByVal lngHWnd As Long) As Long
Function SwitchToFolder(pFolder As String) As Boolean
Dim hWnd As Long
Dim mRet As Long
Dim mText As String
Dim mWinClass As String
Dim mWinTitle As String
SwitchToFolder = False
hWnd = FindWindowEx(0, 0&, vbNullString, vbNullString)
While hWnd <> 0 And SwitchToFolder = False
mText = String(100, Chr(0))
mRet = GetClassName(hWnd, mText, 100)
mWinClass = Left(mText, mRet)
If mWinClass = "CabinetWClass" Then
mText = String(100, Chr(0))
mRet = GetWindowText(hWnd, mText, 100)
If mRet > 0 Then
mWinTitle = Left(mText, mRet)
If UCase(mWinTitle) = UCase(pFolder) Or _
UCase(Right(mWinTitle, Len(pFolder) + 1)) = "\" & UCase(pFolder) Then
BringWindowToTop hWnd
SwitchToFolder = True
End If
End If
End If
hWnd = FindWindowEx(0, hWnd, vbNullString, vbNullString)
Wend
End Function
Make sure that in case your image is not in the dom, and you get it from local directory or server, you should wait for the image to load and just after that to draw it on the canvas.
something like that:
function drawBgImg() {
let bgImg = new Image();
bgImg.src = '/images/1.jpg';
bgImg.onload = () => {
gCtx.drawImage(bgImg, 0, 0, gElCanvas.width, gElCanvas.height);
}
}
Here is my version:
List<object> list = new List<object>(new object[]{ "test", 0, "hello", 1, "world" });
foreach(var x in list)
{
Console.WriteLine("x: {0}", x);
}
If you are trying to delete a column which is a FOREIGN KEY, you must find the correct name which is not the column name. Eg: If I am trying to delete the server field in the Alarms table which is a foreign key to the servers table.
SHOW CREATE TABLE alarm;
Look for the CONSTRAINT `server_id_refs_id_34554433` FORIEGN KEY (`server_id`) REFERENCES `server` (`id`)
line.ALTER TABLE `alarm` DROP FOREIGN KEY `server_id_refs_id_34554433`;
ALTER TABLE `alarm` DROP `server_id`
This will delete the foreign key server from the Alarms table.
There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.
One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.
You can't move a mouse but can lock it. Note: that you must call requestPointerLock in click event.
Small Example:
var canvas = document.getElementById('mycanvas');
canvas.requestPointerLock = canvas.requestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
canvas.requestPointerLock();
Documentation and full code example:
https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API
Basically like this,
<?php
$link = ""; // Link goes here!
print "<a href="'.$link.'">Link</a>";
?>
The keypress
event might be different across browsers.
I created a Jsfiddle to compare keyboard events (using the JQuery shortcuts) on Chrome and Firefox. Depending on the browser you're using a keypress
event will be triggered or not -- backspace will trigger keydown/keypress/keyup
on Firefox but only keydown/keyup
on Chrome.
on Chrome
keydown/keypress/keyup
when browser registers a keyboard input (keypress
is fired)
keydown/keyup
if no keyboard input (tested with alt, shift, backspace, arrow keys)
keydown
only for tab?
on Firefox
keydown/keypress/keyup
when browser registers a keyboard input but also for backspace, arrow keys, tab (so here keypress
is fired even with no input)
keydown/keyup
for alt, shift
This shouldn't be surprising because according to https://api.jquery.com/keypress/:
Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.
The use of the keypress event type is deprecated by W3C (http://www.w3.org/TR/DOM-Level-3-Events/#event-type-keypress)
The keypress event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type. When in editing contexts, authors can subscribe to the beforeinput event instead.
Finally, to answer your question, you should use keyup
or keydown
to detect a backspace across Firefox and Chrome.
Try it out on here:
$(".inputTxt").bind("keypress keyup keydown", function (event) {_x000D_
var evtType = event.type;_x000D_
var eWhich = event.which;_x000D_
var echarCode = event.charCode;_x000D_
var ekeyCode = event.keyCode;_x000D_
_x000D_
switch (evtType) {_x000D_
case 'keypress':_x000D_
$("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<br>");_x000D_
break;_x000D_
case 'keyup':_x000D_
$("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<p>");_x000D_
break;_x000D_
case 'keydown':_x000D_
$("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<br>");_x000D_
break;_x000D_
default:_x000D_
break;_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input class="inputTxt" type="text" />_x000D_
<div id="log"></div>
_x000D_
To redirect everything that doesnt exist to index.php
, you can also use the FallBackResource
directive
FallbackResource /index.php
It works same as the ErrorDocument
, when you request a non-existent path or file on the server, the directive silently forwords the request to index.php
.
If you want to redirect everything (including existant files or folders
) to index.php
, you can use something like the following :
RewriteEngine on
RewriteRule ^((?!index\.php).+)$ /index.php [L]
Note the pattern ^((?!index\.php).+)$
matches any uri except index.php
we have excluded the destination path to prevent infinite looping error.
This has obviously been fixed in newer releases (SE 6 and 7). I experience a 30 second caching time max when running the following code snippet while watching port 53 activity using tcpdump.
/**
* http://stackoverflow.com/questions/1256556/any-way-to-make-java-honor-the-dns-caching-timeout-ttl
*
* Result: Java 6 distributed with Ubuntu 12.04 and Java 7 u15 downloaded from Oracle have
* an expiry time for dns lookups of approx. 30 seconds.
*/
import java.util.*;
import java.text.*;
import java.security.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class Test {
final static String hostname = "www.google.com";
public static void main(String[] args) {
// only required for Java SE 5 and lower:
//Security.setProperty("networkaddress.cache.ttl", "30");
System.out.println(Security.getProperty("networkaddress.cache.ttl"));
System.out.println(System.getProperty("networkaddress.cache.ttl"));
System.out.println(Security.getProperty("networkaddress.cache.negative.ttl"));
System.out.println(System.getProperty("networkaddress.cache.negative.ttl"));
while(true) {
int i = 0;
try {
makeRequest();
InetAddress inetAddress = InetAddress.getLocalHost();
System.out.println(new Date());
inetAddress = InetAddress.getByName(hostname);
displayStuff(hostname, inetAddress);
} catch (UnknownHostException e) {
e.printStackTrace();
}
try {
Thread.sleep(5L*1000L);
} catch(Exception ex) {}
i++;
}
}
public static void displayStuff(String whichHost, InetAddress inetAddress) {
System.out.println("Which Host:" + whichHost);
System.out.println("Canonical Host Name:" + inetAddress.getCanonicalHostName());
System.out.println("Host Name:" + inetAddress.getHostName());
System.out.println("Host Address:" + inetAddress.getHostAddress());
}
public static void makeRequest() {
try {
URL url = new URL("http://"+hostname+"/");
URLConnection conn = url.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
InputStreamReader ird = new InputStreamReader(is);
BufferedReader rd = new BufferedReader(ird);
String res;
while((res = rd.readLine()) != null) {
System.out.println(res);
break;
}
rd.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
OK, got it working with this (creating the UIImageView programmatically):
var imageViewObject :UIImageView
imageViewObject = UIImageView(frame:CGRectMake(0, 0, 600, 600))
imageViewObject.image = UIImage(named:"afternoon")
self.view.addSubview(imageViewObject)
self.view.sendSubviewToBack(imageViewObject)
Starting with PyDev 3.4.1, the default encoding is not being changed anymore. See this ticket for details.
For earlier versions a solution is to make sure PyDev does not run with UTF-8 as the default encoding. Under Eclipse, run dialog settings ("run configurations", if I remember correctly); you can choose the default encoding on the common tab. Change it to US-ASCII if you want to have these errors 'early' (in other words: in your PyDev environment). Also see an original blog post for this workaround.
You can use Hash#reject to remove empty key/value pairs from a ruby Hash.
# Remove empty strings
{ a: 'first', b: '', c: 'third' }.reject { |key,value| value.empty? }
#=> {:a=>"first", :c=>"third"}
# Remove nil
{a: 'first', b: nil, c: 'third'}.reject { |k,v| v.nil? }
# => {:a=>"first", :c=>"third"}
# Remove nil & empty strings
{a: '', b: nil, c: 'third'}.reject { |k,v| v.nil? || v.empty? }
# => {:c=>"third"}
SELECT TOP 14 A, B, C
FROM MyDatabase
Where EXISTS
(
Select Distinct[A] FROM MyDatabase
)
CREATE TABLE #tempww (
LoginName nvarchar(max),
DBname nvarchar(max),
Username nvarchar(max),
AliasName nvarchar(max)
)
INSERT INTO #tempww
EXEC master..sp_msloginmappings
-- display results
declare @col varchar(1000)
declare @sql varchar(2000)
select @col = COALESCE(@col + ', ','') + QUOTENAME(DBname)
from #tempww Group by DBname
Set @sql='select * from (select LoginName,Username,AliasName,DBname,row_number() over(order by (select 0)) rn from #tempww) src
PIVOT (Max(rn) FOR DBname
IN ('+@col+')) pvt'
EXEC(@sql)
-- cleanup
DROP TABLE #tempww
You can do this using Ajax. I have a function that I use for something like this:
function ajax(elementID,filename,str,post)
{
var ajax;
if (window.XMLHttpRequest)
{
ajax=new XMLHttpRequest();//IE7+, Firefox, Chrome, Opera, Safari
}
else if (ActiveXObject("Microsoft.XMLHTTP"))
{
ajax=new ActiveXObject("Microsoft.XMLHTTP");//IE6/5
}
else if (ActiveXObject("Msxml2.XMLHTTP"))
{
ajax=new ActiveXObject("Msxml2.XMLHTTP");//other
}
else
{
alert("Error: Your browser does not support AJAX.");
return false;
}
ajax.onreadystatechange=function()
{
if (ajax.readyState==4&&ajax.status==200)
{
document.getElementById(elementID).innerHTML=ajax.responseText;
}
}
if (post==false)
{
ajax.open("GET",filename+str,true);
ajax.send(null);
}
else
{
ajax.open("POST",filename,true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send(str);
}
return ajax;
}
The first parameter is the element you want to change. The second parameter is the name of the filename you're loading into the element you're changing. The third parameter is the GET or POST data you're using, so for example "total=10000&othernumber=999". The last parameter is true if you want use POST or false if you want to GET.
If you are on OSX and in case the other solutions didn't work for you (just like me).
You can try uninstalling python3 and upgrade pip3
brew uninstall --ignore-dependencies python3
pip3 install --upgrade pip
This worked for me ;)
A bit late but the same question brought me here before reaching the answer so I post it here. Create (if you still don't have it) an application.properties and add
server.contextPath=/api
So in the previous example if you have a RestController with @RequestMapping("/test")
you will access it like localhost:8080/api/test/{your_rest_method}
question source: how do i choose the url for my spring boot webapp
step 1) Declare TextEditingController.
step 2) supply controller to the TextField.
step 3) user controller's text property to change the value of the textField.
follow this official solution to the problem
Ideone supports Python 2.6 and Python 3
I use Goto
For x= 1 to 20
If something then goto continue
skip this code
Continue:
Next x
This thread seems unnecessarily controversial.
If you really want to solve this question correctly, using jQuery, please see the solution below.
The question is "jQuery How do you get an image to fade in on load?"
First, a quick note.
This is not a good candidate for $(document).ready...
Why? Because the document is ready when the HTML DOM is loaded. The logo image will not be ready at this point - it may still be downloading in fact!
So to answer first the general question "jQuery How do you get an image to fade in on load?" - the image in this example has an id="logo" attribute:
$("#logo").bind("load", function () { $(this).fadeIn(); });
This does exactly what the question asks. When the image has loaded, it will fade in. If you change the source of the image, when the new source has loaded, it will fade in.
There is a comment about using window.onload alongside jQuery. This is perfectly possible. It works. It can be done. However, the window.onload event needs a particular bit of care. This is because if you use it more than once, you overwrite your previous events. Example (feel free to try it...).
function SaySomething(words) {
alert(words);
}
window.onload = function () { SaySomething("Hello"); };
window.onload = function () { SaySomething("Everyone"); };
window.onload = function () { SaySomething("Oh!"); };
Of course, you wouldn't have three onload events so close together in your code. You would most likely have a script that does something onload, and then add your window.onload handler to fade in your image - "why has my slide show stopped working!!?" - because of the window.onload problem.
One great feature of jQuery is that when you bind events using jQuery, they ALL get added.
So there you have it - the question has already been marked as answered, but the answer seems to be insufficient based on all the comments. I hope this helps anyone arriving from the world's search engines!
The @ symbol serves 2 purposes in C#:
Firstly, it allows you to use a reserved keyword as a variable like this:
int @int = 15;
The second option lets you specify a string without having to escape any characters. For instance the '\' character is an escape character so typically you would need to do this:
var myString = "c:\\myfolder\\myfile.txt"
alternatively you can do this:
var myString = @"c:\myFolder\myfile.txt"
I just had a similar problem, with the GWT-PlugIn not showing up in the interface. Deleting the eclipse folder did not solve it, GWT was still there! Deleting workspace didn't work! But deleting the .eclipse folder in the home directory did! I'm working under WIndows 7 here, but it should be the same with OSX. But you may have to make the folder visible first. Under linux based system, folders starting with a dot are invisible by default.
This folder was probably the reason I had problems in the first place. If I remember right, I switched from basic Eclipse to EE, but didn't delete this folder.
In my opinion, an uninstall skript would do Eclipse quite good.
While existing answers definitely solve the purpose, if your'e looking to replicate nested directory structure under two different subdirectories, then you can do this
mkdir -p {main,test}/{resources,scala/com/company}
It will create following directory structure under the directory from where it is invoked
+-- main
¦ +-- resources
¦ +-- scala
¦ +-- com
¦ +-- company
+-- test
+-- resources
+-- scala
+-- com
+-- company
The example was taken from this link for creating SBT directory structure
You could even try this expression ^[a-zA-Z\\s]*$
for checking a string with only letters and spaces (nothing else).
For me it worked. Hope it works for you as well.
Or go through this piece of code once:
CharSequence inputStr = expression;
Pattern pattern = Pattern.compile(new String ("^[a-zA-Z\\s]*$"));
Matcher matcher = pattern.matcher(inputStr);
if(matcher.matches())
{
//if pattern matches
}
else
{
//if pattern does not matches
}
Only when using application/json
as the MIME type I have the following (as of November 2011 with the most recent versions of Chrome, Firefox with Firebug):
In many circumstances they are different names for the same thing, but in some contexts they are quite different. So it depends. Terminology is not applied in a totally consistent way across the whole software industry.
For example in the classic sockets API, a non-blocking socket is one that simply returns immediately with a special "would block" error message, whereas a blocking socket would have blocked. You have to use a separate function such as select
or poll
to find out when is a good time to retry.
But asynchronous sockets (as supported by Windows sockets), or the asynchronous IO pattern used in .NET, are more convenient. You call a method to start an operation, and the framework calls you back when it's done. Even here, there are basic differences. Asynchronous Win32 sockets "marshal" their results onto a specific GUI thread by passing Window messages, whereas .NET asynchronous IO is free-threaded (you don't know what thread your callback will be called on).
So they don't always mean the same thing. To distil the socket example, we could say:
You can add hash info in next page url to move browser at specific position(any html element), after page is loaded.
This is can done in this way:
add hash in the url of next_page : example.com#hashkey
$( document ).ready(function() {
##get hash code at next page
var hashcode = window.location.hash;
## move page to any specific position of next page(let that is div with id "hashcode")
$('html,body').animate({scrollTop: $('div#'+hascode).offset().top},'slow');
});
Here is the solution:
d3.select("svg").remove();
This is a remove
function provided by D3.js.
Rotate by 90 degress around 0,0:
x' = -y
y' = x
Rotate by 90 degress around px,py:
x' = -(y - py) + px
y' = (x - px) + py
Our solution, adding some validations to response so we are sure we have a well formed json object in $json variable
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
if (! $result) {
return false;
}
$json = json_decode(utf8_encode($result));
if (empty($json) || json_last_error() !== JSON_ERROR_NONE) {
return false;
}
Bitwise operations, including bit shift, are fundamental to low-level hardware or embedded programming. If you read a specification for a device or even some binary file formats, you will see bytes, words, and dwords, broken up into non-byte aligned bitfields, which contain various values of interest. Accessing these bit-fields for reading/writing is the most common usage.
A simple real example in graphics programming is that a 16-bit pixel is represented as follows:
bit | 15| 14| 13| 12| 11| 10| 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
| Blue | Green | Red |
To get at the green value you would do this:
#define GREEN_MASK 0x7E0
#define GREEN_OFFSET 5
// Read green
uint16_t green = (pixel & GREEN_MASK) >> GREEN_OFFSET;
Explanation
In order to obtain the value of green ONLY, which starts at offset 5 and ends at 10 (i.e. 6-bits long), you need to use a (bit) mask, which when applied against the entire 16-bit pixel, will yield only the bits we are interested in.
#define GREEN_MASK 0x7E0
The appropriate mask is 0x7E0 which in binary is 0000011111100000 (which is 2016 in decimal).
uint16_t green = (pixel & GREEN_MASK) ...;
To apply a mask, you use the AND operator (&).
uint16_t green = (pixel & GREEN_MASK) >> GREEN_OFFSET;
After applying the mask, you'll end up with a 16-bit number which is really just a 11-bit number since its MSB is in the 11th bit. Green is actually only 6-bits long, so we need to scale it down using a right shift (11 - 6 = 5), hence the use of 5 as offset (#define GREEN_OFFSET 5
).
Also common is using bit shifts for fast multiplication and division by powers of 2:
i <<= x; // i *= 2^x;
i >>= y; // i /= 2^y;
There is no need to add a listener to the ?android:attr/ratingBarStyleSmall
. Just add
android:isIndicator=false
and it will capture click events, e.g.
<RatingBar
android:id="@+id/myRatingBar"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="5"
android:isIndicator="false" />
You can use CountIf
. Put the following code in B1 and drag down the whole column
=COUNTIF(A:A,A1)
It will look like this:
Go to properties of your project ( with Alt+Enter or righ-click )
check on Apache Tomcat v7.0 under Targeted Runtime and it works.
The simple one I used to do is
str.contains(" ") ? str.split(" ")[0] : str
Where str
is your string or text bla bla :). So, if
str
is having empty value it returns as it is.str
is having one word, it returns as it is.str
is multiple words, it extract the first word and return.Hope this is helpful.
You can configure the Async thread executor for your Springboot REST services. The setKeepAliveSeconds() should consider the execution time for the requests chain. Set the ThreadPoolExecutor's keep-alive seconds. Default is 60. This setting can be modified at runtime, for example through JMX.
@Bean(name="asyncExec")
public Executor asyncExecutor()
{
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(3);
executor.setMaxPoolSize(3);
executor.setQueueCapacity(10);
executor.setThreadNamePrefix("AsynchThread-");
executor.setAllowCoreThreadTimeOut(true);
executor.setKeepAliveSeconds(10);
executor.initialize();
return executor;
}
Then you can define your REST endpoint as follows
@Async("asyncExec")
@PostMapping("/delayedService")
public CompletableFuture<String> doDelay()
{
String response = service.callDelayedService();
return CompletableFuture.completedFuture(response);
}
I know, I am a little late to the party ... what happen a lot, you just use default settings in your app pool in IIS. In IIS Administration utility, go to app pools->select pool-->advanced settings->Process Model/Identity
and select a user identity which has right permissions. By default it is set to ApplicationPoolIdentity
. If you're developer, you most likely admin on your machine, so you can select your account to run app pool. On the deployment servers, let admins to deal with it.
Passing HTMLInputElement as a generic to the event type should work too:
onUpdatingServerName(event: React.ChangeEvent<HTMLInputElement>) {
console.log(event);
this.newserverName = event.target.value;
}
Similar Question Here
Finalizers in Java are bad. They add a lot of overhead to garbage collection. Avoid them whenever possible.
The shutdownHook will only get called when the VM is shutting down. I think it very well may do what you want.
Hope it might help someone instantly.
In Python 2.7: By default, division operator will return integer output.
to get the result in double multiple 1.0 to "dividend or divisor"
100/35 => 2 #(Expected is 2.857142857142857)
(100*1.0)/35 => 2.857142857142857
100/(35*1.0) => 2.857142857142857
In Python 3
// => used for integer output
/ => used for double output
100/35 => 2.857142857142857
100//35 => 2
100.//35 => 2.0 # floating-point result if divsor or dividend real
If the mouse over for all over the component is your option, you can directly is @hostListener
to handle the events to perform the mouse over al below.
import {HostListener} from '@angular/core';
@HostListener('mouseenter') onMouseEnter() {
this.hover = true;
this.elementRef.nativeElement.addClass = 'edit';
}
@HostListener('mouseleave') onMouseLeave() {
this.hover = false;
this.elementRef.nativeElement.addClass = 'un-edit';
}
Its available in @angular/core
. I tested it in angular 4.x.x
Here's a solution using jQuery:
<script type="text/javascript">
$('#container').css('opacity', 0);
$(window).load(function() {
$('#container').css('opacity', 1);
});
</script>
I put this script just after my </body>
tag. Just replace "#container" with a selector for the DOM element(s) you want to hide. I tried several variations of this (including .hide()
/.show()
, and .fadeOut()
/.fadeIn()
), and just setting the opacity seems to have the fewest ill effects (flicker, changing page height, etc.). You can also replace css('opacity', 0)
with fadeTo(100, 1)
for a smoother transition. (No, fadeIn()
won't work, at least not under jQuery 1.3.2.)
Now the caveats: I implemented the above because I'm using TypeKit and there's an annoying flicker when you refresh the page and the fonts take a few hundred milliseconds to load. So I don't want any text to appear on the screen until TypeKit has loaded. But obviously you're in big trouble if you use the code above and something on your page fails to load. There are two obvious ways that it could be improved:
I won't bother implementing the loading indicator here, but the time limit is easy. Just add this to the script above:
$(document).ready(function() {
setTimeout('$("#container").css("opacity", 1)', 1000);
});
So now, worst-case scenario, your page will take an extra second to appear.
I think the $() syntax is easier to read...
variable=$(ps -ef | grep "port 10 -" | grep -v "grep port 10 -"| awk '{printf "%s", $12}')
But the real issue is probably that $12
should not be qouted with ""
Edited since the question was changed, This returns valid data, but it is not clear what the expected output of ps -ef
is and what is expected in variable.
almost all the solutions above doesn't work with git version 2
mine : git version = 2.28.0
solution of the difftool : git config --global diff.tool vimdiff
after it you can use it without any problems
https://www.npmjs.com/package/babel-register
// This is to allow ES6 export syntax
// to be properly read and processed by node.js application
require('babel-register')({
presets: [
'env',
],
});
// After that, any line you add below that has typical ES6 export syntax
// will work just fine
const utils = require('../../utils.js');
const availableMixins = require('../../../src/lib/mixins/index.js');
export { default as FormValidationMixin } from './form-validation'; // eslint-disable-line import/prefer-default-export
That worked just fine inside my Node.js CLI application.
session_start();
if(isset($_SESSION['current'])){
$_SESSION['oldlink']=$_SESSION['current'];
}else{
$_SESSION['oldlink']='no previous page';
}
$_SESSION['current']=$_SERVER['PHP_SELF'];
Maybe this is what you're looking for? It will remember the old link/page you're coming from (within your website).
Put that piece on top of each page.
If you want to make it 'refresh proof' you can add another check:
if(isset($_SESSION['current']) && $_SESSION['current']!=$_SERVER['PHP_SELF'])
This will make the page not remember itself.
UPDATE: Almost the same as @Brandon though... Just use a php variable, I know this looks like a security risk, but when done correct it isn't.
<a href="home.php?a=register">Register Now!</a>
PHP:
if(isset($_GET['a']) /*you can validate the link here*/){
$_SESSION['link']=$_GET['a'];
}
Why even store the GET in a session? Just use it. Please tell me why you do not want to use GET. « Validate for more security. I maybe can help you with a better script.
Use getDeclaredMethod()
to get a private Method object and then use method.setAccessible()
to allow to actually call it.
I would use du
's --threshold
for this. Not sure if this option is available in all versions of du
but it is implemented in GNU's version.
Quoting from du(1)'s manual:
-t, --threshold=SIZE
exclude entries smaller than SIZE if positive, or entries greater
than SIZE if negative
Here's my solution, using du --threshold=
for OP's use case:
THRESHOLD=90k
if [[ -z "$(du --threshold=${THRESHOLD} file.txt)" ]]; then
mail -s "file.txt size is below ${THRESHOLD}, please fix. " [email protected] < /dev/null
mv -f /root/tmp/file.txt /var/www/file.txt
fi
The advantage of that, is that du
can accept an argument to that option in a known format - either human as in 10K
, 10MiB
or what ever you feel comfortable with - you don't need to manually convert between formats / units since du
handles that.
For reference, here's the explanation on this SIZE
argument from the man page:
The SIZE argument is an integer and optional unit (example: 10K is
10*1024). Units are K,M,G,T,P,E,Z,Y (powers of 1024) or KB,MB,... (powers
of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on.
Change the environment variable RAILS_ENV
to production
.
removing temp files, and did you restart the computer or stop the MySQL service? That's the error message you get when there isn't a MySQL server running.
Give this a try.
The code
new DatePickerDialog(MainActivity.this, R.style.DialogTheme, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//DO SOMETHING
}
}, 2015, 02, 26).show();
The Style In your styles.xml file
EDIT - Changed theme to Theme.AppCompat.Light.Dialog as suggested
<style name="DialogTheme" parent="Theme.AppCompat.Light.Dialog">
<item name="colorAccent">@color/blue_500</item>
</style>
Simply turn the array into a hash:
my %params = map { $_ => 1 } @badparams;
if(exists($params{$someparam})) { ... }
You can also add more (unique) params to the list:
$params{$newparam} = 1;
And later get a list of (unique) params back:
@badparams = keys %params;
In php its as easy as:
$pdo = new PDO('mysql:dbname=YOURDB', 'root', 'root');
$pdo->exec('SET FOREIGN_KEY_CHECKS = 0');
$query = "SELECT concat('DROP TABLE IF EXISTS ', table_name, ';')
FROM information_schema.tables
WHERE table_schema = 'YOURDB'";
foreach($pdo->query($query) as $row) {
$pdo->exec($row[0]);
}
$pdo->exec('SET FOREIGN_KEY_CHECKS = 1');
Just remember to change YOURDB to the name of your database, and obviously the user/pass.
Loading jQuery library before Angularjs library helped me.
<head>_x000D_
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>_x000D_
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>_x000D_
</head>
_x000D_
Suppose you have these buttons on page like :
<input type="submit" class="byBtn" disabled="disabled" value="Change"/>
<input type="submit" class="byBtn" disabled="disabled" value="Change"/>
<input type="submit" class="byBtn" disabled="disabled" value="Change"/>
<input type="submit" class="byBtn" disabled="disabled" value="Change"/>
<input type="submit" class="byBtn" disabled="disabled" value="Change"/>
<input type="submit"value="Enable All" onclick="change()"/>
The js code:
function change(){
var toenable = document.querySelectorAll(".byBtn");
for (var k in toenable){
toenable[k].removeAttribute("disabled");
}
}
There are two solutions to this:
a) Set your PATH variable to include "/usr/local/bin"
export PATH="$PATH:/usr/local/bin"
b) Create a symlink to "/usr/bin" which is already in your PATH
ln -s /usr/bin/nodejs /usr/bin/node
I hope it helps.
Why not just use a step parameter of range function as well to get:
l = range(0, 1000, 10)
For comparison, on my machine:
H:\>python -m timeit -s "l = range(1000)" "l1 = [x for x in l if x % 10 == 0]"
10000 loops, best of 3: 90.8 usec per loop
H:\>python -m timeit -s "l = range(1000)" "l1 = l[0::10]"
1000000 loops, best of 3: 0.861 usec per loop
H:\>python -m timeit -s "l = range(0, 1000, 10)"
100000000 loops, best of 3: 0.0172 usec per loop
Homework question? Well you can modify your original 'right triangle' code to generate an inverted 'right triangle' with spaces So that'll be like
for(i=0; i<6; i++)
{
for(j=6; j>=(6-i); j--)
{
print(" ");
}
for(x=0; x<=((2*i)+1); x++)
{
print("*");
}
print("\n");
}
Reference Resolution is described by RFC 3986 Uniform Resource Identifier (URI): Generic Syntax. And that is exactly how it supposed to work. To preserve base URI path you need to add slash at the end of the base URI and remove slash at the beginning of relative URI.
If base URI contains non-empty path, merge procedure discards it's last part (after last /
). Relevant section:
5.2.3. Merge Paths
The pseudocode above refers to a "merge" routine for merging a relative-path reference with the path of the base URI. This is accomplished as follows:
If the base URI has a defined authority component and an empty path, then return a string consisting of "/" concatenated with the reference's path; otherwise
return a string consisting of the reference's path component appended to all but the last segment of the base URI's path (i.e., excluding any characters after the right-most "/" in the base URI path, or excluding the entire base URI path if it does not contain any "/" characters).
If relative URI starts with a slash, it is called a absolute-path relative URI. In this case merge procedure ignore all base URI path. For more information check 5.2.2. Transform References section.
The default iterator for the JObject is as a dictionary iterating over key/value pairs.
JObject obj = JObject.Parse(response);
foreach (var pair in obj) {
Console.WriteLine (pair.Key);
}
You can just add '\r' at the end of the string plus a comma at the end of print function. For example:
print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!\r'),
In Bash you can do it by enabling the extglob
option, like this (replace ls
with cp
and add the target directory, of course)
~/foobar> shopt extglob
extglob off
~/foobar> ls
abar afoo bbar bfoo
~/foobar> ls !(b*)
-bash: !: event not found
~/foobar> shopt -s extglob # Enables extglob
~/foobar> ls !(b*)
abar afoo
~/foobar> ls !(a*)
bbar bfoo
~/foobar> ls !(*foo)
abar bbar
You can later disable extglob with
shopt -u extglob
I think you should be using "local storage" rather than global variables.
If you are concerned that "local storage" may not be supported in very old browsers, consider using an existing plug-in which checks the availability of "local storage" and uses other methods if it isn't available.
I used http://www.jstorage.info/ and I'm happy with it so far.
From Django documentation for url
url(regex, view, kwargs=None, name=None)
This function is an alias todjango.urls.re_path()
. It’s likely to be deprecated in a future release.
Key difference between path
and re_path
is that path
uses route without regex
You can use re_path
for complex regex calls and use just path
for simpler lookups
This worked for me...
If you are using windows...
Search 'cmd' in the windows search bar.
Enter this:C:\xampp\apache\bin\httpd.exe
Find which file and which line the error occurred.
For example, mine was in the file below on line 37.
httpd-multilang-errordoc.conf
Open the code and fix the error by either removing the line or fixing it.
Done! I should work now.
:)
Refer the react-native official documentation on Generating Signed APK
If you don't care about case, then you perhaps it doesn't matter if it returns all upcase:
target.toUpperCase().replace("FOO", "");
Using find
:
find . -maxdepth 1 -type f
Using the -maxdepth 1
option ensures that you only look in the current directory (or, if you replace the .
with some path, that directory). If you want a full recursive listing of all files in that and subdirectories, just remove that option.
Use the property TextWrapping
of the TextBlock
element:
<TextBlock Text="StackOverflow Forum"
Width="100"
TextWrapping="WrapWithOverflow"/>
The checked answer from balexandre works great. But, it will create a problem if adapted to some other situations.
I used it to change the value of two label controls - lblEditModifiedBy
and lblEditModifiedOn
- when I was editing a row, so that the correct ModifiedBy and ModifiedOn
would be saved to the db on 'Update'.
When I clicked the 'Update' button, in the RowUpdating
event it showed the new values I entered in the OldValues
list. I needed the true "old values" as Original_ values when updating the database. (There's an ObjectDataSource
attached to the GridView
.)
The fix to this is using balexandre's code, but in a modified form in the gv_DataBound
event:
protected void gv_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow gvr in gv.Rows)
{
if (gvr.RowType == DataControlRowType.DataRow && (gvr.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
// Here you will get the Control you need like:
((Label)gvr.FindControl("lblEditModifiedBy")).Text = Page.User.Identity.Name;
((Label)gvr.FindControl("lblEditModifiedOn")).Text = DateTime.Now.ToString();
}
}
}
Add the column and update all rows in the DataTable
, for example:
DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("Name", typeof(string)));
for (Int32 i = 1; i <= 10; i++) {
DataRow row = tbl.NewRow();
row["ID"] = i;
row["Name"] = i + ". row";
tbl.Rows.Add(row);
}
DataColumn newCol = new DataColumn("NewColumn", typeof(string));
newCol.AllowDBNull = true;
tbl.Columns.Add(newCol);
foreach (DataRow row in tbl.Rows) {
row["NewColumn"] = "You DropDownList value";
}
//if you don't want to allow null-values'
newCol.AllowDBNull = false;
Here's my example crontab I always use as a template:
# Use the hash sign to prefix a comment
# +---------------- minute (0 - 59)
# | +------------- hour (0 - 23)
# | | +---------- day of month (1 - 31)
# | | | +------- month (1 - 12)
# | | | | +---- day of week (0 - 7) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
#--------------------------------------------------------------------------
To run my cron job every Monday, Wednesady and Friday at 7:00PM, the result will be:
0 19 * * 1,3,5 nohup /home/lathonez/script.sh > /tmp/script.log 2>&1
Also, take a look at FrameLayout
, that's how the Camera's Gallery application implements the Zoom buttons overlay.
In Python, a method is a function that is available for a given object because of the object's type.
For example, if you create my_list = [1, 2, 3]
, the append
method can be applied to my_list
because it's a Python list: my_list.append(4)
. All lists have an append
method simply because they are lists.
As another example, if you create my_string = 'some lowercase text'
, the upper
method can be applied to my_string
simply because it's a Python string: my_string.upper()
.
Lists don't have an upper
method, and strings don't have an append
method. Why? Because methods only exist for a particular object if they have been explicitly defined for that type of object, and Python's developers have (so far) decided that those particular methods are not needed for those particular objects.
To call a method, the format is object_name.method_name()
, and any arguments to the method are listed within the parentheses. The method implicitly acts on the object being named, and thus some methods don't have any stated arguments since the object itself is the only necessary argument. For example, my_string.upper()
doesn't have any listed arguments because the only required argument is the object itself, my_string
.
One common point of confusion regards the following:
import math
math.sqrt(81)
Is sqrt
a method of the math
object? No. This is how you call the sqrt
function from the math
module. The format being used is module_name.function_name()
, instead of object_name.method_name()
. In general, the only way to distinguish between the two formats (visually) is to look in the rest of the code and see if the part before the period (math
, my_list
, my_string
) is defined as an object or a module.
Its not the Excel. Windows does recognize the formula, the data as a date and autocorrects. You have to change the Windows settings.
"Control Panel" (-> "Switch to Classic View") -> "Regional and Language Options" -> tab "Regional Options" -> "Customize..." -> tab "Numbers" -> And then change the symbols according to what you want.
http://www.pcreview.co.uk/forums/enable-disable-auto-convert-number-date-t3791902.html
It will work on your computer, if these settings are not changed for example on your customers' computer they will see dates instead of data.
You can build a string sprintf-style using String.format().
String w = "world";
String s = String.format("Hello %s %d", w, 3);
You can of course also use special specifiers to modify the output.
More here: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax
If it helps anyone, I tried everything above (https w/token mode) - and still nothing was working. I got no errors, but nothing would be installed in node_modules or package_lock.json. If I changed the token or any letter in the repo name or user name, etc. - I'd get an error. So I knew I had the right token and repo name.
I finally realized it's because the name of the dependency I had in my package.json didn't match the name in the package.json of the repo I was trying to pull. Even npm install --verbose doesn't say there's any problem. It just seems to ignore the dependency w/o error.
You can also use common table expressions to store temporary datasets. They are more elegant and adhoc friendly:
WITH userData (name, oldlocation)
AS
(
SELECT name, location
FROM myTable INNER JOIN
otherTable ON ...
WHERE age>30
)
SELECT *
FROM userData -- you can also reuse the recordset in subqueries and joins
You can try @Rule
annotation. Here is the example from the docs:
public static class UsesExternalResource {
Server myServer = new Server();
@Rule public ExternalResource resource = new ExternalResource() {
@Override
protected void before() throws Throwable {
myServer.connect();
};
@Override
protected void after() {
myServer.disconnect();
};
};
@Test public void testFoo() {
new Client().run(myServer);
}
}
You just need to create FileResource
class extending ExternalResource
.
Full Example
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
public class TestSomething
{
@Rule
public ResourceFile res = new ResourceFile("/res.txt");
@Test
public void test() throws Exception
{
assertTrue(res.getContent().length() > 0);
assertTrue(res.getFile().exists());
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import org.junit.rules.ExternalResource;
public class ResourceFile extends ExternalResource
{
String res;
File file = null;
InputStream stream;
public ResourceFile(String res)
{
this.res = res;
}
public File getFile() throws IOException
{
if (file == null)
{
createFile();
}
return file;
}
public InputStream getInputStream()
{
return stream;
}
public InputStream createInputStream()
{
return getClass().getResourceAsStream(res);
}
public String getContent() throws IOException
{
return getContent("utf-8");
}
public String getContent(String charSet) throws IOException
{
InputStreamReader reader = new InputStreamReader(createInputStream(),
Charset.forName(charSet));
char[] tmp = new char[4096];
StringBuilder b = new StringBuilder();
try
{
while (true)
{
int len = reader.read(tmp);
if (len < 0)
{
break;
}
b.append(tmp, 0, len);
}
reader.close();
}
finally
{
reader.close();
}
return b.toString();
}
@Override
protected void before() throws Throwable
{
super.before();
stream = getClass().getResourceAsStream(res);
}
@Override
protected void after()
{
try
{
stream.close();
}
catch (IOException e)
{
// ignore
}
if (file != null)
{
file.delete();
}
super.after();
}
private void createFile() throws IOException
{
file = new File(".",res);
InputStream stream = getClass().getResourceAsStream(res);
try
{
file.createNewFile();
FileOutputStream ostream = null;
try
{
ostream = new FileOutputStream(file);
byte[] buffer = new byte[4096];
while (true)
{
int len = stream.read(buffer);
if (len < 0)
{
break;
}
ostream.write(buffer, 0, len);
}
}
finally
{
if (ostream != null)
{
ostream.close();
}
}
}
finally
{
stream.close();
}
}
}
It depends on the context.
final
class or method, the C# equivalent is sealed
.final
field, the C# equivalent is readonly
.final
local variable or method parameter, there's no direct C# equivalent.list.count(x)
returns the number of times x
appears in a list
see: http://docs.python.org/tutorial/datastructures.html#more-on-lists
Try this, its working in FF
body,
input,
select,
button {
font-family: Arial,Helvetica,sans-serif;
font-size: 14px;
}
Do dtEmp
on your current working DataTable:
DataTable distinctTable = dtEmp.DefaultView.ToTable( /*distinct*/ true);
It's nice.
I know this is old, but for local dev, this is what got things back to a production .env file:
rm bootstrap/cache/config.php
then
php artisan config:cache
php artisan config:clear
php artisan cache:clear
public String getIMEI(Context context){
TelephonyManager mngr = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
String imei = mngr.getDeviceId();
return imei;
}
namespace: modules are namespaces...which don't exist in java ;)
I also switched from Java and python to Ruby, I remember had exactly this same question...
So the simplest answer is that module is a namespace, which doesn't exist in Java. In java the closest mindset to namespace is a package.
So a module in ruby is like what in java:
class? No
interface? No
abstract class? No
package? Yes (maybe)
static methods inside classes in java: same as methods inside modules in ruby
In java the minimum unit is a class, you can't have a function outside of a class. However in ruby this is possible (like python).
So what goes into a module?
classes, methods, constants. Module protects them under that namespace.
No instance: modules can't be used to create instances
Mixed ins: sometimes inheritance models are not good for classes, but in terms of functionality want to group a set of classes/ methods/ constants together
Rules about modules in ruby:
- Module names are UpperCamelCase
- constants within modules are ALL CAPS (this rule is the same for all ruby constants, not specific to modules)
- access methods: use . operator
- access constants: use :: symbol
simple example of a module:
module MySampleModule
CONST1 = "some constant"
def self.method_one(arg1)
arg1 + 2
end
end
how to use methods inside a module:
puts MySampleModule.method_one(1) # prints: 3
how to use constants of a module:
puts MySampleModule::CONST1 # prints: some constant
Some other conventions about modules:
Use one module in a file (like ruby classes, one class per ruby file)
If you just need a very simple call, you can use URL directly:
import java.net.URL;
new URL("http://wheredatapp.com").openStream();
Try to put in the head section of your html the following:
<meta charset='utf-8'>
I think this need to be the fist in head section. More information about charset: Meta Charset
Run
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
Then run the following command in the folder where you downloaded: get-pip.py
python get-pip.py
In Java, the optimizations are usually done at the JVM level. At runtime, the JVM perform some "complicated" analysis to determine which methods to inline. It can be aggressive in inlining, and the Hotspot JVM actually can inline non-final methods.
The java compilers almost never inline any method call (the JVM does all of that at runtime). They do inline compile time constants (e.g. final static primitive values). But not methods.
For more resources:
Article: The Java HotSpot Performance Engine: Method Inlining Example
Wiki: Inlining in OpenJDK, not fully populated but contains links to useful discussions.
Try this test:
any(substring in string for substring in substring_list)
It will return True
if any of the substrings in substring_list
is contained in string
.
Note that there is a Python analogue of Marc Gravell's answer in the linked question:
from itertools import imap
any(imap(string.__contains__, substring_list))
In Python 3, you can use map
directly instead:
any(map(string.__contains__, substring_list))
Probably the above version using a generator expression is more clear though.
Updated! 3/24/2015 (scroll below hr)
lonesomeday's answer is absolutely correct, I just thought I would add this tidbit. I had made a method a while back for getting browser in Vanilla JS and eventually curved it to replace jQuery.browser
in later versions of jQuery. It does not interfere with any part of the new jQuery lib, but provides the same functionality of the traditional jQuery.browser
object, as well as some other little features.
New Extended Version!
Is much more thorough for newer browser. Also, 90+% accuracy on mobile testing! I won't say 100%, as I haven't tested on every mobile browser, but new feature adds $.browser.mobile
boolean/string. It's false if not mobile, else it will be a String name for the mobile device or browser (Best Guesss like: Android, RIM Tablet, iPod, etc...).
One possible caveat, may not work with some older (unsupported) browsers as it is completely reliant on userAgent
string.
/* quick & easy cut & paste */
;;(function($){if(!$.browser&&1.9<=parseFloat($.fn.jquery)){var a={browser:void 0,version:void 0,mobile:!1};navigator&&navigator.userAgent&&(a.ua=navigator.userAgent,a.webkit=/WebKit/i.test(a.ua),a.browserArray="MSIE Chrome Opera Kindle Silk BlackBerry PlayBook Android Safari Mozilla Nokia".split(" "),/Sony[^ ]*/i.test(a.ua)?a.mobile="Sony":/RIM Tablet/i.test(a.ua)?a.mobile="RIM Tablet":/BlackBerry/i.test(a.ua)?a.mobile="BlackBerry":/iPhone/i.test(a.ua)?a.mobile="iPhone":/iPad/i.test(a.ua)?a.mobile="iPad":/iPod/i.test(a.ua)?a.mobile="iPod":/Opera Mini/i.test(a.ua)?a.mobile="Opera Mini":/IEMobile/i.test(a.ua)?a.mobile="IEMobile":/BB[0-9]{1,}; Touch/i.test(a.ua)?a.mobile="BlackBerry":/Nokia/i.test(a.ua)?a.mobile="Nokia":/Android/i.test(a.ua)&&(a.mobile="Android"),/MSIE|Trident/i.test(a.ua)?(a.browser="MSIE",a.version=/MSIE/i.test(navigator.userAgent)&&0<parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,""))?parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,"")):"Edge",/Trident/i.test(a.ua)&&/rv:([0-9]{1,}[\.0-9]{0,})/.test(a.ua)&&(a.version=parseFloat(a.ua.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].replace(/[^0-9\.]/g,"")))):/Chrome/.test(a.ua)?(a.browser="Chrome",a.version=parseFloat(a.ua.split("Chrome/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Opera/.test(a.ua)?(a.browser="Opera",a.version=parseFloat(a.ua.split("Version/")[1].replace(/[^0-9\.]/g,""))):/Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(a.ua)?(a.mobile="Kindle",/Silk/i.test(a.ua)?(a.browser="Silk",a.version=parseFloat(a.ua.split("Silk/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Kindle/i.test(a.ua)&&/Version/i.test(a.ua)&&(a.browser="Kindle",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,"")))):/BlackBerry/.test(a.ua)?(a.browser="BlackBerry",a.version=parseFloat(a.ua.split("/")[1].replace(/[^0-9\.]/g,""))):/PlayBook/.test(a.ua)?(a.browser="PlayBook",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/BB[0-9]{1,}; Touch/.test(a.ua)?(a.browser="Blackberry",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Android/.test(a.ua)?(a.browser="Android",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Safari/.test(a.ua)?(a.browser="Safari",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Firefox/.test(a.ua)?(a.browser="Mozilla",a.version=parseFloat(a.ua.split("Firefox/")[1].replace(/[^0-9\.]/g,""))):/Nokia/.test(a.ua)&&(a.browser="Nokia",a.version=parseFloat(a.ua.split("Browser")[1].replace(/[^0-9\.]/g,""))));if(a.browser)for(var b in a.browserArray)a[a.browserArray[b].toLowerCase()]=a.browser==a.browserArray[b];$.extend(!0,$.browser={},a)}})(jQuery);
/* quick & easy cut & paste */
jsFiddle "jQuery Plugin: Get Browser (Extended Alt Edition)"
/** jQuery.browser_x000D_
* @author J.D. McKinstry (2014)_x000D_
* @description Made to replicate older jQuery.browser command in jQuery versions 1.9+_x000D_
* @see http://jsfiddle.net/SpYk3/wsqfbe4s/_x000D_
*_x000D_
* @extends jQuery_x000D_
* @namespace jQuery.browser_x000D_
* @example jQuery.browser.browser == 'browserNameInLowerCase'_x000D_
* @example jQuery.browser.version_x000D_
* @example jQuery.browser.mobile @returns BOOLEAN_x000D_
* @example jQuery.browser['browserNameInLowerCase']_x000D_
* @example jQuery.browser.chrome @returns BOOLEAN_x000D_
* @example jQuery.browser.safari @returns BOOLEAN_x000D_
* @example jQuery.browser.opera @returns BOOLEAN_x000D_
* @example jQuery.browser.msie @returns BOOLEAN_x000D_
* @example jQuery.browser.mozilla @returns BOOLEAN_x000D_
* @example jQuery.browser.webkit @returns BOOLEAN_x000D_
* @example jQuery.browser.ua @returns navigator.userAgent String_x000D_
*/_x000D_
;;(function($){if(!$.browser&&1.9<=parseFloat($.fn.jquery)){var a={browser:void 0,version:void 0,mobile:!1};navigator&&navigator.userAgent&&(a.ua=navigator.userAgent,a.webkit=/WebKit/i.test(a.ua),a.browserArray="MSIE Chrome Opera Kindle Silk BlackBerry PlayBook Android Safari Mozilla Nokia".split(" "),/Sony[^ ]*/i.test(a.ua)?a.mobile="Sony":/RIM Tablet/i.test(a.ua)?a.mobile="RIM Tablet":/BlackBerry/i.test(a.ua)?a.mobile="BlackBerry":/iPhone/i.test(a.ua)?a.mobile="iPhone":/iPad/i.test(a.ua)?a.mobile="iPad":/iPod/i.test(a.ua)?a.mobile="iPod":/Opera Mini/i.test(a.ua)?a.mobile="Opera Mini":/IEMobile/i.test(a.ua)?a.mobile="IEMobile":/BB[0-9]{1,}; Touch/i.test(a.ua)?a.mobile="BlackBerry":/Nokia/i.test(a.ua)?a.mobile="Nokia":/Android/i.test(a.ua)&&(a.mobile="Android"),/MSIE|Trident/i.test(a.ua)?(a.browser="MSIE",a.version=/MSIE/i.test(navigator.userAgent)&&0<parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,""))?parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,"")):"Edge",/Trident/i.test(a.ua)&&/rv:([0-9]{1,}[\.0-9]{0,})/.test(a.ua)&&(a.version=parseFloat(a.ua.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].replace(/[^0-9\.]/g,"")))):/Chrome/.test(a.ua)?(a.browser="Chrome",a.version=parseFloat(a.ua.split("Chrome/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Opera/.test(a.ua)?(a.browser="Opera",a.version=parseFloat(a.ua.split("Version/")[1].replace(/[^0-9\.]/g,""))):/Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(a.ua)?(a.mobile="Kindle",/Silk/i.test(a.ua)?(a.browser="Silk",a.version=parseFloat(a.ua.split("Silk/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Kindle/i.test(a.ua)&&/Version/i.test(a.ua)&&(a.browser="Kindle",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,"")))):/BlackBerry/.test(a.ua)?(a.browser="BlackBerry",a.version=parseFloat(a.ua.split("/")[1].replace(/[^0-9\.]/g,""))):/PlayBook/.test(a.ua)?(a.browser="PlayBook",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/BB[0-9]{1,}; Touch/.test(a.ua)?(a.browser="Blackberry",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Android/.test(a.ua)?(a.browser="Android",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Safari/.test(a.ua)?(a.browser="Safari",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Firefox/.test(a.ua)?(a.browser="Mozilla",a.version=parseFloat(a.ua.split("Firefox/")[1].replace(/[^0-9\.]/g,""))):/Nokia/.test(a.ua)&&(a.browser="Nokia",a.version=parseFloat(a.ua.split("Browser")[1].replace(/[^0-9\.]/g,""))));if(a.browser)for(var b in a.browserArray)a[a.browserArray[b].toLowerCase()]=a.browser==a.browserArray[b];$.extend(!0,$.browser={},a)}})(jQuery);_x000D_
/* - - - - - - - - - - - - - - - - - - - */_x000D_
_x000D_
var b = $.browser;_x000D_
console.log($.browser); // see console, working example of jQuery Plugin_x000D_
console.log($.browser.chrome);_x000D_
_x000D_
for (var x in b) {_x000D_
if (x != 'init')_x000D_
$('<tr />').append(_x000D_
$('<th />', { text: x }),_x000D_
$('<td />', { text: b[x] })_x000D_
).appendTo($('table'));_x000D_
}
_x000D_
table { border-collapse: collapse; }_x000D_
th, td { border: 1px solid; padding: .25em .5em; vertical-align: top; }_x000D_
th { text-align: right; }_x000D_
_x000D_
textarea { height: 500px; width: 100%; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<table></table>
_x000D_
the for loop of for(Map.Entry entry: codes.entrySet()
) didn't work for me. Used Iterator instead.
Iterator<Map.Entry<String, String>> i = codes.entrySet().iterator();
while(i.hasNext()){
String key = i.next().getKey();
System.out.println(key+", "+codes.get(key));
}
There's a little Bash script called create-dmg that builds fancy DMGs with custom backgrounds, custom icon positioning and volume name.
I've built it many years ago for the company that I ran at the time; it survives on other people's contribution since then, and reportedly works well.
There's also node-appdmg which looks like a more modern and active effort based on Node.js; check it out as well.
In powershell:
Get-Content file1.txt | Out-File out.txt
Get-Content file2.txt | Select-Object -Skip 1 | Out-File -Append out.txt
Take a Look at this Bundle for Laravel that I Made Recently !
src/googlemap.php
Pls Read the readme file first and don't forget to pass different ID if you want to have multiple Maps in one page
MAKE sure you have thymleaf on page already
//Use this in java
@Controller
@RequestMapping("/showingTymleafTextInJavaScript")
public String thankYou(Model model){
model.addAttribute("showTextFromJavaController","dummy text");
return "showingTymleafTextInJavaScript";
}
//thymleaf page javascript page
<script>
var showtext = "[[${showTextFromJavaController}]]";
console.log(showtext);
</script>
On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.
BTW: The correct way to do this is to use TryGetValue
obj item;
if(!dict.TryGetValue(name, out item))
return null;
return item;
This accesses the dictionary only once instead of twice.
If you really want to just return null
if the key doesn't exist, the above code can be simplified further:
obj item;
dict.TryGetValue(name, out item);
return item;
This works, because TryGetValue
sets item
to null
if no key with name
exists.
You need to use -I
with each directory. But you can still delimit the directories with whitespace if you use (GNU) make's foreach
:
INC=$(DIR1) $(DIR2) ...
INC_PARAMS=$(foreach d, $(INC), -I$d)
Here's a function to pretty up your json: pretty_json
You shouldn't have to set height: 100%
at any point if you want your container to fill the page. Chances are, your problem is rooted in the fact that you haven't cleared the floats in the container's children. There are quite a few ways to solve this problem, mainly adding overflow: hidden
to the container.
#container { overflow: hidden; }
Should be enough to solve whatever height problem you're having.
I have found that using jQuery the best solution is
$(this.form).submit()
Using this statement jquery plugins (e.g. jquery form plugin) works correctly and jquery DOM traversing overhead is minimized.
I think, from my own experience on problems with more advanced data structures, that the most important thing you can do here, is to get a good knowledge on the general concept of tress as data structures. If you understand the basic mechanism behind the concept it will be quite easy to implement the solution that fits your problem. There are a lot of good sources out there describing the concept. What "saved" me years ago on this particular problem was section 2.3 in "The Art of Computer Programming".
Don't take someones word for it, look at the dissassembly for both C and your language-of-choice in any performance critical part of your code. I think you can just look in the disassembly window at runtime in Visual Studio to see disassembled .Net. Should be possible if tricky for Java using windbg, though if you do it with .Net many of the issues would be the same.
I don't like to write in C if I don't need to, but I think many of the claims made in these answers that tout the speed of languages other than C can be put aside by simply disassembling the same routine in C and in your higher level language of choice, especially if lots of data is involved as is common in performance critical applications. Fortran may be an exception in its area of expertise, don't know. Is it higher level than C?
First time I did compared JITed code with native code resolved any and all questions whether .Net code could run comparably to C code. The extra level of abstraction and all the safety checks come with a significant cost. Same costs would probably apply to Java, but don't take my word for it, try it on something where performance is critical. (Anyone know enough about JITed Java to locate a compiled procedure in memory? It should certainly be possible)
This is a slightly modified solution. The Process will be killed when it was idle for at least 1 second. Maybe you should add a timeof of X seconds and call the function from a separate thread.
private void SendToPrinter()
{
ProcessStartInfo info = new ProcessStartInfo();
info.Verb = "print";
info.FileName = @"c:\output.pdf";
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
Process p = new Process();
p.StartInfo = info;
p.Start();
long ticks = -1;
while (ticks != p.TotalProcessorTime.Ticks)
{
ticks = p.TotalProcessorTime.Ticks;
Thread.Sleep(1000);
}
if (false == p.CloseMainWindow())
p.Kill();
}
Use watch to see when a variable is written to, rwatch when it is read and awatch when it is read/written from/to, as noted above. However, please note that to use this command, you must break the program, and the variable must be in scope when you've broken the program:
Use the watch command. The argument to the watch command is an expression that is evaluated. This implies that the variabel you want to set a watchpoint on must be in the current scope. So, to set a watchpoint on a non-global variable, you must have set a breakpoint that will stop your program when the variable is in scope. You set the watchpoint after the program breaks.
I know this is old but none of the above solutions worked for me. After extensive debugging, I figured out the issue.
The solution is setting the android:windowTranslucentStatus
attribute to false in my styles.xml
In the year 2020 / 2021 it is even easier with Array.from
to 'convert' from a array-like nodes to an actual array, and then using .map
to loop through the resulting array.
The code is as simple as the follows:
Array.from(tableFields.children).map((child)=>console.log(child))
Once the file object is iterated, it is exausted.
>>> f = open('1.txt', 'w')
>>> f.write('1\n2\n3\n')
>>> f.close()
>>> f = open('1.txt', 'r')
>>> for line in f: print line
...
1
2
3
# exausted, another iteration does not produce anything.
>>> for line in f: print line
...
>>>
Use file.seek
(or close/open the file) to rewind the file:
>>> f.seek(0)
>>> for line in f: print line
...
1
2
3
In the action you can call:
this.Request.PhysicalPath
that returns the physical path in reference to the current controller. If you only need the root path call:
this.Request.PhysicalApplicationPath
You can use nonzero function. it returns the nonzero indices of the given input.
Easy Way
>>> (e > 15).nonzero()
(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
to see the indices more cleaner, use transpose
method:
>>> numpy.transpose((e>15).nonzero())
[[1 6]
[1 7]
[1 8]
[1 9]
[2 0]
...
Not Bad Way
>>> numpy.nonzero(e > 15)
(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
or the clean way:
>>> numpy.transpose(numpy.nonzero(e > 15))
[[1 6]
[1 7]
[1 8]
[1 9]
[2 0]
...
multipart/form-data contains boundary to separate name/value pairs. The boundary acts like a marker of each chunk of name/value pairs passed when a form gets submitted. The boundary is automatically added to a content-type of a request header.
The form with enctype="multipart/form-data" attribute will have a request header Content-Type : multipart/form-data; boundary --- WebKit193844043-h (browser generated vaue).
The payload passed looks something like this:
Content-Type: multipart/form-data; boundary=---WebKitFormBoundary7MA4YWxkTrZu0gW
-----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name=”file”; filename=”captcha”
Content-Type:
-----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name=”action”
submit
-----WebKitFormBoundary7MA4YWxkTrZu0gW--
On the webservice side, it's consumed in @Consumes("multipart/form-data") form.
Beware, when testing your webservice using chrome postman, you need to check the form data option(radio button) and File menu from the dropdown box to send attachment. Explicit provision of content-type as multipart/form-data throws an error. Because boundary is missing as it overrides the curl request of post man to server with content-type by appending the boundary which works fine.
Anaconda does not use the PYTHONPATH
. One should however note that if the PYTHONPATH
is set it could be used to load a library that is not in the anaconda environment. That is why before activating an environment it might be good to do a
unset PYTHONPATH
For instance this PYTHONPATH points to an incorrect pandas lib:
export PYTHONPATH=/home/john/share/usr/anaconda/lib/python
source activate anaconda-2.7
python
>>>> import pandas as pd
/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/__init__.py", line 6, in <module>
from . import hashtable, tslib, lib
ImportError: /home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
unsetting the PYTHONPATH
prevents the wrong pandas lib from being loaded:
unset PYTHONPATH
source activate anaconda-2.7
python
>>>> import pandas as pd
>>>>
Well, if you are writing to a CSV file, then why do you use space as a delimiter? CSV files use commas or semicolons (in Excel) as cell delimiters, so if you use delimiter=' '
, you are not really producing a CSV file. You should simply construct csv.writer
with the default delimiter and dialect. If you want to read the CSV file later into Excel, you could specify the Excel dialect explicitly just to make your intention clear (although this dialect is the default anyway):
example = csv.writer(open("test.csv", "wb"), dialect="excel")
Inner join, join two table where column name is same.
Natural join, join two table where column name and data types are same.
I wrote a library to do this, you can view it here: https://codepen.io/nicetransition/pen/OyRwKq
to use in your case:
.selector {
scale($context, $base-size, $limit-size-min, $limit-size-max, $property: padding-right);
scale($context, $base-size, $limit-size-min, $limit-size-max, $property: padding-left);
}
$context
: Max-width of your container
$base-size
: Root font size
$limit-size-min
: The minimum size
$limit-size-max
: The maximum size
.selector { scale(1400px, 16px, 5px, 20px, $property: padding-right); scale(1400px, 16px, 5px, 20px, $property: padding-left); }
This would scale down to 5px and up to 20px, between 5-20 it is dynamic based of vw
%08x
means that every number should be printed at least 8 characters wide with filling all missing digits with zeros, e.g. for '1' output will be 00000001
Clearly you need a flexible solution that can support types masquerading as boolean. The following allows for that:
template<typename T> bool Flip(const T& t);
You can then specialize this for different types that might pretend to be boolean. For example:
template<> bool Flip<bool>(const bool& b) { return !b; }
template<> bool Flip<int>(const int& i) { return !(i == 0); }
An example of using this construct:
if(Flip(false)) { printf("flipped false\n"); }
if(!Flip(true)) { printf("flipped true\n"); }
if(Flip(0)) { printf("flipped 0\n"); }
if(!Flip(1)) { printf("flipped 1\n"); }
No, I'm not serious.
Wow, everybody is such a pessimist around here. The answer is yes.
It ain't trivial: by the end, we'll have the core function, a supporting struct, a wrapper function, and a macro around the wrapper function. In my work I have a set of macros to automate all this; once you understand the flow it'll be easy for you to do the same.
I've written this up elsewhere, so here's a detailed external link to supplement the summary here: http://modelingwithdata.org/arch/00000022.htm
We'd like to turn
double f(int i, double x)
into a function that takes defaults (i=8, x=3.14). Define a companion struct:
typedef struct {
int i;
double x;
} f_args;
Rename your function f_base
, and define a wrapper function that sets defaults and calls
the base:
double var_f(f_args in){
int i_out = in.i ? in.i : 8;
double x_out = in.x ? in.x : 3.14;
return f_base(i_out, x_out);
}
Now add a macro, using C's variadic macros. This way users don't have to know they're
actually populating a f_args
struct and think they're doing the usual:
#define f(...) var_f((f_args){__VA_ARGS__});
OK, now all of the following would work:
f(3, 8); //i=3, x=8
f(.i=1, 2.3); //i=1, x=2.3
f(2); //i=2, x=3.14
f(.x=9.2); //i=8, x=9.2
Check the rules on how compound initializers set defaults for the exact rules.
One thing that won't work: f(0)
, because we can't distinguish between a missing value and
zero. In my experience, this is something to watch out for, but can be taken care of as
the need arises---half the time your default really is zero.
I went through the trouble of writing this up because I think named arguments and defaults really do make coding in C easier and even more fun. And C is awesome for being so simple and still having enough there to make all this possible.
neo4j is:
an embedded, disk-based, fully transactional Java persistence engine that stores data structured in graphs rather than in tables
I haven't had a chance to try it yet - but it looks very promising. Note this is not an SQL database - your object graph is persisted for you - so it might not be appropriate for your existing app.
Try GRANT ADMINISTER BULK OPERATIONS TO [server_login]
. It is a server level permission, not a database level. This has fixed a similar issue for me in that past (using OPENROWSET I believe).
strip
does nothing but, removes the the whitespace in your string. If you want to remove the extra whitepace from front and back of your string, you can use strip.
The example string which can illustrate that is this:
In [2]: x = "something \t like \t this"
In [4]: x.split('\t')
Out[4]: ['something ', ' like ', ' this']
See, even after splitting with \t
there is extra whitespace in first and second items which can be removed using strip in your code.
As Niraj suggested, use a SortableBindingList. I've used this very successfully with the DataGridView.
Here's a link to the updated code I used - Presenting the SortableBindingList - Take Two - archive
Just add the two source files to your project, and you'll be in business.
Source is in SortableBindingList.zip - 404 dead link
I would rather use Matchers.<byte[]>any()
. This worked for me.
Another example of a reasonable use in which the object is immediately disposed:
using (IDataReader myReader = DataFunctions.ExecuteReader(CommandType.Text, sql.ToString(), dp.Parameters, myConnectionString))
{
while (myReader.Read())
{
MyObject theObject = new MyObject();
theObject.PublicProperty = myReader.GetString(0);
myCollection.Add(theObject);
}
}
<location path="ForAll/Demo.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
In Addition: If you want to write something on that folder through website , you have to give IIS_User permission to the folder
There's a public Web-accessible version of the Lambda-enabled Java 8 JavaDocs, linked from http://lambdafaq.org/lambda-resources. (This should obviously be a comment on Joachim Sauer's answer, but I can't get into my SO account with the reputation points I need to add a comment.) The lambdafaq site (I maintain it) answers this and a lot of other Java-lambda questions.
NB This answer was written before the Java 8 GA documentation became publicly available. I've left in place, though, because the Lambda FAQ might still be useful to people learning about features introduced in Java 8.
In angularjs this should works:
event.preventDefault();
event.stopPropagation();
@echo off
setlocal EnableDelayedExpansion
set S= This is a test
echo %S%.
for /f "tokens=* delims= " %%a in ('echo %S%') do (set b=%%a & set b=!b: =! & echo !b!)
endlocal & goto :EOF
or
@echo off
setlocal EnableDelayedExpansion
set S= This is a test
echo %S%.
for /f "tokens=* delims= " %%a in ('echo %S%') do (set b=%%a & set b=!b: =_! & echo !b!)
endlocal & goto :EOF
Here is an easy way:
Response.Write("<script>alert('Hello');</script>");
You are missing a closing h2 tag. It should be:
<h2><!-- Content --></h2>
Ion Todirel already mentioned an answer YES using std::reference_wrapper
. Since C++11 we have a mechanism to retrieve object from std::vector
and remove the reference by using std::remove_reference
. Below is given an example compiled using g++
and clang
with option
-std=c++11
and executed successfully.
#include <iostream>
#include <vector>
#include<functional>
class MyClass {
public:
void func() {
std::cout << "I am func \n";
}
MyClass(int y) : x(y) {}
int getval()
{
return x;
}
private:
int x;
};
int main() {
std::vector<std::reference_wrapper<MyClass>> vec;
MyClass obj1(2);
MyClass obj2(3);
MyClass& obj_ref1 = std::ref(obj1);
MyClass& obj_ref2 = obj2;
vec.push_back(obj_ref1);
vec.push_back(obj_ref2);
for (auto obj3 : vec)
{
std::remove_reference<MyClass&>::type(obj3).func();
std::cout << std::remove_reference<MyClass&>::type(obj3).getval() << "\n";
}
}
Based on Jon Skeet answer i've made a class that permits to do it easily at work:
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* <p>
* This permits to easily implement a failsafe implementation of the enums's valueOf
* Better use it inside the enum so that only one of this object instance exist for each enum...
* (a cache could solve this if needed)
* </p>
*
* <p>
* Basic usage exemple on an enum class called MyEnum:
*
* private static final FailSafeValueOf<MyEnum> FAIL_SAFE = FailSafeValueOf.create(MyEnum.class);
* public static MyEnum failSafeValueOf(String enumName) {
* return FAIL_SAFE.valueOf(enumName);
* }
*
* </p>
*
* <p>
* You can also use it outside of the enum this way:
* FailSafeValueOf.create(MyEnum.class).valueOf("EnumName");
* </p>
*
* @author Sebastien Lorber <i>([email protected])</i>
*/
public class FailSafeValueOf<T extends Enum<T>> {
private final Map<String,T> nameToEnumMap;
private FailSafeValueOf(Class<T> enumClass) {
Map<String,T> map = Maps.newHashMap();
for ( T value : EnumSet.allOf(enumClass)) {
map.put( value.name() , value);
}
nameToEnumMap = ImmutableMap.copyOf(map);
}
/**
* Returns the value of the given enum element
* If the
* @param enumName
* @return
*/
public T valueOf(String enumName) {
return nameToEnumMap.get(enumName);
}
public static <U extends Enum<U>> FailSafeValueOf<U> create(Class<U> enumClass) {
return new FailSafeValueOf<U>(enumClass);
}
}
And the unit test:
import org.testng.annotations.Test;
import static org.testng.Assert.*;
/**
* @author Sebastien Lorber <i>([email protected])</i>
*/
public class FailSafeValueOfTest {
private enum MyEnum {
TOTO,
TATA,
;
private static final FailSafeValueOf<MyEnum> FAIL_SAFE = FailSafeValueOf.create(MyEnum.class);
public static MyEnum failSafeValueOf(String enumName) {
return FAIL_SAFE.valueOf(enumName);
}
}
@Test
public void testInEnum() {
assertNotNull( MyEnum.failSafeValueOf("TOTO") );
assertNotNull( MyEnum.failSafeValueOf("TATA") );
assertNull( MyEnum.failSafeValueOf("TITI") );
}
@Test
public void testInApp() {
assertNotNull( FailSafeValueOf.create(MyEnum.class).valueOf("TOTO") );
assertNotNull( FailSafeValueOf.create(MyEnum.class).valueOf("TATA") );
assertNull( FailSafeValueOf.create(MyEnum.class).valueOf("TITI") );
}
}
Notice that i used Guava to make an ImmutableMap but actually you could use a normal map i think since the map is never returned...
You have a couple of options:
Remove the out-of-the-box ROOT/
directory from tomcat and rename your war file to ROOT.war
before deploying it.
Deploy your war as (from your example) war_name.war
and configure the context root in conf/server.xml
to use your war file :
<Context path="" docBase="war_name" debug="0" reloadable="true"></Context>
The first one is easier, but a little more kludgy. The second one is probably the more elegant way to do it.
This error occurs when you're trying to target an element that is wrapped in a condition.
So, here if I use ngIf in place of [hidden], it will give me TypeError: Cannot read property 'nativeElement' of undefined
So use [hidden], class.show or class.hide in place of *ngIf.
<button (click)="displayMap()" class="btn btn-primary">Display Map</button>
<div [hidden]="!display">
<div #mapContainer id="map">Content to render when condition is true.</div>
</div>
You cannot refer non-static members from a static method.
Non-Static members (like your fxn(int y)) can be called only from an instance of your class.
Example:
You can do this:
public class A
{
public int fxn(int y) {
y = 5;
return y;
}
}
class Two {
public static void main(String[] args) {
int x = 0;
A a = new A();
System.out.println("x = " + x);
x = a.fxn(x);
System.out.println("x = " + x);
}
or you can declare you method as static.
Live streaming in HTML5 is possible via the use of Media Source Extensions (MSE) - the relatively new W3C standard: https://www.w3.org/TR/media-source/
MSE is an an extension of HTML5 <video>
tag; the javascript on webpage can fetch audio/video segments from the server and push them to MSE for playback. The fetching mechanism can be done via HTTP requests (MPEG-DASH) or via WebSockets. As of September 2016 all major browsers on all devices support MSE. iOS is the only exception.
For high latency (5+ seconds) HTML5 live video streaming you can consider MPEG-DASH implementations by video.js or Wowza streaming engine.
For low latency, near real-time HTML5 live video streaming, take a look at EvoStream media server, Unreal media server, and WebRTC.
The other answers assume that your compiler is C++11 compliant. That is fine if it is. But what if you are using an older compiler?
I picked up the following hack somewhere on the net. It works well enough for me:
#if defined __UINT32_MAX__ or UINT32_MAX
#include <inttypes.h>
#else
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned long uint32_t;
typedef unsigned long long uint64_t;
#endif
It is not portable, of course. But it might work for your compiler.
I got the solution of my problem Hope this will help others also.I have used onTextChnaged it invokes When an object of a type is attached to an Editable, its methods will be called when the text is changed.
public class MainActivity extends Activity {
TextView emailId;
ImageView continuebooking;
EditText firstName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
emailId = (TextView)findViewById(R.id.emailid);
continuebooking = (ImageView)findViewById(R.id.continuebooking);
firstName= (EditText)findViewById(R.id.firstName);
emailId.setText("[email protected]");
setTittle();
continuebooking.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if(firstName.getText().toString().trim().equalsIgnoreCase("")){
firstName.setError("Enter FirstName");
}
}
});
firstName.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
firstName.setError(null);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
firstName.setError(null);
}
});
}
In terms of pattern interpretation, there's no difference between the following forms:
/pattern/
new RegExp("pattern")
If you want to replace a literal string using the replace
method, I think you can just pass a string instead of a regexp to replace
.
Otherwise, you'd have to escape any regexp special characters in the pattern first - maybe like so:
function reEscape(s) {
return s.replace(/([.*+?^$|(){}\[\]])/mg, "\\$1");
}
// ...
var re = new RegExp(reEscape(pattern), "mg");
this.markup = this.markup.replace(re, value);
Your tables should have as immediate children just tbody
and thead
elements, with the rows within*. So, amend the HTML to be:
<table border="1" width="100%" id="test">
<tbody>
<tr>
<td>
<table border="1" width="100%">
<tbody>
<tr>
<td>table 2</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
</tbody>
</table>
Then amend your selector slightly to this:
#test > tbody > tr:last-child { background:#ff0000; }
See it in action here. That makes use of the child selector, which:
...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.
So, you are targeting only direct children of tbody
elements that are themselves direct children of your #test
table.
The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:
#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }
* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:
...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.
None of the answers here actually helped my case (proxy + password), instead I found a solution on a Github issue:
https://github.com/rubygems/rubygems/issues/1068
Basically I had to set three variables:
set http_proxy=proxy_ip:port
set http_proxy_user=user
set http_proxy_pass=password
You can use the asp:Table in your web form and build it via code:
http://msdn.microsoft.com/en-us/library/7bewx260.aspx
Also, check out asp.net for tutorials and such.
For multiple files input using lodash or underscore:
.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
return _.map(changeEvent.target.files, function(file){
scope.fileread = [];
var reader = new FileReader();
reader.onload = function (loadEvent) {
scope.$apply(function () {
scope.fileread.push(loadEvent.target.result);
});
}
reader.readAsDataURL(file);
});
});
}
}
}]);
Short and sweet:
A hash table wraps up an array, lets call it internalArray
. Items are inserted into the array in this way:
let insert key value =
internalArray[hash(key) % internalArray.Length] <- (key, value)
//oversimplified for educational purposes
Sometimes two keys will hash to the same index in the array, and you want to keep both values. I like to store both values in the same index, which is simple to code by making internalArray
an array of linked lists:
let insert key value =
internalArray[hash(key) % internalArray.Length].AddLast(key, value)
So, if I wanted to retrieve an item out of my hash table, I could write:
let get key =
let linkedList = internalArray[hash(key) % internalArray.Length]
for (testKey, value) in linkedList
if (testKey = key) then return value
return null
Delete operations are just as simple to write. As you can tell, inserts, lookups, and removal from our array of linked lists is nearly O(1).
When our internalArray gets too full, maybe at around 85% capacity, we can resize the internal array and move all of the items from the old array into the new array.
To use foreach
would require you have an array that contains every row from the query result. Some DB libraries for PHP provide a fetch_all
function that provides an appropriate array but I could not find one for mysql
(however the mysqli extension does) . You could of course write your own, like so
function mysql_fetch_all($result) {
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row;
}
return $rows;
}
However I must echo the "why?" Using this function you are creating two loops instead of one, and requring the entire result set be loaded in to memory. For sufficiently large result sets, this could become a serious performance drag. And for what?
foreach (mysql_fetch_all($result) as $row)
vs
while ($row = mysql_fetch_array($result))
while
is just as concise and IMO more readable.
EDIT There is another option, but it is pretty absurd. You could use the Iterator Interface
class MysqlResult implements Iterator {
private $rownum = 0;
private $numrows = 0;
private $result;
public function __construct($result) {
$this->result = $result;
$this->numrows = mysql_num_rows($result);
}
public function rewind() {
$this->rownum = 0;
}
public function current() {
mysql_data_seek($this->result, $this->rownum);
return mysql_fetch_array($this->result);
}
public function key() {
return $this->rownum;
}
public function next() {
$this->rownum++;
}
public function valid() {
return $this->rownum < $this->numrows ? true : false;
}
}
$rows = new MysqlResult(mysql_query($query_select));
foreach ($rows as $row) {
//code...
}
In this case, the MysqlResult
instance fetches rows only on request just like with while
, but wraps it in a nice foreach-able package. While you've saved yourself a loop, you've added the overhead of class instantiation and a boat load of function calls, not to mention a good deal of added code complexity.
But you asked if it could be done without using while
(or for
I imagine). Well it can be done, just like that. Whether it should be done is up to you.
Put the entire script into a template string, with {SERVERNAME} placeholders. Then edit the string using:
SET @SQL_SCRIPT = REPLACE(@TEMPLATE, '{SERVERNAME}', @DBNAME)
and then run it with
EXECUTE (@SQL_SCRIPT)
It's hard to believe that, in the course of three years, nobody noticed that my code doesn't work!
You can't EXEC
multiple batches. GO
is a batch separator, not a T-SQL statement. It's necessary to build three separate strings, and then to EXEC
each one after substitution.
I suppose one could do something "clever" by breaking the single template string into multiple rows by splitting on GO
; I've done that in ADO.NET code.
And where did I get the word "SERVERNAME" from?
Here's some code that I just tested (and which works):
DECLARE @DBNAME VARCHAR(255)
SET @DBNAME = 'TestDB'
DECLARE @CREATE_TEMPLATE VARCHAR(MAX)
DECLARE @COMPAT_TEMPLATE VARCHAR(MAX)
DECLARE @RECOVERY_TEMPLATE VARCHAR(MAX)
SET @CREATE_TEMPLATE = 'CREATE DATABASE {DBNAME}'
SET @COMPAT_TEMPLATE='ALTER DATABASE {DBNAME} SET COMPATIBILITY_LEVEL = 90'
SET @RECOVERY_TEMPLATE='ALTER DATABASE {DBNAME} SET RECOVERY SIMPLE'
DECLARE @SQL_SCRIPT VARCHAR(MAX)
SET @SQL_SCRIPT = REPLACE(@CREATE_TEMPLATE, '{DBNAME}', @DBNAME)
EXECUTE (@SQL_SCRIPT)
SET @SQL_SCRIPT = REPLACE(@COMPAT_TEMPLATE, '{DBNAME}', @DBNAME)
EXECUTE (@SQL_SCRIPT)
SET @SQL_SCRIPT = REPLACE(@RECOVERY_TEMPLATE, '{DBNAME}', @DBNAME)
EXECUTE (@SQL_SCRIPT)
All basic validation by using a class:
$('.IsInteger,.IsDecimal').focus(function (e) {
if (this.value == "0") {
this.value = "";
}
});
$('.IsInteger,.IsDecimal').blur(function (e) {
if (this.value == "") {
this.value = "0";
}
});
$('.IsInteger').keypress(function (e) {
var charCode = (e.which) ? e.which : e.keyCode;
if (charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
});
$('.IsDecimal').keypress(function (e) {
var charCode = (e.which) ? e.which : e.keyCode;
if (this.value.indexOf(".") > 0) {
if (charCode == 46) {
return false;
}
}
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
});
$('.IsSpecialChar').keypress(function (e) {
if (e.keyCode != 8 && e.keyCode != 46 && e.keyCode != 37 && e.keyCode != 38 && e.keyCode != 39 && e.keyCode != 40)
return false;
else
return true;
});
$('.IsMaxLength').keypress(function (e) {
var length = $(this).attr("maxlength");
return (this.value.length <= length);
});
$('.IsPhoneNumber').keyup(function (e) {
var numbers = this.value.replace(/\D/g, ''),
char = { 0: '(', 3: ') ', 6: ' - ' };
this.value = '';
for (var i = 0; i < numbers.length; i++) {
this.value += (char[i] || '') + numbers[i];
}
});
$('.IsEmail').blur(function (e) {
var flag = false;
var email = this.value;
if (email.length > 0) {
var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
flag = regex.test(email);
}
if (!flag)
this.value = "";
});
Example:
<asp:TextBox
runat="server"
ID="txtDeliveryFee"
TextMode="SingleLine"
CssClass="form-control IsInteger"
MaxLength="3"
Text="0"
></asp:TextBox>
Just put the class name in the input.
In addition to --date=(relative|local|default|iso|iso-strict|rfc|short|raw)
, as others have mentioned, you can also use a custom log date format with
--date=format:'%Y-%m-%d %H:%M:%S'
This outputs something like 2016-01-13 11:32:13
.
NOTE: If you take a look at the commit linked to below, I believe you'll need at least Git v2.6.0-rc0 for this to work.
In a full command it would be something like:
git config --global alias.lg "log --graph --decorate
-30 --all --date-order --date=format:'%Y-%m-%d %H:%M:%S'
--pretty=format:'%C(cyan)%h%Creset %C(black bold)%ad%Creset%C(auto)%d %s'"
I haven't been able to find this in documentation anywhere (if someone knows where to find it, please comment) so I originally found the placeholders by trial and error.
In my search for documentation on this I found a commit to Git itself that indicates the format is fed directly to strftime
. Looking up strftime
(here or here) the placeholders I found match the placeholders listed.
The placeholders include:
%a Abbreviated weekday name
%A Full weekday name
%b Abbreviated month name
%B Full month name
%c Date and time representation appropriate for locale
%d Day of month as decimal number (01 – 31)
%H Hour in 24-hour format (00 – 23)
%I Hour in 12-hour format (01 – 12)
%j Day of year as decimal number (001 – 366)
%m Month as decimal number (01 – 12)
%M Minute as decimal number (00 – 59)
%p Current locale's A.M./P.M. indicator for 12-hour clock
%S Second as decimal number (00 – 59)
%U Week of year as decimal number, with Sunday as first day of week (00 – 53)
%w Weekday as decimal number (0 – 6; Sunday is 0)
%W Week of year as decimal number, with Monday as first day of week (00 – 53)
%x Date representation for current locale
%X Time representation for current locale
%y Year without century, as decimal number (00 – 99)
%Y Year with century, as decimal number
%z, %Z Either the time-zone name or time zone abbreviation, depending on registry settings
%% Percent sign
In a full command it would be something like
git config --global alias.lg "log --graph --decorate -30 --all --date-order --date=format:'%Y-%m-%d %H:%M:%S' --pretty=format:'%C(cyan)%h%Creset %C(black bold)%ad%Creset%C(auto)%d %s'"
With multidimensional arrays, you can use the same method to iterate through the elements, for example:
int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } }; foreach (int i in numbers2D) { System.Console.Write("{0} ", i); }
The output of this example is:
9 99 3 33 5 55
In Java, multidimensional arrays are array of arrays, so the following works:
int[][] table = {
{ 1, 2, 3 },
{ 4, 5, 6 },
};
for (int[] row : table) {
for (int el : row) {
System.out.println(el);
}
}
I built a Bash debugger. Just give it a try. I hope it will help https://sourceforge.net/projects/bashdebugingbash
Know it's an old post. But these issues still exist.
Here are some of my findings on the subject, grossly explained.
"Status" 0 means one of 3 things, as per the XMLHttpRequest spec:
dns name resolution failed (that's for instance when network plug is pulled out)
server did not answer (a.k.a. unreachable or unresponding)
request was aborted because of a CORS issue (abortion is performed by the user-agent and follows a failing OPTIONS pre-flight).
If you want to go further, dive deep into the inners of XMLHttpRequest. I suggest reading the ready-state update sequence ([0,1,2,3,4] is the normal sequence, [0,1,4] corresponds to status 0, [0,1,2,4] means no content sent which may be an error or not). You may also want to attach listeners to the xhr (onreadystatechange, onabort, onerror, ontimeout) to figure out details.
From the spec (XHR Living spec):
const unsigned short UNSENT = 0;
const unsigned short OPENED = 1;
const unsigned short HEADERS_RECEIVED = 2;
const unsigned short LOADING = 3;
const unsigned short DONE = 4;
You are comparing a jQuery object (jQuery('input:first')
) to strings (the elements of the array).
Change the code in order to compare the input's value (wich is a string) to the array elements:
if (jQuery.inArray(jQuery("input:first").val(), ar) != -1)
The inArray
method returns -1
if the element wasn't found in the array, so as your bonus answer to how to determine if an element is not in an array, use this :
if(jQuery.inArray(el,arr) == -1){
// the element is not in the array
};
I received this error when I copied a class object using JSON.parse and JSON.stringify() which removed the function like:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Method
calcArea() {
return this.height * this.width;
}
}
const square = new Rectangle(10, 10);
console.log('area of square: ', square.calcArea());
const squareCopy = JSON.parse(JSON.stringify(square));
// Will throw an exception since calcArea() is no longer function
console.log('area of square copy: ', squareCopy.calcArea());
Add your path into environment variable "PATH" where you installed your sdk with below:
\Sdk\platform-tools
You can in image below for example:
and reopen your command prompt to see changes.
The term "clone" is ambiguous (though the Java class library includes a Cloneable interface) and can refer to a deep copy or a shallow copy. Deep/shallow copies are not specifically tied to Java but are a general concept relating to making a copy of an object, and refers to how members of an object are also copied.
As an example, let's say you have a person class:
class Person {
String name;
List<String> emailAddresses
}
How do you clone objects of this class? If you are performing a shallow copy, you might copy name and put a reference to emailAddresses
in the new object. But if you modified the contents of the emailAddresses
list, you would be modifying the list in both copies (since that's how object references work).
A deep copy would mean that you recursively copy every member, so you would need to create a new List
for the new Person
, and then copy the contents from the old to the new object.
Although the above example is trivial, the differences between deep and shallow copies are significant and have a major impact on any application, especially if you are trying to devise a generic clone method in advance, without knowing how someone might use it later. There are times when you need deep or shallow semantics, or some hybrid where you deep copy some members but not others.
not sure if it'll work in your scenario, but try adding the following to your web.config
under <system.web>
:
<system.web>
<customErrors mode="Off" />
...
</system.web>
works in my instance.
also see:
I think what BrandonS wants is not the position of the mouse relative to the root element, but rather the position of some descendant element.
For that, there is the TransformToAncestor method:
Point relativePoint = myVisual.TransformToAncestor(rootVisual)
.Transform(new Point(0, 0));
Where myVisual
is the element that was just double-clicked, and rootVisual
is Application.Current.MainWindow or whatever you want the position relative to.
Python is white-space sensitive in regard to the indentation. Once the indentation level falls back to the level at which the function is defined, the function has ended.
== operator compares two object references to check whether they refer to same instance. This also, will return true on successful match.for example
public class Example{
public static void main(String[] args){
String s1 = "Java";
String s2 = "Java";
String s3 = new string ("Java");
test(Sl == s2) //true
test(s1 == s3) //false
}}
above example == is a reference comparison i.e. both objects point to the same memory location
String equals() is evaluates to the comparison of values in the objects.
public class EqualsExample1{
public static void main(String args[]){
String s = "Hell";
String s1 =new string( "Hello");
String s2 =new string( "Hello");
s1.equals(s2); //true
s.equals(s1) ; //false
}}
above example It compares the content of the strings. It will return true if string matches, else returns false.
Unlike languages that employ 'true' lexical scoping, Python opts to have specific 'namespaces' for variables, whether it be global
, nonlocal
, or local. It could be argued that making developers consciously code with such namespaces in mind is more explicit, thus more understandable. I would argue that such complexities make the language more unwieldy, but I guess it's all down to personal preference.
Here are some examples regarding global
:-
>>> global_var = 5
>>> def fn():
... print(global_var)
...
>>> fn()
5
>>> def fn_2():
... global_var += 2
... print(global_var)
...
>>> fn_2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in fn_2
UnboundLocalError: local variable 'global_var' referenced before assignment
>>> def fn_3():
... global global_var
... global_var += 2
... print(global_var)
...
>>> fn_3()
7
The same patterns can be applied to nonlocal
variables too, but this keyword is only available to the latter Python versions.
In case you're wondering, nonlocal
is used where a variable isn't global, but isn't within the function definition it's being used. For example, a def
within a def
, which is a common occurrence partially due to a lack of multi-statement lambdas. There's a hack to bypass the lack of this feature in the earlier Pythons though, I vaguely remember it involving the use of a single-element list...
Note that writing to variables is where these keywords are needed. Just reading from them isn't ambiguous, thus not needed. Unless you have inner def
s using the same variable names as the outer ones, which just should just be avoided to be honest.
this
is the key (vs evt.target). See example.
document.body.addEventListener("click", function (evt) {_x000D_
console.dir(this);_x000D_
//note evt.target can be a nested element, not the body element, resulting in misfires_x000D_
console.log(evt.target);_x000D_
alert("body clicked");_x000D_
});
_x000D_
<h4>This is a heading.</h4>_x000D_
<p>this is a paragraph.</p>
_x000D_
Quick extension of cmsjr's answer that works for strings with more than one character.
CREATE FUNCTION dbo.CountOccurrencesOfString
(
@searchString nvarchar(max),
@searchTerm nvarchar(max)
)
RETURNS INT
AS
BEGIN
return (LEN(@searchString)-LEN(REPLACE(@searchString,@searchTerm,'')))/LEN(@searchTerm)
END
Usage:
SELECT * FROM MyTable
where dbo.CountOccurrencesOfString(MyColumn, 'MyString') = 1
Below is how I got this working.
The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.
[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]
[HttpPost]
public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)
{
var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
}
The JQuery script used to call this action method:
var requestData = {
InvoiceNumber: $.trim(this.value),
SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
};
$.ajax({
url: '/en/myController/GetDataForInvoiceNumber',
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
CheckIfInvoiceFound(result);
},
async: true,
processData: false
});
You are pretty confused my friend. There are no LOOPS in SQL, only in PL/SQL. Here's a few examples based on existing Oracle table - copy/paste to see results:
-- Numeric FOR loop --
set serveroutput on -->> do not use in TOAD --
DECLARE
k NUMBER:= 0;
BEGIN
FOR i IN 1..10 LOOP
k:= k+1;
dbms_output.put_line(i||' '||k);
END LOOP;
END;
/
-- Cursor FOR loop --
set serveroutput on
DECLARE
CURSOR c1 IS SELECT * FROM scott.emp;
i NUMBER:= 0;
BEGIN
FOR e_rec IN c1 LOOP
i:= i+1;
dbms_output.put_line(i||chr(9)||e_rec.empno||chr(9)||e_rec.ename);
END LOOP;
END;
/
-- SQL example to generate 10 rows --
SELECT 1 + LEVEL-1 idx
FROM dual
CONNECT BY LEVEL <= 10
/
SELECT *
FROM Customer
WHERE (I.IsClose=@ISClose OR @ISClose is NULL)
AND (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )
AND (isnull(@Value,1) <> 2
OR I.RecurringCharge = @Total
OR @Total is NULL )
AND (isnull(@Value,2) <> 3
OR I.RecurringCharge like '%'+cast(@Total as varchar(50))+'%'
OR @Total is NULL )
Basically, your condition was
if (@Value=2)
TEST FOR => (I.RecurringCharge=@Total or @Total is NULL )
flipped around,
AND (isnull(@Value,1) <> 2 -- A
OR I.RecurringCharge = @Total -- B
OR @Total is NULL ) -- C
When (A) is true, i.e. @Value is not 2, [A or B or C] will become TRUE regardless of B and C results. B and C are in reality only checked when @Value = 2
, which is the original intention.
First of all check your windows update by searching "Windows Update"
or
Download updates from microsoft windows site (i had windows 7 x64 updated to service pack 1 full) windows 7 Service pack 1 download
Now there are some more downloads that support WAMP for installing time
From the readme.txt
BEFORE proceeding with the installation of Wampserver, you must ensure that certain elements are installed on your system, otherwise Wampserver will absolutely not run, and in addition, the installation will be faulty and you need to remove Wampserver BEFORE installing the elements that were missing.
Make sure you are "up to date" in the redistributable packages VC9, VC10, VC11, VC13 and VC14 Even if you think you are up to date, install each package as administrator and if message "Already installed", validate Repair.
The following packages (VC9, VC10, VC11) are imperatively required to Wampserver 2.4, 2.5 and 3.0, even if you use only Apache and PHP versions VC11 and VC14 is required for PHP 7 and Apache 2.4.17
VC9 Packages (Visual C++ 2008 SP1) https://www.microsoft.com/en-us/download/details.aspx?id=5582 https://www.microsoft.com/en-us/download/details.aspx?id=2092
VC10 Packages (Visual C++ 2010 SP1) https://www.microsoft.com/en-us/download/details.aspx?id=8328 https://www.microsoft.com/en-us/download/details.aspx?id=13523
VC11 Packages (Visual C++ 2012 Update 4) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page: http://www.microsoft.com/en-us/download/details.aspx?id=30679
VC13 Packages[/b] (Visual C++ 2013) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe
VC14 Packages (Visual C++ 2015) The two files vcredist_x86.exe and vcredist_x64.exe to be download are on the same page: https://www.microsoft.com/en-us/download/details.aspx?id=52685
VC Packages x64 (Visual C++ 2017)
https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads
The following works:
sudo apt-get --purge remove mysql-client mysql-server mysql-common
sudo apt-get autoremove
Why not trying something simple and human-readable, like JSON (or XML) ?
There are many pre-made open-source implementations of JSON (or XML) for C++ - I would use one of them.
And if you want something more "binary" - try BJSON or BSON :)
You can't do something like that: (int(sumall[0])+int(sumall[1]))
That's because sumall
is an int
and not a list or dict.
So, summ + sumd
will be you're lucky number
In Scala 2.10
val name = "Ivan"
val weather = "sunny"
s"Hello $name, it's $weather today!"
HTML Code
<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload" class="send_upload" value="upload" />
jQuery Code using bind method
$(document).ready(function() {
$('#upload').bind("click",function()
{ if(!$('#uploadImage').val()){
alert("empty");
return false;} }); });
Here you will find the simplest possible example of using distutils and setup.py:
https://docs.python.org/2/distutils/introduction.html#distutils-simple-example
This assumes that all your code is in a single file and tells how to package a project containing a single module.
Perhaps your subquery (SELECT ename FROM EMP WHERE empno = mgr)
thinks, give me the employee records that are their own managers! (i.e., where the empno of a row is the same as the mgr of the same row.)
have you considered perhaps rewriting this to use an inner (self) join? (I'm asking, becuase i'm not even sure if the following will work or not.)
SELECT t1.ename, t1.empno, t2.ename as MANAGER, t1.mgr
from emp as t1
inner join emp t2 ON t1.mgr = t2.empno
order by t1.empno;
Coming from SQL Server as well, and this really bugged me. For those using Toad Data Point or Toad for Oracle, it's extremely simple. Just putting a colon in front of your variable name will prompt Toad to open a dialog where you enter the value on execute.
SELECT * FROM some_table WHERE some_column = :var_name;
It depends on what encoding you use. If you want to convert utf-8 encoded hex to string, use this:
function fromHex(hex,str){
try{
str = decodeURIComponent(hex.replace(/(..)/g,'%$1'))
}
catch(e){
str = hex
console.log('invalid hex input: ' + hex)
}
return str
}
For the other direction use this:
function toHex(str,hex){
try{
hex = unescape(encodeURIComponent(str))
.split('').map(function(v){
return v.charCodeAt(0).toString(16)
}).join('')
}
catch(e){
hex = str
console.log('invalid text input: ' + str)
}
return hex
}
window.setInterval(function() {
alert('test');
}, 10000);
Calls a function repeatedly, with a fixed time delay between each call to that function.
0: U
1: n
2: i
3: v
4: e
5: r
6: s
7: i
8: t
9: y
Start index is inclusive
End index is exclusive
You can use a variety of methods, one uses Javascript window.onload function in a simple function call from a script or from the body as in the solutions above, you can also use jQuery to do this but its just a modification of Javascript...Just add Jquery to your header by pasting
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
to your head section and open another script tag where you display the alert when the DOM is ready i.e. `
<script>
$("document").ready( function () {
alert("Hello, world");
});
</script>
`
This uses Jquery to run the function but since jQuery is a Javascript framework it contains Javascript code hence the Javascript alert function..hope this helps...
For z-index:1000
to have an effect you need a non-static positioning scheme.
Add position:relative;
to a rule selecting the element you want to be on top
Write your regex differently:
var r = /^a$/;
r.test('a'); // true
r.test('ba'); // false
So I found a solution. I created an angularJS service, we'll call it MyDataRepository and I created a module for it. I then serve up this javascript file from my server-side controller:
HTML:
<script src="path/myData.js"></script>
Server-side:
@RequestMapping(value="path/myData.js", method=RequestMethod.GET)
public ResponseEntity<String> getMyDataRepositoryJS()
{
// Populate data that I need into a Map
Map<String, String> myData = new HashMap<String,String>();
...
// Use Jackson to convert it to JSON
ObjectMapper mapper = new ObjectMapper();
String myDataStr = mapper.writeValueAsString(myData);
// Then create a String that is my javascript file
String myJS = "'use strict';" +
"(function() {" +
"var myDataModule = angular.module('myApp.myData', []);" +
"myDataModule.service('MyDataRepository', function() {" +
"var myData = "+myDataStr+";" +
"return {" +
"getData: function () {" +
"return myData;" +
"}" +
"}" +
"});" +
"})();"
// Now send it to the client:
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "text/javascript");
return new ResponseEntity<String>(myJS , responseHeaders, HttpStatus.OK);
}
I can then inject MyDataRepository where ever I need it:
someOtherModule.service('MyOtherService', function(MyDataRepository) {
var myData = MyDataRepository.getData();
// Do what you have to do...
}
This worked great for me, but I am open to any feedback if anyone has any. }
It is commonly agreed that primary keys should be immutable (or as stable as possible since immutability can not be enforced in the DB). While there is nothing that will prevent you from updating a primary key (except integrity constraint), it may not be a good idea:
From a performance point of view:
Other considerations:
In conclusion, during design, it is generally safer to use a surrogate key in lieu of a natural primary key that is supposed not to change -- but may eventually need to be updated because of changed requirements or even data entry error.
If you absolutely have to update a primary key with children table, see this post by Tom Kyte for a solution.
Error points directly that RestTemplate
bean is not defined in context and it cannot load the beans.
If you are sure that the bean is defined for the RestTemplate then use the following to print the beans that are available in the context loaded by spring boot application
ApplicationContext ctx = SpringApplication.run(Application.class, args);
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
If this contains the bean by the name/type given, then all good. Or else define a new bean and then use it.
I run the below commands.
There is no need to rebuilt images afterwards.
docker rm $(docker ps -qf 'status=exited')
docker rmi $(docker images -qf "dangling=true")
docker volume rm $(docker volume ls -qf dangling=true)
These remove exited/dangling containers and dangling volumes.
Maybe this is helpful, too.
for (var i = countries.length - 1; i--;) {
if (countries[i]['id'] === 'AF' || countries[i]['name'] === 'Algeria'{
countries.splice(i, 1);
}
}