I am currently responsible for an Excel application with a lot of legacy code. One of the slowest pieces of this code was looping through 500 Rows in 6 Columns, setting conditional formatting formulae for each. The formulae are to identify where the cell contents are non-blank but do not form part of a Named Range, therefore referring twice to the cell itself, originally written as:
=AND(COUNTIF(<rangename>,<cellref>)=0,<cellref><>"")
Obviously the overheads would be much reduced by updating all Cells in each Column (Range) at once. However, as noted above, using ADDRESS(ROW(),COLUMN(),n) does not work in this circumstance, i.e. this does not work:
=AND(COUNTIF(<rangename>,ADDRESS(ROW(),COLUMN(),1))=0,ADDRESS(ROW(),COLUMN(),1)<>"")
I experimented extensively with a blank workbook and could find no way around this, using various alternatives such as ISBLANK. In the end, to get around this, I created two User-Defined Functions (using a tip I found elsewhere on this site):
Public Function returnCellContent() As Variant
returnCellContent = Application.Caller.Value
End Function
Public Function Cell_HasContent() As Boolean
If Application.Caller.Value = "" Then
Cell_HasContent = False
Else
Cell_HasContent = True
End If
End Function
The conditional formula is now:
=AND(COUNTIF(<rangename>,returnCellContent()=0,Cell_HasContent())
which works fine.
This has sped the code up, in Excel 2010, from 5s to 1s. Because this code is run whenever data is loaded into the application, this saving is significant and noticeable to the user. It's also a lot cleaner and reusable.
I've taken the time to post this because I could not find any answers on this site or elsewhere that cover all of the circumstances, whilst I'm sure that there are others who could benefit from the above approach, potentially with much larger numbers of cells to update.
you could try this:
I have these two columns (column "A" and column "B"). I want to color them when the values between cells in the same row mismatch.
Follow these steps:
Select the elements in column "A" (excluding A1);
Click on "Conditional formatting -> New Rule -> Use a formula to determine which cells to format";
Insert the following formula: =IF(A2<>B2;1;0);
Select the format options and click "OK";
Select the elements in column "B" (excluding B1) and repeat the steps from 2 to 4.
=AND(LEN($A1), COLUMN()<3, COUNTBLANK($E1:$H1))
=AND(LEN($A1), OR(COLUMN()<3, AND(COLUMN()>4, COUNTBLANK(A1))), COUNTBLANK($E1:$H1))
=$A:$H
.Results should be similar to the following.
¹ The COUNTBLANK function was introduced with Excel 2007. It will count both true blanks and zero-length strings left by formulas (e.g. ""
).
Use the "indirect" function on conditional formatting.
=INDIRECT("g"&ROW())="X"
=$A$1:$Z$1500
(or however wide/long you want the conditional formatting to extend depending on your worksheet)For every row in the G column that has an X, it will now turn to the format you specified. If there isn't an X in the column, the row won't be formatted.
You can repeat this to do multiple row formatting depending on a column value. Just change either the g
column or x
specific text in the formula and set different formats.
For example, if you add a new rule with the formula, =INDIRECT("h"&ROW())="CAR"
, then it will format every row that has CAR
in the H Column as the format you specified.
change the background color of cell B5 based on the value of another cell - C5. If C5 is greater than 80% then the background color is green but if it's below, it will be amber/red.
There is no mention that B5 contains any value so assuming 80%
is .8
formatted as percentage without decimals and blank counts as "below":
Select B5, colour "amber/red" with standard fill then Format - Conditional formatting..., Custom formula is and:
=C5>0.8
with green fill and Done.
<i class="fa" v-bind:class="cravings"></i>
and add in computed :
computed: {
cravings: function() {
return this.content['cravings'] ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline';
}
}
This worked for me:
=NOT(ISBLANK(A1))
I wanted a box around NOT Blank cells in an entire worksheet. Use the $A1 if you want the WHOLE ROW formatted based on the A1, B1, etc result.
Thanks!
Your first problem was you weren't using your compare symbols correctly.
< less than
> greater than
<= less than or equal to
>= greater than or equal to
To answer your other questions; get the condition to work on every cell in the column and what about blanks?
What about blanks?
Add an extra IF
condition to check if the cell is blank or not, if it isn't blank perform the check. =IF(B2="","",B2<=TODAY())
Condition on every cell in column
I unable to comment on the top answer, but Excel actually lets you do this without adding the ugly conditional logic.
Conditional formatting is automatically applied to any input that isn't an error, so you can achieve the same effect as:
=NOT(ISERROR(MATCH(A1,$B$1:$B$1000,0)))
With this:
= MATCH(A1,$B$1:$B$1000,0)))
If the above is applied to your data, A1 will be formatted if it matches any cell in $B$1:$B$1000, as any non-match will return an error.
This will get you to an answer for your simple case, but can you expand on how you'll know which columns will need to be compared (B and C in this case) and what the initial range (A1:D5
in this case) will be? Then I can try to provide a more complete answer.
Sub setCondFormat()
Range("B3").Select
With Range("B3:H63")
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=IF($D3="""",FALSE,IF($F3>=$E3,TRUE,FALSE))"
With .FormatConditions(.FormatConditions.Count)
.SetFirstPriority
With .Interior
.PatternColorIndex = xlAutomatic
.Color = 5287936
.TintAndShade = 0
End With
End With
End With
End Sub
Note: this is tested in Excel 2010.
Edit: Updated code based on comments.
select *
from blah
where DatetimeField between '22/02/2009 09:00:00.000' and '23/05/2009 10:30:00.000'
Depending on the country setting for the login, the month/day may need to be swapped around.
For EF 6 here's a one-liner if you're re-scaffolding a lot in development. Just update the vars and then keep using the up arrow in package manager console to rinse and repeat.
$lastGoodTarget = "OldTargetName"; $newTarget = "NewTargetName"; Update-Database -TargetMigration "$lastGoodTarget" -Verbose; Add-Migration "$newTarget" -Verbose -Force
Why is this necessary you ask? Not sure which versions of EF6 this applies but if your new migration target has already been applied then using '-Force' to re-scaffold in Add-Migration will not actually re-scaffold, but instead make a new file (this is a good thing though because you wouldn't want to lose your 'Down'). The above snippet does the 'Down' first if necessary then -Force works properly to re-scaffold.
This problem occurs when the controller or directive are not specified as a array of dependencies and function. For example
angular.module("appName").directive('directiveName', function () {
return {
restrict: 'AE',
templateUrl: 'calender.html',
controller: function ($scope) {
$scope.selectThisOption = function () {
// some code
};
}
};
});
When minified The '$scope' passed to the controller function is replaced by a single letter variable name . This will render angular clueless of the dependency . To avoid this pass the dependency name along with the function as a array.
angular.module("appName").directive('directiveName', function () {
return {
restrict: 'AE',
templateUrl: 'calender.html'
controller: ['$scope', function ($scope) { //<-- difference
$scope.selectThisOption = function () {
// some code
};
}]
};
});
The customary method for doing this sort of thing is to "print to string". In C++ that means using std::stringstream
something like:
std::stringstream ss;
ss << std::fixed << std::setprecision(2) << number;
std::string mystring = ss.str();
You might need to allow different combinations of data in your intent filter to get it to work in different cases (http/
vs https/
, www.
vs no www.
, etc).
For example, I had to do the following for an app which would open when the user opened a link to Google Drive forms (www.docs.google.com/forms
)
Note that path prefix is optional.
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http" />
<data android:scheme="https" />
<data android:host="www.docs.google.com" />
<data android:host="docs.google.com" />
<data android:pathPrefix="/forms" />
</intent-filter>
The sequences in postgresql are transaction safe. So you can use the
currval(sequence)
currval
Return the value most recently obtained by nextval for this sequence in the current session. (An error is reported if nextval has never been called for this sequence in this session.) Notice that because this is returning a session-local value, it gives a predictable answer even if other sessions are executing nextval meanwhile.
I personally prefer the former approach (returning an error indicator).
Where necessary the return result should just indicate that an error occurred, with another function being used to find out the exact error.
In your getSize() example I'd consider that sizes must always be zero or positive, so returning a negative result can indicate an error, much like UNIX system calls do.
I can't think of any library that I've used that goes for the latter approach with an error object passed in as a pointer. stdio
, etc all go with a return value.
New-style classes (i.e. subclassed from object
, which is the default in Python 3) have a __subclasses__
method which returns the subclasses:
class Foo(object): pass
class Bar(Foo): pass
class Baz(Foo): pass
class Bing(Bar): pass
Here are the names of the subclasses:
print([cls.__name__ for cls in Foo.__subclasses__()])
# ['Bar', 'Baz']
Here are the subclasses themselves:
print(Foo.__subclasses__())
# [<class '__main__.Bar'>, <class '__main__.Baz'>]
Confirmation that the subclasses do indeed list Foo
as their base:
for cls in Foo.__subclasses__():
print(cls.__base__)
# <class '__main__.Foo'>
# <class '__main__.Foo'>
Note if you want subsubclasses, you'll have to recurse:
def all_subclasses(cls):
return set(cls.__subclasses__()).union(
[s for c in cls.__subclasses__() for s in all_subclasses(c)])
print(all_subclasses(Foo))
# {<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>}
Note that if the class definition of a subclass hasn't been executed yet - for example, if the subclass's module hasn't been imported yet - then that subclass doesn't exist yet, and __subclasses__
won't find it.
You mentioned "given its name". Since Python classes are first-class objects, you don't need to use a string with the class's name in place of the class or anything like that. You can just use the class directly, and you probably should.
If you do have a string representing the name of a class and you want to find that class's subclasses, then there are two steps: find the class given its name, and then find the subclasses with __subclasses__
as above.
How to find the class from the name depends on where you're expecting to find it. If you're expecting to find it in the same module as the code that's trying to locate the class, then
cls = globals()[name]
would do the job, or in the unlikely case that you're expecting to find it in locals,
cls = locals()[name]
If the class could be in any module, then your name string should contain the fully-qualified name - something like 'pkg.module.Foo'
instead of just 'Foo'
. Use importlib
to load the class's module, then retrieve the corresponding attribute:
import importlib
modname, _, clsname = name.rpartition('.')
mod = importlib.import_module(modname)
cls = getattr(mod, clsname)
However you find the class, cls.__subclasses__()
would then return a list of its subclasses.
I had the same problem, but believe it or not is was a case of case sensitivity.
This on localhost: http://localhost/.../getdata.php?id=3
Did not behave the same as this on the server: http://server/.../getdata.php?id=3
Changing the server url to this (notice the capital D in getData) solved my issue. http://localhost/.../getData.php?id=3
NavigationView
has a method called setItemTextColor()
. It uses a ColorStateList
.
// FOR NAVIGATION VIEW ITEM TEXT COLOR
int[][] state = new int[][] {
new int[] {-android.R.attr.state_enabled}, // disabled
new int[] {android.R.attr.state_enabled}, // enabled
new int[] {-android.R.attr.state_checked}, // unchecked
new int[] { android.R.attr.state_pressed} // pressed
};
int[] color = new int[] {
Color.WHITE,
Color.WHITE,
Color.WHITE,
Color.WHITE
};
ColorStateList csl = new ColorStateList(state, color);
// FOR NAVIGATION VIEW ITEM ICON COLOR
int[][] states = new int[][] {
new int[] {-android.R.attr.state_enabled}, // disabled
new int[] {android.R.attr.state_enabled}, // enabled
new int[] {-android.R.attr.state_checked}, // unchecked
new int[] { android.R.attr.state_pressed} // pressed
};
int[] colors = new int[] {
Color.WHITE,
Color.WHITE,
Color.WHITE,
Color.WHITE
};
ColorStateList csl2 = new ColorStateList(states, colors);
Here is where I got that answer. And then right after assigning my NavigationView:
if (nightMode == 0) {
navigationView.setItemTextColor(csl);
navigationView.setItemIconTintList(csl2);
}
You could just write to the file as you would write any normal file.
with open('csvfile.csv','wb') as file:
for l in text:
file.write(l)
file.write('\n')
If just in case, it is a list of lists, you could directly use built-in csv
module
import csv
with open("csvfile.csv", "wb") as file:
writer = csv.writer(file)
writer.writerows(text)
It's better if you just cover the bottom part with another div and you will get consistent drop shadow across the board.
#servicesContainer {
/*your css*/
position: relative;
}
and it's fixed! like magic!
For a missing jvm.dll
file, we can provide the path of the dll file in eclipse.ini
file as
-vm
C:\Progra~1\Java\jdk1.6.0_38\jre\bin\server\jvm.dll
Here it is important to remove any space in the path and the double quotes. It worked for me when i removed the quotes and space.
I hope it helps someone.
Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.
The relevant paragraph:
Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.
This makes lots of sense.
For your specific question.. the o
in the <o:p>
means "Office namespace" so anything following the o:
in a tag means "I'm part of Office namespace" - in case of <o:p>
it just means paragraph, the equivalent of the ordinary <p>
tag.
I assume that every HTML tag has its Office "equivalent" and they have more.
this is my solution to the problem. I used it in a chatbot to replace the different words at once.
def mass_replace(text, dct):
new_string = ""
old_string = text
while len(old_string) > 0:
s = ""
sk = ""
for k in dct.keys():
if old_string.startswith(k):
s = dct[k]
sk = k
if s:
new_string+=s
old_string = old_string[len(sk):]
else:
new_string+=old_string[0]
old_string = old_string[1:]
return new_string
print mass_replace("The dog hunts the cat", {"dog":"cat", "cat":"dog"})
this will become The cat hunts the dog
ArrayList<Customer> custArr = new ArrayList<Customer>();
while(youWantToContinue) {
//get a customerName
//get an amount
custArr.add(new Customer(customerName, amount);
}
For this to work... you'll have to fix your constructor...
Assuming your Customer
class has variables called name
and sale
, your constructor should look like this:
public Customer(String customerName, double amount) {
name = customerName;
sale = amount;
}
Change your Store
class to something more like this:
public class Store {
private ArrayList<Customer> custArr;
public new Store() {
custArr = new ArrayList<Customer>();
}
public void addSale(String customerName, double amount) {
custArr.add(new Customer(customerName, amount));
}
public Customer getSaleAtIndex(int index) {
return custArr.get(index);
}
//or if you want the entire ArrayList:
public ArrayList getCustArr() {
return custArr;
}
}
Starting Python 3.8
, the standard library comes with the quantiles
function as part of the statistics
module:
from statistics import quantiles
quantiles([1, 2, 3, 4, 5], n=100)
# [0.06, 0.12, 0.18, 0.24, 0.3, 0.36, 0.42, 0.48, 0.54, 0.6, 0.66, 0.72, 0.78, 0.84, 0.9, 0.96, 1.02, 1.08, 1.14, 1.2, 1.26, 1.32, 1.38, 1.44, 1.5, 1.56, 1.62, 1.68, 1.74, 1.8, 1.86, 1.92, 1.98, 2.04, 2.1, 2.16, 2.22, 2.28, 2.34, 2.4, 2.46, 2.52, 2.58, 2.64, 2.7, 2.76, 2.82, 2.88, 2.94, 3.0, 3.06, 3.12, 3.18, 3.24, 3.3, 3.36, 3.42, 3.48, 3.54, 3.6, 3.66, 3.72, 3.78, 3.84, 3.9, 3.96, 4.02, 4.08, 4.14, 4.2, 4.26, 4.32, 4.38, 4.44, 4.5, 4.56, 4.62, 4.68, 4.74, 4.8, 4.86, 4.92, 4.98, 5.04, 5.1, 5.16, 5.22, 5.28, 5.34, 5.4, 5.46, 5.52, 5.58, 5.64, 5.7, 5.76, 5.82, 5.88, 5.94]
quantiles([1, 2, 3, 4, 5], n=100)[49] # 50th percentile (e.g median)
# 3.0
quantiles
returns for a given distribution dist
a list of n - 1
cut points separating the n
quantile intervals (division of dist
into n
continuous intervals with equal probability):
statistics.quantiles(dist, *, n=4, method='exclusive')
where n
, in our case (percentiles
) is 100
.
Request.QueryString
returns you a collection of Key/Value pairs representing the Query String. Not a String. Don't think that would cause a Object Reference error though. The reason your getting that is because as Mauro pointed out in the comments. It's QueryString and not Querystring.
Try:
Request.QueryString.ToString();
or
<%
string URL = Request.Url.AbsoluteUri
System.Net.WebClient wc = new System.Net.WebClient();
string data = wc.DownloadString(URL);
Response.Output.Write(data);
%>
Same as your code but Request.Url.AbsoluteUri
will return the full path, including the query string.
Application pools are used to separate set of IIS worker processes that share the same configuration. Application pools enable us to isolate our web application for better security, reliability, and availability
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script>_x000D_
var currFFZoom = 1;_x000D_
var currIEZoom = 100;_x000D_
_x000D_
function plus(){_x000D_
//alert('sad');_x000D_
var step = 0.02;_x000D_
currFFZoom += step;_x000D_
$('body').css('MozTransform','scale(' + currFFZoom + ')');_x000D_
var stepie = 2;_x000D_
currIEZoom += stepie;_x000D_
$('body').css('zoom', ' ' + currIEZoom + '%');_x000D_
_x000D_
};_x000D_
function minus(){_x000D_
//alert('sad');_x000D_
var step = 0.02;_x000D_
currFFZoom -= step;_x000D_
$('body').css('MozTransform','scale(' + currFFZoom + ')');_x000D_
var stepie = 2;_x000D_
currIEZoom -= stepie;_x000D_
$('body').css('zoom', ' ' + currIEZoom + '%');_x000D_
};_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
<!--zoom controls-->_x000D_
<a id="minusBtn" onclick="minus()">------</a>_x000D_
<a id="plusBtn" onclick="plus()">++++++</a>_x000D_
</body>_x000D_
</html>
_x000D_
in Firefox will not change the zoom only change scale!!!
Once I packed JS code doing that to a tiny library:
https://github.com/AlexLibs/client-side-csv-generator
The Code, Documentation and Demo/Playground are provided on Github.
Enjoy :)
Pull requests are welcome.
You can get the Parent of a control via
myControl.Parent
See MSDN: Control.Parent
You add to the back state from the FragmentTransaction
and remove from the backstack using FragmentManager
pop methods:
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove(myFrag);
trans.commit();
manager.popBackStack();
This works on VS2017 w/ SDK Core MSBuild configurations.
You need to NuGet in the EnvDTE / EnvDTE80 packages.
Do not use COM or interop. anything.... garbage!!
internal class Program {
private static readonly DTE2 _dte2;
// Static Constructor
static Program() {
_dte2 = (DTE2)Marshal.GetActiveObject("VisualStudio.DTE.15.0");
}
private static void FindProjectsIn(ProjectItem item, List<Project> results) {
if (item.Object is Project) {
var proj = (Project) item.Object;
if (new Guid(proj.Kind) != new Guid(Constants.vsProjectItemKindPhysicalFolder))
results.Add((Project) item.Object);
else
foreach (ProjectItem innerItem in proj.ProjectItems)
FindProjectsIn(innerItem, results);
}
if (item.ProjectItems != null)
foreach (ProjectItem innerItem in item.ProjectItems)
FindProjectsIn(innerItem, results);
}
private static void FindProjectsIn(UIHierarchyItem item, List<Project> results) {
if (item.Object is Project) {
var proj = (Project) item.Object;
if (new Guid(proj.Kind) != new Guid(Constants.vsProjectItemKindPhysicalFolder))
results.Add((Project) item.Object);
else
foreach (ProjectItem innerItem in proj.ProjectItems)
FindProjectsIn(innerItem, results);
}
foreach (UIHierarchyItem innerItem in item.UIHierarchyItems)
FindProjectsIn(innerItem, results);
}
private static IEnumerable<Project> GetEnvDTEProjectsInSolution() {
var ret = new List<Project>();
var hierarchy = _dte2.ToolWindows.SolutionExplorer;
foreach (UIHierarchyItem innerItem in hierarchy.UIHierarchyItems)
FindProjectsIn(innerItem, ret);
return ret;
}
private static void Main() {
var projects = GetEnvDTEProjectsInSolution();
var solutiondir = Path.GetDirectoryName(_dte2.Solution.FullName);
// TODO
...
var project = projects.FirstOrDefault(p => p.Name == <current project>);
Console.WriteLine(project.FullName);
}
}
If you are really looking to speed your code navigation, you might want to take a look at nWire for Java. It is a code exploration plugin for Eclipse. You can instantly see all the related artifacts. So, in that case, you will focus on the method call and instantly see all possible implementations, declarations, invocations, etc.
First watch this and try reinstall - https://youtu.be/trHinrIm6DM
After if you get "Could not initialize class org.codehaus.groovy.runtime.InvokerHelper"
1.install Java SDK 14 and update env path.
2."[Your RN or Flutter Project Folder]\android\gradle\wrapper\gradle-wrapper.properties" this file edit as ...(upgrade gradle version)
#Fri Jun 23 08:50:38 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-all.zip
3.run gradlew in cmd path "[Your RN or Flutter Project Folder]\android\"
4.it takes time.after if shows "BUILD SUCCESSFUL" you can "flutter run" in ur project folder
Yeah It's work
String content = "";
char character;
if(Serial.available() >0){
//reset this variable!
content = "";
//make string from chars
while(Serial.available()>0) {
character = Serial.read();
content.concat(character);
}
//send back
Serial.print("#");
Serial.print(content);
Serial.print("#");
Serial.flush();
}
$(function () {
$('#startTime, #endTimeContent').datetimepicker({
format: 'HH:mm',
pickDate: false,
pickSeconds: false,
pick12HourFormat: false
});
});
your selector seems to be wrong,please check it
Java LinkedList provides both the addFirst(E e) and the push(E e) method that add an element to the front of the list.
https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html#addFirst(E)
map
creates a new list by applying a function to every element of the source:
xs = [1, 2, 3]
# all of those are equivalent — the output is [2, 4, 6]
# 1. map
ys = map(lambda x: x * 2, xs)
# 2. list comprehension
ys = [x * 2 for x in xs]
# 3. explicit loop
ys = []
for x in xs:
ys.append(x * 2)
n-ary map
is equivalent to zipping input iterables together and then applying the transformation function on every element of that intermediate zipped list. It's not a Cartesian product:
xs = [1, 2, 3]
ys = [2, 4, 6]
def f(x, y):
return (x * 2, y // 2)
# output: [(2, 1), (4, 2), (6, 3)]
# 1. map
zs = map(f, xs, ys)
# 2. list comp
zs = [f(x, y) for x, y in zip(xs, ys)]
# 3. explicit loop
zs = []
for x, y in zip(xs, ys):
zs.append(f(x, y))
I've used zip
here, but map
behaviour actually differs slightly when iterables aren't the same size — as noted in its documentation, it extends iterables to contain None
.
You can use the PostBuild event of the project. After the build is completed, you can run a DOS batch file and copy the desired files to your desired folder.
In Eclipse:
Window -> Preferences -> Android -> Lint Error Checking.
In the list find an entry with ID = ProtectedPermission
. Set the Severity to something lower than Error. This way you can still compile the project using Eclipse.
In Android Studio:
File -> Settings -> Editor -> Inspections
Under Android Lint
, locate Using system app permission
. Either uncheck the checkbox or choose a Severity lower than Error.
If, after reading the other questions and viewing the links mentioned in the comment sections, you still can't figure it out, read on.
First of all, where you're going wrong is the offset.
It should look more like this...
set mydate=%date:~10,4%%date:~6,2%/%date:~4,2%
echo %mydate%
If the date was Tue 12/02/2013
then it would display it as 2013/02/12
.
To remove the slashes, the code would look more like
set mydate=%date:~10,4%%date:~7,2%%date:~4,2%
echo %mydate%
which would output 20130212
And a hint for doing it in the future, if mydate
equals something like %date:~10,4%%date:~7,2%
or the like, you probably forgot a tilde (~).
You should verify following things if the two way binding does not work.
In html the ngModel should be called this way. There is no dependency on other attribute of the input element
<input [(ngModel)]="inputText">
Make Sure FormsModule is imported into the modules file
app.modules.ts
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
HomeComponent // suppose, this is the component in which you are trying to use two ay binding
],
imports: [
BrowserModule,
FormsModule,
// other modules
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Make sure the component in which you are trying to use ngModel for two way binding is added in the declarations of the. Code added in the previous point #2
This is everything that you need to do to make the two way binding using ngModel work, this is validated up to angular 9
Pretty straight forward, use relative path
string[] offerFiles = Directory.GetFiles(Server.MapPath("~/offers"), "*.csv");
This code explains the use of the ~tilda character, which was the most confusing thing to me. Once I understood this, it makes things much easier to understand:
@ECHO off
SET "PATH=%~dp0;%PATH%"
ECHO %PATH%
ECHO.
CALL :testargs "these are days" "when the brave endure"
GOTO :pauseit
:testargs
SET ARGS=%~1;%~2;%1;%2
ECHO %ARGS%
ECHO.
exit /B 0
:pauseit
pause
In Chrome and IE9 (and I'm guessing all other browsers too) only the latter will generate a socket connect, the first one will be discarded. (The browser detects this as both requests are sent within one JavaScript "timeslice" in your code above, and discards all but the last request.)
If you instead have some event callback do the second submission (but before the reply is received), the socket of the first request will be cancelled. This is definitely nothing to recommend as the server in that case may well have handled your first request, but you will never know for sure.
I recommend you use/generate a single request which you can transact server-side.
1> Add this namspace. using Newtonsoft.Json.Linq;
2> use this source code.
JObject joResponse = JObject.Parse(response);
JObject ojObject = (JObject)joResponse["response"];
JArray array= (JArray)ojObject ["chats"];
int id = Convert.ToInt32(array[0].toString());
Here I have a solution that avoid multiple requests, for loops and old document removal.
You can easily create a new idea manually using something like:_id:ObjectId()
But knowing Mongo will automatically assign an _id if missing, you can use aggregate to create a $project
containing all the fields of your document, but omit the field _id. You can then save it with $out
So if your document is:
{
"_id":ObjectId("5b5ed345cfbce6787588e480"),
"title": "foo",
"description": "bar"
}
Then your query will be:
db.getCollection('myCollection').aggregate([
{$match:
{_id: ObjectId("5b5ed345cfbce6787588e480")}
}
{$project:
{
title: '$title',
description: '$description'
}
},
{$out: 'myCollection'}
])
A class in HTML means that in order to set attributes to it in CSS, you simply need to add a period in front of it.
For example, the CSS code of that html code may be:
.clear { height: 50px; width: 25px; }
Also, if you, as suggested by abiessu, are attempting to add the CSS clear: both;
attribute to the div to prevent anything from floating to the left or right of this div, you can use this CSS code:
.clear { clear: both; }
This is an interesting question and since it isn't explained very explicitly in the documentation I'll answer this by going through the sourcecode of mod_rewrite; demonstrating a big benefit of open-source.
In the top section you'll quickly spot the defines used to name these flags:
#define CONDFLAG_NONE 1<<0
#define CONDFLAG_NOCASE 1<<1
#define CONDFLAG_NOTMATCH 1<<2
#define CONDFLAG_ORNEXT 1<<3
#define CONDFLAG_NOVARY 1<<4
and searching for CONDFLAG_ORNEXT confirms that it is used based on the existence of the [OR] flag:
else if ( strcasecmp(key, "ornext") == 0
|| strcasecmp(key, "OR") == 0 ) {
cfg->flags |= CONDFLAG_ORNEXT;
}
The next occurrence of the flag is the actual implementation where you'll find the loop that goes through all the RewriteConditions a RewriteRule has, and what it basically does is (stripped, comments added for clarity):
# loop through all Conditions that precede this Rule
for (i = 0; i < rewriteconds->nelts; ++i) {
rewritecond_entry *c = &conds[i];
# execute the current Condition, see if it matches
rc = apply_rewrite_cond(c, ctx);
# does this Condition have an 'OR' flag?
if (c->flags & CONDFLAG_ORNEXT) {
if (!rc) {
/* One condition is false, but another can be still true. */
continue;
}
else {
/* skip the rest of the chained OR conditions */
while ( i < rewriteconds->nelts
&& c->flags & CONDFLAG_ORNEXT) {
c = &conds[++i];
}
}
}
else if (!rc) {
return 0;
}
}
You should be able to interpret this; it means that OR has a higher precedence, and your example indeed leads to if ( (A OR B) AND (C OR D) )
. If you would, for example, have these Conditions:
RewriteCond A [or]
RewriteCond B [or]
RewriteCond C
RewriteCond D
it would be interpreted as if ( (A OR B OR C) and D )
.
Use below code to find key is exist or not in JsonObject
. has("key")
method is used to find keys in JsonObject
.
containerObject = new JSONObject(container);
//has method
if (containerObject.has("video")) {
//get Value of video
String video = containerObject.optString("video");
}
If you are using optString("key")
method to get String value then don't worry about keys are existing or not in the JsonObject
.
In Mysql Latest docker container
ALTER USER root IDENTIFIED WITH mysql_native_password BY 'password';
Take a look at the facilities provided by the time
module
You have several conversion functions there.
Edit: see the datetime
module for more OOP-like solutions. The time
library linked above is kinda imperative.
Rebasing can be a real headache. You have to resolve the merge conflicts and continue rebasing. For example you can use the merge tool (which differs depending on your settings)
git mergetool
Then add your changes and go on
git rebase --continue
Good luck
You can use the CSVToArray() function mentioned in this blog entry.
<script type="text/javascript">
// ref: http://stackoverflow.com/a/1293163/2343
// This will parse a delimited string into an array of
// arrays. The default delimiter is the comma, but this
// can be overriden in the second argument.
function CSVToArray( strData, strDelimiter ){
// Check to see if the delimiter is defined. If not,
// then default to comma.
strDelimiter = (strDelimiter || ",");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"
),
"gi"
);
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec( strData )){
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[ 1 ];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (
strMatchedDelimiter.length &&
strMatchedDelimiter !== strDelimiter
){
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push( [] );
}
var strMatchedValue;
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[ 2 ]){
// We found a quoted value. When we capture
// this value, unescape any double quotes.
strMatchedValue = arrMatches[ 2 ].replace(
new RegExp( "\"\"", "g" ),
"\""
);
} else {
// We found a non-quoted value.
strMatchedValue = arrMatches[ 3 ];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[ arrData.length - 1 ].push( strMatchedValue );
}
// Return the parsed data.
return( arrData );
}
</script>
Try this.
public class RoundedImageView extends android.support.v7.widget.AppCompatImageView {
private int borderWidth = 4;
private int viewWidth;
private int viewHeight;
private Bitmap image;
private Paint paint;
private Paint paintBorder;
private BitmapShader shader;
public RoundedImageView(Context context)
{
super(context);
setup();
}
public RoundedImageView(Context context, AttributeSet attrs)
{
super(context, attrs);
setup();
}
public RoundedImageView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
setup();
}
private void setup()
{
paint = new Paint();
paint.setAntiAlias(true);
paintBorder = new Paint();
setBorderColor(Color.WHITE);
paintBorder.setAntiAlias(true);
this.setLayerType(LAYER_TYPE_SOFTWARE, paintBorder);
paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.WHITE);
}
public void setBorderWidth(int borderWidth)
{
this.borderWidth = borderWidth;
this.invalidate();
}
public void setBorderColor(int borderColor)
{
if (paintBorder != null)
paintBorder.setColor(borderColor);
this.invalidate();
}
private void loadBitmap()
{
BitmapDrawable bitmapDrawable = (BitmapDrawable) this.getDrawable();
if (bitmapDrawable != null)
image = bitmapDrawable.getBitmap();
}
@SuppressLint("DrawAllocation")
@Override
public void onDraw(Canvas canvas)
{
loadBitmap();
if (image != null)
{
shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvas.getWidth(), canvas.getHeight(), false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
paint.setShader(shader);
int circleCenter = viewWidth / 2;
canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter + borderWidth - 4.0f, paintBorder);
canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter - 4.0f, paint);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int width = measureWidth(widthMeasureSpec);
int height = measureHeight(heightMeasureSpec, widthMeasureSpec);
viewWidth = width - (borderWidth * 2);
viewHeight = height - (borderWidth * 2);
setMeasuredDimension(width, height);
}
private int measureWidth(int measureSpec)
{
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY)
{
result = specSize;
}
else
{
// Measure the text
result = viewWidth;
}
return result;
}
private int measureHeight(int measureSpecHeight, int measureSpecWidth)
{
int result = 0;
int specMode = MeasureSpec.getMode(measureSpecHeight);
int specSize = MeasureSpec.getSize(measureSpecHeight);
if (specMode == MeasureSpec.EXACTLY)
{
result = specSize;
}
else
{
result = viewHeight;
}
return (result + 2);
}
}
and use this ImageView in layout like:
<com.app.Demo.RoundedImageView
android:id="@+id/iv_profileImage"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_centerHorizontal="true"
/>
You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?
This is code to compile and run java in sublime text 3
"shell_cmd": "javac -d . $file && java ${file_base_name}.${file_base_name}", "shell": true
There's a method that does this for you:
def show
@city = @user.city.present?
end
The present?
method tests for not-nil
plus has content. Empty strings, strings consisting of spaces or tabs, are considered not present.
Since this pattern is so common there's even a shortcut in ActiveRecord:
def show
@city = @user.city?
end
This is roughly equivalent.
As a note, testing vs nil
is almost always redundant. There are only two logically false values in Ruby: nil
and false
. Unless it's possible for a variable to be literal false
, this would be sufficient:
if (variable)
# ...
end
This is preferable to the usual if (!variable.nil?)
or if (variable != nil)
stuff that shows up occasionally. Ruby tends to wards a more reductionist type of expression.
One reason you'd want to compare vs. nil
is if you have a tri-state variable that can be true
, false
or nil
and you need to distinguish between the last two states.
lista = list.sort(lista)
This should be
lista.sort()
The .sort()
method is in-place, and returns None. If you want something not in-place, which returns a value, you could use
sorted_list = sorted(lista)
Aside #1: please don't call your lists list
. That clobbers the builtin list type.
Aside #2: I'm not sure what this line is meant to do:
print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")
is it simply
print "value 1a + value 2 = value 3a value 4"
? In other words, I don't know why you're calling str on things which are already str.
Aside #3: sometimes you use print("something")
(Python 3 syntax) and sometimes you use print "something"
(Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..
The exception TypeError: 'NoneType' object is not subscriptable
happens because the value of lista
is actually None
. You can reproduce TypeError
that you get in your code if you try this at the Python command line:
None[0]
The reason that lista
gets set to None is because the return value of list.sort()
is None
... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).
If you do not want to alter the original version you can use
other_list = sorted(lista)
Running as administrator then following other comments fixed the problem for me :)
Delete import android.R; from all the files.. once clean the the project and build the project.... It will generate
You could pass the messages as explicit URL parameter (appropriately encoded), or store the messages into session
(cookie) variable before redirecting and then get the variable before rendering the template. For example:
from flask import session, url_for
def do_baz():
messages = json.dumps({"main":"Condition failed on page baz"})
session['messages'] = messages
return redirect(url_for('.do_foo', messages=messages))
@app.route('/foo')
def do_foo():
messages = request.args['messages'] # counterpart for url_for()
messages = session['messages'] # counterpart for session
return render_template("foo.html", messages=json.loads(messages))
(encoding the session variable might not be necessary, flask may be handling it for you, but can't recall the details)
Or you could probably just use Flask Message Flashing if you just need to show simple messages.
In my case my object also had property which was array of files. Since they are binary they should be dealt differently - index doesn't need to be part of the key. So i modified @Vladimir Novopashin's and @developer033's answer:
export function convertToFormData(data, formData, parentKey) {
if(data === null || data === undefined) return null;
formData = formData || new FormData();
if (typeof data === 'object' && !(data instanceof Date) && !(data instanceof File)) {
Object.keys(data).forEach(key =>
convertToFormData(data[key], formData, (!parentKey ? key : (data[key] instanceof File ? parentKey : `${parentKey}[${key}]`)))
);
} else {
formData.append(parentKey, data);
}
return formData;
}
I would try to give them all display: block;
attribute and using float: left;
.
You can then set width
and/or height
as you like. You can even specify some vertical-alignment rules.
You don't need "string" in your call to wordLengthFunction()
.
int wordLength = wordLengthFunction(string word);
should be
int wordLength = wordLengthFunction(word);
Try:
function LoadData (callback)
{
// ... Process whatever data
callback (loadedData, currentObject);
}
Functions are first class in JavaScript; you can just pass them around.
Proper answer is here: http://scratching.psybermonkey.net/2011/02/ssh-how-to-pipe-output-from-local-to.html
your_command | ssh username@server "cat > filename.txt"
Do that like this
db.Users.OrderByDescending(u => u.UserId).FirstOrDefault();
According to documentation:
random.sample(population, k)
Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
Basically, it picks k unique random elements, a sample, from a sequence:
>>> import random
>>> c = list(range(0, 15))
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> random.sample(c, 5)
[9, 2, 3, 14, 11]
random.sample
works also directly from a range:
>>> c = range(0, 15)
>>> c
range(0, 15)
>>> random.sample(c, 5)
[12, 3, 6, 14, 10]
In addition to sequences, random.sample
works with sets too:
>>> c = {1, 2, 4}
>>> random.sample(c, 2)
[4, 1]
However, random.sample
doesn't work with arbitrary iterators:
>>> c = [1, 3]
>>> random.sample(iter(c), 5)
TypeError: Population must be a sequence or set. For dicts, use list(d).
Join on one-to-many relation in JPQL looks as follows:
select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName
When several properties are specified in select
clause, result is returned as Object[]
:
Object[] temp = (Object[]) em.createNamedQuery("...")
.setParameter("groupName", groupName)
.getSingleResult();
String fname = (String) temp[0];
String lname = (String) temp[1];
By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table
to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:
@Entity @Table(name = "Users")
public class User implements Serializable { ... }
The simplest way, based on @nosklo's comment and answer:
import tempfile
tmp = tempfile.mkdtemp()
But if you want to manually control the creation of the directories:
import os
from tempfile import gettempdir
tmp = os.path.join(gettempdir(), '.{}'.format(hash(os.times())))
os.makedirs(tmp)
That way you can easily clean up after yourself when you are done (for privacy, resources, security, whatever) with:
from shutil import rmtree
rmtree(tmp, ignore_errors=True)
This is similar to what applications like Google Chrome and Linux systemd
do. They just use a shorter hex hash and an app-specific prefix to "advertise" their presence.
Many devices with different screen sizes/ratios/resolutions have come out even in the last five years, including new types of iPhones and iPads. It would be very difficult to customize a website for each device.
Meanwhile, media queries for device-width
, device-height
, and device-aspect-ratio
have been deprecated, so they may not work in future browser versions. (Source: MDN)
TLDR: Design based on browser widths, not devices. Here's a good introduction to this topic.
You can delete documents from type with following query:
POST /index/type/_delete_by_query
{
"query" : {
"match_all" : {}
}
}
I tested this query in Kibana and Elastic 5.5.2
Try one of the following, depending on your image format:
UIImageJPEGRepresentation
Returns the data for the specified image in JPEG format.
NSData * UIImageJPEGRepresentation (
UIImage *image,
CGFloat compressionQuality
);
UIImagePNGRepresentation
Returns the data for the specified image in PNG format
NSData * UIImagePNGRepresentation (
UIImage *image
);
EDIT:
if you want to access the raw bytes that make up the UIImage, you could use this approach:
CGDataProviderRef provider = CGImageGetDataProvider(image.CGImage);
NSData* data = (id)CFBridgingRelease(CGDataProviderCopyData(provider));
const uint8_t* bytes = [data bytes];
This will give you the low-level representation of the image RGB pixels.
(Omit the CFBridgingRelease
bit if you are not using ARC).
For the warning by warning case, It's wise to restore it to default at some point, since you are doing it on a case by case basis.
#pragma warning(disable: 4996) /* Disable deprecation */
// Code that causes it goes here
#pragma warning(default: 4996) /* Restore default */
You need to edit the Tomcat/conf/server.xml
and change the connector port. The connector setting should look something like this:
<Connector port="8080" maxHttpHeaderSize="8192"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" />
Just change the connector port from default 8080 to another valid port number.
I post the below solution here because after some searching this is where I landed, so other may too. I was trying to use EF 6 to call a stored procedure, but had a similar error because the stored procedure had a linked server being utilized.
The operation could not be performed because OLE DB provider _ for linked server _ was unable to begin a distributed transaction
The partner transaction manager has disabled its support for remote/network transactions*
Jumping over to SQL Client did fix my issue, which also confirmed for me that it was an EF thing.
EF model generated method based attempt:
db.SomeStoredProcedure();
ExecuteSqlCommand based attempt:
db.Database.ExecuteSqlCommand("exec [SomeDB].[dbo].[SomeStoredProcedure]");
With:
var connectionString = db.Database.Connection.ConnectionString;
var connection = new System.Data.SqlClient.SqlConnection(connectionString);
var cmd = connection.CreateCommand();
cmd.CommandText = "exec [SomeDB].[dbo].[SomeStoredProcedure]";
connection.Open();
var result = cmd.ExecuteNonQuery();
That code can be shortened, but I think that version is slightly more convenient for debugging and stepping through.
I don't believe that Sql Client is necessarily a preferred choice, but I felt this was at least worth sharing if anyone else having similar problems gets landed here by google.
The above Code is C#, but the concept of trying to switch over to Sql Client still applies. At the very least it will be diagnostic to attempt to do so.
Simple query that has excellent performance and works with gaps:
SELECT * FROM tbl AS t1 JOIN (SELECT id FROM tbl ORDER BY RAND() LIMIT 10) as t2 ON t1.id=t2.id
This query on a 200K table takes 0.08s and the normal version (SELECT * FROM tbl ORDER BY RAND() LIMIT 10) takes 0.35s on my machine.
This is fast because the sort phase only uses the indexed ID column. You can see this behaviour in the explain:
SELECT * FROM tbl ORDER BY RAND() LIMIT 10:
SELECT * FROM tbl AS t1 JOIN (SELECT id FROM tbl ORDER BY RAND() LIMIT 10) as t2 ON t1.id=t2.id
Weighted Version: https://stackoverflow.com/a/41577458/893432
Apple provides detailed, illustrated instructions covering every step of the process. Log in to the iPhone developer site and click the "program portal" link. In the program portal you'll find a link to the program portal user's guide, which is a really good reference and guide on this topic.
You can't alter the existing columns for identity.
You have 2 options,
Create a new table with identity & drop the existing table
Create a new column with identity & drop the existing column
Approach 1. (New table) Here you can retain the existing data values on the newly created identity column.
CREATE TABLE dbo.Tmp_Names
(
Id int NOT NULL
IDENTITY(1, 1),
Name varchar(50) NULL
)
ON [PRIMARY]
go
SET IDENTITY_INSERT dbo.Tmp_Names ON
go
IF EXISTS ( SELECT *
FROM dbo.Names )
INSERT INTO dbo.Tmp_Names ( Id, Name )
SELECT Id,
Name
FROM dbo.Names TABLOCKX
go
SET IDENTITY_INSERT dbo.Tmp_Names OFF
go
DROP TABLE dbo.Names
go
Exec sp_rename 'Tmp_Names', 'Names'
Approach 2 (New column) You can’t retain the existing data values on the newly created identity column, The identity column will hold the sequence of number.
Alter Table Names
Add Id_new Int Identity(1, 1)
Go
Alter Table Names Drop Column ID
Go
Exec sp_rename 'Names.Id_new', 'ID', 'Column'
See the following Microsoft SQL Server Forum post for more details:
String dt = Date.Now.ToString("yyyy-MM-dd");
Now you got this for dt, 2010-09-09
Not sure what you mean with "class constructor" but I'd assume you mean one of the ones below.
Instance constructor:
Public Sub New()
End Sub
Shared constructor:
Shared Sub New()
End Sub
You can programatically change it by setting the system property:
public class App {
public static void main(String[] args) {
System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "TRACE");
final org.slf4j.Logger log = LoggerFactory.getLogger(App.class);
log.trace("trace");
log.debug("debug");
log.info("info");
log.warn("warning");
log.error("error");
}
}
The log levels are ERROR > WARN > INFO > DEBUG > TRACE.
Please note that once the logger is created the log level can't be changed. If you need to dynamically change the logging level you might want to use log4j with SLF4J.
They are not different from the point of view of JVM. Immutable objects don't have methods that can change the instance variables. And the instance variables are private; therefore you can't change it after you create it. A famous example would be String. You don't have methods like setString, or setCharAt. And s1 = s1 + "w" will create a new string, with the original one abandoned. That's my understanding.
Apple has changed the interface.
The team ID could be found via this link: https://developer.apple.com/account/#/membership
I have used Fredrik's code above in a project with some slight modifications, thought I'd share:
private static bool DownloadRemoteImageFile(string uri, string fileName)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (Exception)
{
return false;
}
// Check that the remote file was found. The ContentType
// check is performed since a request for a non-existent
// image file might be redirected to a 404-page, which would
// yield the StatusCode "OK", even though the image was not
// found.
if ((response.StatusCode == HttpStatusCode.OK ||
response.StatusCode == HttpStatusCode.Moved ||
response.StatusCode == HttpStatusCode.Redirect) &&
response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
{
// if the remote file was found, download it
using (Stream inputStream = response.GetResponseStream())
using (Stream outputStream = File.OpenWrite(fileName))
{
byte[] buffer = new byte[4096];
int bytesRead;
do
{
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
outputStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
return true;
}
else
return false;
}
Main changes are:
loadXMLDoc JS function should return false, otherwise it will result in postback.
Just my two cents:
git ls-files | grep -x relative/path
where relative/path
can be easily determined by pressing tab
within an auto-completion shell. Add an additional | wc -l
to get a 1 or 0 output.
An IntPtr is an integer which is the same size as a pointer.
You can use IntPtr to store a pointer value in a non-pointer type. This feature is important in .NET since using pointers is highly error prone and therefore illegal in most contexts. By allowing the pointer value to be stored in a "safe" data type, plumbing between unsafe code segments may be implemented in safer high-level code -- or even in a .NET language that doesn't directly support pointers.
The size of IntPtr is platform-specific, but this detail rarely needs to be considered, since the system will automatically use the correct size.
The name "IntPtr" is confusing -- something like Handle
might have been more appropriate. My initial guess was that "IntPtr" was a pointer to an integer. The MSDN documentation of IntPtr goes into somewhat cryptic detail without ever providing much insight about the meaning of the name.
An IntPtr
is a pointer with two limitations:
In other words, an IntPtr
is just like a void*
-- but with the extra feature that it can (but shouldn't) be used for basic pointer arithmetic.
In order to dereference an IntPtr
, you can either cast it to a true pointer (an operation which can only be performed in "unsafe" contexts) or you can pass it to a helper routine such as those provided by the InteropServices.Marshal
class. Using the Marshal
class gives the illusion of safety since it doesn't require you to be in an explicit "unsafe" context. However, it doesn't remove the risk of crashing which is inherent in using pointers.
Check your line endings! If you see an error about the file not being found, followed by this "premature of end headers" error in your Apache log - it may be that you have Windows line endings in your script in instead of Unix style. I ran into that problem / solution.
If you patch /Developer/Platforms/iPhoneOS.platform/Info.plist
and then try to debug a application running on the device using a real development provisionen profile from Apple it will probably not work. Symptoms are weird error messages from com.apple.debugserver
and that you can use any bundle identifier without getting a error when building in Xcode. The solution is to restore Info.plist
.
In PHP:
$driver->navigate()->refresh();
You don't need raw performance from an operation you will perform extremely infrequently from the point of view of the CPU.
You can, use:
if (date >= startDate && date<= EndDate) { return true; }
I found that calling git is rather slow (any of the subcommands), especially for updating the prompt. Time varies between .1 and .2 seconds within the root dir of a repo, and over .2 seconds outside a repo, on a top notch machine (raid 1, 8 gb ram, 8 hardware threads). It does run Cygwin, though.
Therefore I wrote this script for speed:
#!/usr/bin/perl
$cwd=$ENV{PWD}; #`pwd`;
chomp $cwd;
while (length $cwd)
{
-d "$cwd/.git" and do {
-f "$cwd/.git/HEAD" and do {
open IN, "<", "$cwd/.git/HEAD";
$_=<IN>;
close IN;
s@ref: refs/heads/@@;
print $_;
};
exit;
};
$cwd=~s@/[^/]*$@@;
}
May need some tweaking.
Guess I'm going to answer my own questions....Sarfraz was close but not quite right. The correct answer is:
alert(col.firstChild.value);
You have to distinguish between overriding and overloading. Without the virtual
keyword you only overload a method of a base class. This means nothing but hiding.
Let's say you have a base class Base
and a derived class Specialized
which both implement void foo()
. Now you have a pointer to Base
pointing to an instance of Specialized
. When you call foo()
on it you can observe the difference that virtual
makes: If the method is virtual, the implementation of Specialized
will be used, if it is missing, the version from Base
will be chosen.
It is best practice to never overload methods from a base class. Making a method non-virtual is the way of its author to tell you that its extension in subclasses is not intended.
Out of the following two:
(1) List<?> myList = new ArrayList<?>();
(2) ArrayList<?> myList = new ArrayList<?>();
First is generally preferred. As you will be using methods from List
interface only, it provides you the freedom to use some other implementation of List
e.g. LinkedList
in future. So it decouples you from specific implementation. Now there are two points worth mentioning:
ArrayList
over LinkedList
. More here.I am wondering if anyone uses (2)
Yes sometimes (read rarely). When we need methods that are part of implementation of ArrayList
but not part of the interface List
. For example ensureCapacity
.
Also, how often (and can I please get an example) does the situation actually require using (1) over (2)
Almost always you prefer option (1). This is a classical design pattern in OOP where you always try to decouple your code from specific implementation and program to the interface.
This guide says:
6.1.5 Sending JDBC NULL as an IN parameter
The setNull method allows a programmer to send a JDBC NULL (a generic SQL NULL) value to the database as an IN parameter. Note, however, that one must still specify the JDBC type of the parameter.
A JDBC NULL will also be sent to the database when a Java null value is passed to a setXXX method (if it takes Java objects as arguments). The method setObject, however, can take a null value only if the JDBC type is specified.
So yes they're equivalent.
In Linux i want to add a daemon that cannot be stopped and which monitors filesystem changes. If any changes would be detected it should write the path to the console where it was started + a newline.
Daemons work in the background and (usually...) don't belong to a TTY that's why you can't use stdout/stderr in the way you probably want. Usually a syslog daemon (syslogd) is used for logging messages to files (debug, error,...).
Besides that, there are a few required steps to daemonize a process.
If I remember correctly these steps are:
To give you a starting point: Look at this skeleton code that shows the basic steps. This code can now also be forked on GitHub: Basic skeleton of a linux daemon
/*
* daemonize.c
* This example daemonizes a process, writes a few log messages,
* sleeps 20 seconds and terminates afterwards.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <syslog.h>
static void skeleton_daemon()
{
pid_t pid;
/* Fork off the parent process */
pid = fork();
/* An error occurred */
if (pid < 0)
exit(EXIT_FAILURE);
/* Success: Let the parent terminate */
if (pid > 0)
exit(EXIT_SUCCESS);
/* On success: The child process becomes session leader */
if (setsid() < 0)
exit(EXIT_FAILURE);
/* Catch, ignore and handle signals */
//TODO: Implement a working signal handler */
signal(SIGCHLD, SIG_IGN);
signal(SIGHUP, SIG_IGN);
/* Fork off for the second time*/
pid = fork();
/* An error occurred */
if (pid < 0)
exit(EXIT_FAILURE);
/* Success: Let the parent terminate */
if (pid > 0)
exit(EXIT_SUCCESS);
/* Set new file permissions */
umask(0);
/* Change the working directory to the root directory */
/* or another appropriated directory */
chdir("/");
/* Close all open file descriptors */
int x;
for (x = sysconf(_SC_OPEN_MAX); x>=0; x--)
{
close (x);
}
/* Open the log file */
openlog ("firstdaemon", LOG_PID, LOG_DAEMON);
}
int main()
{
skeleton_daemon();
while (1)
{
//TODO: Insert daemon code here.
syslog (LOG_NOTICE, "First daemon started.");
sleep (20);
break;
}
syslog (LOG_NOTICE, "First daemon terminated.");
closelog();
return EXIT_SUCCESS;
}
gcc -o firstdaemon daemonize.c
./firstdaemon
Check if everything is working properly: ps -xj | grep firstdaemon
The output should be similar to this one:
+------+------+------+------+-----+-------+------+------+------+-----+ | PPID | PID | PGID | SID | TTY | TPGID | STAT | UID | TIME | CMD | +------+------+------+------+-----+-------+------+------+------+-----+ | 1 | 3387 | 3386 | 3386 | ? | -1 | S | 1000 | 0:00 | ./ | +------+------+------+------+-----+-------+------+------+------+-----+
What you should see here is:
Reading the syslog:
/var/log/syslog
Do a: grep firstdaemon /var/log/syslog
The output should be similar to this one:
firstdaemon[3387]: First daemon started. firstdaemon[3387]: First daemon terminated.
A note:
In reality you would also want to implement a signal handler and set up the logging properly (Files, log levels...).
Further reading:
I suspect you're confused here because it's fundamentally confusing. To make things worse, the whole ours/theirs stuff switches roles (becomes backwards) when you are doing a rebase.
Ultimately, during a git merge
, the "ours" branch refers to the branch you're merging into:
git checkout merge-into-ours
and the "theirs" branch refers to the (single) branch you're merging:
git merge from-theirs
and here "ours" and "theirs" makes some sense, as even though "theirs" is probably yours anyway, "theirs" is not the one you were on when you ran git merge
.
While using the actual branch name might be pretty cool, it falls apart in more complex cases. For instance, instead of the above, you might do:
git checkout ours
git merge 1234567
where you're merging by raw commit-ID. Worse, you can even do this:
git checkout 7777777 # detach HEAD
git merge 1234567 # do a test merge
in which case there are no branch names involved!
I think it's little help here, but in fact, in gitrevisions
syntax, you can refer to an individual path in the index by number, during a conflicted merge
git show :1:README
git show :2:README
git show :3:README
Stage #1 is the common ancestor of the files, stage #2 is the target-branch version, and stage #3 is the version you are merging from.
The reason the "ours" and "theirs" notions get swapped around during rebase
is that rebase works by doing a series of cherry-picks, into an anonymous branch (detached HEAD mode). The target branch is the anonymous branch, and the merge-from branch is your original (pre-rebase) branch: so "--ours" means the anonymous one rebase is building while "--theirs" means "our branch being rebased".
As for the gitattributes entry: it could have an effect: "ours" really means "use stage #2" internally. But as you note, it's not actually in place at the time, so it should not have an effect here ... well, not unless you copy it into the work tree before you start.
Also, by the way, this applies to all uses of ours and theirs, but some are on a whole file level (-s ours
for a merge strategy; git checkout --ours
during a merge conflict) and some are on a piece-by-piece basis (-X ours
or -X theirs
during a -s recursive
merge). Which probably does not help with any of the confusion.
I've never come up with a better name for these, though. And: see VonC's answer to another question, where git mergetool
introduces yet more names for these, calling them "local" and "remote"!
The best solution is:
Computer
-> Properties
-> Device manager
.View
-> Show hidden devices
.Non-plug and plug drivers
-> HTTP
-> Disable
.SELECT id
FROM tablename
ORDER BY id
DESC
LIMIT 2 , 1
This is only for get 3rd highest value .
Not the best method, use an array instead. This is just an alternative method.
http://www.w3schools.com/jsref/jsref_getday.asp
var date = new Date();
var day = date.getDay();
You should really use google before you post here.
Since other people posted the array method I'll show you an alternative way using a switch statement.
switch(day) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
... rest of cases
default:
// do something
break;
}
The above works, however, the array is the better alternative. You may also use if()
statements however a switch statement would be much cleaner then several if's.
One nice bonus of the already-mentioned sshpass
is that you can use it with autossh
, eliminating even more of the interactive inefficiency.
sshpass -p mypassword autossh -M0 -t [email protected]
This will allow autoreconnect if, e.g. your wifi is interrupted by closing your laptop.
static variables are used when only one copy of the variable is required. so if you declare variable inside the method there is no use of such variable it's become local to function only..
example of static is
class myclass
{
public static int a = 0;
}
Variables declared static are commonly shared across all instances of a class.
Variables declared static are commonly shared across all instances of a class. When you create multiple instances of VariableTest class This variable permanent is shared across all of them. Thus, at any given point of time, there will be only one string value contained in the permanent variable.
Since there is only one copy of the variable available for all instances, the code this.permament will result in compilation errors because it can be recalled that this.variablename refers to the instance variable name. Thus, static variables are to be accessed directly, as indicated in the code.
You can see the differences b/w these two
import sys
for i in range(1,10 ):
sys.stdout.write(str(i))
sys.stdout.flush()
for i in range(1,10 ):
print i
If you have a QMainWindow
you can override closeEvent
method.
#include <QCloseEvent>
void MainWindow::closeEvent (QCloseEvent *event)
{
QMessageBox::StandardButton resBtn = QMessageBox::question( this, APP_NAME,
tr("Are you sure?\n"),
QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
QMessageBox::Yes);
if (resBtn != QMessageBox::Yes) {
event->ignore();
} else {
event->accept();
}
}
If you're subclassing a QDialog
, the closeEvent
will not be called and so you have to override reject()
:
void MyDialog::reject()
{
QMessageBox::StandardButton resBtn = QMessageBox::Yes;
if (changes) {
resBtn = QMessageBox::question( this, APP_NAME,
tr("Are you sure?\n"),
QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
QMessageBox::Yes);
}
if (resBtn == QMessageBox::Yes) {
QDialog::reject();
}
}
mv server.log logs/$(date -d "today" +"%Y%m%d%H%M").log
UPDATED
Some time on, I see a comment that brings me back to my old answer, and I think I'd do it differently now. These days I'd write:
private static IEnumerable<T> GetEnumValues<T>()
{
// Can't use type constraints on value types, so have to do check like this
if (typeof(T).BaseType != typeof(Enum))
{
throw new ArgumentException("T must be of type System.Enum");
}
return Enum.GetValues(typeof(T)).Cast<T>();
}
use return
for this
if(i==1) {
return; //stop the execution of function
}
//keep on going
I want to add something.
Actually, Task.Delay
is a timer based wait mechanism. If you look at the source you would find a reference to a Timer
class which is responsible for the delay. On the other hand Thread.Sleep
actually makes current thread to sleep, that way you are just blocking and wasting one thread. In async programming model you should always use Task.Delay()
if you want something(continuation) happen after some delay.
You can use the @Value
annotation for reading values from an application.properties/yml file.
@Value("${application.name}")
private String applicationName;
One of the fast ways to create a dict from equal-length tuples:
>>> t1 = (a,b,c,d)
>>> t2 = (1,2,3,4)
>>> dict(zip(t1, t2))
{'a':1, 'b':2, 'c':3, 'd':4, }
As of OkHttp3 you can do this through the Builder like so
client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
You can also view the recipe here.
For older versions, you simply have to do this
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(15, TimeUnit.SECONDS); // connect timeout
client.setReadTimeout(15, TimeUnit.SECONDS); // socket timeout
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
Be aware that value set in setReadTimeout
is the one used in setSoTimeout
on the Socket
internally in the OkHttp
Connection
class.
Not setting any timeout on the OkHttpClient
is the equivalent of setting a value of 0
on setConnectTimeout
or setReadTimeout
and will result in no timeout at all. Description can be found here.
As mentioned by @marceloquinta in the comments setWriteTimeout
can also be set.
As of version 2.5.0
read / write / connect timeout values are set to 10 seconds by default as mentioned by @ChristerNordvik. This can be seen here.
if (typeof v === 'function') {
// do something
}
SET SESSION group_concat_max_len = 1000000;
is a temporary, session-scope, setting. It only applies to the current session You should use it like this.
SET SESSION group_concat_max_len = 1000000;
select group_concat(column) from table group by column
You can do this even in sharing hosting, but when you use an other session, you need to repeat the SET SESSION
command.
Use margins instead of line-height and then apply float to the buttons. By default they are displaying as inline-block
, so when one is pushed down the hole line is pushed down with him. Float fixes this:
#header button {
float:left;
}
Here's a working jsfidle.
For the solution i used a concept of padding which aligns the memory and do not waste the memory of a single byte .
If there are constraints that, you cannot waste a single byte. All pointers allocated with malloc are 16 bytes aligned.
C11 is supported, so you can just call aligned_alloc (16, size)
.
void *mem = malloc(1024+16);
void *ptr = ((char *)mem+16) & ~ 0x0F;
memset_16aligned(ptr, 0, 1024);
free(mem);
Once you're logged in as postgres
, you should be able to write:
psql -t -d database_name -c $'SELECT c_defaults FROM user_info WHERE c_uid = \'testuser\';'
to print out just the value of that field, which means that you can capture it to (for example) save in a Bash variable:
testuser_defaults="$(psql -t -d database_name -c $'SELECT c_defaults FROM user_info WHERE c_uid = \'testuser\';')"
To handle the logging in as postgres
, I recommend using sudo
. You can give a specific user the permission to run
sudo -u postgres /path/to/this/script.sh
so that they can run just the one script as postgres
.
The problem is that some versions of explorer don't support the window.open javascript function
Say what? Can you provide a reference for that statement? With respect, I think you must be mistaken. This works on IE6 and IE9, for instance.
Most modern browsers won't let your code use window.open
except in direct response to a user event, in order to keep spam pop-ups and such at bay; perhaps that's what you're thinking of. As long as you only use window.open
when responding to a user event, you should be fine using window.open
— with all versions of IE.
There is no way to use location
to open a new window. Just window.open
or, of course, the user clicking a link with target="_blank"
.
The issue is that NULL is not considered to be equal to anything even not to itself, but the strange part is that is also not not equal to itself.
Consider the following statements (which is BTW illegal in SQL Server T-SQL but is valid in My-SQL, however this is what ANSI defines for null, and can be verified even in SQL Server by using case statements etc.)
SELECT NULL = NULL -- Results in NULL
SELECT NULL <> NULL -- Results in NULL
So there is no true/false answer to the question, instead the answer is also null.
This has many implications, for example in
WHEN NULL
condition )SELECT a + NULL -- Results in NULL
One can override this behavior in SQL Server by specifying SET ANSI_NULLS OFF
, however this is NOT recommended and should not be done as it can cause many issues, simply because deviation of the standard.
(As a side note, in My-SQL there is an option to use a special operator <=>
for null comparison.)
In comparison, in general programming languages null is treated is a regular value and is equal to itself, however the is the NAN value which is also not equal to itself, but at least it returns 'false' when comparing it to itself, (and when checking for not equals different programming languages have different implementations).
Note however that in the Basic languages (i.e. VB etc.) there is no 'null' keyword and instead one uses the 'Nothing' keyword, which cannot be used in direct comparison and instead one needs to use 'IS' as in SQL, however it is in fact equal to itself (when using indirect comparisons).
I think it's local to the file you declared offset. Consider every file to be a method itself.
Maybe put the whole thing into a class and then make offset a class variable with @@offset = Point.new(100, 200);
?
Simply move the declaration outside of the if block.
@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="";
if (currentstore == "www.mydomain.com")
{
<link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
imgsrc="/content/images/uploaded/store1_logo.jpg";
}
else
{
<link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
imgsrc="/content/images/uploaded/store2_logo.gif";
}
}
<a href="@Url.RouteUrl("HomePage")" class="logo"><img alt="" src="@imgsrc"></a>
You could make it a bit cleaner.
@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="/content/images/uploaded/store2_logo.gif";
if (currentstore == "www.mydomain.com")
{
<link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
imgsrc="/content/images/uploaded/store1_logo.jpg";
}
else
{
<link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
}
}
This approach avoids the warnings while preserving the array-oriented evaluation.
import numpy as np
def isnat(x):
"""
datetime64 analog to isnan.
doesn't yet exist in numpy - other ways give warnings
and are likely to change.
"""
return x.astype('i8') == np.datetime64('NaT').astype('i8')
There are really two separate issues. The first is keeping the elements of the array in proper order so that there are no "holes" after removing an element. The second is actually resizing the array itself.
Arrays in C are allocated as a fixed number of contiguous elements. There is no way to actually remove the memory used by an individual element in the array but the elements can be shifted to fill the hole made by removing an element. For example:
void remove_element(array_type *array, int index, int array_length)
{
int i;
for(i = index; i < array_length - 1; i++) array[i] = array[i + 1];
}
Statically allocated arrays can not be resized. Dynamically allocated arrays can be resized with realloc(). This will potentially move the entire array to another location in memory, so all pointers to the array or to its elements will have to be updated. For example:
remove_element(array, index, array_length); /* First shift the elements, then reallocate */
array_type *tmp = realloc(array, (array_length - 1) * sizeof(array_type) );
if (tmp == NULL && array_length > 1) {
/* No memory available */
exit(EXIT_FAILURE);
}
array_length = array_length - 1;
array = tmp;
realloc will return a NULL pointer if the requested size is 0, or if there is an error. Otherwise it returns a pointer to the reallocated array. The temporary pointer is used to detect errors when calling realloc because instead of exiting it is also possible to just leave the original array as it was. When realloc fails to reallocate an array it does not alter the original array.
Note that both of these operations will be fairly slow if the array is large or if a lot of elements are removed. There are other data structures like linked lists and hashes that can be used if efficient insertion and deletion is a priority.
I would think you should add it to ~/.bash_profile
instead of .bashrc
, (creating .bash_profile
if it doesn't exist.) Then you don't have to add the extra step of checking for ~/.bashrc
in your .bash_profile
Are you comfortable working and editing in a terminal? Just in case, ~/
means your home directory, so if you open a new terminal window that is where you will be "located". And the dot at the front makes the file invisible to normal ls
command, unless you put -a
or specify the file name.
Check this answer for more detail.
I'm using something very similar to Clement's answer:
private int GetSignificantDecimalPlaces(decimal number, bool trimTrailingZeros = true)
{
string stemp = Convert.ToString(number);
if (trimTrailingZeros)
stemp = stemp.TrimEnd('0');
return stemp.Length - 1 - stemp.IndexOf(
Application.CurrentCulture.NumberFormat.NumberDecimalSeparator);
}
Remember to use System.Windows.Forms to get access to Application.CurrentCulture
First of all - use single quotes around your date literals!
Second of all, I would strongly recommend always using the ISO-8601 date format - this works regardless of what your locale, regional or language settings are on your SQL Server.
The ISO-8601 format is either:
YYYYMMDD
for dates only (e.g. 20110825
for the 25th of August, 2011)YYYY-MM-DDTHH:MM:SS
for dates and time (e.g. 2011-08-25T14:15:00
for 25th of AUgust, 14:15/2:15pm in the afternoon)The only solution I've found (almost instantly after posting the question), is to loop through the array and use Object.assign()
Like this:
public duplicateArray() {
let arr = [];
this.content.forEach((x) => {
arr.push(Object.assign({}, x));
})
arr.map((x) => {x.status = DEFAULT});
return this.content.concat(arr);
}
I know this is not optimal. And I wonder if there's any better solutions.
It seems if you have a strongly typed view you need to change the ID of the dropdown so that it is NOT the name of a property on the inherrited class. You then need to put some logic in your edit (POST) method to pull off the selected value from the FORMCollection and put it on to your instance before committing your changes.
This is certainly a little strange, but i tried it and it works.
So if you class has a field called CountryId say, and you're displaying a list of country names, make the dropdown have an id of CountryName rather than CountryId, then in the post, you can do something with Collection["CountryName"].
Let me give an example for Including express module with require & import
-require
var express = require('express');
-import
import * as express from 'express';
So after using any of the above statement we will have a variable called as 'express' with us. Now we can define 'app' variable as,
var app = express();
So we use 'require' with 'CommonJS' and 'import' with 'ES6'.
For more info on 'require' & 'import', read through below links.
require - Requiring modules in Node.js: Everything you need to know
import - An Update on ES6 Modules in Node.js
See http://www.w3.org/TR/html401/interact/forms.html#h-17.9 for the W3 recommendations.
They say it can be done either way. They describe the two methods as explicit (using "for" with the element's id) and implicit (embedding the element in the label):
Explicit:
The for attribute associates a label with another control explicitly: the value of the for attribute must be the same as the value of the id attribute of the associated control element.
Implicit:
To associate a label with another control implicitly, the control element must be within the contents of the LABEL element. In this case, the LABEL may only contain one control element.
This is a peculiar question because it's not supposed to be a matter of choice.
When you launch the JVM, you specify a class to run, and it is the main()
of this class where your program starts.
By init()
, I assume you mean the JApplet method. When an applet is launched in the browser, the init()
method of the specified applet is executed as the first order of business.
By run()
, I assume you mean the method of Runnable. This is the method invoked when a new thread is started.
If Eclipse is running your run()
method even though you have no main()
, then it is doing something peculiar and non-standard, but not infeasible. Perhaps you should post a sample class that you've been running this way.
If you comparing 2 arrays but values not in same index, then try this
var array1=[1,2,3,4]
var array2=[1,4,3,2]
var is_equal = array1.length==array2.length && array1.every(function(v,i) { return ($.inArray(v,array2) != -1)})
console.log(is_equal)
Check the execution path of python3 where it has libraries
$ which python3
/usr/local/bin/python3 some OS might have /usr/bin/python3
open bash_profile file and add an alias
vi ~/.bash_profile
alias python='/usr/local/bin/python3' or alias python='/usr/bin/python3'
Reload bash_profile to take effect of modifications
source ~/.bash_profile
Run python command and check whether it's getting loading with python3
$ python --version
Python 3.6.5
All cookies are client and server
There is no difference. A regular cookie can be set server side or client side. The 'classic' cookie will be sent back with each request. A cookie that is set by the server, will be sent to the client in a response. The server only sends the cookie when it is explicitly set or changed, while the client sends the cookie on each request.
But essentially it's the same cookie.
But, behavior can change
A cookie is basically a name=value
pair, but after the value can be a bunch of semi-colon separated attributes that affect the behavior of the cookie if it is so implemented by the client (or server).
Those attributes can be about lifetime, context and various security settings.
HTTP-only (is not server-only)
One of those attributes can be set by a server to indicate that it's an HTTP-only cookie. This means that the cookie is still sent back and forth, but it won't be available in JavaScript. Do note, though, that the cookie is still there! It's only a built in protection in the browser, but if somebody would use a ridiculously old browser like IE5, or some custom client, they can actually read the cookie!
So it seems like there are 'server cookies', but there are actually not. Those cookies are still sent to the client. On the client there is no way to prevent a cookie from being sent to the server.
Alternatives to achieve 'only-ness'
If you want to store a value only on the server, or only on the client, then you'd need some other kind of storage, like a file or database on the server, or Local Storage on the client.
I guess it is what you are looking for: http://blogsh.de/tag/bootstrap-less/
@import 'bootstrap.less';
div.my-class {
.border-radius( 5px );
}
You can use it because there is a mixin:
.border-radius(@radius: 5px) {
-webkit-border-radius: @radius;
-moz-border-radius: @radius;
border-radius: @radius;
}
For Bootstrap 3, there are 4 mixins you can use...
.border-top-radius(@radius);
.border-right-radius(@radius);
.border-bottom-radius(@radius);
.border-left-radius(@radius);
or you can make your own mixin using the top 4 to do it in one shot.
.border-radius(@radius){
.border-top-radius(@radius);
.border-right-radius(@radius);
.border-bottom-radius(@radius);
.border-left-radius(@radius);
}
For as long as there is no official date and time picker from angular itself, I would advise to make a combination of the default angular date picker and this Angular Material Timepicker. I've chosen that one because all the other ones I found at this time lack support for issues, are outdated or are not functioning well in the most recent angular versions. This guy seems to be very responsive.
I've wrapped them both in one component so that it looks like it is one unit. You just have to make sure to do a few things:
When no input has been given yet, I would advise:
touchUi = true
on the datepicker, so that both the datepicker and the timepicker come as a dialog after each other.After a value has been given, it is clear that one part contains the time and the other part contains the date. At that moment it is clear that the user has to click on the time to change the time, and on the date to change the date. But before that, so when both fields are empty (and 'attached' to each other as one field) you should make sure the user cannot be confused by doing above recommendations.
My component is not complete yet, I will try to remember myself to share the code later. Shoot a comment if this question is more then a month old or so.
Edit: Result
<div fxLayout="row">
<div *ngIf="!dateOnly" [formGroup]="timeFormGroup">
<mat-form-field>
<input matInput [ngxTimepicker]="endTime" [format]="24" placeholder="{{placeholderTime}}" formControlName="endTime" />
</mat-form-field>
<ngx-material-timepicker #endTime (timeSet)="timeChange($event)" [minutesGap]="10"></ngx-material-timepicker>
</div>
<div>
<mat-form-field>
<input id="pickerId" matInput [matDatepicker]="datepicker" placeholder="{{placeholderDate}}" [formControl]="dateForm"
[min]="config.minDate" [max]="config.maxDate" (dateChange)="dateChange($event)">
<mat-datepicker-toggle matSuffix [for]="datepicker"></mat-datepicker-toggle>
<mat-datepicker #datepicker [disabled]="disabled" [touchUi]="config.touchUi" startView="{{config.startView}}"></mat-datepicker>
</mat-form-field>
</div>
</div>
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { DateAdapter, MatDatepickerInputEvent } from '@angular/material';
import * as moment_ from 'moment';
const moment = moment_;
import { MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter';
class DateConfig {
startView: 'month' | 'year' | 'multi-year';
touchUi: boolean;
minDate: moment_.Moment;
maxDate: moment_.Moment;
}
@Component({
selector: 'cb-datetimepicker',
templateUrl: './cb-datetimepicker.component.html',
styleUrls: ['./cb-datetimepicker.component.scss'],
})
export class DatetimepickerComponent implements OnInit {
@Input() disabled: boolean;
@Input() placeholderDate: string;
@Input() placeholderTime: string;
@Input() model: Date;
@Input() purpose: string;
@Input() dateOnly: boolean;
@Output() dateUpdate = new EventEmitter<Date>();
public pickerId: string = "_" + Math.random().toString(36).substr(2, 9);
public dateForm: FormControl;
public timeFormGroup: FormGroup;
public endTime: FormControl;
public momentDate: moment_.Moment;
public config: DateConfig;
//myGroup: FormGroup;
constructor(private adapter : DateAdapter<any>) { }
ngOnInit() {
this.adapter.setLocale("nl-NL");//todo: configurable
this.config = new DateConfig();
if (this.purpose === "birthday") {
this.config.startView = 'multi-year';
this.config.maxDate = moment().add('year', -15);
this.config.minDate = moment().add('year', -90);
this.dateOnly = true;
} //add more configurations
else {
this.config.startView = 'month';
this.config.maxDate = moment().add('year', 100);
this.config.minDate = moment().add('year', -100);
}
if (window.screen.width < 767) {
this.config.touchUi = true;
}
if (this.model) {
var mom = moment(this.model);
if (mom.isBefore(moment('1900-01-01'))) {
this.momentDate = moment();
} else {
this.momentDate = mom;
}
} else {
this.momentDate = moment();
}
this.dateForm = new FormControl(this.momentDate);
if (this.disabled) {
this.dateForm.disable();
}
this.endTime = new FormControl(this.momentDate.format("HH:mm"));
this.timeFormGroup = new FormGroup({
endTime: this.endTime
});
}
public dateChange(date: MatDatepickerInputEvent<any>) {
if (moment.isMoment(date.value)) {
this.momentDate = moment(date.value);
if (this.dateOnly) {
this.momentDate = this.momentDate.utc(true);
}
var newDate = this.momentDate.toDate();
this.model = newDate;
this.dateUpdate.emit(newDate);
}
console.log("datechange",date);
}
public timeChange(time: string) {
var splitted = time.split(':');
var hour = splitted[0];
var minute = splitted[1];
console.log("time change", time);
this.momentDate = this.momentDate.set('hour', parseInt(hour));
this.momentDate = this.momentDate.set('minute', parseInt(minute));
var newDate = this.momentDate.toDate();
this.model = newDate;
this.dateUpdate.emit(newDate);
}
}
One important source: https://github.com/Agranom/ngx-material-timepicker/issues/126
I think it still deserves some tweaks, as I think it can work a bit better when I would have more time creating this. Most importantly I tried to solve the UTC issue as well, so all dates should be shown in local time but should be sent to the server in UTC format (or at least saved with the correct timezone added to it).
A different answer that worked for me. Is that, to install [sudo] apt-get install libapache2-mod-php5.X
This is defined in PEP8 here:
Global Variable Names
(Let's hope that these variables are meant for use inside one module only.) The conventions are about the same as those for functions.
Modules that are designed for use via
from M import *
should use the__all__
mechanism to prevent exporting globals, or use the older convention of prefixing such globals with an underscore (which you might want to do to indicate these globals are "module non-public").
PEP8 provides coding conventions for the Python code comprising the standard library in the main Python distribution. The more you follow this, closer you are to the original intent.
The above answer is totally true but not working for me.
I solved my problem with the following things.
Actually My XML is like that:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/confirm_order_mail_layout"
android:layout_width="match_parent"
android:layout_height="fill_parent">
<android.support.design.widget.AppBarLayout
android:id="@+id/confirm_order_appbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/confirm_order_list_collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:layout_scrollFlags="scroll|enterAlways">
<android.support.v7.widget.Toolbar
android:id="@+id/confirm_order_toolbar_layout"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
I have tried all the option and after all I just removed CollapsingToolbarLayout
because of i do not need to use in that particular XML
So My Final XML is like:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/confirm_order_mail_layout"
android:layout_width="match_parent"
android:layout_height="fill_parent">
<android.support.design.widget.AppBarLayout
android:id="@+id/confirm_order_appbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/confirm_order_toolbar_layout"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
Now you have to use setTitle()
like above answer:
mActionBarToolbar = (Toolbar) findViewById(R.id.confirm_order_toolbar_layout);
setSupportActionBar(mActionBarToolbar);
getSupportActionBar().setTitle("My Title");
Now If you want to use CollapsingToolbarLayout
and Toolbar
together then you have to use setTitle()
of CollapsingToolbarLayout
CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.confirm_order_mail_layout);
collapsingToolbarLayout.setTitle("My Title");
May it will helps you. Thank you.
I think thats not the reason everybody told above. There is something wrong in your code, maybe miss spelling or mismatching with the database column names. If mysqli query gets no result then it will return false, so that it is not a object - is a wrong idea. Everything works fine. it returns 1 or 0 if query have result or not.
So, my suggestion is check your variable names and table column names or any other misspelling.
You'll need to consider this in context of the application. In general, you should design an application, not a database (the database simply being part of the application).
Consider how your application should respond to various cases.
The default action is to restrict (i.e. not permit) the operation, which is normally what you want as it prevents stupid programming errors. However, on DELETE CASCADE can also be useful. It really depends on your application and how you intend to delete particular objects.
Personally, I'd use InnoDB because it doesn't trash your data (c.f. MyISAM, which does), rather than because it has FK constraints.
You could do something like this:
var radio_buttons = $("input[name='html_elements']");
if( radio_buttons.filter(':checked').length == 0){
// None checked
} else {
// If you need to use the result you can do so without
// another (costly) jQuery selector call:
var val = radio_buttons.val();
}
The 32-bit vs 64-bit difference does become more important when you are interfacing with native libraries. 64-bit Java will not be able to interface with a 32-bit non-Java dll (via JNI)
Here is a class providing a cancel method for a delayed action
public class DelayedAction {
private Handler _handler;
private Runnable _runnable;
/**
* Constructor
* @param runnable The runnable
* @param delay The delay (in milli sec) to wait before running the runnable
*/
public DelayedAction(Runnable runnable, long delay) {
_handler = new Handler(Looper.getMainLooper());
_runnable = runnable;
_handler.postDelayed(_runnable, delay);
}
/**
* Cancel a runnable
*/
public void cancel() {
if ( _handler == null || _runnable == null ) {
return;
}
_handler.removeCallbacks(_runnable);
}}
I know it's late, but I take the original code and change some stuff to control easily the css. So I made a code with the addClass() and the removeClass()
Here the full code : http://jsfiddle.net/e5qaD/4837/
if( bottom_of_window > bottom_of_object ){
$(this).addClass('showme');
}
if( bottom_of_window < bottom_of_object ){
$(this).removeClass('showme');
Just in case you would need to delete a variable, you could use SETENV from Vincent Fatica available at http://barnyard.syr.edu/~vefatica. Not exactly recent ('98) but still working on Windows 7 x64.
while (true)
{//ie is the WebBrowser object
if (ie.ReadyState == tagREADYSTATE.READYSTATE_COMPLETE)
{
break;
}
Thread.Sleep(500);
}
I used this way to wait untill the page loads.
Use array_name.pop(index_no.)
ex:-
>>> arr = [1,2,3,4]
>>> arr.pop(2)
>>>arr
[1,2,4]
>>> arr1 = ['python3.6' , 'python2' ,'python3']
>>> arr1.remove('python2')
>>> arr1
['python3.6','python3']
I figured it out from the PostgreSQL docs, the exact syntax is:
ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn);
Thanks Fred.
if you are windows user, then it's in C:\Users\your_user_name\Envs. You can delete it from there.
Also try in command prompt rmvirtualenv environment name.
I tried with command prompt so it said deleted but it was still existed. So i manually delete it.
i had got the same error. Actually i tried to override the flutter Old SDK Package with new Updated Package. so that error occurred.
i opened flutter sdk directory with VS Code and cleaned the project
use this code in VSCode cmd
git clean -dxf
then use git pull
Sometimes when you are not sure what -1 or the like will result in, you may wish to set the nth bit without using -1:
number = (((number | (1 << n)) ^ (1 << n))) | (x << n);
Explanation: ((number | (1 << n)
sets the nth bit to 1 (where |
denotes bitwise OR), then with (...) ^ (1 << n)
we set the nth bit to 0, and finally with (...) | x << n)
we set the nth bit that was 0, to (bit value) x
.
This also works in golang
.
Use the in
keyword without is
.
if "x" in dog:
print "Yes!"
If you'd like to check for the non-existence of a character, use not in
:
if "x" not in dog:
print "No!"
Maybe you mean comm
?
Compare sorted files FILE1 and FILE2 line by line.
With no options, produce three-column output. Column one contains lines unique to FILE1, column two contains lines unique to FILE2, and column three contains lines common to both files.
The secret in finding these information are the info pages. For GNU programs, they are much more detailed than their man-pages. Try info coreutils
and it will list you all the small useful utils.
I found this much easier(https://docs.oracle.com/javase/tutorial/datetime/iso/enum.html)
private void getCalendarMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Month month = Month.of(calendar.get(Calendar.MONTH));
Locale locale = Locale.getDefault();
System.out.println(month.getDisplayName(TextStyle.FULL, locale));
System.out.println(month.getDisplayName(TextStyle.NARROW, locale));
System.out.println(month.getDisplayName(TextStyle.SHORT, locale));
}
I am using the rebase for years and I had never encountered such a problem. However, your first problem is, that you try to do it directly on the remote branch development
from the remote repository, called origin
. That is literally wrong because rebase is a dangerous command, that restructures the git history. Having said that, you should first try on your local repository and pushing it only, if it works for you as expected.
So, my usual rebase workflow looks like following (but please keep in mind, that you should not use rebase on branches, which you are not the only one committee. For such branches, use simply merge and resolve conflicts, if applicable):
master
; as a one-line command): git checkout master && git pull origin master && git checkout development
git rebase master
git push -f origin development
As I already mentioned, keep in mind, that rebase manipulates the git history, that is usually a bad thing. However, it's possible to do that on branches, where no one else commits to. In order to keep the branch pull-able for the other developers, use another merge strategy like merge itself, squash or cherrypick. So, in other words: Rebase shouldn't be your tool on distributed development. It works fine for you if you are the only one who works on this repository.
We use the feature branch strategy. In this, I usually use rebase in order to get the "updates" from the other developers, that happened in the meantime on the master branch. Doing so, it reduces the size of commits that are visible in a pull request. Therefore, it makes it easier for the code reviewer to see my changes made in this feature branch.
You can also set the title of your chart by adding the title parameter as follows
ax.set(xlabel='common xlabel', ylabel='common ylabel', title='some title')
Use the .classList.add()
method:
const element = document.querySelector('div.foo');_x000D_
element.classList.add('bar');_x000D_
console.log(element.className);
_x000D_
<div class="foo"></div>
_x000D_
This method is better than overwriting the className
property, because it doesn't remove other classes and doesn't add the class if the element already has it.
You can also toggle or remove classes using element.classList
(see the MDN documentation).
Another solution is the following:
ISNULL(NULLIF(DATEPART(dw,DateField)-1,0),7)
#include<stdio.h>
int main()
{
int a,b,i,c,j;
printf("\n Enter the two no. in between you want to check:");
scanf("%d%d",&a,&c);
printf("%d-%d\n",a,c);
for(j=a;j<=c;j++)
{
b=0;
for(i=1;i<=c;i++)
{
if(j%i==0)
{
b++;
}
}
if(b==2)
{
printf("\nPrime number:%d\n",j);
}
else
{
printf("\n\tNot prime:%d\n",j);
}
}
}
String url = "http://test.com/Services/rest/{id}/Identifier";
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1234");
URI uri = UriComponentsBuilder.fromUriString(url)
.buildAndExpand(params)
.toUri();
uri = UriComponentsBuilder
.fromUri(uri)
.queryParam("name", "myName")
.build()
.toUri();
restTemplate.exchange(uri , HttpMethod.PUT, requestEntity, class_p);
The safe way is to expand the path variables first, and then add the query parameters:
For me this resulted in duplicated encoding, e.g. a space was decoded to %2520 (space -> %20 -> %25).
I solved it by:
String url = "http://test.com/Services/rest/{id}/Identifier";
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1234");
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(url);
uriComponentsBuilder.uriVariables(params);
Uri uri = uriComponentsBuilder.queryParam("name", "myName");
.build()
.toUri();
restTemplate.exchange(uri , HttpMethod.PUT, requestEntity, class_p);
Essentially I am using uriComponentsBuilder.uriVariables(params);
to add path parameters. The documentation says:
... In contrast to UriComponents.expand(Map) or buildAndExpand(Map), this method is useful when you need to supply URI variables without building the UriComponents instance just yet, or perhaps pre-expand some shared default values such as host and port. ...
I actually discovered something recently that seems to work for styling individual <option></option>
elements within Chrome, Firefox, and IE using pure CSS.
Maybe, try the following:
HTML:
<select>
<option value="blank">Blank</option>
<option class="white" value="white">White</option>
<option class="red" value="red">Red</option>
<option class="blue" value="blue">Blue</option>
</select>
CSS:
select {
background-color:#000;
color: #FFF;
}
select * {
background-color:#000;
color:#FFF;
}
select *.red { /* This, miraculously, styles the '<option class="red"></option>' elements. */
background-color:#F00;
color:#FFF;
}
select *.white {
background-color:#FFF;
color:#000;
}
select *.blue {
background-color:#06F;
color:#FFF;
}
Strange what throwing caution to the wind does. It doesn't seem to support the :active :hover :focus :link :visited :after :before
, though.
Example on JSFiddle: http://jsfiddle.net/Xd7TJ/2/
You may want to double check the authorized_keys file permissions:
$ chmod 600 ~/.ssh/authorized_keys
Newer SSH server versions are very picky on this respect.
Tweet's answer can be passed to BrenBarn's answer above with
data.reindex_axis(sorted(data.columns, key=lambda x: float(x[1:])), axis=1)
So for your example, say:
vals = randint(low=16, high=80, size=25).reshape(5,5)
cols = ['Q1.3', 'Q6.1', 'Q1.2', 'Q9.1', 'Q10.2']
data = DataFrame(vals, columns = cols)
You get:
data
Q1.3 Q6.1 Q1.2 Q9.1 Q10.2
0 73 29 63 51 72
1 61 29 32 68 57
2 36 49 76 18 37
3 63 61 51 30 31
4 36 66 71 24 77
Then do:
data.reindex_axis(sorted(data.columns, key=lambda x: float(x[1:])), axis=1)
resulting in:
data
Q1.2 Q1.3 Q6.1 Q9.1 Q10.2
0 2 0 1 3 4
1 7 5 6 8 9
2 2 0 1 3 4
3 2 0 1 3 4
4 2 0 1 3 4
Base64 is a way to represent bytes in a textual form (as a string). So there is no such thing as a Base64 encoded byte[]. You'd have a base64 encoded string, which you could decode back to a byte[]
.
However, if you want to end up with a byte array, you could take the base64 encoded string and convert it to a byte array, like:
string base64String = Convert.ToBase64String(bytes);
byte[] stringBytes = Encoding.ASCII.GetBytes(base64String);
This, however, makes no sense because the best way to represent a byte[] as a byte[], is the byte[] itself :)
This article can provide a lot of insight here: http://redis.io/topics/memory-optimization
There are many ways to store an array of Objects in Redis (spoiler: I like option 1 for most use cases):
Store the entire object as JSON-encoded string in a single key and keep track of all Objects using a set (or list, if more appropriate). For example:
INCR id:users
SET user:{id} '{"name":"Fred","age":25}'
SADD users {id}
Generally speaking, this is probably the best method in most cases. If there are a lot of fields in the Object, your Objects are not nested with other Objects, and you tend to only access a small subset of fields at a time, it might be better to go with option 2.
Advantages: considered a "good practice." Each Object is a full-blown Redis key. JSON parsing is fast, especially when you need to access many fields for this Object at once. Disadvantages: slower when you only need to access a single field.
Store each Object's properties in a Redis hash.
INCR id:users
HMSET user:{id} name "Fred" age 25
SADD users {id}
Advantages: considered a "good practice." Each Object is a full-blown Redis key. No need to parse JSON strings. Disadvantages: possibly slower when you need to access all/most of the fields in an Object. Also, nested Objects (Objects within Objects) cannot be easily stored.
Store each Object as a JSON string in a Redis hash.
INCR id:users
HMSET users {id} '{"name":"Fred","age":25}'
This allows you to consolidate a bit and only use two keys instead of lots of keys. The obvious disadvantage is that you can't set the TTL (and other stuff) on each user Object, since it is merely a field in the Redis hash and not a full-blown Redis key.
Advantages: JSON parsing is fast, especially when you need to access many fields for this Object at once. Less "polluting" of the main key namespace. Disadvantages: About same memory usage as #1 when you have a lot of Objects. Slower than #2 when you only need to access a single field. Probably not considered a "good practice."
Store each property of each Object in a dedicated key.
INCR id:users
SET user:{id}:name "Fred"
SET user:{id}:age 25
SADD users {id}
According to the article above, this option is almost never preferred (unless the property of the Object needs to have specific TTL or something).
Advantages: Object properties are full-blown Redis keys, which might not be overkill for your app. Disadvantages: slow, uses more memory, and not considered "best practice." Lots of polluting of the main key namespace.
Option 4 is generally not preferred. Options 1 and 2 are very similar, and they are both pretty common. I prefer option 1 (generally speaking) because it allows you to store more complicated Objects (with multiple layers of nesting, etc.) Option 3 is used when you really care about not polluting the main key namespace (i.e. you don't want there to be a lot of keys in your database and you don't care about things like TTL, key sharding, or whatever).
If I got something wrong here, please consider leaving a comment and allowing me to revise the answer before downvoting. Thanks! :)
With MVC5 i have done it like this and it is 100% working code....
@Html.ActionLink(department.Name, "Index", "Employee", new {
departmentId = department.DepartmentID }, null)
You guys can get an idea from this...
Actually you can do with VS Code the following:
As Wingman said, Google App Engine is a great solution for your scenario.
You can get some information about GAE+Android here: https://developers.google.com/eclipse/docs/appengine_connected_android
And from this Google IO 2012 session: http://www.youtube.com/watch?v=NU_wNR_UUn4
Please check the following.
<canvas id="myCanvas" width="200" height="100"></canvas>
<div id="mydiv"></div>
JS:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.strokeStyle="red";
ctx.moveTo(0,100);
ctx.lineTo(200,0);
ctx.stroke();
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
CSS:
html, body {
margin: 0;
padding: 0;
}
#myCanvas {
padding: 0;
margin: 0;
width: 200px;
height: 100px;
}
#mydiv {
position: absolute;
left: 0px;
right: 0;
height: 102px;
width: 202px;
background: rgba(255,255,255,0);
padding: 0;
margin: 0;
}
Some compilers support compound literals as an extention, allowing this construct:
Customer customerRecords[2];
customerRecords[0] = (Customer){25, "Bob Jones"};
customerRecords[1] = (Customer){26, "Jim Smith"};
But it's rather unportable.
I know this topic is old but I think my answer can be useful for a lot of people.
Here is jQuery plugin made from Pointy's answer using ES6:
/**
* Sort values alphabetically in select
* source: http://stackoverflow.com/questions/12073270/sorting-options-elements-alphabetically-using-jquery
*/
$.fn.extend({
sortSelect() {
let options = this.find("option"),
arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
arr.sort((o1, o2) => { // sort select
let t1 = o1.t.toLowerCase(),
t2 = o2.t.toLowerCase();
return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
});
options.each((i, o) => {
o.value = arr[i].v;
$(o).text(arr[i].t);
});
}
});
Use is very easy
$("select").sortSelect();
Perhaps a simpler one-liner, with identical or different column names. Worked even when df2['Name2'] contained duplicate values.
newDf = df1.set_index('Name1')
.drop(df2['Name2'], errors='ignore')
.reset_index(drop=False)
Another sneaky issue related to this is naming your columns with -
instead of _
.
Something like this will trigger an error at the moment your tables are getting created.
@Column(name="verification-token")
If you uncheck the ADB Integration, you cannot use the debug any more.You may just restart the adb server, run
$adb kill-server
$adb start-server
in Terminal to restart the adb server without restarting the Android Studio. Then the emulator shows up.
private void SaveFileStream(String path, Stream stream)
{
var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write);
stream.CopyTo(fileStream);
fileStream.Dispose();
}
for center and auto zoom on display markers
// map: an instance of google.maps.Map object
// latlng_points_array: an array of google.maps.LatLng objects
var latlngbounds = new google.maps.LatLngBounds( );
for ( var i = 0; i < latlng_points_array.length; i++ ) {
latlngbounds.extend( latlng_points_array[i] );
}
map.fitBounds( latlngbounds );
If you're using Bootstrap 3, you can use the embed-responsive class and set the padding bottom as the height divided by the width plus a little extra for toolbars. For example, to display an 8.5 by 11 PDF, use 130% (11/8.5) plus a little extra (20%).
<div class='embed-responsive' style='padding-bottom:150%'>
<object data='URL.pdf' type='application/pdf' width='100%' height='100%'></object>
</div>
Here's the Bootstrap CSS:
.embed-responsive {
position: relative;
display: block;
height: 0;
padding: 0;
overflow: hidden;
}
It usually happens with projects that were created in other machines. To fix this on Android Studio 3.1.3:
Edit 2019-05-28 - I don't know how long this option is enabled but I have noticed that in Android Studio 3.4 it's easier to Enable Dart Support in projects that were developed in other machines.
Just Close()
all active/existing forms and the application should exit.
Maybe a little more readable?
public static class StringExtension {
private static Dictionary<string, string> _replacements = new Dictionary<string, string>();
static StringExtension() {
_replacements["&"] = "and";
_replacements[","] = "";
_replacements[" "] = " ";
// etc...
}
public static string clean(this string s) {
foreach (string to_replace in _replacements.Keys) {
s = s.Replace(to_replace, _replacements[to_replace]);
}
return s;
}
}
Also add New In Town's suggestion about StringBuilder...
I have been looking for simple and clean way to clear HTML file input, the above answers are great, but none of them really answers what i'm looking for, until i came across on the web with simple an elegant way to do it :
var $input = $("#control");
$input.replaceWith($input.val('').clone(true));
all the credit goes to Chris Coyier.
// Referneces_x000D_
var control = $("#control"),_x000D_
clearBn = $("#clear");_x000D_
_x000D_
// Setup the clear functionality_x000D_
clearBn.on("click", function(){_x000D_
control.replaceWith( control.val('').clone( true ) );_x000D_
});_x000D_
_x000D_
// Some bound handlers to preserve when cloning_x000D_
control.on({_x000D_
change: function(){ console.log( "Changed" ) },_x000D_
focus: function(){ console.log( "Focus" ) }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="file" id="control">_x000D_
<br><br>_x000D_
<a href="#" id="clear">Clear</a>
_x000D_
Arrays.copyOfRange(..)
was added in Java 1.6. So perhaps you don't have the latest version. If it's not possible to upgrade, look at System.arraycopy(..)
Actually I think the LIMIT 10
would be issued to the database so slicing would not occur in Python but in the database.
See limiting-querysets for more information.
SELECT * from table where field in (SELECT distinct field from table)
The problem with singletons is not their implementation. It is that they conflate two different concepts, neither of which is obviously desirable.
1) Singletons provide a global access mechanism to an object. Although they might be marginally more threadsafe or marginally more reliable in languages without a well-defined initialization order, this usage is still the moral equivalent of a global variable. It's a global variable dressed up in some awkward syntax (foo::get_instance() instead of g_foo, say), but it serves the exact same purpose (a single object accessible across the entire program) and has the exact same drawbacks.
2) Singletons prevent multiple instantiations of a class. It's rare, IME, that this kind of feature should be baked into a class. It's normally a much more contextual thing; a lot of the things that are regarded as one-and-only-one are really just happens-to-be-only-one. IMO a more appropriate solution is to just create only one instance--until you realize that you need more than one instance.
You can Use ngValue
. ngValue
passes sting and object both.
Pass as Object:
<select (change)="onItemChange($event.value)">
<option *ngFor="#obj of arr" [ngValue]="obj.value">
{{obj.value}}
</option>
</select>
Pass as String:
<select (change)="onItemChange($event.value)">
<option *ngFor="#obj of arr" [ngValue]="obj">
{{obj.value}}
</option>
</select>
you can split a string by line break by using the following statement :
String textStr[] = yourString.split("\\r?\\n");
you can split a string by Whitespace by using the following statement :
String textStr[] = yourString.split("\\s+");
When you added it to X, you should have incremented X's version number i.e X-1.2
Then X-1.2 should have been installed/deployed and you should have changed your projects dependency on X to be dependent on the new version X-1.2
A more general answer which accepts all the special characters including _
would be slightly different:
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[\W|\_])(?=\S+$).{8,}$
The difference (?=.*[\W|\_])
translates to "at least one of all the special characters including the underscore".
You can use the built in Object.keys
method to get a list of keys on an object and test its length.
var x = {};
// some code where value of x changes and than you want to check whether it is null or some object with values
if(Object.keys(x).length){
// Your code here if x has some properties
}
Use
document.getElementById("file-id").files[0].name;
instead of
document.getElementById('file-id').value
mod_php
means PHP, as an Apache module.
Basically, when loading mod_php
as an Apache module, it allows Apache to interpret PHP files (those are interpreted by mod_php
).
EDIT : There are (at least) two ways of running PHP, when working with Apache :
mod_php
) : the PHP interpreter is then kind of "embedded" inside the Apache process : there is no external PHP process -- which means that Apache and PHP can communicate better.
And re-edit, after the comment : using CGI or mod_php
is up to you : it's only a matter of configuration of your webserver.
To know which way is currently used on your server, you can check the output of phpinfo()
: there should be something indicating whether PHP is running via mod_php
(or mod_php5
), or via CGI.
You might also want to take a look at the php_sapi_name()
function : it returns the type of interface between web server and PHP.
If you check in your Apache's configuration files, when using mod_php
, there should be a LoadModule
line looking like this :
LoadModule php5_module modules/libphp5.so
(The file name, on the right, can be different -- on Windows, for example, it should be a .dll
)
You can select on any attribute and its value by using the attribute selector [attributename=optionalvalue]
, so in your case you can select the option and set the selected attribute.
$("div.id_100 > select > option[value=" + value + "]").prop("selected",true);
Where value
is the value you wish to select by.
If you need to removed any prior selected values, as would be the case if this is used multiple times you'd need to change it slightly so as to first remove the selected attribute
$("div.id_100 option:selected").prop("selected",false);
$("div.id_100 option[value=" + value + "]")
.prop("selected",true);
Here's an approach:
HTML:
<div id="1">
My Content 1
</div>
<div id="2" style="display:none;">
My Dynamic Content
</div>
<button id="btnClick">Click me!</button>
jQuery:
$('#btnClick').on('click',function(){
if($('#1').css('display')!='none'){
$('#2').html('Here is my dynamic content').show().siblings('div').hide();
}else if($('#2').css('display')!='none'){
$('#1').show().siblings('div').hide();
}
});
JsFiddle:
http://jsfiddle.net/ha6qp7w4/
http://jsfiddle.net/ha6qp7w4/4 <--- Commented
For selecting only specific columns out of multiple columns for a given value in Pandas:
select col_name1, col_name2 from table where column_name = some_value.
Options:
df.loc[df['column_name'] == some_value][[col_name1, col_name2]]
or
df.query['column_name' == 'some_value'][[col_name1, col_name2]]
Not All Components.
the state
in component looks like the source of the waterfall of state of the whole APP.
So the change happens from where the setState called. The tree of renders
then get called from there. If you've used pure component, the render
will be skipped.
It is also possible to use span
tag instead of a
tag:
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
document.getElementById('someId').InnerHTML = splitText;
</script>
<body>
<span id="someId"></span>
</body>
</html>
It worked well for me
Here is another quick way, just using the key as an index into the hash table to get the value:
$hash = @{
'a' = 1;
'b' = 2;
'c' = 3
};
foreach($key in $hash.keys) {
Write-Host ("Key = " + $key + " and Value = " + $hash[$key]);
}
You can do this entirely with html and css and i have.
HTML
First you give the div you wish to hide an ID
to target like #view_element
and a class to target like #hide_element
. You can if you wish make both of these classes but i don't know if you can make them both IDs. Then have your Show button target your show id and your Hide button target your hide class. That is it for the html the hiding and showing is done in the CSS.
CSS The css to show and hide this should look something like this
#hide_element:target {
display:none;
}
.show_element:target{
display:block;
}
This should allow you to hide and show elements at will. This should work nicely on spans and divs.
It is better to use .Value2() instead of .Value(). This is faster and gives the exact value in the cell. For certain type of data, truncation can be observed when .Value() is used.
I just came up with the same problem since we still use bootstrap 2.3.2.
My solution for this: http://jsfiddle.net/KnuU6/281/
css:
.myCollapse {
display: none;
}
.myCollapse.in {
display: block;
}
javascript:
$("[data-toggle=myCollapse]").click(function( ev ) {
ev.preventDefault();
var target;
if (this.hasAttribute('data-target')) {
target = $(this.getAttribute('data-target'));
} else {
target = $(this.getAttribute('href'));
};
target.toggleClass("in");
});
html:
<table>
<tr><td><a href="#demo" data-toggle="myCollapse">Click me to toggle next row</a></td></tr>
<tr class="collapse" id="#demo"><td>You can collapse and expand me.</td></tr>
</table>