dt = dt.AsEnumerable().GroupBy(r => r.Field<int>("ID")).Select(g => g.First()).CopyToDataTable();
Try this
myDataTable.Select("[Name] is NULL OR [Name] <> 'n/a'" )
Edit: Relevant sources:
Dim rows() AS DataRow = DataTable.Select("ColumnName1 = 'value3'")
If rows.Count > 0 Then
searchedValue = rows(0).Item("ColumnName2")
End If
With FirstOrDefault
:
Dim row AS DataRow = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault()
If Not row Is Nothing Then
searchedValue = row.Item("ColumnName2")
End If
In C#:
var row = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault();
if (row != null)
searchedValue = row["ColumnName2"];
Generic List<T>
have the Where<T>(Func<T, Boolean>)
extension method that can be used to filter data.
In your case with a row array:
var rows = rowsArray.Where(row => row["LastName"].ToString().StartsWith("a"));
If you are using DataRowCollection
, you need to cast it first.
var rows = dataTableRows.Cast<DataRow>().Where(row => row["LastName"].ToString().StartsWith("a"));
I found that having too many and's would return incorrect results (for .NET 1.1 anyway)
DataRow[] results = table.Select("A = 'foo' AND B = 'bar' AND C = 'baz' and D ='fred' and E = 'marg'");
In my case A was the 12th field in a table and the select was effectively ignoring it.
However if I did
DataRow[] results = table.Select("A = 'foo' AND (B = 'bar' AND C = 'baz' and D ='fred' and E = 'marg')");
The filter worked correctly!
Extension method based on Linq
public static void DeleteRows(this DataTable dt, Func<DataRow, bool> predicate)
{
foreach (var row in dt.Rows.Cast<DataRow>().Where(predicate).ToList())
row.Delete();
}
Then use:
DataTable dt = GetSomeData();
dt.DeleteRows(r => r.Field<double>("Amount") > 123.12 && r.Field<string>("ABC") == "XYZ");
Have you tried using the DataTable.Select(filterExpression, sortExpression) method?
I was looking for same and finally I found the solution
using (CString conn = new CString())
{
USER user = conn.USERs.Find(CMN.CurrentUser.ID);
user.PASSWORD = txtPass.Text;
conn.SaveChanges();
}
believe me it work for me like a charm.
Sharing a few functions which I created for dates:
Please note that I wanted to get time for a particular location (not just UTC time). If you want UTC time, just remove loc variable and .In(loc) function call.
func GetTimeStamp() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
t := time.Now().In(loc)
return t.Format("20060102150405")
}
func GetTodaysDate() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
current_time := time.Now().In(loc)
return current_time.Format("2006-01-02")
}
func GetTodaysDateTime() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
current_time := time.Now().In(loc)
return current_time.Format("2006-01-02 15:04:05")
}
func GetTodaysDateTimeFormatted() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
current_time := time.Now().In(loc)
return current_time.Format("Jan 2, 2006 at 3:04 PM")
}
func GetTimeStampFromDate(dtformat string) string {
form := "Jan 2, 2006 at 3:04 PM"
t2, _ := time.Parse(form, dtformat)
return t2.Format("20060102150405")
}
There is a firefox plugin that saves the whole page's HTML, CSS, etc.. but I have not seen one that does a partial save.
I remember IE 5.5 had what you were looking for though ;)
No. Looking at the syntax from the man page for GNU make
make [ -f makefile ] [ options ] ... [ targets ] ...
you can specify multiple targets, hence 'no' (at least no in the exact way you specified).
If you're using Visual Studio (this might work in Eclipse also, but I never tried) and you copy & paste into Microsoft Word (or any other microsoft product) it will paste the code in whatever color your IDE had. Then you just need to copy the text out of word and into your desired application and it will paste as rich text.
I've only seen this work across Visual Studio to other Microsoft products though so I don't know if it will be any help.
You can achieve your results with two methods:-
First Method define position values:-
HTML
<ul>
<li>Hello</li>
<li>Hello world</li>
</ul>
CSS
ul{
width:100px;
}
ul li{
border:1px solid orange;
background: url("http://www.adaweb.net/Portals/0/Images/arrow1.gif") no-repeat 90% 5px;
}
ul li:hover{
background: yellow url("http://www.adaweb.net/Portals/0/Images/arrow1.gif") no-repeat 90% 5px;
}
First Demo:- http://jsfiddle.net/QeGAd/18/
Second Method by CSS :before:after Selectors
HTML
<ul>
<li>Hello</li>
<li>Hello world</li>
CSS
ul{
width:100px;
}
ul li{
border:1px solid orange;
}
ul li:after {
content: " ";
padding-right: 16px;
background: url("http://www.adaweb.net/Portals/0/Images/arrow1.gif") no-repeat center right;
}
ul li:hover {
background:yellow;
}
ul li:hover:after {
content: " ";
padding-right: 16px;
background: url("http://www.adaweb.net/Portals/0/Images/arrow1.gif") no-repeat center right;
}
Second Demo:- http://jsfiddle.net/QeGAd/17/
@Bangonkali provide the right answer, but this syntax seems more readable and just nicer to me:
eventChange($event: KeyboardEvent): void {
(<HTMLInputElement>$event.target).value;
}
I solved is by using android:background instead of app:srcCompact.
This is caused by xmlns:app="http://schemas.android.com/apk/res-auto". As people have suggested above, you could use /lib-auto or /lib/your-package but I got suspicious namespace error when I tried using /lib-auto and unexpected namespace prefix error with /lib/my-package .
The code below combines simple iteration for small copies and Array.Copy for large copies
public static void Populate<T>( T[] array, int startIndex, int count, T value ) {
if ( array == null ) {
throw new ArgumentNullException( "array" );
}
if ( (uint)startIndex >= array.Length ) {
throw new ArgumentOutOfRangeException( "startIndex", "" );
}
if ( count < 0 || ( (uint)( startIndex + count ) > array.Length ) ) {
throw new ArgumentOutOfRangeException( "count", "" );
}
const int Gap = 16;
int i = startIndex;
if ( count <= Gap * 2 ) {
while ( count > 0 ) {
array[ i ] = value;
count--;
i++;
}
return;
}
int aval = Gap;
count -= Gap;
do {
array[ i ] = value;
i++;
--aval;
} while ( aval > 0 );
aval = Gap;
while ( true ) {
Array.Copy( array, startIndex, array, i, aval );
i += aval;
count -= aval;
aval *= 2;
if ( count <= aval ) {
Array.Copy( array, startIndex, array, i, count );
break;
}
}
}
The benchmarks for different array length using an int[] array are :
2 Iterate: 1981 Populate: 2845
4 Iterate: 2678 Populate: 3915
8 Iterate: 4026 Populate: 6592
16 Iterate: 6825 Populate: 10269
32 Iterate: 16766 Populate: 18786
64 Iterate: 27120 Populate: 35187
128 Iterate: 49769 Populate: 53133
256 Iterate: 100099 Populate: 71709
512 Iterate: 184722 Populate: 107933
1024 Iterate: 363727 Populate: 126389
2048 Iterate: 710963 Populate: 220152
4096 Iterate: 1419732 Populate: 291860
8192 Iterate: 2854372 Populate: 685834
16384 Iterate: 5703108 Populate: 1444185
32768 Iterate: 11396999 Populate: 3210109
The first columns is the array size, followed by the time of copying using a simple iteration ( @JaredPared implementation ). The time of this method is after that. These are the benchmarks using an array of a struct of four integers
2 Iterate: 2473 Populate: 4589
4 Iterate: 3966 Populate: 6081
8 Iterate: 7326 Populate: 9050
16 Iterate: 14606 Populate: 16114
32 Iterate: 29170 Populate: 31473
64 Iterate: 57117 Populate: 52079
128 Iterate: 112927 Populate: 75503
256 Iterate: 226767 Populate: 133276
512 Iterate: 447424 Populate: 165912
1024 Iterate: 890158 Populate: 367087
2048 Iterate: 1786918 Populate: 492909
4096 Iterate: 3570919 Populate: 1623861
8192 Iterate: 7136554 Populate: 2857678
16384 Iterate: 14258354 Populate: 6437759
32768 Iterate: 28351852 Populate: 12843259
Here's some PowerShell code that should work. You can combine most of this into fewer lines, but I wanted to keep it clear and readable.
[string]$filePath = "C:\tempFile.zip";
[string]$directory = [System.IO.Path]::GetDirectoryName($filePath);
[string]$strippedFileName = [System.IO.Path]::GetFileNameWithoutExtension($filePath);
[string]$extension = [System.IO.Path]::GetExtension($filePath);
[string]$newFileName = $strippedFileName + [DateTime]::Now.ToString("yyyyMMdd-HHmmss") + $extension;
[string]$newFilePath = [System.IO.Path]::Combine($directory, $newFileName);
Move-Item -LiteralPath $filePath -Destination $newFilePath;
The Google Play Store doesn't provide this data, so the sites must just be scraping it.
I solved the same problem in a React Native project. I solved it using this.
let data = snapshot.val();
if(data){
let items = Object.values(data);
}
else{
//return null
}
You have to be more precise, using parentheses, otherwise Java will not use the order of operands that you want it to use.
if ((a[0] & 1 == 0) && (a[1] & 1== 0) && (a[2] & 1== 0)){
Becomes
if (((a[0] & 1) == 0) && ((a[1] & 1) == 0) && ((a[2] & 1) == 0)){
You can use date
to get time and date of a day:
[pengyu@GLaDOS ~]$date
Tue Aug 27 15:01:27 CST 2013
Also hwclock
would do:
[pengyu@GLaDOS ~]$hwclock
Tue 27 Aug 2013 03:01:29 PM CST -0.516080 seconds
For customized output, you can either redirect the output of date
to something like awk
, or write your own program to do that.
Remember to put your own executable scripts/binary into your PATH
(e.g. /usr/bin) to make it invokable anywhere.
If you are using Excel 2013 Than do the following File > Option > Advanced > Under Display options for this worksheet: uncheck the checkbox before Show formulas in cells instead of their calculated results This should resolve the issue.
Just return your existing check from a function.
function _isCurl(){
return function_exists('curl_version');
}
I assume you are using ASP.NET MVC (C#), if not then this answer is not in your issue.
Is it impossible to assign session values directly through javascript? No, there is a way to do that.
Look again your code:
<script type="text/javascript" >
{
Session["controlID"] ="This is my session";
}
</script>
A little bit change:
<script type="text/javascript" >
{
<%Session["controlID"] = "This is my session";%>
}
</script>
The session "controlID" has created, but what about the value of session? is that persistent or can changeable via javascript?
Let change a little bit more:
<script type="text/javascript" >
{
var strTest = "This is my session";
<%Session["controlID"] = "'+ strTest +'";%>
}
</script>
The session is created, but the value inside of session will be "'+ strTest +'" but not "This is my session". If you try to write variable directly into server code like:
<%Session["controlID"] = strTest;%>
Then an error will occur in you page "There is no parameter strTest in current context...". Until now it is still seem impossible to assign session values directly through javascript.
Now I move to a new way. Using WebMethod at code behind to do that. Look again your code with a little bit change:
<script type="text/javascript" >
{
var strTest = "This is my session";
PageMethods.CreateSessionViaJavascript(strTest);
}
</script>
In code-behind page. I create a WebMethod:
[System.Web.Services.WebMethod]
public static string CreateSessionViaJavascript(string strTest)
{
Page objp = new Page();
objp.Session["controlID"] = strTest;
return strTest;
}
After call the web method to create a session from javascript. The session "controlID" will has value "This is my session".
If you use the way I have explained, then please add this block of code inside form tag of your aspx page. The code help to enable page methods.
<asp:ScriptManager EnablePageMethods="true" ID="MainSM" runat="server" ScriptMode="Release" LoadScriptsBeforeUI="true"></asp:ScriptManager>
Source: JavaScript - How to Set values to Session in Javascript
Happy codding, Tri
Make a sample request to https://http-tools.appspot.com/reflect-http-request/some-unique-id and check what this request contains (request header, request body, request parameters) by its corresponding finder url https://http-tools.appspot.com/reflect-http-request-finder/some-unique-id. You can use any string instead of some-unique-id
, check out https://http-tools.appspot.com for more details.
This works for me. Returns the number that Excel displays in the bottom status line when a pivot
column
is filtered
and I need the count
of the visible cells
.
Global Const DashBoardSheet = "DashBoard"
Global Const ProfileColRng = "$L:$L"
.
.
.
Sub MySub()
Dim myreccnt as long
.
.
.
myreccnt = GetFilteredPivotRowCount(DashBoardSheet, ProfileColRng)
.
.
.
End Sub
Function GetFilteredPivotRowCount(sheetname As String, cntrange As String) As long
Dim reccnt As Long
reccnt = Sheets(sheetname).Range(cntrange).SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeConstants).Count - 1
GetFilteredPivotRowCount = reccnt
End Function
First, I agree with you as a matter of style - I would also (and do also) conditionally apply classes rather than inline styles. But you can use the same technique:
<div className={{completed ? "completed" : ""}}></div>
For more complex sets of state, accumulate an array of classes and apply them:
var classes = [];
if (completed) classes.push("completed");
if (foo) classes.push("foo");
if (someComplicatedCondition) classes.push("bar");
return <div className={{classes.join(" ")}}></div>;
How about:
prog1 & prog2 && fg
This will:
prog1
.prog2
, and keep it in foreground, so you can close it with ctrl-c
.prog2
, you'll return to prog1
's foreground, so you can also close it with ctrl-c
.If you are not sure Object.keys() is going to return you the keys in the right order, you can try this logic instead
var keys = []
var obj = {
'key1' : 'value1',
'key2' : 'value2',
'key3' : 'value3',
}
for (var key in obj){
keys.push(key)
}
console.log(obj[keys[1]])
console.log(obj[keys[2]])
console.log(obj[keys[3]])
<form action="Delegate_update.php" method="post">
Name
<input type="text" name= "Name" value= "<?php echo $row['Name']; ?> "size=10>
Username
<input type="text" name= "Username" value= "<?php echo $row['Username']; ?> "size=10>
Password
<input type="text" name= "Password" value= "<?php echo $row['Password']; ?>" size=17>
<input type="submit" name= "submit" value="Update">
</form>
look into this
Installing framework 4.0 redistributable is also enough to create application pool. You can download it from here.
The error says it all, change:
ViewPager mPager = (ViewPager) findViewById(R.id.fieldspager);
to
final ViewPager mPager = (ViewPager) findViewById(R.id.fieldspager);
I used a form with a single submit button. Point the "action" attribute to the ID of the element that needs to be navigated to. Worked for me with just "#top" without needing to define an ID in my stylesheet:
<form action="#top">
<button type="submit">Back to Top</button>
</form>
Maybe a couple extra lines than is desirable but it's a button, at least. I find this the most concise and descriptive way to go about it.
Using cuzillion you can test the affect on page load of different placement of script tags using different methods: inline, external, "HTML tags", "document.write", "JS DOM element", "iframe", and "XHR eval". See the help for an explanation of the differences. It can also test stylesheets, images and iframes.
why isn't this one of the answers yet?:
$("#manual2").click(function() {
$.fancybox([
'http://farm5.static.flickr.com/4044/4286199901_33844563eb.jpg',
'http://farm3.static.flickr.com/2687/4220681515_cc4f42d6b9.jpg',
{
'href' : 'http://farm5.static.flickr.com/4005/4213562882_851e92f326.jpg',
'title' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'
}
], {
'padding' : 0,
'transitionIn' : 'none',
'transitionOut' : 'none',
'type' : 'image',
'changeFade' : 0
});
});
now just trigger your link!!
got this from the Fancybox homepage
You need to initialize the list first:
protected List<string> list = new List<string>();
How about something like this?
val newDF = df.filter($"B" === "").take(1) match {
case Array() => df
case _ => df.withColumn("D", $"B" === "")
}
Using take(1)
should have a minimal hit
In JavaScript you declare variables or functions by using the keywords var, let or function. In TypeScript classes you declare class members or methods without these keywords followed by a colon and the type or interface of that class member.
It’s just syntax sugar, there is no difference between:
var el: HTMLElement = document.getElementById('content');
and:
var el = document.getElementById('content');
On the other hand, because you specify the type you get all the information of your HTMLElement object.
Use System.Windows.Forms.SystemInformation.UserName
for the actually logged in user as Environment.UserName
still returns the account being used by the current process.
Try:
#!/bin/bash
if [ "$#" -eq "0" ]
then
echo "No arguments supplied"
else
echo "Hello world"
fi
If you find yourself frequently wanting CSS3 selectors, you can always use the selectivizr library on your site:
It's a JS script that adds support for almost all of the CSS3 selectors to browsers that wouldn't otherwise support them.
Throw it into your <head>
tag with an IE conditional:
<!--[if (gte IE 6)&(lte IE 8)]>
<script src="/js/selectivizr-min.js" type="text/javascript"></script>
<![endif]-->
A simpler way would be to filter your results using "grep -v".
grep -i needle -R * | grep -v node_modules
Should I use JSTL ?
Yes.
You can use <c:if>
and <c:choose>
tags to make conditional rendering in jsp using JSTL.
To simulate if , you can use:
<c:if test="condition"></c:if>
To simulate if...else, you can use:
<c:choose>
<c:when test="${param.enter=='1'}">
pizza.
<br />
</c:when>
<c:otherwise>
pizzas.
<br />
</c:otherwise>
</c:choose>
Another method is by using the menu within visual studio. Project -> Add Reference... I recommend copying the needed .dll to your resource folder, or local project folder.
If you are looking for an answer in java code,
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setGravity(Gravity.CENTER);
// add children
I have a very effective method to save the notebooks in a desired location in windows.
jupyter-notebook.exe
is
saved under environment variable. jupyter-notebook.exe
Piggybacking off of jonnii:
Topic.find(:all, :conditions => ['forum_id not in (?)', @forums.pluck(:id)])
using pluck rather than mapping over the elements
found via railsconf 2012 10 things you did not know rails could do
For the most part you treat it as if you are validating any other kind of control but use the InitialValue property of the required field validator.
<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="your-dropdownlist" InitialValue="Please select" ErrorMessage="Please select something" />
Basically what it's saying is that validation will succeed if any other value than the 1 set in InitialValue is selected in the dropdownlist.
If databinding you will need to insert the "Please select" value afterwards as follows
this.ddl1.Items.Insert(0, "Please select");
I know I'm a little late to the party, but I did want to throw some interjections. (I would have commented but not enough reputation points yet, so, here's a full answer).
This requires the latest version of VS Code, Azure Repo Extention, and Git to be installed.
Anyone looking to use the new VS Code (or using the preview like myself), when you go to the Settings (Still File -> Preferences -> Settings or CTRL+, ) you'll be looking under User Settings -> Extensions -> Azure Repos.
Then under Tfvc: Location you can paste the location of the executable.
For 2017 it'll be
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe
Or for 2019 (Preview)
C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe
After adding the location, I closed my VS Code (not sure if this was needed) and went my git repo to copy the git URL.
After that, went back into VS Code went to the Command Palette (View -> Command Palette or CTRL+Shift+P) typed Git: Clone
pasted my repo:
Selected the location for the repo to be stored. Next was an error that popped up. I proceeded to follow this video which walked me through clicking on the Team button with the exclamation mark on the bottom of your VS Code Screen
Then chose the new method of authentication
Copy by using CTRL+C and then press enter. Your browser will launch a page where you'll enter the code you copied (CTRL+V).
Click Continue
Log in with your Microsoft Credentials and you should see a change on the bottom bar of VS Code.
Cheers!
Another way to handle the situation is exception handling.
Every time a non-existent value is called, your code will recover from the exception and just continue with the loop. In the catch-block you can handle the error the same way you write it down in your else-statement when the expression (... != null) returns false. Of course throwing and handling exceptions is a relatively costly operation which might not be ideal depending on the performance requirements.
Here is the jsFiddle
#backdrop{
border: 2px solid red;
width: 400px;
height: 200px;
position: absolute;
}
#curtain {
border: 1px solid blue;
width: 400px;
height: 200px;
position: absolute;
}
Use Z-index to move the one you want on top.
You can also do way more complex commands, just to round out the examples above. So, say I want to get the number of processes running on the system and store it in the ${NUM_PROCS} variable.
All you have to so is generate the command pipeline and stuff it's output (the process count) into the variable.
It looks something like this:
NUM_PROCS=$(ps -e | sed 1d | wc -l)
I hope that helps add some handy information to this discussion.
You're targeting the wrong item with that jQuery selector. The name
of your search bar is searchBar
, not the id
. What you want to use is $('#main_search').val('hi')
.
nvarchar with preprocessing to standardize them as much as possible. You'll probably want to extract extensions and store them in another field.
Sleep is used in cases where independent program(s) that you have no control over may sometimes use a commonly used resource (say, a file), that your program needs to access when it runs, and when the resource is in use by these other programs your program is blocked from using it. In this case, where you access the resource in your code, you put your access of the resource in a try-catch (to catch the exception when you can't access the resource), and you put this in a while loop. If the resource is free, the sleep never gets called. But if the resource is blocked, then you sleep for an appropriate amount of time, and attempt to access the resource again (this why you're looping). However, bear in mind that you must put some kind of limiter on the loop, so it's not a potentially infinite loop. You can set your limiting condition to be N number of attempts (this is what I usually use), or check the system clock, add a fixed amount of time to get a time limit, and quit attempting access if you hit the time limit.
This can be caused by not having administrator permissions for Oracle Client
. Add this in App.config
file:
<IPermission class="Oracle.DataAccess.Client.OraclePermission,
Oracle.DataAccess, Version=2.111.7.20, Culture=neutral,
PublicKeyToken=89b483f429c47342" version= "1" Unrestricted="true"/>
Power is **
and e^
is math.exp
:
x.append(1 - math.exp(-0.5 * (value1*value2)**2))
This example might be seem a bit lengthy, but its intention should be quite clear.
It uses 3 Boolean properties in the ViewModel called, FlagForValue1
, FlagForValue2
and FlagForValue3
.
Each of these 3 properties is backed by a single private field called _intValue
.
The 3 Radio buttons of the view (xaml) are each bound to its corresponding Flag property in the view model. This means the radio button displaying "Value 1" is bound to the FlagForValue1
bool property in the view model and the other two accordingly.
When setting one of the properties in the view model (e.g. FlagForValue1
), its important to also raise property changed events for the other two properties (e.g. FlagForValue2
, and FlagForValue3
) so the UI (WPF INotifyPropertyChanged
infrastructure) can selected / deselect each radio button correctly.
private int _intValue;
public bool FlagForValue1
{
get
{
return (_intValue == 1) ? true : false;
}
set
{
_intValue = 1;
RaisePropertyChanged("FlagForValue1");
RaisePropertyChanged("FlagForValue2");
RaisePropertyChanged("FlagForValue3");
}
}
public bool FlagForValue2
{
get
{
return (_intValue == 2) ? true : false;
}
set
{
_intValue = 2;
RaisePropertyChanged("FlagForValue1");
RaisePropertyChanged("FlagForValue2");
RaisePropertyChanged("FlagForValue3");
}
}
public bool FlagForValue3
{
get
{
return (_intValue == 3) ? true : false;
}
set
{
_intValue = 3;
RaisePropertyChanged("FlagForValue1");
RaisePropertyChanged("FlagForValue2");
RaisePropertyChanged("FlagForValue3");
}
}
The xaml looks like this:
<RadioButton GroupName="Search" IsChecked="{Binding Path=FlagForValue1, Mode=TwoWay}"
>Value 1</RadioButton>
<RadioButton GroupName="Search" IsChecked="{Binding Path=FlagForValue2, Mode=TwoWay}"
>Value 2</RadioButton>
<RadioButton GroupName="Search" IsChecked="{Binding Path=FlagForValue3, Mode=TwoWay}"
>Value 3</RadioButton>
return new String(Hex.encode(digest));
The most recent solution is right. You are reading solutions as a string, in which case the order is 1, then 100, then 104 followed by 2 then 21, then 2001001010, 3 and so forth.
You have to CAST your input as an int instead:
sorted strings:
stringList = (1, 10, 2, 21, 3)
sorted ints:
intList = (1, 2, 3, 10, 21)
To cast, just put the stringList inside int ( blahblah ).
Again:
stringList = (1, 10, 2, 21, 3)
newList = int (stringList)
print newList
=> returns (1, 2, 3, 10, 21)
Try
sudo apt-get update
sudo apt-get install build-essential
(If I recall correctly the package name is without the extra s
at the end).
In the spirit of a DVCS (as in "Distributed"), you don't cancel something you have published:
Pull requests are essentially patches you have send (normally by email, here by GitHub webapp), and you wouldn't cancel an email either ;)
But since the GitHub Pull Request system also includes a discussion section, that would be there that you could voice your concern to the recipient of those changes, asking him/her to disregards 29 of your 30 commits.
Finally, remember:
That being said, since January 2011 ("Refreshed Pull Request Discussions"), and mentioned in the answer above, you can close a pull request in the comments.
Look for that "Comment and Close" button at the bottom of the discussion page:
I found one elegant solution as well, have not tested it rigorously though:
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (m_webView.getProgress() == 100) {
progressBar.setVisibility(View.GONE);
m_webView.setVisibility(View.VISIBLE);
}
}
If you want to change the format for all dates you can add a builder customizer. Here is an example of a bean that converts dates to ISO 8601:
@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder builder) {
builder.dateFormat(new ISO8601DateFormat());
}
};
}
None of the answers here show idiomatic functional programming. The recursive factorial answer is great for representing recursion in FP, but the majority of code is not recursive so I don't think that answer is fully representative.
Say you have an arrays of strings, and each string represents an integer like "5" or "-200". You want to check this input array of strings against your internal test case (Using integer comparison). Both solutions are shown below
arr_equal(a : [Int], b : [Str]) -> Bool {
if(a.len != b.len) {
return false;
}
bool ret = true;
for( int i = 0; i < a.len /* Optimized with && ret*/; i++ ) {
int a_int = a[i];
int b_int = parseInt(b[i]);
ret &= a_int == b_int;
}
return ret;
}
eq = i, j => i == j # This is usually a built-in
toInt = i => parseInt(i) # Of course, parseInt === toInt here, but this is for visualization
arr_equal(a : [Int], b : [Str]) -> Bool =
zip(a, b.map(toInt)) # Combines into [Int, Int]
.map(eq)
.reduce(true, (i, j) => i && j) # Start with true, and continuously && it with each value
While pure functional languages are generally research languages (As the real-world likes free side-effects), real-world procedural languages will use the much simpler functional syntax when appropriate.
This is usually implemented with an external library like Lodash, or available built-in with newer languages like Rust. The heavy lifting of functional programming is done with functions/concepts like map
, filter
, reduce
, currying
, partial
, the last three of which you can look up for further understanding.
In order to be used in the wild, the compiler will normally have to work out how to convert the functional version into the procedural version internally, as function call overhead is too high. Recursive cases such as the factorial shown will use tricks such as tail call to remove O(n) memory usage. The fact that there are no side effects allows functional compilers to implement the && ret
optimization even when the .reduce
is done last. Using Lodash in JS, obviously does not allow for any optimization, so it is a hit to performance (Which isn't usually a concern with web development). Languages like Rust will optimize internally (And have functions such as try_fold
to assist && ret
optimization).
I used this and it works well:
string[] filePaths = Directory.GetFiles(Path.GetDirectoryName(dialog.FileName));
foreach (string file in filePaths)
{
if (comboBox1.SelectedItem.ToString() == "")
{
if (file.Contains("c"))
{
comboBox2.Items.Add(Path.GetFileName(file));
}
}
}
You can pass parameters with arbitrary attributes. This works in all recent browsers.
<script type="text/javascript" data-my_var_1="some_val_1" data-my_var_2="some_val_2" src="/js/somefile.js"></script>
Inside somefile.js you can get passed variables values this way:
........
var this_js_script = $('script[src*=somefile]'); // or better regexp to get the file name..
var my_var_1 = this_js_script.attr('data-my_var_1');
if (typeof my_var_1 === "undefined" ) {
var my_var_1 = 'some_default_value';
}
alert(my_var_1); // to view the variable value
var my_var_2 = this_js_script.attr('data-my_var_2');
if (typeof my_var_2 === "undefined" ) {
var my_var_2 = 'some_default_value';
}
alert(my_var_2); // to view the variable value
...etc...
There is a quite easy and useful solution for creating an INSERT Statement for editing without the need to export SQL with just Copy & Paste (Clipboard):
lst = [['a','b','c'], [1,2,3], ['x','y','z']]
outputlist = []
for values in lst:
outputlist.append(values[0])
print(outputlist)
Output: ['a', 1, 'x']
In Django 3.0 auto_now_add
seems to work with auto_now
reg_date=models.DateField(auto_now=True,blank=True)
Instead of using KO's internal functions and dealing with JQuery's blanket event handler removal, a much better idea is using with
or template
bindings. When you do this, ko re-creates that part of DOM and so it automatically gets cleaned. This is also recommended way, see here: https://stackoverflow.com/a/15069509/207661.
Try do something like this (the problem was that you trying to use MyBook.Worksheets
, but MyBook
is not a Workbook
object, but string
, containing workbook name. I've added new varible Set WB = ActiveWorkbook
, so you can use WB.Worksheets
instead MyBook.Worksheets
):
Sub NewWBandPasteSpecialALLSheets()
MyBook = ActiveWorkbook.Name ' Get name of this book
Workbooks.Add ' Open a new workbook
NewBook = ActiveWorkbook.Name ' Save name of new book
Workbooks(MyBook).Activate ' Back to original book
Set WB = ActiveWorkbook
Dim SH As Worksheet
For Each SH In WB.Worksheets
SH.Range("WholePrintArea").Copy
Workbooks(NewBook).Activate
With SH.Range("A1")
.PasteSpecial (xlPasteColumnWidths)
.PasteSpecial (xlFormats)
.PasteSpecial (xlValues)
End With
Next
End Sub
But your code doesn't do what you want: it doesen't copy something to a new WB. So, the code below do it for you:
Sub NewWBandPasteSpecialALLSheets()
Dim wb As Workbook
Dim wbNew As Workbook
Dim sh As Worksheet
Dim shNew As Worksheet
Set wb = ThisWorkbook
Workbooks.Add ' Open a new workbook
Set wbNew = ActiveWorkbook
On Error Resume Next
For Each sh In wb.Worksheets
sh.Range("WholePrintArea").Copy
'add new sheet into new workbook with the same name
With wbNew.Worksheets
Set shNew = Nothing
Set shNew = .Item(sh.Name)
If shNew Is Nothing Then
.Add After:=.Item(.Count)
.Item(.Count).Name = sh.Name
Set shNew = .Item(.Count)
End If
End With
With shNew.Range("A1")
.PasteSpecial (xlPasteColumnWidths)
.PasteSpecial (xlFormats)
.PasteSpecial (xlValues)
End With
Next
End Sub
There are already nice solution has been given. The below code can help others to query over datatable and get the value of each row of the datatable for the ImagePath column.
for (int i = 0; i < dataTable.Rows.Count; i++)
{
var theUrl = dataTable.Rows[i]["ImagePath"].ToString();
}
Like all enum instances, Java instantiates each object when the class is loaded, with some guarantee that it's instantiated exactly once per JVM. Think of the INSTANCE
declaration as a public static final field: Java will instantiate the object the first time the class is referred to.
The instances are created during static initialization, which is defined in the Java Language Specification, section 12.4.
For what it's worth, Joshua Bloch describes this pattern in detail as item 3 of Effective Java Second Edition.
Another approach when you have many updates would be to use COALESCE:
UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET
[ABC] = COALESCE(@ABC, [ABC]),
[ABCD] = COALESCE(@ABCD, [ABCD])
In Python 3, pdb will automatically install a signal handler the first time you use c(ont(inue)) in the debugger. Pressing Control-C afterwards will drop you right back in there. In Python 2, here's a one-liner which should work even in relatively old versions (tested in 2.7 but I checked Python source back to 2.4 and it looked okay):
import pdb, signal
signal.signal(signal.SIGINT, lambda sig, frame: pdb.Pdb().set_trace(frame))
pdb is worth learning if you spend any amount of time debugging Python. The interface is a bit obtuse but should be familiar to anyone who has used similar tools, such as gdb.
You can fix this issue by adding a project ext property googlePlayServicesVersion
to app/App_Resources/Android/app.gradle
file like this:
project.ext {
googlePlayServicesVersion = "+"
}
This should work
<a href="#" onclick="function hi(){alert('Hi!')};hi()">click</a>
You may inline any javascript inside the onclick as if you were assigning the method through javascript. I think is just a matter of making code cleaner keeping your js inside a script block
The command I use is:
diff -qr dir1/ dir2/
It is exactly the same as Mark's :) But his answer bothered me as it uses different types of flags, and it made me look twice. Using Mark's more verbose flags it would be:
diff --brief --recursive dir1/ dir2/
I apologise for posting when the other answer is perfectly acceptable. Could not stop myself... working on being less pedantic.
This one works even with spaces:
format="\t%2s - %s\n"
function doAction
{
local_array=("$@")
for (( i = 0 ; i < ${#local_array[@]} ; i++ ))
do
printf "${format}" $i "${local_array[$i]}"
done
echo -n "Choose: "
option=""
read -n1 option
echo ${local_array[option]}
return
}
#the call:
doAction "${tools[@]}"
I believe if you combine the delete by query with a match all it should do what you are looking for, something like this (using your example):
curl -XDELETE 'http://localhost:9200/twitter/tweet/_query' -d '{
"query" : {
"match_all" : {}
}
}'
Or you could just delete the type:
curl -XDELETE http://localhost:9200/twitter/tweet
Keep derived data but use the DSTROOT to specify the destination.
Use DEPLOYMENT_LOCATION to force deployment.
Use the undocumented DWARF_DSYM_FOLDER_PATH to copy the dSYM over too.
This allows you to use derived data location from xcodebuild and not have to do wacky stuff to find the app.
xcodebuild -sdk "iphoneos" -workspace Foo.xcworkspace -scheme Foo -configuration "Debug" DEPLOYMENT_LOCATION=YES DSTROOT=tmp DWARF_DSYM_FOLDER_PATH=tmp build
double a = 100.3;
printf("%f %d\n", a, (int)(a* 10.0));
Output Cygwin 100.3 1003
Output MinGW: 100.3 1002
Using (int) to convert double to int seems not to be fail-safe
You can find more about that here: Convert double to int?
use: https://registry.npmjs.org/ Make sure you are trying to connect to:
if there is no error,try to clear cache
npm cache clean --force
then try
npm install
even you have any error
npm config set registry https://registry.npmjs.org/
then try
npm install -g @angular/cli
A gcc spec file can do the job, however all users on the machine will be affected.
See here
This works great for large tables.
SELECT NUM_ROWS FROM ALL_TABLES WHERE TABLE_NAME = 'TABLE_NAME_IN_UPPERCASE';
For small to medium size tables, following will be ok.
SELECT COUNT(Primary_Key) FROM table_name;
Cheers,
The ISO C99 standard specifies that these macros must only be defined if explicitly requested.
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
... now PRIu64 will work
I use this piece of code for age calculation ,Hope this helps ..no libraries used
private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
public static int calculateAge(String date) {
int age = 0;
try {
Date date1 = dateFormat.parse(date);
Calendar now = Calendar.getInstance();
Calendar dob = Calendar.getInstance();
dob.setTime(date1);
if (dob.after(now)) {
throw new IllegalArgumentException("Can't be born in the future");
}
int year1 = now.get(Calendar.YEAR);
int year2 = dob.get(Calendar.YEAR);
age = year1 - year2;
int month1 = now.get(Calendar.MONTH);
int month2 = dob.get(Calendar.MONTH);
if (month2 > month1) {
age--;
} else if (month1 == month2) {
int day1 = now.get(Calendar.DAY_OF_MONTH);
int day2 = dob.get(Calendar.DAY_OF_MONTH);
if (day2 > day1) {
age--;
}
}
} catch (ParseException e) {
e.printStackTrace();
}
return age ;
}
A node can be a number of different kinds of things: some text, a comment, an element, an entity, etc. An element is a particular kind of node.
Comparator does everything that comparable does, plus more.
| | Comparable | Comparator ._______________________________________________________________________________ Is used to allow Collections.sort to work | yes | yes Can compare multiple fields | yes | yes Lives inside the class you’re comparing and serves | | as a “default” way to compare | yes | yes Can live outside the class you’re comparing | no | yes Can have multiple instances with different method names | no | yes Input arguments can be a list of | just Object| Any type Can use enums | no | yes
I found the best approach to use comparators as anonymous classes as follows:
private static void sortAccountsByPriority(List<AccountRecord> accounts) {
Collections.sort(accounts, new Comparator<AccountRecord>() {
@Override
public int compare(AccountRecord a1, AccountRecord a2) {
return a1.getRank().compareTo(a2.getRank());
}
});
}
You can create multiple versions of such methods right inside the class you’re planning to sort. So you can have:
sortAccountsByPriorityAndType
etc...
Now, you can use these sort methods anywhere and get code reuse. This gives me everything a comparable would, plus more ... so I don’t see any reason to use comparable at all.
Solution that works for me is adding event listener to paste event if you are pasting to a text input. Since paste event happens before text in input changes, inside my on paste handler I create a deferred function inside which I check for changes in my input box that happened on paste:
onPaste: function() {
var oThis = this;
setTimeout(function() { // Defer until onPaste() is done
console.log('paste', oThis.input.value);
// Manipulate pasted input
}, 1);
}
Comparison of strings is very easy in Ruby:
v1 = "string1"
v2 = "string2"
puts v1 == v2 # prints false
puts "hello"=="there" # prints false
v1 = "string2"
puts v1 == v2 # prints true
Make sure your var2 is not an array (which seems to be like)
Have a look at using something like
Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. A parameter specifies whether the operation is case-sensitive. The return value indicates whether the conversion succeeded.
or
Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
If you define your array in properties file like:
base.module.elementToSearch=1,2,3,4,5,6
You can load such array in your Java class like this:
@Value("${base.module.elementToSearch}")
private String[] elementToSearch;
ggplot
allows you to have multiple layers, and that is what you should take advantage of here.
In the plot created below, you can see that there are two geom_line
statements hitting each of your datasets and plotting them together on one plot. You can extend that logic if you wish to add any other dataset, plot, or even features of the chart such as the axis labels.
library(ggplot2)
jobsAFAM1 <- data.frame(
data_date = runif(5,1,100),
Percent.Change = runif(5,1,100)
)
jobsAFAM2 <- data.frame(
data_date = runif(5,1,100),
Percent.Change = runif(5,1,100)
)
ggplot() +
geom_line(data = jobsAFAM1, aes(x = data_date, y = Percent.Change), color = "red") +
geom_line(data = jobsAFAM2, aes(x = data_date, y = Percent.Change), color = "blue") +
xlab('data_date') +
ylab('percent.change')
No, You can't do that, the only place you can call the constructor from another constructor in C# is immediately after ":" after the constructor. for example
class foo
{
public foo(){}
public foo(string s ) { }
public foo (string s1, string s2) : this(s1) {....}
}
This is how I do this in order to work with LINQ.
DateTime date_time_to_compare = DateTime.Now;
//Compare only date parts
context.YourObject.FirstOrDefault(r =>
EntityFunctions.TruncateTime(r.date) == EntityFunctions.TruncateTime(date_to_compare));
If you only use dtOne.Date == dtTwo.Date
it wont work with LINQ (Error: The specified type member 'Date' is not supported in LINQ to Entities)
This whole answer is in the context of spec compliance, not what any engine does at a particular moment or historically.
The actual question is very vague.
will the properties be in the same order that I added them
In what context?
The answer is: it depends on a number of factors. In general, no.
Here is where you can count on property key order for plain Objects
:
Object.getOwnPropertyNames()
, Reflect.ownKeys()
, Object.getOwnPropertySymbols(O)
In all cases these methods include non-enumerable property keys and order keys as specified by [[OwnPropertyKeys]]
(see below). They differ in the type of key values they include (String
and / or Symbol
). In this context String
includes integer values.
Object.getOwnPropertyNames(O)
Returns O
's own String
-keyed properties (property names).
Reflect.ownKeys(O)
Returns O
's own String
- and Symbol
-keyed properties.
Object.getOwnPropertySymbols(O)
Returns O
's own Symbol
-keyed properties.
[[OwnPropertyKeys]]
The order is essentially: integer-like Strings
in ascending order, non-integer-like Strings
in creation order, Symbols in creation order. Depending which function invokes this, some of these types may not be included.
The specific language is that keys are returned in the following order:
... each own property key
P
ofO
[the object being iterated] that is an integer index, in ascending numeric index order... each own property key
P
ofO
that is a String but is not an integer index, in property creation order... each own property key
P
ofO
that is a Symbol, in property creation order
Map
If you're interested in ordered maps you should consider using the Map
type introduced in ES2015 instead of plain Objects
.
DirectoryInfo dirinfo = new DirectoryInfo(strMainPath);
String[] exts = new string[] { "*.jpeg", "*.jpg", "*.gif", "*.tiff", "*.bmp","*.png", "*.JPEG", "*.JPG", "*.GIF", "*.TIFF", "*.BMP","*.PNG" };
ArrayList files = new ArrayList();
foreach (string ext in exts)
files.AddRange(dirinfo.GetFiles(ext).OrderBy(x => x.CreationTime).ToArray());
Got this error randomly in VS1017, when trying to build a project that was building perfectly fine the day before. Restarting the PC fixed the issue worked (I also ran the following command beforehand, not sure if it's required: netsh winsock reset)
I think you want to set the response of the call to the URL 'compz.php?prodid=' + x + '&qbuys=' + y
as value of the textbox right? If so, you have to do something like:
$.get('compz.php?prodid=' + x + '&qbuys=' + y, function(data) {
$('#subtotal').val(data);
});
Reference: get()
You have two errors in your code:
load()
puts the HTML returned from the Ajax into the specified element:
Load data from the server and place the returned HTML into the matched element.
You cannot set the value of a textbox with that method.
$(selector).load()
returns the a jQuery object. By default an object is converted to [object Object]
when treated as string.
Further clarification:
Assuming your URL returns 5
.
If your HTML looks like:
<div id="foo"></div>
then the result of
$('#foo').load('/your/url');
will be
<div id="foo">5</div>
But in your code, you have an input element. Theoretically (it is not valid HTML and does not work as you noticed), an equivalent call would result in
<input id="foo">5</input>
But you actually need
<input id="foo" value="5" />
Therefore, you cannot use load()
. You have to use another method, get the response and set it as value yourself.
I assume by "key" and "value" you mean:
<select>
<option value="KEY">VALUE</option>
</select>
If that's the case, this will get you the "VALUE":
$(this).find('option:selected').text();
And you can get the "KEY" like this:
$(this).find('option:selected').val();
You need to use Arrow function ()=>
ES6 feature to preserve this
context within setTimeout
.
// var that = this; // no need of this line
this.messageSuccess = true;
setTimeout(()=>{ //<<<---using ()=> syntax
this.messageSuccess = false;
}, 3000);
I have found that the simplest way to do this is to set onClick for each button in the xml
<Button
android:id="@+id/vrHelp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_menu_help"
android:onClick="helpB" />
and then you can do a switch case like this
public void helpB(View v) {
Button clickedButton = (Button) v;
switch (clickedButton.getId()) {
case R.id.vrHelp:
dosomething...
break;
case R.id.coHelp:
dosomething...
break;
case R.id.ksHelp:
dosomething...
break;
case R.id.uHelp:
dosomething...
break;
case R.id.pHelp:
dosomething...
break;
}
}
./Database/DataModels/RelationalDataModel/WeakEntity
It probably can be written in two factors:
If we would think of a database holding questions and answers, then the questions would be the strong entity and the answers would be the weak entity. So, Question (id, text) and Answer (number, question_id, text) would be our tables. But why is the Answer's table a weak entity?
Dependence to the question table. Every answer is connected to one question (assumption) and so it cannot be on its own. That is why we have people who ask one question and answer it themselves so that they can help other people and get some extra likings.
Identification from the primary key of the question. One would not be able to identify an answer (assuming that its id is a number identifier) because a question might be answered by answers whose identifier might exist in other questions too. Primary key of the answer table: (number, question_id).
Ian Mackinnon found the answer, but it's better with xargs:
git ls-files --deleted -z | xargs -r0 git rm
As a git alias:
git config --global alias.rm-deleted '!git ls-files --deleted -z | xargs -r0 git rm'
This uses xargs with NUL termination (the only byte guarranteed not to appear in a path) and the option to not run git rm
if the file list is empty.
This syntax is also fish compatible.
FOR Visual Studio Code
What works for me is to make sure I do the standard JQuery library loading via a < script > tag in the index.html.
Run
npm install --save @types/jquery
Now the JQuery $ functions are available in all .ts files, no need of any other imports.
You can look up an object's keys and values by either invoking JavaScript's native for in
loop:
var obj = {
foo: 'bar',
base: 'ball'
};
for(var key in obj) {
alert('key: ' + key + '\n' + 'value: ' + obj[key]);
}
or using jQuery's .each()
method:
$.each(obj, function(key, element) {
alert('key: ' + key + '\n' + 'value: ' + element);
});
With the exception of six primitive types, everything in ECMA-/JavaScript is an object. Arrays; functions; everything is an object. Even most of those primitives are actually also objects with a limited selection of methods. They are cast into objects under the hood, when required. To know the base class name, you may invoke the Object.prototype.toString
method on an object, like this:
alert(Object.prototype.toString.call([]));
The above will output [object Array]
.
There are several other class names, like [object Object]
, [object Function]
, [object Date]
, [object String]
, [object Number]
, [object Array]
, and [object Regex]
.
They pretty much got it there... just like a checkbox, all you have to do is add the attribute checked="checked" like so:
<input type="radio" checked="checked">
...and you got it.
Cheers!
The following VBA code should get you started. It will copy all of the data in the original workbook to a new workbook, but it will have added 1 to each value, and all blank cells will have been ignored.
Option Explicit
Public Sub exportDataToNewBook()
Dim rowIndex As Integer
Dim colIndex As Integer
Dim dataRange As Range
Dim thisBook As Workbook
Dim newBook As Workbook
Dim newRow As Integer
Dim temp
'// set your data range here
Set dataRange = Sheet1.Range("A1:B100")
'// create a new workbook
Set newBook = Excel.Workbooks.Add
'// loop through the data in book1, one column at a time
For colIndex = 1 To dataRange.Columns.Count
newRow = 0
For rowIndex = 1 To dataRange.Rows.Count
With dataRange.Cells(rowIndex, colIndex)
'// ignore empty cells
If .value <> "" Then
newRow = newRow + 1
temp = doSomethingWith(.value)
newBook.ActiveSheet.Cells(newRow, colIndex).value = temp
End If
End With
Next rowIndex
Next colIndex
End Sub
Private Function doSomethingWith(aValue)
'// This is where you would compute a different value
'// for use in the new workbook
'// In this example, I simply add one to it.
aValue = aValue + 1
doSomethingWith = aValue
End Function
in my case i want something like
[10,5,15,20,25] -> [ 2, 1, 3, 4, 5 ]
function ratio(array){_x000D_
let min = Math.min(...array);_x000D_
let ratio = array.map((element)=>{_x000D_
return element/min;_x000D_
});_x000D_
return ratio;_x000D_
}_x000D_
document.write(ratio([10,5,15,20,25])); // [ 2, 1, 3, 4, 5 ]
_x000D_
You need to add the Servlet API to your classpath. In Tomcat 6.0, this is in a JAR called servlet-api.jar
in Tomcat's lib
folder. You can either add a reference to that JAR to the project's classpath, or put a copy of the JAR in your Eclipse project and add it to the classpath from there.
If you want to leave the JAR in Tomcat's lib
folder:
servlet-api.jar
and select it.Or, if you copy the JAR into your project:
servlet-api.jar
in your project and select it.with pure javascript
var condition = true; // your condition
if(condition) {
var theSelect = document.getElementById('val');
var options = theSelect.getElementsByTagName('OPTION');
for(var i=0; i<options.length; i++) {
if(options[i].innerHTML == 'Apple' || options[i].innerHTML == 'Cars') {
theSelect.removeChild(options[i]);
i--; // options have now less element, then decrease i
}
}
}
not tested with IE (if someone can confirm it...)
Commenting out this line worked for me: $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin'; But I found several config.inc.php files on my computer because I had a couple installations of MySQL and php haha. I changed it by finding the one under Xampp by just clicking on the config button under Apache for the Xampp control panel then commenting out the line. //
You are right - you declared a new use defined type (Name_pairs) and you need variable of that type to use it.
The code should go like this:
Name_pairs np;
np.read_names()
For me this was caused by a limit on the number of concurrent ssh sessions. I added the two params below to /etc/ssh/sshd_config and then things worked.
echo 'MaxSessions 2000' >> /etc/ssh/sshd_config
echo 'MaxStartups 2000' >> /etc/ssh/sshd_config
service ssh restart
Just come across this, the answer is simple, use ISNULL
. SQL won't return rows if the field you are testing has no value (in some of the records) when doing a text comparison search, eg:
WHERE wpp.comment NOT LIKE '%CORE%'
So, you have temporarily substitute a value in the null
(empty) records by using the ISNULL
command, eg
WHERE (ISNULL(wpp.comment,'')) NOT LIKE '%CORE%'
This will then show all your records that have nulls and omit any that have your matching criteria. If you wanted, you could put something in the commas to help you remember, eg
WHERE (ISNULL(wpp.comment,'some_records_have_no_value')) NOT LIKE '%CORE%'
The problem is that undefined compared to null using == gives true. The common check for undefined is therefore done like this:
typeof x == "undefined"
this ensures the type of the variable is really undefined.
Combine JS & CSS :
button{
/* 1st state */
}
button:hover{
/* hover state */
}
button:active{
/* click state */
}
button.active{
/* after click state */
}
jQuery('button').click(function(){
jQuery(this).toggleClass('active');
});
This is the most important part in the code provided in the original post.
Button one = (Button) this.findViewById(R.id.button1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
mp.start();
}
});
To explain it step by step:
Button one = (Button) this.findViewById(R.id.button1);
First is the initialization of the button to be used in playing the sound. We use the Activity's findViewById
, passing the Id we assigned to it (in this example's case: R.id.button1
), to get the button that we need. We cast it as a Button
so that it is easy to assign it to the variable one
that we are initializing. Explaining more of how this works is out of scope for this answer. This gives a brief insight on how it works.
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
This is how to initialize a MediaPlayer
. The MediaPlayer follows the Static Factory Method Design Pattern. To get an instance, we call its create()
method and pass it the context and the resource Id of the sound we want to play, in this case R.raw.soho
. We declare it as final
. Jon Skeet provided a great explanation on why we do so here.
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
//code
}
});
Finally, we set what our previously initialized button will do. Play a sound on button click! To do this, we set the OnClickListener
of our button one
. Inside is only one method, onClick()
which contains what instructions the button should do on click.
public void onClick(View v) {
mp.start();
}
To play the sound, we call MediaPlayer's start()
method. This method starts the playback of the sound.
There, you can now play a sound on button click in Android!
Bonus part:
As noted in the comment belowThanks Langusten Gustel!, and as recommended in the Android Developer Reference, it is important to call the release()
method to free up resources that will no longer be used. Usually, this is done once the sound to be played has completed playing. To do so, we add an OnCompletionListener
to our mp
like so:
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
//code
}
});
Inside the onCompletion
method, we release it like so:
public void onCompletion(MediaPlayer mp) {
mp.release();
}
There are obviously better ways of implementing this. For example, you can make the MediaPlayer a class variable and handle its lifecycle along with the lifecycle of the Fragment
or Activity
that uses it. However, this is a topic for another question. To keep the scope of this answer small, I wrote it just to illustrate how to play a sound on button click in Android.
First. You should put your statements inside a block, and in this case the onCreate method.
Second. You initialized the button as variable one, then you used a variable zero and set its onClickListener to an incomplete onClickListener. Use the variable one for the setOnClickListener.
Third, put the logic to play the sound inside the onClick.
In summary:
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class BasicScreenActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic_screen);
Button one = (Button)this.findViewById(R.id.button1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
mp.start();
}
});
}
}
In Spring Boot 2, the easiest way is to declare in your application.properties:
spring.jackson.serialization.WRITE_ENUMS_USING_TO_STRING=true
spring.jackson.deserialization.READ_ENUMS_USING_TO_STRING=true
and define the toString() method of your enums.
Inspite of many answers and almost same result. I would like to add my answer and explain its working. Because it is important to understand its working rather than copy pasting one line code. Generating random numbers is nothing but simple maths.
CODE:
function getR(lower, upper) {
var percent = (Math.random() * 100);
// this will return number between 0-99 because Math.random returns decimal number from 0-0.9929292 something like that
//now you have a percentage, use it find out the number between your INTERVAL :upper-lower
var num = ((percent * (upper - lower) / 100));
//num will now have a number that falls in your INTERVAL simple maths
num += lower;
//add lower to make it fall in your INTERVAL
//but num is still in decimal
//use Math.floor>downward to its nearest integer you won't get upper value ever
//use Math.ceil>upward to its nearest integer upper value is possible
//Math.round>to its nearest integer 2.4>2 2.5>3 both lower and upper value possible
console.log(Math.floor(num), Math.ceil(num), Math.round(num));
}
This rings a bell. I came across a similar problem in the past,
You can generate an assemblyInfo.cs by right clicking the project and chosing properties. In the application tab fill in the details and press save, this will generate the assemblyInfo.cs file for you. If you build your project after that, it should work.
Cheers, Tarun
Update 2016-07-08:
For Visual Studio 2010 through the most recent version (2015 at time of writing), LandedGently's comment still applies:
After you select project Properties and the Application tab as @Tarun mentioned, there is a button "Assembly Information..." which opens another dialog. You need to at least fill in the Title here. VS will add the GUID and versions, but if the title is empty, it will not create the AssemblyInfo.cs file.
In my delegate callback, I check to see if I'm running in a simulator (#if TARGET_ IPHONE_SIMULATOR
) and if so, I supply my own, pre-looked-up, Lat/Long. To my knowledge, there's no other way.
Move all of your state and your handleClick
function from Header
to your MainWrapper
component.
Then pass values as props to all components that need to share this functionality.
class MainWrapper extends React.Component {
constructor() {
super();
this.state = {
sidbarPushCollapsed: false,
profileCollapsed: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
profileCollapsed: !this.state.profileCollapsed
});
}
render() {
return (
//...
<Header
handleClick={this.handleClick}
sidbarPushCollapsed={this.state.sidbarPushCollapsed}
profileCollapsed={this.state.profileCollapsed} />
);
Then in your Header's render() method, you'd use this.props
:
<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>
View if you need change background color , Space if not .
that dosent mean you have to change view background .
<View
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="@color/YOUR_BACKGROUND">
</View>
or Space
<Space
android:layout_width="match_parent"
android:layout_height="20dp"
/>
"12".match(/^(\d)+$/) # true
"1.2".match(/^(\d)+$/) # false
"dfs2".match(/^(\d)+$/) # false
"13422".match(/^(\d)+$/) # true
Use REG to save/modify/restore what ever values are most useful for your bat file. This is windows 7, for other versions you may need a different key name.
reg save "HKEY_CURRENT_USER\Control Panel\International" _tmp.reg /y
reg add "HKEY_CURRENT_USER\Control Panel\International" /v sShortDate /d "yyyy-MM-dd" /f
set file=%DATE%-%TIME: =0%
reg restore "HKEY_CURRENT_USER\Control Panel\International" _tmp.reg
set file=%file::=-%
set file=%file:.=-%
set file
For most installations, you should not set these variables since they are not needed for Python to run. Python knows where to find its standard library.
The only reason to set PYTHONPATH is to maintain directories of custom Python libraries that you do not want to install in the global default location (i.e., the site-packages
directory).
Make sure to read: http://docs.python.org/using/cmdline.html#environment-variables
it is important to remove the browser interpreted setting from the parent div. So if you want the real image width and height you can just use
$('.right-sidebar').find('img').each(function(){
$(this).removeAttr("width");
$(this).removeAttr("height");
$(this).imageResize();
});
This is one TYPO3 Project example from me where I need the real properties of the image to scale it with the right relation.
You need to add in the seconds, too:
unsigned long time_in_micros = 1000000 * tv.tv_sec + tv.tv_usec;
Note that this will only last for about 232/106 =~ 4295 seconds, or roughly 71 minutes though (on a typical 32-bit system).
there should has a concurrent implemention of List interface supporting such operation.
try java.util.concurrent.CopyOnWriteArrayList.class
Which whitespace character? The empty string is pretty unambiguous - it's a sequence of 0 characters. However, " "
, "\t"
and "\n"
are all strings containing a single character which is characterized as whitespace.
If you just mean a space, use a space. If you mean some other whitespace character, there may well be a custom escape sequence for it (e.g. "\t"
for tab) or you can use a Unicode escape sequence ("\uxxxx"
). I would discourage you from including non-ASCII characters in your source code, particularly whitespace ones.
EDIT: Now that you've explained what you want to do (which should have been in your question to start with) you'd be better off using Regex.Split
with a regular expression of \s
which represents whitespace:
Regex regex = new Regex(@"\s");
string[] bits = regex.Split(text.ToLower());
See the Regex Character Classes documentation for more information on other character classes.
This is the solution that worked for me
https://gist.github.com/elidickinson/5525752#gistcomment-1649300, thanks to @philipp-klinz
<table cellpadding="0" cellspacing="0" border="0" style="padding:0px;margin:0px;width:100%;">
<tr><td colspan="3" style="padding:0px;margin:0px;font-size:20px;height:20px;" height="20"> </td></tr>
<tr>
<td style="padding:0px;margin:0px;"> </td>
<td style="padding:0px;margin:0px;" width="560"><!-- max width goes here -->
<!-- PLACE CONTENT HERE -->
</td>
<td style="padding:0px;margin:0px;"> </td>
</tr>
<tr><td colspan="3" style="padding:0px;margin:0px;font-size:20px;height:20px;" height="20"> </td></tr>
</table>
If you see this message in Debug from Visual Studio and solution contains WCF project. Then open this WCF project settings -> go to "WCF Options" tab -> off "Start WCF Service Host when debugging..." option
If you are trying to get the id, then please update your code like
html += '<option id = "' + n.id + "' value="' + i + '">' + n.names + '</option>';
To retrieve id,
$('option:selected').attr("id")
To retrieve Value
$('option:selected').val()
in Javascript
var e = document.getElementById("jobSel");
var job = e.options[e.selectedIndex].value;
There are 3 ways to do it.
You can directly access
HttpContext.Current.Session
You can Mock
HttpContextBase
Create a extension method for
HttpContextBase
I prefer 3rd way.This link is good reference.
Singleton that can't change the object after the instantiation
class User {
final int age;
final String name;
User({
this.name,
this.age
});
static User _instance;
static User getInstance({name, age}) {
if(_instance == null) {
_instance = User(name: name, age: age);
return _instance;
}
return _instance;
}
}
print(User.getInstance(name: "baidu", age: 24).age); //24
print(User.getInstance(name: "baidu 2").name); // is not changed //baidu
print(User.getInstance()); // {name: "baidu": age 24}
Here is my answer,
In row.model.ts
export interface Row {
otherProperty : type;
checked : bool;
otherProperty : type;
...
}
In .html
<tr class="even" *ngFor="let item of rows">
<input [checked]="item.checked" type="checkbox">
</tr>
In .ts
rows : Row[] = [];
update the rows in component.ts
You can use a set to remove duplicates, and then the len function to count the elements in the set:
len(set(new_words))
Use DateTime.Today as opposed to DateTime.Now (which is what Get-Date returns) because Today is just the date with 00:00 as the time, and now is the moment in time down to the millisecond. (from masenkablast)
> [DateTime]::Today.AddDays(-1).AddHours(22)
Thursday, March 11, 2010 10:00:00 PM
Use below method, just pass the subject and body as arguments of the method
public static void shareText(String subject,String body) {
Intent txtIntent = new Intent(android.content.Intent.ACTION_SEND);
txtIntent .setType("text/plain");
txtIntent .putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
txtIntent .putExtra(android.content.Intent.EXTRA_TEXT, body);
startActivity(Intent.createChooser(txtIntent ,"Share"));
}
I just managed how to center icons and and making them a container instead of putting them into one.
.fas {
position: relative;
color: #EEE;
font-size: 16px;
}
.fas:before {
position: absolute;
left: calc(50% - .5em);
top: calc(50% - .5em);
}
.fas.fa-icon {
width: 60px;
height: 60px;
color: white;
background-color: black;
}
To add to Amol's answer, don't make the mistake of specifying the Interface class type. Make sure you specify the implementation class. (Ie. don't use IDomainObjectType). Not that I made this mistake... :)
One Line:
ALTER TABLE `user_customer_permission` DROP PRIMARY KEY , ADD PRIMARY KEY ( `id` )
You will also not lose the auto-increment and have to re-add it which could have side-effects.
Actually if you create func:
create function p1() returns INTEGER DETERMINISTIC NO SQL return @p1;
and view:
create view h_parm as
select * from sw_hardware_big where unit_id = p1() ;
Then you can call a view with a parameter:
select s.* from (select @p1:=12 p) parm , h_parm s;
I hope it helps.
U can also try this
$("#dialog").dialog({
autoOpen: false,
resizable: true,
height: 400,
width: 150,
position: 'center',
title: 'Term Sheet',
beforeClose: function(event, ui) {
console.log('Event Fire');
},
modal: true,
buttons: {
"Submit": function () {
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
A MemoryStream can be helpful for this. You could put it in an extension method:
public static class ImageExtensions
{
public static byte[] ToByteArray(this Image image, ImageFormat format)
{
using(MemoryStream ms = new MemoryStream())
{
image.Save(ms, format);
return ms.ToArray();
}
}
}
You could just use it like:
var image = new Bitmap(10, 10);
// Draw your image
byte[] arr = image.ToByteArray(ImageFormat.Bmp);
I partially disagree with prestomanifto's answer in regards to the ImageConverter. Do not use ImageConverter. There's nothing technically wrong with it, but simply the fact that it uses boxing/unboxing from object tells me it's code from the old dark places of the .NET framework and its not ideal to use with image processing (it's overkill for converting to a byte[] at least), especially when you consider the following.
I took a look at the ImageConverter
code used by the .Net framework, and internally it uses code almost identical to the one I provided above. It creates a new MemoryStream
, saves the Bitmap
in whatever format it was in when you provided it, and returns the array. Skip the extra overhead of creating an ImageConverter
class by using MemoryStream
if you are not using model as per your question you can do like this
@Html.Hidden("hdnFlag" , new {id = "hdnFlag", value = "hdnFlag_value" })
else if you are using model (considering passing model has hdnFlag property), you can use this approch
@Html.HiddenFor(model => model.hdnFlag, new { value = Model.hdnFlag})
Correct Method is
.PopupPanel
{
border: solid 1px black;
position: fixed;
left: 50%;
top: 50%;
background-color: white;
z-index: 100;
height: 400px;
margin-top: -200px;
width: 600px;
margin-left: -300px;
}
Answer in short: (search your situation)
SQL Loader helps load csv files into tables: SQL*Loader
If you want sqlplus only, then it gets a bit complicated. You need to locate your sqlloader script and csv file, then run the sqlldr command.
OK so I think i know the issue you're having.
Basically, because Composer can't see the migration files you are creating, you are having to run the dump-autoload command which won't download anything new, but looks for all of the classes it needs to include again. It just regenerates the list of all classes that need to be included in the project (autoload_classmap.php), and this is why your migration is working after you run that command.
How to fix it (possibly) You need to add some extra information to your composer.json file.
"autoload": {
"classmap": [
"PATH TO YOUR MIGRATIONS FOLDER"
],
}
You need to add the path to your migrations folder to the classmap array. Then run the following three commands...
php artisan clear-compiled
composer dump-autoload
php artisan optimize
This will clear the current compiled files, update the classes it needs and then write them back out so you don't have to do it again.
Ideally, you execute composer dump-autoload -o
, for a faster load of your webpages. The only reason it is not default, is because it takes a bit longer to generate (but is only slightly noticable).
Hope you can manage to get this sorted, as its very annoying indeed :(
There is a good class that does what you want. It can be downloaded at: http://sourceforge.net/projects/snoopy/
For those, who don't like Regex
, here is a method that uses the StringBuilder
:
public static string FilterWhiteSpaces(string input)
{
if (input == null)
return string.Empty;
StringBuilder stringBuilder = new StringBuilder(input.Length);
for (int i = 0; i < input.Length; i++)
{
char c = input[i];
if (i == 0 || c != ' ' || (c == ' ' && input[i - 1] != ' '))
stringBuilder.Append(c);
}
return stringBuilder.ToString();
}
In my tests, this method was 16 times faster on average with a very large set of small-to-medium sized strings, compared to a static compiled Regex. Compared to a non-compiled or non-static Regex, this should be even faster.
Keep in mind, that it does not remove leading or trailing spaces, only multiple occurrences of such.
First add HTML code:
<form action="" method="post">
<input type="text" name="search">
<input type="submit" name="submit" value="Search">
</form>
Now added PHP code:
<?php
$search_value=$_POST["search"];
$con=new mysqli($servername,$username,$password,$dbname);
if($con->connect_error){
echo 'Connection Faild: '.$con->connect_error;
}else{
$sql="select * from information where First_Name like '%$search_value%'";
$res=$con->query($sql);
while($row=$res->fetch_assoc()){
echo 'First_name: '.$row["First_Name"];
}
}
?>
it is simple just use .qsize() example:
a=Queue()
a.put("abcdef")
print a.qsize() #prints 1 which is the size of queue
The above snippet applies for Queue()
class of python. Thanks @rayryeng for the update.
for deque from collections
we can use len()
as stated here by K Z.
use enumerate:
>>> l = ['a', 'b', 'c', 'd']
>>> for index, val in enumerate(l):
... print "%d: %s" % (index, val)
...
0: a
1: b
2: c
3: d
If you define the ListView
in XAML:
<ListView x:Name="listView"/>
Then you can add columns and populate it in C#:
public Window()
{
// Initialize
this.InitializeComponent();
// Add columns
var gridView = new GridView();
this.listView.View = gridView;
gridView.Columns.Add(new GridViewColumn {
Header = "Id", DisplayMemberBinding = new Binding("Id") });
gridView.Columns.Add(new GridViewColumn {
Header = "Name", DisplayMemberBinding = new Binding("Name") });
// Populate list
this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}
See definition of MyItem
below.
However, it's easier to define the columns in XAML (inside the ListView
definition):
<ListView x:Name="listView">
<ListView.View>
<GridView>
<GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
</GridView>
</ListView.View>
</ListView>
And then just populate the list in C#:
public Window()
{
// Initialize
this.InitializeComponent();
// Populate list
this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}
See definition of MyItem
below.
MyItem
DefinitionMyItem
is defined like this:
public class MyItem
{
public int Id { get; set; }
public string Name { get; set; }
}
sudo gem install cocoapods --pre -n /usr/local/bin
This works for me.
http://php.net/ereg_replace says:
Note: As of PHP 5.3.0, the regex extension is deprecated in favor of the PCRE extension.
Thus, preg_replace is in every way better choice. Note there are some differences in pattern syntax though.
For %d
part refer to this How does this program work? and for decimal places use %.2f
Another way to understand the relationship between these concepts is to interpret a ROLE as a container of Authorities.
Authorities are fine-grained permissions targeting a specific action coupled sometimes with specific data scope or context. For instance, Read, Write, Manage, can represent various levels of permissions to a given scope of information.
Also, authorities are enforced deep in the processing flow of a request while ROLE are filtered by request filter way before reaching the Controller. Best practices prescribe implementing the authorities enforcement past the Controller in the business layer.
On the other hand, ROLES are coarse grained representation of an set of permissions. A ROLE_READER would only have Read or View authority while a ROLE_EDITOR would have both Read and Write. Roles are mainly used for a first screening at the outskirt of the request processing such as http. ... .antMatcher(...).hasRole(ROLE_MANAGER)
The Authorities being enforced deep in the request's process flow allows a finer grained application of the permission. For instance, a user may have Read Write permission to first level a resource but only Read to a sub-resource. Having a ROLE_READER would restrain his right to edit the first level resource as he needs the Write permission to edit this resource but a @PreAuthorize interceptor could block his tentative to edit the sub-resource.
Jake
Exchanges will usually publish an up-to-date list of securities on their web pages. For example, these pages offer CSV downloads:
NASDAQ Updated their site, so you will have to modify the URLS:
NASDAQ
AMEX
NYSE
Depending on your requirement, you could create the map of these URLs by exchange in your own code.
Put the following line in your myscript
set myFold = '~/Files/Scripts/Main'
In the terminal use
source myscript
cd $myFold
Hi I know this post has been going on for a while, but I had a very similar problem with my canvas. like mentioned as the viewport gets resized and so does the elements within the window. This can be done using css, however it doesnt quite apply to the elements within the canvas. Now if your canvas context is 2D this is the solution that works for me... This can be used as a method.
class ParentObject{
constructor()
/**
* @this this._width - Private width variable that would store the size of the window width
*/
this._width = Number();
/**
* @this this._height - Private Height variable that would store the height of the window
*/
this._height= Number();
/**
* Calls the getCanvasDimensions method
*/
this.getCanvasDimensions();
//Getting the Width and Height as soon as the Window loads
window.addEventListener('load',()=>{
this.getCanvasDimensions()
})
//As the window is resized we are getting the new Canvas Dimensions
window.addEventListener('resize',()=>{
this.getCanvasDimensions();
getCanvasDimensions() {
// Width is determined by the css value for the viewport width this is then respected by the device pixel ratio. This is then used to set the canvas.width value
this._width = Math.round((Number(getComputedStyle(canvas).getPropertyValue('width').slice(0,-2))/devicePixelRatio) * devicePixelRatio);
//Setting the canvas width
canvas.width = this._width
// height is determined by the css value for the viewport height this is then respected by the device pixel ratio. This is then used to set the canvas.height value
this._height = Math.round((Number(getComputedStyle(canvas).getPropertyValue('height').slice(0,-2))/devicePixelRatio) * devicePixelRatio);
//Setting the canvas height
canvas.height = this._height
}
get width(){
//This sets the width to the private _width value
return this._width
}
get height(){
//This sets the height to the private _height value
return this._height
}
As a function on the global scope:
let width,height
function responsiveCanvas(){
let w = Math.round((Number(getComputedStyle(canvas).getPropertyValue('width').slice(0,-2))/devicePixelRatio) * devicePixelRatio);
width = canvas.height = w;
let h = Math.round((Number(getComputedStyle(canvas).getPropertyValue('height').slice(0,-2))/devicePixelRatio) * devicePixelRatio);
height = canvas.height = h;
}
window.addEventListener('load',responsiveCanvas)
window.addEventListener('resize',responsiveCanvas)
Then just use the width
and height
variables to reference the sizes.
Anyways I hope that this helps someone out.
This function will tell you the x,y position of the element relative to the page. Basically you have to loop up through all the element's parents and add their offsets together.
function getPos(el) {
// yay readability
for (var lx=0, ly=0;
el != null;
lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
return {x: lx,y: ly};
}
However, if you just wanted the x,y position of the element relative to its container, then all you need is:
var x = el.offsetLeft, y = el.offsetTop;
To put an element directly below this one, you'll also need to know its height. This is stored in the offsetHeight/offsetWidth property.
var yPositionOfNewElement = el.offsetTop + el.offsetHeight + someMargin;
Check for root:
ROOT_UID=0 # Root has $UID 0.
if [ "$UID" -eq "$ROOT_UID" ]
then
echo "You are root."
else
echo "You are just an ordinary user."
fi
exit 0
Tested and running in root.
Assuming you're referring to this plugin, your code should be:
// To Store
$(function() {
$.session.set("myVar", "value");
});
// To Read
$(function() {
alert($.session.get("myVar"));
});
Before using a plugin, remember to read its documentation in order to learn how to use it. In this case, an usage example can be found in the README.markdown
file, which is displayed on the project page.
Just another viewpoint. Performing an "or" in Prolog can also be done with the "disjunct" operator or semi-colon:
registered(X, Y) :-
X = ct101; X = ct102; X = ct103.
For a fuller explanation:
Eric Lippert did a very interesting (as always) post about the probability of hash collisions.
You should read it all but he concluded with this very illustrative graphic:
Related to your specific question, I would also go with GetHashCode
since collisions will be unavoidable either way.
To make POST request instead of GET request using urllib2
, you need to specify empty data, for example:
import urllib2
req = urllib2.Request("http://am.domain.com:8080/openam/json/realms/root/authenticate?authIndexType=Module&authIndexValue=LDAP")
req.add_header('X-OpenAM-Username', 'demo')
req.add_data('')
r = urllib2.urlopen(req)
This appears to be a UTF-8 encoding issue that may have been caused by a double-UTF8-encoding of the database file contents.
This situation could happen due to factors such as the character set that was or was not selected (for instance when a database backup file was created) and the file format and encoding database file was saved with.
I have seen these strange UTF-8 characters in the following scenario (the description may not be entirely accurate as I no longer have access to the database in question):
Looking into the file contents:
So, the issue is that "false" (UTF8-encoded twice) utf-8 needs to be converted back into "correct" utf-8 (only UTF8-encoded once).
Trying to fix this in PHP turns out to be a bit challenging:
utf8_decode() is not able to process the characters.
// Fails silently (as in - nothing is output)
$str = "så";
$str = utf8_decode($str);
printf("\n%s", $str);
$str = utf8_decode($str);
printf("\n%s", $str);
iconv() fails with "Notice: iconv(): Detected an illegal character in input string".
echo iconv("UTF-8", "ISO-8859-1", "så");
Another fine and possible solution fails silently too in this scenario
$str = "så";
echo html_entity_decode(htmlentities($str, ENT_QUOTES, 'UTF-8'), ENT_QUOTES , 'ISO-8859-15');
mb_convert_encoding() silently: #
$str = "så";
echo mb_convert_encoding($str, 'ISO-8859-15', 'UTF-8');
// (No output)
Trying to fix the encoding in MySQL by converting the MySQL database characterset and collation to UTF-8 was unsuccessfully:
ALTER DATABASE myDatabase CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE myTable CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
I see a couple of ways to resolve this issue.
The first is to make a backup with correct encoding (the encoding needs to match the actual database and table encoding). You can verify the encoding by simply opening the resulting SQL file in a text editor.
The other is to replace double-UTF8-encoded characters with single-UTF8-encoded characters. This can be done manually in a text editor. To assist in this process, you can manually pick incorrect characters from Try UTF-8 Encoding Debugging Chart (it may be a matter of replacing 5-10 errors).
Finally, a script can assist in the process:
$str = "så";
// The two arrays can also be generated by double-encoding values in the first array and single-encoding values in the second array.
$str = str_replace(["Ã","Â¥"], ["Ã","¥"], $str);
$str = utf8_decode($str);
echo $str;
// Output: "så" (correct)
This question is now a bit old... but I'll throw my hat into the ring.
I personally find an algorithm of the form find_paths[s, t, d, k]
useful, where:
Using your programming language's form of infinity for d
and k
will give you all paths§.
§ obviously if you are using a directed graph and you want all undirected paths between s
and t
you will have to run this both ways:
find_paths[s, t, d, k] <join> find_paths[t, s, d, k]
I personally like recursion, although it can difficult some times, anyway first lets define our helper function:
def find_paths_recursion(graph, current, goal, current_depth, max_depth, num_paths, current_path, paths_found)
current_path.append(current)
if current_depth > max_depth:
return
if current == goal:
if len(paths_found) <= number_of_paths_to_find:
paths_found.append(copy(current_path))
current_path.pop()
return
else:
for successor in graph[current]:
self.find_paths_recursion(graph, successor, goal, current_depth + 1, max_depth, num_paths, current_path, paths_found)
current_path.pop()
With that out of the way, the core function is trivial:
def find_paths[s, t, d, k]:
paths_found = [] # PASSING THIS BY REFERENCE
find_paths_recursion(s, t, 0, d, k, [], paths_found)
First, lets notice a few thing:
[]
is an uninitialized list, replace this with the equivalent for your programming language of choicepaths_found
is passed by reference. It is clear that the recursion function doesn't return anything. Handle this appropriately.graph
is assuming some form of hashed
structure. There are a plethora of ways to implement a graph. Either way, graph[vertex]
gets you a list of adjacent vertices in a directed graph - adjust accordingly.This worked for me in newer browsers:
autocomplete="new-password"
This works with our libraries running GIT v1.7.1, where we have a DEV package repo and LIVE package repo. The repositories themselves are nothing but a shell to package the assets for a project. all submodules.
The LIVE is never updated intentionally, however cache files or accidents can occur, leaving the repo dirty. New submodules added to the DEV must be initialized within LIVE as well.
Package Repository in DEV
Here we want to pull all upstream changes that we are not yet aware of, then we will update our package repository.
# Recursively reset to the last HEAD
git submodule foreach --recursive git reset --hard
# Recursively cleanup all files and directories
git submodule foreach --recursive git clean -fd
# Recursively pull the upstream master
git submodule foreach --recursive git pull origin master
# Add / Commit / Push all updates to the package repo
git add .
git commit -m "Updates submodules"
git push
Package Repository in LIVE
Here we want to pull the changes that are committed to the DEV repository, but not unknown upstream changes.
# Pull changes
git pull
# Pull status (this is required for the submodule update to work)
git status
# Initialize / Update
git submodule update --init --recursive
ssh -t 'command; bash -l'
will execute the command and then start up a login shell when it completes. For example:
ssh -t [email protected] 'cd /some/path; bash -l'
No.
The content-type should be whatever it is known to be, if you know it. application/octet-stream
is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.
You can combine the use of Content-Disposition
with other content-types, such as image/png
or even text/html
to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html
but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).
RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline
to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename
part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.
Hence:
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"
Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"
Means "This is a PNG image. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: inline; filename="picture.png"
Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".
Of those browsers that recognise inline
some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).
Incase their is local uncommitted changes and avoid merge conflict while pulling.
git stash save
git pull
git stash pop
It sounds like you're using an incorrect address:
To access the Service I enter http://localhost/project/myService.svc/FileUpload
Assuming you mean this is the address you give your client code then I suspect it should actually be:
http://localhost/project/myService.svc
Use sub query e.g:
SELECT field1,field2,(SELECT distinct field3 FROM tbl2 WHERE criteria) AS field3
FROM tbl1 GROUP BY field1,field2
OR
SELECT DISTINCT field1,field2,(SELECT distinct field3 FROM tbl2 WHERE criteria) AS field3
FROM tbl1
This works for me:
blablabla [<sup>1</sup>](#1)
blablabla
footnotes:
reference to blablabla <a class="anchor" id="1"></a>
Why don't you try to grep the return of your command ? Something like :
adb devices -l | grep 123abc12
It should return only the line you want to.
You can create table variables:
DECLARE @result1 TABLE (a INT, b INT, c INT)
INSERT INTO @result1
SELECT a, b, c
FROM table1
SELECT a AS val FROM @result1
UNION
SELECT b AS val FROM @result1
UNION
SELECT c AS val FROM @result1
This should be fine for what you need.
But we can declare a function inside main():
int main()
{
void a();
}
Although the syntax is correct, sometimes it can lead to the "Most vexing parse":
#include <iostream>
struct U
{
U() : val(0) {}
U(int val) : val(val) {}
int val;
};
struct V
{
V(U a, U b)
{
std::cout << "V(" << a.val << ", " << b.val << ");\n";
}
~V()
{
std::cout << "~V();\n";
}
};
int main()
{
int five = 5;
V v(U(five), U());
}
=> no program output.
(Only Clang warning after compilation).
Unless your do_something
function actually does something with any given arguments, you can just pass it as the event handler.
var first = document.getElementById('first');
first.addEventListener('touchstart', do_something, false);
first.addEventListener('click', do_something, false);
Use Object.entries
to get each element of Object in key & value
format, then map
through them like this:
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}_x000D_
_x000D_
var res = Object.entries(obj).map(([k, v]) => ([Number(k), v]));_x000D_
_x000D_
console.log(res);
_x000D_
But, if you are certain that the keys will be in progressive order you can use Object.values
and Array#map
to do something like this:
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}; _x000D_
_x000D_
// idx is the index, you can use any logic to increment it (starts from 0)_x000D_
let result = Object.values(obj).map((e, idx) => ([++idx, e]));_x000D_
_x000D_
console.log(result);
_x000D_
It's not a big deal, it's pretty easy to switch between them. MSTest being integrated isn't a big deal either, just grab testdriven.net.
Like the previous person said pick a mocking framework, my favourite at the moment is Moq.
Using plain JavaScript in IE 9+ compatible syntax in just a few lines:
let children = document.querySelector('#listItem').childNodes;
if (children.length > 0) {
childrenLoop:
for (var i = 0; i < children.length; i++) {
//only target text nodes (nodeType of 3)
if (children[i].nodeType === 3) {
//do not target any whitespace in the HTML
if (children[i].nodeValue.trim().length > 0) {
children[i].nodeValue = 'Replacement text';
//optimized to break out of the loop once primary text node found
break childrenLoop;
}
}
}
}
Double click on the home button and then click and hold the icon like a normal phone and then click close I believe.
Use:
docker inspect -f "{{.Name}} {{.Config.Cmd}}" $(docker ps -a -q)
... it does a "docker inspect" for all containers.
-webkit-transform
is no more needed
ms already support rotation ( -ms-transform: rotate(-10deg);
)
try this:
li a {
...
-webkit-transform: rotate(-10deg);
-moz-transform: rotate(-10deg);
-o-transform: rotate(-10deg);
-ms-transform: rotate(-10deg);
-sand-transform: rotate(10deg);
display: block;
position: fixed;
}
Most of the answers are correct but I want to add little more. The ternary operator is right-associative, which means it can be chained in the following way if … else-if … else-if … else
:
function example() {
return condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: value4;
}
Equivalent to:
function example() {
if (condition1) { return value1; }
else if (condition2) { return value2; }
else if (condition3) { return value3; }
else { return value4; }
}
More details is here
I was facing the same issue while i was using "jdk-10.0.1_windows-x64_bin" and eclipse-jee-oxygen-3a-win32-x86_64 on Windows 64 bit Operating System.
But Finally i resolved this issue by changing my jdk to "jdk-8u172-windows-x64", Now its working fine. @Thanks
No, the String.isEmpty()
method looks as following:
public boolean isEmpty() {
return this.value.length == 0;
}
as you can see it checks the length of the string so you definitely have to check if the string is null before.
I resolved it by giving permission to the user on each of the directories that you're using, like so:
sudo chown user /home/user/git
and so on.
What about this:
import urllib, os
def from_url( url, filename = None ):
'''Store the url content to filename'''
if not filename:
filename = os.path.basename( os.path.realpath(url) )
req = urllib.request.Request( url )
try:
response = urllib.request.urlopen( req )
except urllib.error.URLError as e:
if hasattr( e, 'reason' ):
print( 'Fail in reaching the server -> ', e.reason )
return False
elif hasattr( e, 'code' ):
print( 'The server couldn\'t fulfill the request -> ', e.code )
return False
else:
with open( filename, 'wb' ) as fo:
fo.write( response.read() )
print( 'Url saved as %s' % filename )
return True
##
def main():
test_url = 'http://cdn.sstatic.net/stackoverflow/img/favicon.ico'
from_url( test_url )
if __name__ == '__main__':
main()
Here's a question and answer for this: Difference between screen.availHeight and window.height()
Has pics too, so you can actually see the differences. Hope this helps.
Basically, $(window).height()
give you the maximum height inside of the browser window (viewport), and$(document).height()
gives you the height of the document inside of the browser. Most of the time, they will be exactly the same, even with scrollbars.
In this case, using WebView#loadDataWithBaseUrl()
is better than WebView#loadUrl()
!
webView.loadDataWithBaseURL(url,
data,
"text/html",
"utf-8",
null);
url: url/path String pointing to the directory all your JavaScript files and html links have their origin. If null, it's about:blank. data: String containing your hmtl file, read with BufferedReader for example
In my case, because I had reinstalled iis, I needed to register iis with dot net 4 using this command:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i
when you write formcontrolname Angular 2 do not accept. You have to write formControlName . it is about uppercase second words.
<input type="number" [(ngModel)]="myObject.name" formcontrolname="nameFormControl"/>
if the error still conitnue try to set form control for all of object(myObject) field.
between start <form> </form>
for example: <form [formGroup]="myForm" (ngSubmit)="submitForm(myForm.value)"> set form control for all input field </form>.
I also experienced this when I upgraded operating system from Windows 8
to Windows 8.1
. Un-installing Virtualbox
and re-installing worked for me.