Just try this one as a full copy paste in the shell and you will grasp it
# create the example file to be working on ..
cat << EOF > tmp.json
[
{ "card_id": "id-00", "card_id_type": "card_id_type-00"},
{"card_id": "id-01", "card_id_type": "card_id_type-01"},
{ "card_id": "id-02", "card_id_type": "card_id_type-02"}
]
EOF
# pipe the content of the file to the jq query, which gets the array of objects
# and select the attribute named "card_id" ONLY if it's neighbour attribute
# named "card_id_type" has the "card_id_type-01" value
# jq -r means give me ONLY the value of the jq query no quotes aka raw
cat tmp.json | jq -r '.[]| select (.card_id_type == "card_id_type-01")|.card_id'
id-01
or with an aws cli command
# list my vpcs or
# list the values of the tags which names are "Name"
aws ec2 describe-vpcs | jq -r '.| .Vpcs[].Tags[]|select (.Key == "Name") | .Value'|sort -nr
From http://www.sqlite.org/cvstrac/wiki?p=UnsupportedSql
To create a new database, just do sqlite_open(). To drop a database, delete the file.
I found so many solution but I never got correct solution. But i have created some code to find minutes please check it.
<?php
$time1 = "23:58";
$time2 = "01:00";
$time1 = explode(':',$time1);
$time2 = explode(':',$time2);
$hours1 = $time1[0];
$hours2 = $time2[0];
$mins1 = $time1[1];
$mins2 = $time2[1];
$hours = $hours2 - $hours1;
$mins = 0;
if($hours < 0)
{
$hours = 24 + $hours;
}
if($mins2 >= $mins1) {
$mins = $mins2 - $mins1;
}
else {
$mins = ($mins2 + 60) - $mins1;
$hours--;
}
if($mins < 9)
{
$mins = str_pad($mins, 2, '0', STR_PAD_LEFT);
}
if($hours < 9)
{
$hours =str_pad($hours, 2, '0', STR_PAD_LEFT);
}
echo $hours.':'.$mins;
?>
It gives output in hours and minutes for example 01 hour 02 minutes like 01:02
Your server may read a different my.cnf
than the one you're editing (unless you specified it when starting mysqld).
From the MySQL Certification Study Guide:
The search order includes two general option files,
/etc/my.cnf
and$MYSQL_HOME/my.cnf
. The second file is used only if theMYSQL_HOME
environment variable is set. Typically, you seet it to the MySQL installation directory. (The mysqld_safe script attempts to setMYSQL_HOME
if it is not set before starting the server.) The option file search order also includes~/.my.cnf
(that is the home directory). This isn't an especially suitable location for server options. (Normally, you invoke the server asmysql
, or asroot
with a--user=mysql
option. The user-specific file read by the server would depend on which login account you invoke it from, possibly leading to inconsistent sets of options being used.)
Another possibility is of course, that your sql-mode
option gets overwritten further down in the same file. Multiple options have to be separated by ,
in the same line.
P.S.: And you need the quotes, IIRC. Now that you've tried it without quotes, I'm pretty sure, you're editing the wrong file, since MySQL doesn't start when there's an error in the option file.
P.P.S.: Had a look at my config files again, there it's
[mysqld]
sql_mode = "NO_ENGINE_SUBSTITUTION"
and it's working.
Another possible cause of similar issue could be wrong processorArchitecture
in the cx_freeze manifest, trying to load x86 common controls dll in x64 process - should be fixed by this patch:
The SSL errors are often thrown by network management software such as Cyberroam.
To answer your question,
you will have to enter badidea into Chrome every time you visit a website.
You might at times have to enter it more than once, as the site may try to pull in various resources before load, hence causing multiple SSL errors
Set the touch-action CSS property to none
, which works even with passive event listeners:
touch-action: none;
Applying this property to an element will not trigger the default (scroll) behavior when the event is originating from that element.
Here is the code little modified that i got it from google -
List data_table = new ArrayList<>();
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(conn_url, user_id, password);
Statement stmt = con.createStatement();
System.out.println("query_string: "+query_string);
ResultSet rs = stmt.executeQuery(query_string);
ResultSetMetaData rsmd = rs.getMetaData();
int row_count = 0;
while (rs.next()) {
HashMap<String, String> data_map = new HashMap<>();
if (row_count == 240001) {
break;
}
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
data_map.put(rsmd.getColumnName(i), rs.getString(i));
}
data_table.add(data_map);
row_count = row_count + 1;
}
rs.close();
stmt.close();
con.close();
I saw this problem when I annotated a class with @ManagedBean (javax.annotation.ManagedBean). The warning message came up when running the newly complied app on JBoss EAP 6.2.0. Ignoring it and running anyway did not help - the breakpoint was never reached.
I was calling that bean using EL in a JSF page. Now... it's possible that @ManagedBean is no good for that (I'm new to CDI). When I changed my annotation to @Model, my bean executed but the breakpoint warning also went away and I hit the breakpoint as expected.
In summary it certainly looked as though the @ManagedBean annotation messed up the lines numbers, regardless of whether or not it was the wrong annotation to use.
I stumbled across this article in my search for this same answer. What I ended up doing is just popping out obj.pop()
all the stored values/objects in my object so I could reuse the object. Not sure if this is bad practice or not. This technique came in handy for me testing my code in Chrome Dev tools or FireFox Web Console.
A little more information on XOR operation.
Here is my simplistic log4j2.xml
that prints to console and writes to a daily rolling file:
// java
private static final Logger LOGGER = LogManager.getLogger(MyClass.class);
// log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Properties>
<Property name="logPath">target/cucumber-logs</Property>
<Property name="rollingFileName">cucumber</Property>
</Properties>
<Appenders>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
</Console>
<RollingFile name="rollingFile" fileName="${logPath}/${rollingFileName}.log" filePattern="${logPath}/${rollingFileName}_%d{yyyy-MM-dd}.log">
<PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
<Policies>
<!-- Causes a rollover if the log file is older than the current JVM's start time -->
<OnStartupTriggeringPolicy />
<!-- Causes a rollover once the date/time pattern no longer applies to the active file -->
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Root level="DEBUG" additivity="false">
<AppenderRef ref="console" />
<AppenderRef ref="rollingFile" />
</Root>
</Loggers>
</Configuration>
TimeBasedTriggeringPolicy
interval (integer) - How often a rollover should occur based on the most specific time unit in the date pattern. For example, with a date pattern with hours as the most specific item and and increment of 4 rollovers would occur every 4 hours. The default value is 1.
modulate (boolean) - Indicates whether the interval should be adjusted to cause the next rollover to occur on the interval boundary. For example, if the item is hours, the current hour is 3 am and the interval is 4 then the first rollover will occur at 4 am and then next ones will occur at 8 am, noon, 4pm, etc.
Source: https://logging.apache.org/log4j/2.x/manual/appenders.html
Output:
[INFO ] 2018-07-21 12:03:47,412 ScenarioHook.beforeScenario() - Browser=CHROME32_NOHEAD
[INFO ] 2018-07-21 12:03:48,623 ScenarioHook.beforeScenario() - Screen Resolution (WxH)=1366x768
[DEBUG] 2018-07-21 12:03:52,125 HomePageNavigationSteps.I_Am_At_The_Home_Page() - Base URL=http://simplydo.com/projector/
[DEBUG] 2018-07-21 12:03:52,700 NetIncomeProjectorSteps.I_Enter_My_Start_Balance() - Start Balance=348000
A new log file will be created daily with previous day automatically renamed to:
cucumber_yyyy-MM-dd.log
In a Maven project, you would put the log4j2.xml
in src/main/resources
or src/test/resources
.
Take care though:
If you want to sort the file primarily by field 3, and secondarily by field 2 you want this:
sort -k 3,3 -k 2,2 < inputfile
Not this: sort -k 3 -k 2 < inputfile
which sorts the file by the string from the beginning of field 3 to the end of line (which is potentially unique).
-k, --key=POS1[,POS2] start a key at POS1 (origin 1), end it at POS2
(default end of line)
There are 2 answers forthis for two different senarios:-
If you are using JavaScript on a website(i.e; or any front-end part) The simplest way to do it is:
<h2>The Navigator Object</h2>
<p>The onLine property returns true if the browser is online:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "navigator.onLine is " + navigator.onLine;
</script>
But if you're using js on server side(i.e; node etc.), You can determine that the connection is lost by making failed XHR requests.
The standard approach is to retry the request a few times. If it doesn't go through, alert the user to check the connection, and fail gracefully.
merge into MY_TABLE tgt
using (select [expressions]
from dual ) src
on (src.key_condition = tgt.key_condition)
when matched then
update tgt
set tgt.column1 = src.column1 [,...]
when not matched then
insert into tgt
([list of columns])
values
(src.column1 [,...]);
An object can't be null - the value of an expression can be null. It's worth making the difference clear in your mind. The value of s
isn't an object - it's a reference, which is either null or refers to an object.
And yes, you should just use
if (s == null)
Note that this will still use the overloaded == operator defined in string, but that will do the right thing.
Default methods in Java Interface are to be used more for providing dummy implementation of a function thus saving any implementing class of that interface from the pain of declaring all the abstract methods even if they want to deal with only one. Default methods in interface are thus in a way more a replacement for the concept of adapter classes.
The methods in abstract class are however supposed to give a meaningful implementation which any child class should override only if needed to override a common functionality.
Toggle both modals
$('#modalOne').modal('toggle');
$('#modalTwo').modal('toggle');
With iOS 13.1.2, orientation always return 0 until device is rotated. I need to call UIDevice.current.beginGeneratingDeviceOrientationNotifications() before any rotation event occurs to get actual rotation.
This is also another good Home Screen script that support iphone/ipad, Mobile Safari, Android, Blackberry touch smartphones and Playbook .
https://github.com/h5bp/mobile-boilerplate/wiki/Mobile-Bookmark-Bubble
On Windows 64bits it´s works:
Copy and Past this command
cmake -G "MinGW Makefiles" -D CMAKE_CXX_COMPILER=mingw32-g++.exe -D WITH_IPP=OFF MAKE_MAKE_PROGRAM=mingw32-make.exe ..\
Execute this command mingw32-make
Execute this command mingw32-make install
DONE
Given a branch foo
and a remote upstream
:
As of Git 1.8.0:
git branch -u upstream/foo
Or, if local branch foo
is not the current branch:
git branch -u upstream/foo foo
Or, if you like to type longer commands, these are equivalent to the above two:
git branch --set-upstream-to=upstream/foo
git branch --set-upstream-to=upstream/foo foo
As of Git 1.7.0 (before 1.8.0):
git branch --set-upstream foo upstream/foo
Notes:
foo
to track remote branch foo
from remote upstream
.git fetch upstream
beforehand.See also: Why do I need to do `--set-upstream` all the time?
If you are interested only in the last X lines, you can use the "tail" command like this.
$ tail -n XXXXX yourlogfile.log >> mycroppedfile.txt
This will save the last XXXXX lines of your log file to a new file called "mycroppedfile.txt"
1. Response to the main question
The script $(window).height()
does work well (showing the viewport's height and not the document with scrolling height), BUT it needs that you put correctly the doctype tag in your document, for example these doctypes:
For HTML 5:
<!DOCTYPE html>
For transitional HTML4:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Probably the default doctype assumed by some browsers is such, that $(window).height()
takes the document's height and not the browser's height. With the doctype specification, it's satisfactorily solved, and I'm pretty sure you peps will avoid the "changing scroll-overflow to hidden and then back", which is, I'm sorry, a bit dirty trick, specially if you don't document it on the code for future programmer's usage.
2. An ADDITIONAL tip, note aside: Moreover, if you are doing a script, you can invent tests to help programmers in using your libraries, let me invent a couple:
$(document).ready(function() {
if(typeof $=='undefined') {
alert("PROGRAMMER'S Error: you haven't called JQuery library");
} else if (typeof $.ui=='undefined') {
alert("PROGRAMMER'S Error: you haven't installed the UI Jquery library");
}
if(document.doctype==null || screen.height < parseInt($(window).height()) ) {
alert("ERROR, check your doctype, the calculated heights are not what you might expect");
}
});
EDIT: about the part 2, "An ADDITIONAL tip, note aside": @Machiel, in yesterday's comment (2014-09-04), was UTTERLY right: the check of the $ can not be inside the ready event of Jquery, because we are, as he pointed out, assuming $ is already defined. THANKS FOR POINTING THAT OUT, and do please the rest of you readers correct this, if you used it in your scripts. My suggestion is: in your libraries put an "install_script()" function which initializes the library (put any reference to $ inside such init function, including the declaration of ready()) and AT THE BEGINNING of such "install_script()" function, check if the $ is defined, but make everything independent of JQuery, so your library can "diagnose itself" when JQuery is not yet defined. I prefer this method rather than forcing the automatic creation of a JQuery bringing it from a CDN. Those are tiny notes aside for helping out other programmers. I think that people who make libraries must be richer in the feedback to potential programmer's mistakes. For example, Google Apis need an aside manual to understand the error messages. That's absurd, to need external documentation for some tiny mistakes that don't need you to go and search a manual or a specification. The library must be SELF-DOCUMENTED. I write code even taking care of the mistakes I might commit even six months from now, and it still tries to be a clean and not-repetitive code, already-written-to-prevent-future-developer-mistakes.
If you are familiar with RxJava, you can use Observable.interval(), which is pretty neat.
Observable.interval(60, TimeUnits.SECONDS)
.flatMap(new Function<Long, ObservableSource<String>>() {
@Override
public ObservableSource<String> apply(@NonNull Long aLong) throws Exception {
return getDataObservable(); //Where you pull your data
}
});
The downside of this is that you have to architect polling your data in a different way. However, there are a lot of benefits to the Reactive Programming way:
With RxAndroid, you can handle threads in just 2 lines of code.
Observable.interval(60, TimeUnits.SECONDS)
.flatMap(...) // polling data code
.subscribeOn(Schedulers.newThread()) // poll data on a background thread
.observeOn(AndroidSchedulers.mainThread()) // populate UI on main thread
.subscribe(...); // your UI code
Please check out RxJava. It has a high learning curve but it will make handling asynchronous calls in Android so much easier and cleaner.
The -I
directive does the job:
gcc -Icore -Ianimator -Iimages -Ianother_dir -Iyet_another_dir my_file.c
In my case, I had the following set in my JenkinsFile
node('node'){
...
}
There was no node called 'node', only master (the value had been left in there after following some basic tutorials). Changing the value to 'master' got the build working.
Try like
<script>
function Data(string)
{
$('.filter').removeClass('active');
$(this).parent('.filter').addClass('active') ;
}
</script>
For the class selector you need to use .
before the classname.And you need to add the class for the parent. Bec you are clicking on anchor tag not the filter
.
How to reproduce the above error in PHP:
php> $yarr = array(3 => 'c', 4 => 'd');
php> echo $yarr[4];
d
php> echo $yarr[1];
PHP Notice: Undefined offset: 1 in
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(578) :
eval()'d code on line 1
What does that error message mean?
It means the php compiler looked for the key 1
and ran the hash against it and didn't find any value associated with it then said Undefined offset: 1
How do I make that error go away?
Ask the array if the key exists before returning its value like this:
php> echo array_key_exists(1, $yarr);
php> echo array_key_exists(4, $yarr);
1
If the array does not contain your key, don't ask for its value. Although this solution makes double-work for your program to "check if it's there" and then "go get it".
Alternative solution that's faster:
If getting a missing key is an exceptional circumstance caused by an error, it's faster to just get the value (as in echo $yarr[1];
), and catch that offset error and handle it like this: https://stackoverflow.com/a/5373824/445131
Here is simple way to handle the above.
In Html Template we put Post
<form action="/useradd/addnewroute/" method="post" id="login-form">{% csrf_token %}
<!-- add details of form here-->
<form>
<form action="/useradd/addarea/" method="post" id="login-form">{% csrf_token %}
<!-- add details of form here-->
<form>
In View
def addnewroute(request):
if request.method == "POST":
# do something
def addarea(request):
if request.method == "POST":
# do something
In URL Give needed info like
urlpatterns = patterns('',
url(r'^addnewroute/$', views.addnewroute, name='addnewroute'),
url(r'^addarea/', include('usermodules.urls')),
You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:
Dim MyVar as string = "some text ""hello"" "
This will give the MyVar
variable a value of some text "hello"
.
Providing that you have LINQ available and don't care too much about performance, the easiest thing is the following:
var arraysAreEqual = Enumerable.SequenceEqual(a1, a2);
In fact, it's probably worth checking with Reflector or ILSpy what the SequenceEqual
methods actually does, since it may well optimise for the special case of array values anyway!
Create a FormData
object
const formData: any = new FormData();
And append to the same keyName
photos.forEach((_photoInfo: { localUri: string, file: File }) => {
formData.append("file", _photoInfo.file);
});
and send it to server
// angular code
this.http.post(url, formData)
this will automatically create an array of object under file
if you are using nodejs
const files :File[] = req.files ? req.files.file : null;
I would like to do this without attaching a class to every td
Personally, I would go with the the class-on-each-td/th/col approach. Then you can switch columns on and off using a single write to className on the container, assuming style rules like:
table.hide1 .col1 { display: none; }
table.hide2 .col2 { display: none; }
...
This is going to be faster than any JS loop approach; for really long tables it can make a significant difference to responsiveness.
If you can get away with not supporting IE6, you could use adjacency selectors to avoid having to add the class attributes to tds. Or alternatively, if your concern is making the markup cleaner, you could add them from JavaScript automatically in an initialisation step.
I think you'll find your answer if you refer to this post: Deserialize JSON into C# dynamic object?
There are various ways of achieving what you want here. The System.Web.Helpers.Json approach (a few answers down) seems to be the simplest.
Specifying the columns on your query should do the trick:
select a.col1, b.col2, a.col3, b.col4, a.category_id
from items_a a, items_b b
where a.category_id = b.category_id
should do the trick with regards to picking the columns you want.
To get around the fact that some data is only in items_a and some data is only in items_b, you would be able to do:
select
coalesce(a.col1, b.col1) as col1,
coalesce(a.col2, b.col2) as col2,
coalesce(a.col3, b.col3) as col3,
a.category_id
from items_a a, items_b b
where a.category_id = b.category_id
The coalesce function will return the first non-null value, so for each row if col1 is non null, it'll use that, otherwise it'll get the value from col2, etc.
There is very good package available to parse the email contents with proper documentation.
import mailparser
mail = mailparser.parse_from_file(f)
mail = mailparser.parse_from_file_obj(fp)
mail = mailparser.parse_from_string(raw_mail)
mail = mailparser.parse_from_bytes(byte_mail)
How to Use:
mail.attachments: list of all attachments
mail.body
mail.to
Token Mantra response: you should not tweak/modify/harvest/or otherwise produce html/xml using regular expression.
there are too may corner case conditionals such as \' and \" which must be accounted for. You are much better off using a proper DOM Parser, XML Parser, or one of the many other dozens of tried and tested tools for this job instead of inventing your own.
I don't really care which one you use, as long as its recognized, tested, and you use one.
my $foo = Someclass->parse( $xmlstring );
my @links = $foo->getChildrenByTagName("a");
my @srcs = map { $_->getAttribute("src") } @links;
# @srcs now contains an array of src attributes extracted from the page.
You might want to try this approach:
var str ="{ "name" : "user"}";
var jsonData = JSON.parse(str);
console.log(jsonData.name)
//Array Object
str ="[{ "name" : "user"},{ "name" : "user2"}]";
jsonData = JSON.parse(str);
console.log(jsonData[0].name)
You have to go to the folder where eclipse is installed and then you have to change the eclipse.ini file.
You have to add
-vm
C:\Program Files\Java\jdk1.8.0_202\bin\javaw.exe
Your eclipse.ini file will look like the below screenshot
Following this resource page, if the length of x is varying, we can use:
', '.join(['%.2f']*len(x))
to create a place holder for each element from the list x
. Here is the example:
x = [1/3.0, 1/6.0, 0.678]
s = ("elements in the list are ["+', '.join(['%.2f']*len(x))+"]") % tuple(x)
print s
>>> elements in the list are [0.33, 0.17, 0.68]
If you need the subdirectories too you need a "dir" command and a "For" command
dir /b /s DIRECTORY\*.* > list1.txt
for /f "tokens=*" %%A in (list1.txt) do echo %%~nxA >> list.txt
del list1.txt
put your root directory in dir command. It will create a list1.txt with full path names and then a list.txt with only the file names.
@Hooman: actually with the latest versions of Xampp you don't need to know where the configuration or log files are; in the Control panel you have log and config buttons for each tool (php, mysql, tomcat...) and clicking them offers to open all the relevant file (you can even change the default editing application with the general Config button at the top right). Well done for whoever designed it!
You can create a .a
file using the ar
utility, like so:
ar crf lib/libHeader.a header.o
lib
is a directory that contains all your libraries. it is good practice to organise your code this way and separate the code and the object files. Having everything in one directory generally looks ugly. The above line creates libHeader.a
in the directory lib
. So, in your current directory, do:
mkdir lib
Then run the above ar
command.
When linking all libraries, you can do it like so:
g++ test.o -L./lib -lHeader -o test
The -L
flag will get g++
to add the lib/
directory to the path. This way, g++
knows what directory to search when looking for libHeader
. -llibHeader
flags the specific library to link.
where test.o is created like so:
g++ -c test.cpp -o test.o
On Mac OS press: CMD
+OPTION
+J
for console
You probably want to use an ExpandableListView, a special ListView that allows you to open and close groups.
I think the best way to do it to bind it with ngModel.
<select name="num" [(ngModel)]="number">
<option *ngFor="let n of numbers" [value]="n">{{n}}</option>
</select>
and in ts file add
number=47;
numbers=[45,46,47]
I have also faced the same issues, to fix, download the jar files from the below url
http://commons.apache.org/logging/download_logging.cgi
and copy to your lib folder, will resolve your issue.
You can ping ip from one virtual machine to another machine by using these steps:
Guest Isolation : ENABLED, ENABLED and select box : ENABLE VMCI
RecyclerViews are fine to put in ScrollViews so long as they aren't scrolling themselves. In this case, it makes sense to make it a fixed height.
The proper solution is to use wrap_content
on the RecyclerView height and then implement a custom LinearLayoutManager that can properly handle the wrapping.
Copy this LinearLayoutManager into your project: https://github.com/serso/android-linear-layout-manager/blob/master/lib/src/main/java/org/solovyev/android/views/llm/LinearLayoutManager.java
Then wrap the RecyclerView:
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
And set it up like so:
RecyclerView list = (RecyclerView)findViewById(R.id.list);
list.setHasFixedSize(true);
list.setLayoutManager(new com.example.myapp.LinearLayoutManager(list.getContext()));
list.setAdapter(new MyViewAdapter(data));
Edit: This can cause complications with scrolling because the RecyclerView can steal the ScrollView's touch events. My solution was just to ditch the RecyclerView in all and go with a LinearLayout, programmatically inflate subviews, and add them to the layout.
<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %> <i class="fa fa-facebook"> Facebook Share </i> <%end%>
I am assuming that current_article_url
is http://0.0.0.0:4567/link_to_title
This one-liner works:
var currentDirectory = window.location.pathname.split('/').slice(0, -1).join('/')
This is happening because this is a dynamic component and you didn't add it to entryComponents
under @NgModule
.
Simply add it there:
@NgModule({
/* ----------------- */
entryComponents: [ DialogResultExampleDialog ] // <---- Add it here
Look at how the Angular team talks about entryComponents
:
entryComponents?: Array<Type<any>|any[]>
Specifies a list of components that should be compiled when this module is defined. For each component listed here, Angular will create a ComponentFactory and store it in the ComponentFactoryResolver.
Also, this is the list of the methods on @NgModule
including entryComponents
...
As you can see, all of them are optional (look at the question marks), including entryComponents
which accept an array of components:
@NgModule({
providers?: Provider[]
declarations?: Array<Type<any>|any[]>
imports?: Array<Type<any>|ModuleWithProviders|any[]>
exports?: Array<Type<any>|any[]>
entryComponents?: Array<Type<any>|any[]>
bootstrap?: Array<Type<any>|any[]>
schemas?: Array<SchemaMetadata|any[]>
id?: string
})
Use an ArrayList or juggle to arrays to auto increment the array size.
A temporary solution if you don't want to get into the x
, y
position of your title.
Following worked for me.
plt.title('Capital Expenditure\n') # Add a next line after your title
kudos.
Remove the position: relative;
line. I'm not sure why exactly but it fixes it for me.
Modern solution - works in all browsers and IE9+
caniuse - browser support.
.v-center {
position: relative;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
Example: http://jsbin.com/rehovixufe/1/
I disagree with the accepted answer being "the easiest", particularly if you want to use virtualenv.
You can use the Unofficial Windows Binaries instead. Download the appropriate wheel from there, and install it with pip
:
pip install pywin32-219-cp27-none-win32.whl
(Make sure you pick the one for the right version and bitness of Python).
You might be able to get the URL and install it via pip
without downloading it first, but they're made it a bit harder to just grab the URL. Probably better to download it and host it somewhere yourself.
Low
is a string.
.toFixed()
only works with a number.
A simple way to overcome such problem is to use type coercion:
Low = (Low*1).toFixed(..);
The multiplication by 1 forces to code to convert the string to number and doesn't change the value.
Add an id
to the meta
element that holds the token
<meta name="csrf-token" id="csrf-token" content="{{ csrf_token() }}">
And then you can get it in your Javascript
$.ajax({
url : "your_url",
method:"post",
data : {
"_token": $('#csrf-token')[0].content //pass the CSRF_TOKEN()
},
...
});
EDIT: Easier way without changing the meta
line.
data : {
_token: "{{ csrf_token() }}"
}
Or
data : {
_token: @json(csrf_token()),
}
Thanks to @martin-hartmann
You have two possible ways of doing it:
{{ form_errors(form) }}
within template file$form->getErrors()
If your post try to reach the following URL
mypage.php?id=1
you will have the POST data but also GET data.
You need to use a constant.
CONST NumberOfZombies = 20000
Dim Zombies(NumberOfZombies) As Zombies
or if you want to use a variable you have to do it this way:
Dim NumberOfZombies As Integer
NumberOfZombies = 20000
Dim Zombies() As Zombies
ReDim Zombies(NumberOfZombies)
ClassLoader cl = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader)cl).getURLs();
for(URL url: urls){
System.out.println(url.getFile());
}
You most likely want to examine the documentation for T-SQL's CAST and CONVERT functions, located in the documentation here: http://msdn.microsoft.com/en-US/library/ms187928(v=SQL.90).aspx
You will then use one of those functions in your T-SQL query to convert the [idate] column from the database into the datetime format of your liking in the output.
<?php
$browser_ver = get_browser(null,true);
//echo $browser_ver['browser'];
if($browser_ver['browser'] == 'IE') {
?>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>pdf print test</title>
<style>
html { height:100%; }
</style>
<script>
function printIt(id) {
var pdf = document.getElementById("samplePDF");
pdf.click();
pdf.setActive();
pdf.focus();
pdf.print();
}
</script>
</head>
<body style="margin:0; height:100%;">
<embed id="samplePDF" type="application/pdf" src="/pdfs/2010/dash_fdm350.pdf" width="100%" height="100%" />
<button onClick="printIt('samplePDF')">Print</button>
</body>
</html>
<?php
} else {
?>
<HTML>
<script Language="javascript">
function printfile(id) {
window.frames[id].focus();
window.frames[id].print();
}
</script>
<BODY marginheight="0" marginwidth="0">
<iframe src="/pdfs/2010/dash_fdm350.pdf" id="objAdobePrint" name="objAdobePrint" height="95%" width="100%" frameborder=0></iframe><br>
<input type="button" value="Print" onclick="javascript:printfile('objAdobePrint');">
</BODY>
</HTML>
<?php
}
?>
After many diff's, this was what was missing from the httpd.conf
file on the server in question:
AddHandler php5-script .php
Solved the issue.
set identity_insert customer on
insert into Customer(id,Name,city,Salary) values(8,'bcd','Amritsar',1234)
where 'customer' is table name
I don't understand why nobody points to the specific issue and some answers are totally misleading, especially the accepted answer. The issue is that the OP did not pick a rule that could possibly override the margin property that is set by the User Agent (UA) directly on the ul
tag. Let's consider all the rules with a margin property used by the OP.
body {
margin:0px;
...
}
The body element is way up in the DOM and the UA rule matches an element below, so the UA wins. It's the way inheritance works. Inheritance is the means by which, in the absence of any specific declarations from any source applied by the CSS cascade, a property value of an element is obtained from its parent element. Specificity on the parent element is useless, because the UA rule matches directly the element.
#mainNav{
margin:0 auto;
...
}
This is a better attempt, a more specific selector #mainNav
, which matches the mainNav element lower in the DOM, but the same principle applies, because the ul
element is still below this element in the DOM.
#mainNav ul li{
...
margin:0;
...
}
This went too far down in the DOM! Now, the selector matches the li
element, which is below the ul
element.
So, assuming that the UA rule used the selector ul
and not !important
, which is most likely the case, the solution would have been a simple ul { margin: 0; }
, but it would be safer to make it more specific, say #mainNav ul { margin: 0 }
.
Swift
Easier way to get any elements of date as an optional String.
extension Date {
// Year
var currentYear: String? {
return getDateComponent(dateFormat: "yy")
//return getDateComponent(dateFormat: "yyyy")
}
// Month
var currentMonth: String? {
return getDateComponent(dateFormat: "M")
//return getDateComponent(dateFormat: "MM")
//return getDateComponent(dateFormat: "MMM")
//return getDateComponent(dateFormat: "MMMM")
}
// Day
var currentDay: String? {
return getDateComponent(dateFormat: "dd")
//return getDateComponent(dateFormat: "d")
}
func getDateComponent(dateFormat: String) -> String? {
let format = DateFormatter()
format.dateFormat = dateFormat
return format.string(from: self)
}
}
let today = Date()
print("Current Year - \(today.currentYear)") // result Current Year - Optional("2017")
print("Current Month - \(today.currentMonth)") // result Current Month - Optional("7")
print("Current Day - \(today.currentDay)") // result Current Day - Optional("10")
If you don't want to install the Windows SDK you can get the dll by running the following command in powershell:
Copy ([PSObject].Assembly.Location) C:\
<div class="scrollingDiv">foo</div>
div.scrollingDiv
{
overflow:scroll;
}
Wrong:
case AnotherClass.MyEnum.VALUE_A
Right:
case VALUE_A:
Disclaimer: I'm not a radioactivity professional nor worked for this kind of application. But I worked on soft errors and redundancy for long term archival of critical data, which is somewhat linked (same problem, different goals).
The main problem with radioactivity in my opinion is that radioactivity can switch bits, thus radioactivity can/will tamper any digital memory. These errors are usually called soft errors, bit rot, etc.
The question is then: how to compute reliably when your memory is unreliable?
To significantly reduce the rate of soft errors (at the expense of computational overhead since it will mostly be software-based solutions), you can either:
rely on the good old redundancy scheme, and more specifically the more efficient error correcting codes (same purpose, but cleverer algorithms so that you can recover more bits with less redundancy). This is sometimes (wrongly) also called checksumming. With this kind of solution, you will have to store the full state of your program at any moment in a master variable/class (or a struct?), compute an ECC, and check that the ECC is correct before doing anything, and if not, repair the fields. This solution however does not guarantee that your software can work (simply that it will work correctly when it can, or stops working if not, because ECC can tell you if something is wrong, and in this case you can stop your software so that you don't get fake results).
or you can use resilient algorithmic data structures, which guarantee, up to a some bound, that your program will still give correct results even in the presence of soft errors. These algorithms can be seen as a mix of common algorithmic structures with ECC schemes natively mixed in, but this is much more resilient than that, because the resiliency scheme is tightly bounded to the structure, so that you don't need to encode additional procedures to check the ECC, and usually they are a lot faster. These structures provide a way to ensure that your program will work under any condition, up to the theoretical bound of soft errors. You can also mix these resilient structures with the redundancy/ECC scheme for additional security (or encode your most important data structures as resilient, and the rest, the expendable data that you can recompute from the main data structures, as normal data structures with a bit of ECC or a parity check which is very fast to compute).
If you are interested in resilient data structures (which is a recent, but exciting, new field in algorithmics and redundancy engineering), I advise you to read the following documents:
Resilient algorithms data structures intro by Giuseppe F.Italiano, Universita di Roma "Tor Vergata"
Christiano, P., Demaine, E. D., & Kishore, S. (2011). Lossless fault-tolerant data structures with additive overhead. In Algorithms and Data Structures (pp. 243-254). Springer Berlin Heidelberg.
Ferraro-Petrillo, U., Grandoni, F., & Italiano, G. F. (2013). Data structures resilient to memory faults: an experimental study of dictionaries. Journal of Experimental Algorithmics (JEA), 18, 1-6.
Italiano, G. F. (2010). Resilient algorithms and data structures. In Algorithms and Complexity (pp. 13-24). Springer Berlin Heidelberg.
If you are interested in knowing more about the field of resilient data structures, you can checkout the works of Giuseppe F. Italiano (and work your way through the refs) and the Faulty-RAM model (introduced in Finocchi et al. 2005; Finocchi and Italiano 2008).
/EDIT: I illustrated the prevention/recovery from soft-errors mainly for RAM memory and data storage, but I didn't talk about computation (CPU) errors. Other answers already pointed at using atomic transactions like in databases, so I will propose another, simpler scheme: redundancy and majority vote.
The idea is that you simply do x times the same computation for each computation you need to do, and store the result in x different variables (with x >= 3). You can then compare your x variables:
This redundancy scheme is very fast compared to ECC (practically O(1)) and it provides you with a clear signal when you need to failsafe. The majority vote is also (almost) guaranteed to never produce corrupted output and also to recover from minor computation errors, because the probability that x computations give the same output is infinitesimal (because there is a huge amount of possible outputs, it's almost impossible to randomly get 3 times the same, even less chances if x > 3).
So with majority vote you are safe from corrupted output, and with redundancy x == 3, you can recover 1 error (with x == 4 it will be 2 errors recoverable, etc. -- the exact equation is nb_error_recoverable == (x-2)
where x is the number of calculation repetitions because you need at least 2 agreeing calculations to recover using the majority vote).
The drawback is that you need to compute x times instead of once, so you have an additional computation cost, but's linear complexity so asymptotically you don't lose much for the benefits you gain. A fast way to do a majority vote is to compute the mode on an array, but you can also use a median filter.
Also, if you want to make extra sure the calculations are conducted correctly, if you can make your own hardware you can construct your device with x CPUs, and wire the system so that calculations are automatically duplicated across the x CPUs with a majority vote done mechanically at the end (using AND/OR gates for example). This is often implemented in airplanes and mission-critical devices (see triple modular redundancy). This way, you would not have any computational overhead (since the additional calculations will be done in parallel), and you have another layer of protection from soft errors (since the calculation duplication and majority vote will be managed directly by the hardware and not by software -- which can more easily get corrupted since a program is simply bits stored in memory...).
You can't do it through jQuery alone; you'll need a combination of Ajax (which you can do with jQuery) and a PHP back-end. A very simple version might look like this:
HTML:
<img class="foo" src="img.jpg" />
<img class="foo" src="img2.jpg" />
<img class="foo" src="img3.jpg" />
Javascript:
$("img.foo").onclick(function()
{
// Get the src of the image
var src = $(this).attr("src");
// Send Ajax request to backend.php, with src set as "img" in the POST data
$.post("/backend.php", {"img": src});
});
PHP (backend.php):
<?php
// do any authentication first, then add POST variable to session
$_SESSION['imgsrc'] = $_POST['img'];
?>
Why not something simple like:
egrep -o 'abc|efg' $file | grep -A1 abc | grep efg | wc -l
returns 0 or a positive integer.
egrep -o (Only shows matches, trick: multiple matches on the same line produce multi-line output as if they are on different lines)
grep -A1 abc
(print abc and the line after it)
grep efg | wc -l
(0-n count of efg lines found after abc on the same or following lines, result can be used in an 'if")
grep can be changed to egrep etc. if pattern matching is needed
<ComboBox Text="Something">
<ComboBoxItem Content="Item1"></ComboBoxItem >
<ComboBoxItem Content="Item2"></ComboBoxItem >
<ComboBoxItem Content="Item3"></ComboBoxItem >
</ComboBox>
There's two options:
Log Navigator (command-7 or view|navigators|log) and select your debug session.
"View | Show Debug Area" to view the NSLog output and interact with the debugger.
Here's a pic with both on. You wouldn't normally have both on, but I can only link one image per post! http://i.stack.imgur.com/4gG4P.png
No, there is not, see how the "Related XML Attributes" section is missing in the ImageView.setAlpha(int) documentation. The alternative is to use View.setAlpha(float) whose XML counterpart is android:alpha
. It takes a range of 0.0 to 1.0 instead of 0 to 255. Use it e.g. like
<ImageView android:alpha="0.4">
However, the latter in available only since API level 11.
This can also be done in later versions of handlebars using the key=value
notation:
{{> mypartial foo='bar' }}
Allowing you to pass specific values to your partial context.
Reference: Context different for partial #182
Another way of doing it is defining a resources array in strings.xml like below.
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE resources [
<!ENTITY supportDefaultSelection "Choose your issue">
<!ENTITY issueOption1 "Support">
<!ENTITY issueOption2 "Feedback">
<!ENTITY issueOption3 "Help">
]>
and then defining a string array using the above resources
<string-array name="support_issues_array">
<item>&supportDefaultSelection;</item>
<item>&issueOption1;</item>
<item>&issueOption2;</item>
<item>&issueOption3;</item>
</string-array>
You could refer the same string into other xmls too keeping DRY intact. The advantage I see is, with a single value change it would effect all the references in the code.
Note that Office Web Components are dead, see does-office-xp-web-components-compatable-with-windows-7. OWC was discontinued from XP onward for security reasons.
Since then, and only recently, Microsoft pushes Excel Web App as alternative (a poor alternative IMHO)
As a side note: Microsoft also deprecated the other way round, i.e. embedding the webbrowser control into an excel sheet, see adding-web-browser-control-to-excel-2013. As an alternative Microsoft offers Office Apps (a very limited alternative with respect to interfacing Excel and IE)
Google Hosted jQuery
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
Backup/Fallback Plan!
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>if (!window.jQuery) { document.write('<script src="/path/to/your/jquery"><\/script>'); }
</script>
Reference: http://websitespeedoptimizations.com/ContentDeliveryNetworkPost.aspx
The best looking way I've found to go through a cursor is the following:
Cursor cursor;
... //fill the cursor here
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
// do what you need with the cursor here
}
Don't forget to close the cursor afterwards
EDIT: The given solution is great if you ever need to iterate a cursor that you are not responsible of. A good example would be, if you are taking a cursor as argument in a method, and you need to scan the cursor for a given value, without having to worry about the cursor's current position.
As other commenters correctly noted, you should never use floating-point arithmetic when exact values are required, such as for monetary values. The main reason is indeed the rounding behaviour inherent in floating-points, but let's not forget that dealing with floating-points means also having to deal with infinite and NaN values.
As an illustration that your approach simply doesn't work, here is some simple test code. I simply add your EPSILON
to 10.0
and look whether the result is equal to 10.0
-- which it shouldn't be, as the difference is clearly not less than EPSILON
:
double a = 10.0;
double b = 10.0 + EPSILON;
if (!equals(a, b)) {
System.out.println("OK: " + a + " != " + b);
} else {
System.out.println("ERROR: " + a + " == " + b);
}
Surprise:
ERROR: 10.0 == 10.00001
The errors occurs because of the loss if significant bits on subtraction if two floating-point values have different exponents.
If you think of applying a more advanced "relative difference" approach as suggested by other commenters, you should read Bruce Dawson's excellent article Comparing Floating Point Numbers, 2012 Edition, which shows that this approach has similar shortcomings and that there is actually no fail-safe approximate floating-point comparison that works for all ranges of floating-point numbers.
To make things short: Abstain from double
s for monetary values, and use exact number representations such as BigDecimal
. For the sake of efficiency, you could also use longs
interpreted as "millis" (tenths of cents), as long as you reliably prevent over- and underflows. This yields a maximum representable values of 9'223'372'036'854'775.807
, which should be enough for most real-world applications.
If you know the header name, you can find the column based on that:
Option Explicit
Public Sub changeData()
Application.ScreenUpdating = False ' faster for modifying values on sheet
Dim header As String
Dim numRows As Long
Dim col As Long
Dim c As Excel.Range
header = "this one" ' header name to find
Set c = ActiveSheet.Range("1:1").Find(header, LookIn:=xlValues)
If Not c Is Nothing Then
col = c.Column
Else
' can't work with it
Exit Sub
End If
numRows = 50 ' (whatever this is in your code)
With ActiveSheet
.Range(.Cells(2, col), .Cells(numRows, col)).Value = "PHEV"
End With
Application.ScreenUpdating = True ' reset
End Sub
You could do something like this instead:
<form name="myform" action="action.php" onsubmit="DoSubmit();">
<input type="hidden" name="myinput" value="0" />
<input type="text" name="message" value="" />
<input type="submit" name="submit" />
</form>
And then modify your DoSubmit function to just return true, indicating that "it's OK, now you can submit the form" to the browser:
function DoSubmit(){
document.myform.myinput.value = '1';
return true;
}
I'd also be wary of using onclick events on a submit button; the order of events isn't immediately obvious, and your callback won't get called if the user submits by, for example, hitting return in a textbox.
You can remove the "not null" property from your column in mysql table if not necessary. when you remove "not null" property no need for "0000-00-00 00:00:00" conversion and problem is gone.
At least worked for me.
you could simply type :
background: linear-gradient(_x000D_
to bottom,_x000D_
rgba(0,0,0, 0),_x000D_
rgba(0,0,0, 100)_x000D_
),url(../images/image.jpg);
_x000D_
I just release my latest library for Google Maps Direction API on Android https://github.com/akexorcist/Android-GoogleDirectionLibrary
Best way i learnt is using express with html files as express gives lots of advantage. Also you can extend it to a Heroku platform if you want..Just saying :)
var express = require("express");
var app = express();
var path = require("path");
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
});
app.listen(3000);
console.log("Running at Port 3000");
Clean and best..!!!
If you want to print the last 10 lines, use
tail(dataset, 10)
for the first 10, you could also do
head(dataset, 10)
I resolved this by adding @Transactional
to the base/generic Hibernate DAO implementation class (the parent class which implements the saveOrUpdate() method inherited by the DAO I use in the main program), i.e. the @Transactional
needs to be specified on the actual class which implements the method. My assumption was instead that if I declared @Transactional
on the child class then it included all of the methods that were inherited by the child class. However it seems that the @Transactional
annotation only applies to methods implemented within a class and not to methods inherited by a class.
You may want to look at how this is done in the cat
utility, for example.
See code here.
If there is no filename as argument, or it is "-", then stdin
is used for input.
stdin
will be there, even if no data is pushed to it (but then, your read call may wait forever).
shuf -i 2000-65000 -n 1
Enjoy!
Edit: The range is inclusive.
Here is one way to do this using css
HTML
<div class="imageWrapper">
<img src="http://lorempixel.com/300/300/" alt="" />
<a href="http://google.com" class="cornerLink">Link</a>
</div>?
CSS
.imageWrapper {
position: relative;
width: 300px;
height: 300px;
}
.imageWrapper img {
display: block;
}
.imageWrapper .cornerLink {
opacity: 0;
position: absolute;
bottom: 0px;
left: 0px;
right: 0px;
padding: 2px 0px;
color: #ffffff;
background: #000000;
text-decoration: none;
text-align: center;
-webkit-transition: opacity 500ms;
-moz-transition: opacity 500ms;
-o-transition: opacity 500ms;
transition: opacity 500ms;
}
.imageWrapper:hover .cornerLink {
opacity: 0.8;
}
Or if you just want it in the bottom left corner:
you can probably ping the server via ajax inside javascript. The php file might look something like:
<?php
session_start();
$id = session_id();
echo $id;
?>
This will return you the current session id. Was this what you were looking for.
First of all, be careful! All of your security depends on the… er… privacy of your private keys. Keytool doesn't have key export built in to avoid accidental disclosure of this sensitive material, so you might want to consider some extra safeguards that could be put in place to protect your exported keys.
Here is some simple code that gives you unencrypted PKCS #8 PrivateKeyInfo that can be used by OpenSSL (see the -nocrypt
option of its pkcs8 utility):
KeyStore keys = ...
char[] password = ...
Enumeration<String> aliases = keys.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
if (!keys.isKeyEntry(alias))
continue;
Key key = keys.getKey(alias, password);
if ((key instanceof PrivateKey) && "PKCS#8".equals(key.getFormat())) {
/* Most PrivateKeys use this format, but check for safety. */
try (FileOutputStream os = new FileOutputStream(alias + ".key")) {
os.write(key.getEncoded());
os.flush();
}
}
}
If you need other formats, you can use a KeyFactory to get a transparent key specification for different types of keys. Then you can get, for example, the private exponent of an RSA private key and output it in your desired format. That would make a good topic for a follow-up question.
I want to post a simple solution for every schema you've got. If you are using MySQL DB, you can simply get from your schema all the table's name and add the WHERE-LIKE condition on it. You also could do it with the usual command line as follows:
SHOW TABLES WHERE tables_in_<your_shcema_name> LIKE '%<table_partial_name>%';
where tables_in_<your_shcema_name>
returns the column's name of SHOW TABLES
command.
For checking type conversions in version 3, you can go to their github and check into the different liquibase types and check the method toDatabaseDataType. For example, for Boolean, you can check here:
For version 2.0.x, the conversion seems to be into database specific classes. For example, for Mysql:
Detail blog to fix this issue is : http://goo.gl/JXWqfJ
You can solve this problem by following two ways:
A) Start your WAMP befor you login to skype. So that WAMP will take over the the port and there will be no conflict with the port number. And you are able to use Skype as well as WAMP.
But this is not the permanent solution for your problem. Whenever you want to start WAMP you need to signout Skype first and than only you are able to start WAMP. Which is really i don’t like.
B) Second option is to change the port of Skype itself, so that it will not conflict with WAMP. Following screen/steps will help you to solve this problem:
1) SignIn to Skype.
2) Got to the Tools -> options
3) Select the “Advanced” -> Connection
4) Unchecked “Use port 80 and 443 as alternatives for incoming connections” checkbox and click save.
5) Now Signout and SignIn again to skype. (this change will take affect only you relogin to skype)
Now every time you start WAMP will not conflict with skype.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
final String myPackageName = getPackageName();
if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, myPackageName);
startActivityForResult(intent, 1);
}else {
List<Sms> lst = getAllSms();
}
}else {
List<Sms> lst = getAllSms();
}
Set app as default SMS app
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
final String myPackageName = getPackageName();
if (Telephony.Sms.getDefaultSmsPackage(mActivity).equals(myPackageName)) {
List<Sms> lst = getAllSms();
}
}
}
}
}
Function to get SMS
public List<Sms> getAllSms() {
List<Sms> lstSms = new ArrayList<Sms>();
Sms objSms = new Sms();
Uri message = Uri.parse("content://sms/");
ContentResolver cr = mActivity.getContentResolver();
Cursor c = cr.query(message, null, null, null, null);
mActivity.startManagingCursor(c);
int totalSMS = c.getCount();
if (c.moveToFirst()) {
for (int i = 0; i < totalSMS; i++) {
objSms = new Sms();
objSms.setId(c.getString(c.getColumnIndexOrThrow("_id")));
objSms.setAddress(c.getString(c
.getColumnIndexOrThrow("address")));
objSms.setMsg(c.getString(c.getColumnIndexOrThrow("body")));
objSms.setReadState(c.getString(c.getColumnIndex("read")));
objSms.setTime(c.getString(c.getColumnIndexOrThrow("date")));
if (c.getString(c.getColumnIndexOrThrow("type")).contains("1")) {
objSms.setFolderName("inbox");
} else {
objSms.setFolderName("sent");
}
lstSms.add(objSms);
c.moveToNext();
}
}
// else {
// throw new RuntimeException("You have no SMS");
// }
c.close();
return lstSms;
}
Sms class is below:
public class Sms{
private String _id;
private String _address;
private String _msg;
private String _readState; //"0" for have not read sms and "1" for have read sms
private String _time;
private String _folderName;
public String getId(){
return _id;
}
public String getAddress(){
return _address;
}
public String getMsg(){
return _msg;
}
public String getReadState(){
return _readState;
}
public String getTime(){
return _time;
}
public String getFolderName(){
return _folderName;
}
public void setId(String id){
_id = id;
}
public void setAddress(String address){
_address = address;
}
public void setMsg(String msg){
_msg = msg;
}
public void setReadState(String readState){
_readState = readState;
}
public void setTime(String time){
_time = time;
}
public void setFolderName(String folderName){
_folderName = folderName;
}
}
Don't forget to define permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.READ_SMS" />
The biggest threat is that an attacker could leverage a vulnerability such as; directory traversal, or using SQL Injection to call load_file()
to read the plain text username/password in the configuration file and then Login using phpmyadmin or over tcp port 3306. As a pentester I have used this attack pattern to compromise a system.
Here is a great way to lock down phpmyadmin:
grant
or file_priv
. file_priv
permissions from every account. file_priv
is one of the most dangerous privileges in MySQL because it allows an attacker to read files or upload a backdoor. Order deny,allow Deny from all allow from 199.166.210.1
Do not have a predictable file location like: http://127.0.0.1/phpmyadmin
. Vulnerability scanners like Nessus/Nikto/Acunetix/w3af will scan for this.
Firewall off tcp port 3306 so that it cannot be accessed by an attacker.
I think the best answer I've come up with is here: https://codepen.io/sentrathis96/pen/yJPZGx
I can't take credit for this, I forked this from another codepen user to fix the google maps dependency to actually load
Make note of the call to:
InfoWindow() // constructor
Socket.IO uses WebSocket and when WebSocket is not available uses fallback algo to make real time connections.
You can perform a simple each
loop on the range from 1 to `x´:
(1..x).each do |i|
#...
end
Solution is
Connect your computer to the internet
Click
Sync project with Gradle files
On toolbar
It will automatically sync the gradle.
var=$(echo "asdf")
echo $var
# => asdf
Using this method, the command is immediately evaluated and it's return value is stored.
stored_date=$(date)
echo $stored_date
# => Thu Jan 15 10:57:16 EST 2015
# (wait a few seconds)
echo $stored_date
# => Thu Jan 15 10:57:16 EST 2015
Same with backtick
stored_date=`date`
echo $stored_date
# => Thu Jan 15 11:02:19 EST 2015
# (wait a few seconds)
echo $stored_date
# => Thu Jan 15 11:02:19 EST 2015
Using eval in the $(...)
will not make it evaluated later
stored_date=$(eval "date")
echo $stored_date
# => Thu Jan 15 11:05:30 EST 2015
# (wait a few seconds)
echo $stored_date
# => Thu Jan 15 11:05:30 EST 2015
Using eval, it is evaluated when eval
is used
stored_date="date" # < storing the command itself
echo $(eval "$stored_date")
# => Thu Jan 15 11:07:05 EST 2015
# (wait a few seconds)
echo $(eval "$stored_date")
# => Thu Jan 15 11:07:16 EST 2015
# ^^ Time changed
In the above example, if you need to run a command with arguments, put them in the string you are storing
stored_date="date -u"
# ...
For bash scripts this is rarely relevant, but one last note. Be careful with eval
. Eval only strings you control, never strings coming from an untrusted user or built from untrusted user input.
if you getting this type of error so I suggest you used to stored proc data as usual list then binding the other controls because I also get this error so I solved it like this ex:-
repeater.DataSource = data.SPBinsReport().Tolist();
repeater.DataBind();
try like this
Two other alternatives:
a combination of NULLIF
and NVL2
. You can only use this if emp_id
is NOT NULL
, which it is in your case:
select nvl2(nullif(emp_id,1),'False','True') from employee;
simple CASE
expression (Mt. Schneiders used a so-called searched CASE
expression)
select case emp_id when 1 then 'True' else 'False' end from employee;
Clojure can be used, but it's slow.
See also: Clojure fork for Android, and a tutorial.
Here's a reusable Angular directive that will hide and show a Bootstrap modal.
app.directive("modalShow", function () {
return {
restrict: "A",
scope: {
modalVisible: "="
},
link: function (scope, element, attrs) {
//Hide or show the modal
scope.showModal = function (visible) {
if (visible)
{
element.modal("show");
}
else
{
element.modal("hide");
}
}
//Check to see if the modal-visible attribute exists
if (!attrs.modalVisible)
{
//The attribute isn't defined, show the modal by default
scope.showModal(true);
}
else
{
//Watch for changes to the modal-visible attribute
scope.$watch("modalVisible", function (newValue, oldValue) {
scope.showModal(newValue);
});
//Update the visible value when the dialog is closed through UI actions (Ok, cancel, etc.)
element.bind("hide.bs.modal", function () {
scope.modalVisible = false;
if (!scope.$$phase && !scope.$root.$$phase)
scope.$apply();
});
}
}
};
});
Usage Example #1 - this assumes you want to show the modal - you could add ng-if as a condition
<div modal-show class="modal fade"> ...bootstrap modal... </div>
Usage Example #2 - this uses an Angular expression in the modal-visible attribute
<div modal-show modal-visible="showDialog" class="modal fade"> ...bootstrap modal... </div>
Another Example - to demo the controller interaction, you could add something like this to your controller and it will show the modal after 2 seconds and then hide it after 5 seconds.
$scope.showDialog = false;
$timeout(function () { $scope.showDialog = true; }, 2000)
$timeout(function () { $scope.showDialog = false; }, 5000)
I'm late to contribute to this question - created this directive for another question here. Simple Angular Directive for Bootstrap Modal
Hope this helps.
You can simply use CSS transitions, see this fiddle
.on {
color:#fff;
transition:all 1s;
}
.off{
color:#000;
transition:all 1s;
}
Not long ago I wrote an example of the haversine formula, and published it on my website:
/**
* Calculates the great-circle distance between two points, with
* the Haversine formula.
* @param float $latitudeFrom Latitude of start point in [deg decimal]
* @param float $longitudeFrom Longitude of start point in [deg decimal]
* @param float $latitudeTo Latitude of target point in [deg decimal]
* @param float $longitudeTo Longitude of target point in [deg decimal]
* @param float $earthRadius Mean earth radius in [m]
* @return float Distance between points in [m] (same as earthRadius)
*/
function haversineGreatCircleDistance(
$latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371000)
{
// convert from degrees to radians
$latFrom = deg2rad($latitudeFrom);
$lonFrom = deg2rad($longitudeFrom);
$latTo = deg2rad($latitudeTo);
$lonTo = deg2rad($longitudeTo);
$latDelta = $latTo - $latFrom;
$lonDelta = $lonTo - $lonFrom;
$angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
return $angle * $earthRadius;
}
? Note that you get the distance back in the same unit as you pass in with the parameter $earthRadius
. The default value is 6371000 meters so the result will be in [m] too. To get the result in miles, you could e.g. pass 3959 miles as $earthRadius
and the result would be in [mi]. In my opinion it is a good habit to stick with the SI units, if there is no particular reason to do otherwise.
Edit:
As TreyA correctly pointed out, the Haversine formula has weaknesses with antipodal points because of rounding errors (though it is stable for small distances). To get around them, you could use the Vincenty formula instead.
/**
* Calculates the great-circle distance between two points, with
* the Vincenty formula.
* @param float $latitudeFrom Latitude of start point in [deg decimal]
* @param float $longitudeFrom Longitude of start point in [deg decimal]
* @param float $latitudeTo Latitude of target point in [deg decimal]
* @param float $longitudeTo Longitude of target point in [deg decimal]
* @param float $earthRadius Mean earth radius in [m]
* @return float Distance between points in [m] (same as earthRadius)
*/
public static function vincentyGreatCircleDistance(
$latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371000)
{
// convert from degrees to radians
$latFrom = deg2rad($latitudeFrom);
$lonFrom = deg2rad($longitudeFrom);
$latTo = deg2rad($latitudeTo);
$lonTo = deg2rad($longitudeTo);
$lonDelta = $lonTo - $lonFrom;
$a = pow(cos($latTo) * sin($lonDelta), 2) +
pow(cos($latFrom) * sin($latTo) - sin($latFrom) * cos($latTo) * cos($lonDelta), 2);
$b = sin($latFrom) * sin($latTo) + cos($latFrom) * cos($latTo) * cos($lonDelta);
$angle = atan2(sqrt($a), $b);
return $angle * $earthRadius;
}
The DateTime.Now
property returns the current date and time, for example 2011-07-01 10:09.45310
.
The DateTime.Today
property returns the current date with the time compnents set to zero, for example 2011-07-01 00:00.00000
.
The DateTime.Today
property actually is implemented to return DateTime.Now.Date
:
public static DateTime Today {
get {
DateTime now = DateTime.Now;
return now.Date;
}
}
The query can be written slightly simpler, like this:
DECLARE @T INT = 2
SELECT CASE
WHEN @T < 1 THEN 'less than one'
WHEN @T = 1 THEN 'one'
ELSE 'greater than one'
END T
Put the line in a stringstream and extract word by word back:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string t;
getline(cin,t);
istringstream iss(t);
string word;
while(iss >> word) {
/* do stuff with word */
}
}
Of course, you can just skip the getline part and read word by word from cin
directly.
And here you can read why is using namespace std
considered bad practice.
Just set Integrated Security=False
and it will work ,according to a comment difference between True
and False
is:
True
ignoresUser ID
andPassword
if provided and uses those of the running process,SSPI(Security Support Provider Interface )
it will use them if provided which is why MS prefers this. They are equivalent in that they use the same security mechanism to authenticate but that is it.
for swift :
button.setTitle("Swift", forState: UIControlState.Normal)
As many other pointed out, Intel HAXM only supports Intel CPUs. Since Windows 1804 you can use Microsoft's Hyper-V instead of HAXM for the emulator. This also helps people who want to use Hyper-V for virtual machines as you need to disable hyper-v to run haxm.
Short version:
Long version with more details:
https://blogs.msdn.microsoft.com/visualstudio/2018/05/08/hyper-v-android-emulator-support/
Requirements docs:
.NET is seeing an invalid SSL certificate on the other end of the connection. There is a workaround for it, but obviously not recommended for production code:
// Put this somewhere that is only once - like an initialization method
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateCertificate);
...
static bool ValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
If you use :active selector in combination with :hover you can achieve this according to w3schools as long as the :active selector is called after the :hover selector.
.info-slide:hover, .info-slide:active{
height:300px;
}
You'd have to test the FIDDLE in a mobile environment. I can't at the moment.
correction - I just tested in a mobile, it works fine
If you don't handle an exception, it will propagate up the call stack up to the interpreter, which will then display a traceback and exit. IOW : you don't have to do anything to make your script exit when an exception happens.
In Ruby:
ruby -rdebug myscript.rb
then,
b <line>
: put break-point n(ext)
or s(tep)
and c(ontinue)
p(uts)
for display(like perl debug)
In Rails: Launch the server with
script/server --debugger
and add debugger
in the code.
jQuery doesn't work on plain object literals. You can use the below function in a similar way to search all 'id's (or any other property), regardless of its depth in the object:
function getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else if (i == key && obj[key] == val) {
objects.push(obj);
}
}
return objects;
}
Use like so:
getObjects(TestObj, 'id', 'A'); // Returns an array of matching objects
I follow the Python Idioms and Efficiency guidelines, by Rob Knight. I think they are exactly the same as PEP 8, but are more synthetic and based on examples.
If you are using wxPython you might also want to check Style Guide for wxPython code, by Chris Barker, as well.
Take a look on this answer to another related question. It shows how to enable, disable and to see the logs on live servers without restarting.
Here is a summary:
If you don't want or cannot restart the MySQL server you can proceed like this on your running server:
Create your log tables (see answer)
Enable Query logging on the database (Note that the string 'table' should be put literally and not substituted by any table name. Thanks Nicholas Pickering)
SET global general_log = 1;
SET global log_output = 'table';
select * from mysql.general_log;
SET global general_log = 0;
TRUNCATE mysql.general_log
This worked for me just now:
<canvas id="c" height="100" width="100" style="border:1px solid red"></canvas>
<script>
var c = document.getElementById('c');
alert(c.height + ' ' + c.width);
c.height = 200;
c.width = 200;
alert(c.height + ' ' + c.width);
</script>
getActiveNetworkInfo
is deprecated from in API 29. So we can use it in bellow 29.
New code in Kotlin for All the API
fun isNetworkAvailable(context: Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
// For 29 api or above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) ?: return false
return when {
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
else -> false
}
}
// For below 29 api
else {
if (connectivityManager.activeNetworkInfo != null && connectivityManager.activeNetworkInfo!!.isConnectedOrConnecting) {
return true
}
}
return false
}
For me, this simply works:
error: function(xhr, status, error) {
alert(xhr.responseText);
}
Personally, I tend to use awk for jobs like this. For example:
ps axu| grep jboss | grep -v grep | awk '{print $5}'
SELECT group, date, checks
FROM table
WHERE checks > 0
GROUP BY group HAVING date = max(date)
should work.
See here for more details. The default is none of private/public/protected, but a completely different access specification. It's not widely used, and I prefer to be much more specific in my access definitions.
What operating system are you using?
I know that on windows, you can do something like this:
//include crap
#include <windows.h>
int main () {
//do things
Sleep(/* ur wait time in ms */);// wait for param1 ms
//continue to do things
}
Its because of wrong path provided. It may be that the url contains space and if the case url has to be properly constructed.
The correct url should be in the format with file name included like "http://server name/document library name/new file name"
So if report.xlsx is the file that has to be uploaded at "http://server name/Team/Dev Team" then path comes out to be is "http://server name/Team/Dev Team/report.xlsx". It contains space so it should be reconstructed as "http://server name/Team/Dev%20Team/report.xlsx" and should be used.
Just replace "UTC" with "GMT" -- simple and doesn't break correctly formatted dates:
DateTime.Parse("Tue, 1 Jan 2008 00:00:00 UTC".Replace("UTC", "GMT"))
We have following script for create new table:
CREATE TABLE new_table
(
id NUMBER(32) PRIMARY KEY,
referenced_table_id NUMBER(32) NOT NULL,
CONSTRAINT fk_new_table_referenced_table_id
FOREIGN KEY (referenced_table_id)
REFERENCES referenced_table (id)
);
and we were getting this error on execute:
[42000][2270] ORA-02270: no matching unique or primary key for this column-list
The issue was due to disabled primary key of referenced table in our case. We have enabled it by
ALTER TABLE referenced_table ENABLE PRIMARY KEY USING INDEX;
after that we created new table using first script without any issues
You can directly install an github repo by npm install
command, like this:
npm install https://github.com/futurechallenger/npm_git_install.git --save
NOTE: In the repo which will be installed by npm command:
Corrected a few things and added an alternative select - delete as appropriate.
DELIMITER |
CREATE PROCEDURE getNearestCities
(
IN p_cityID INT -- should this be int unsigned ?
)
BEGIN
DECLARE cityLat FLOAT; -- should these be decimals ?
DECLARE cityLng FLOAT;
-- method 1
SELECT lat,lng into cityLat, cityLng FROM cities WHERE cities.cityID = p_cityID;
SELECT
b.*,
HAVERSINE(cityLat,cityLng, b.lat, b.lng) AS dist
FROM
cities b
ORDER BY
dist
LIMIT 10;
-- method 2
SELECT
b.*,
HAVERSINE(a.lat, a.lng, b.lat, b.lng) AS dist
FROM
cities AS a
JOIN cities AS b on a.cityID = p_cityID
ORDER BY
dist
LIMIT 10;
END |
delimiter ;
First, import java.util.Calendar
Calendar now = Calendar.getInstance();
System.out.println(now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE));
For any executable file, you can run your program using cmd with "c" parameter:
cmd /c "your program address"\"YourFileName".bat
(->if it's a batch file!) As a final solution, I suggest that you create a .cmd file and put this command in it:
cmd /c "your program address"\"YourFileName".bat
exit
Now just run this .cmd file.
You can analyse problem (dex file references) using Android Studio:
Build -> Analyse APK ..
On the result panel click on classes.dex file
And you'll see:
in my case it is present as "php.ini-development" and "php.ini-production" in php folder
If your compiler is GCC you can also use following syntax:
int array[256] = {[0 ... 255] = 0};
Please look at http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Designated-Inits.html#Designated-Inits, and note that this is a compiler-specific feature.
This way we can do this with minimal changes :)
<html>
<head>
<style>
option:hover {
background-color: yellow;
}
</style>
</head>
<body>
<select onfocus='this.size=10;' onblur='this.size=0;' onchange='this.size=1; this.blur();'>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
</body>
</html>
_x000D_
This is working as documented. Any paths specified in PYTHONPATH
are documented as normally coming after the working directory but before the standard interpreter-supplied paths. sys.path.append()
appends to the existing path. See here and here. If you want a particular directory to come first, simply insert it at the head of sys.path:
import sys
sys.path.insert(0,'/path/to/mod_directory')
That said, there are usually better ways to manage imports than either using PYTHONPATH
or manipulating sys.path
directly. See, for example, the answers to this question.
If you have the need to keep the environment variables in a script you can put your command in a here document like this. Especially if you have lots of variables to set things look tidy this way.
# prepare a script e.g. for running maven
runmaven=/tmp/runmaven$$
# create the script with a here document
cat << EOF > $runmaven
#!/bin/bash
# run the maven clean with environment variables set
export ANT_HOME=/usr/share/ant
export MAKEFLAGS=-j4
mvn clean install
EOF
# make the script executable
chmod +x $runmaven
# run it
sudo $runmaven
# remove it or comment out to keep
rm $runmaven
Take a look at rogerdudler/eclipse-ui-themes . In the readme there is a link to a file that you need to extract into your eclipse/dropins
folder.
When you have done that go to
Window -> Preferences -> General -> Appearance
And change the theme from GTK (or what ever it is currently) to Dark Juno
(or Dark).
That will change the UI to a nice dark theme but to get the complete look and feel you can get the Eclipse Color Theme plugin from eclipsecolorthemes.org. The easiest way is to add this update URI to "Help -> Install New Software" and install it from there.
This adds a "Color Theme" menu item under
Window -> Preferences -> Appearance
Where you can select from a large range of editor themes. My preferred one to use with PyDev is Wombat. For Java Solarized Dark
>>> a.argmax(axis=0)
array([1, 1, 0])
trim off everything after the last instance of ":"
cat fileListingPathsAndFiles.txt | grep -o '^.*:'
and if you wanted to drop that last ":"
cat file.txt | grep -o '^.*:' | sed 's/:$//'
@kp123: you'd want to replace :
with /
(where the sed colon should be \/
)
For this answer, I refer to querySelector
and querySelectorAll
as querySelector* and to getElementById
, getElementsByClassName
, getElementsByTagName
, and getElementsByName
as getElement*.
querySelector
and getElementById
both return a single element. querySelectorAll
and getElementsByName
both return NodeLists, being newer functions that were added after HTMLCollection went out of fashion. The older getElementsByClassName
and getElementsByTagName
both return HTMLCollections. Again, this is essentially irrelevant to whether the elements are live or static.These concepts are summarized in the following table.
Function | Live? | Type | Time Complexity
querySelector | N | Element | O(n)
querySelectorAll | N | NodeList | O(n)
getElementById | Y | Element | O(1)
getElementsByClassName | Y | HTMLCollection | O(1)
getElementsByTagName | Y | HTMLCollection | O(1)
getElementsByName | Y | NodeList | O(1)
HTMLCollections are not as array-like as NodeLists and do not support .forEach(). I find the spread operator useful to work around this:
[...document.getElementsByClassName("someClass")].forEach()
Every element, and the global document
, have access to all of these functions except for getElementById
and getElementsByName
, which are only implemented on document
.
Chaining getElement* calls instead of using querySelector* will improve performance, especially on very large DOMs. Even on small DOMs and/or with very long chains, it is generally faster. However, unless you know you need the performance, the readability of querySelector* should be preferred. querySelectorAll
is often harder to rewrite, because you must select elements from the NodeList or HTMLCollection at every step. For example, the following code does not work:
document.getElementsByClassName("someClass").getElementsByTagName("div")
because you can only use getElements* on single elements, not collections. For example:
document.querySelector("#someId .someClass div")
could be written as:
document.getElementById("someId").getElementsByClassName("someClass")[0].getElementsByTagName("div")[0]
Note the use of [0]
to get just the first element of the collection at each step that returns a collection, resulting in one element at the end just like with querySelector
.
Since all elements have access to both querySelector* and getElement* calls, you can make chains using both calls, which can be useful if you want some performance gain, but cannot avoid a querySelector that can not be written in terms of the getElement* calls.
Though it is generally easy to tell if a selector can be written using only getElement* calls, there is one case that may not be obvious:
document.querySelectorAll(".class1.class2")
can be rewritten as
document.getElementsByClassName("class1 class2")
Using getElement* on a static element fetched with querySelector* will result in an element that is live with respect to the static subset of the DOM copied by querySelector, but not live with respect to the full document DOM... this is where the simple live/static interpretation of elements begins to fall apart. You should probably avoid situations where you have to worry about this, but if you do, remember that querySelector* calls copy elements they find before returning references to them, but getElement* calls fetch direct references without copying.
Neither API specifies which element should be selected first if there are multiple matches.
Because querySelector* iterates through the DOM until it finds a match (see Main Difference #2), the above also implies that you cannot rely on the position of an element you are looking for in the DOM to guarantee that it is found quickly - the browser may iterate through the DOM backwards, forwards, depth first, breadth first, or otherwise. getElement* will still find elements in roughly the same amount of time regardless of their placement.
Another way of getting the first row and preserving the index:
x = df.first('d') # Returns the first day. '3d' gives first three days.
Here is a function that takes in another function and outputs a version that runs async.
var async = function (func) {
return function () {
var args = arguments;
setTimeout(function () {
func.apply(this, args);
}, 0);
};
};
It is used as a simple way to make an async function:
var anyncFunction = async(function (callback) {
doSomething();
callback();
});
This is different from @fider's answer because the function itself has its own structure (no callback added on, it's already in the function) and also because it creates a new function that can be used.
This is what I use to control headers/caching, I'm not an Apache pro, so let me know if there is room for improvement, but I know that this has been working well on all of my sites for some time now.
http://httpd.apache.org/docs/2.2/mod/mod_expires.html
This module controls the setting of the Expires HTTP header and the max-age directive of the Cache-Control HTTP header in server responses. The expiration date can set to be relative to either the time the source file was last modified, or to the time of the client access.
These HTTP headers are an instruction to the client about the document's validity and persistence. If cached, the document may be fetched from the cache rather than from the source until this time has passed. After that, the cache copy is considered "expired" and invalid, and a new copy must be obtained from the source.
# BEGIN Expires
<ifModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 seconds"
ExpiresByType text/html "access plus 1 seconds"
ExpiresByType image/gif "access plus 2592000 seconds"
ExpiresByType image/jpeg "access plus 2592000 seconds"
ExpiresByType image/png "access plus 2592000 seconds"
ExpiresByType text/css "access plus 604800 seconds"
ExpiresByType text/javascript "access plus 216000 seconds"
ExpiresByType application/x-javascript "access plus 216000 seconds"
</ifModule>
# END Expires
http://httpd.apache.org/docs/2.2/mod/mod_headers.html
This module provides directives to control and modify HTTP request and response headers. Headers can be merged, replaced or removed.
# BEGIN Caching
<ifModule mod_headers.c>
<filesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf)$">
Header set Cache-Control "max-age=2592000, public"
</filesMatch>
<filesMatch "\.(css)$">
Header set Cache-Control "max-age=604800, public"
</filesMatch>
<filesMatch "\.(js)$">
Header set Cache-Control "max-age=216000, private"
</filesMatch>
<filesMatch "\.(xml|txt)$">
Header set Cache-Control "max-age=216000, public, must-revalidate"
</filesMatch>
<filesMatch "\.(html|htm|php)$">
Header set Cache-Control "max-age=1, private, must-revalidate"
</filesMatch>
</ifModule>
# END Caching
Yes and no. The solution is to build a Wrapper clas for your values that contains the 2 (3, or more) values that correspond to your key.
Similarly along the lines of these answers written as a plugin:
$.fn.sum = function () {
var sum = 0;
this.each(function () {
sum += 1*($(this).val());
});
return sum;
};
For the record 1 * x is faster than Number(x) in Chrome
This weird error happens, when you play around with different versions of EntityFramework versions in Nuget Packages like I did.
First, Uninstall your Entity Framework DLL from NuGet packages and then Clean up app.config. By removing the entry from configSections and entity framework element.
Next, install the desired version. This should fix the problem.
The current accepted answer is out of date. Now if you want to create a post request and add parameters to it you should user MultipartBody.Builder as Mime Craft now is deprecated.
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("somParam", "someValue")
.build();
Request request = new Request.Builder()
.url(BASE_URL + route)
.post(requestBody)
.build();
I assume you are using Series.plot() to plot your data. If you look at the docs for Series.plot() here:
http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.plot.html
there is no color parameter listed where you might be able to set the colors for your bar graph.
However, the Series.plot() docs state the following at the end of the parameter list:
kwds : keywords
Options to pass to matplotlib plotting method
What that means is that when you specify the kind argument for Series.plot() as bar, Series.plot() will actually call matplotlib.pyplot.bar(), and matplotlib.pyplot.bar() will be sent all the extra keyword arguments that you specify at the end of the argument list for Series.plot().
If you examine the docs for the matplotlib.pyplot.bar() method here:
http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar
..it also accepts keyword arguments at the end of it's parameter list, and if you peruse the list of recognized parameter names, one of them is color, which can be a sequence specifying the different colors for your bar graph.
Putting it all together, if you specify the color keyword argument at the end of your Series.plot() argument list, the keyword argument will be relayed to the matplotlib.pyplot.bar() method. Here is the proof:
import pandas as pd
import matplotlib.pyplot as plt
s = pd.Series(
[5, 4, 4, 1, 12],
index = ["AK", "AX", "GA", "SQ", "WN"]
)
#Set descriptions:
plt.title("Total Delay Incident Caused by Carrier")
plt.ylabel('Delay Incident')
plt.xlabel('Carrier')
#Set tick colors:
ax = plt.gca()
ax.tick_params(axis='x', colors='blue')
ax.tick_params(axis='y', colors='red')
#Plot the data:
my_colors = 'rgbkymc' #red, green, blue, black, etc.
pd.Series.plot(
s,
kind='bar',
color=my_colors,
)
plt.show()
Note that if there are more bars than colors in your sequence, the colors will repeat.
I really liked the suggestion in https://stackoverflow.com/a/60313570/770134, so I adapted it to Typescript like so
import React, { FunctionComponent } from 'react'
import { Optional } from "typescript-optional";
const { ofNullable } = Optional
interface SwitchProps {
test: string
defaultComponent: JSX.Element
}
export const Switch: FunctionComponent<SwitchProps> = (props) => {
return ofNullable(props.children)
.map((children) => {
return ofNullable((children as JSX.Element[]).find((child) => child.props['value'] === props.test))
.orElse(props.defaultComponent)
})
.orElseThrow(() => new Error('Children are required for a switch component'))
}
const Foo = ({ value = "foo" }) => <div>foo</div>;
const Bar = ({ value = "bar" }) => <div>bar</div>;
const value = "foo";
const SwitchExample = <Switch test={value} defaultComponent={<div />}>
<Foo />
<Bar />
</Switch>;
Your setters are strange, which is why you may be seeing a problem.
First, consider whether you even need these setters - if so, they should take a List<string>
, not just a string
:
set
{
_subHead = value;
}
These lines:
newSec.subHead.Add("test string");
Are calling the getter and then call Add
on the returned List<string>
- the setter is not invoked.
You can convert a number to a string with n decimal places using the SPRINTF command:
>> x = 1.23; >> sprintf('%0.6f', x) ans = 1.230000 >> x = 1.23456789; >> sprintf('%0.6f', x) ans = 1.234568
Please Try to pass parameters in httpoptions
, you can follow function below
deleteAction(url, data) {
const authToken = sessionStorage.getItem('authtoken');
const options = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
Authorization: 'Bearer ' + authToken,
}),
body: data,
};
return this.client.delete(url, options);
}
I had the problem occur on my system in a very strange way. In my system customers create products that sit inside a directory structure of product categories. So ProductA might sit in the folder CategoryInner inside the folder CategoryOuter. I had just added a feature where my URL would show the category nesting on the URL thusly:
http://www.somedomain.com/product/CategoryOuter/CategoryInner/ProductA.aspx
Obviously the nesting on the URL was just for SEO purposes (and to show the user what category their product was sitting in. But when I used ResolveClientUrl on some URLs that used to work, it must've been confused by the extra fake pathing. The error message was popping up in the debugger on some line that was never the problem so it took me quite some time to figure out what was going on. I wnet through and removed all of my ResolveClientUrl calls that acted on anything that didn't start with a ~ and made the rest of the paths absolute paths.
Just to clarify things, you don't/can't "execute it within the HTML body".
You can modify the contents of the HTML using javascript.
You decide at what point you want the javascript to be executed.
For example, here is the contents of a html file, including javascript, that does what you want.
<html>
<head>
<script>
// The next line document.addEventListener....
// tells the browser to execute the javascript in the function after
// the DOMContentLoaded event is complete, i.e. the browser has
// finished loading the full webpage
document.addEventListener("DOMContentLoaded", function(event) {
var col1 = ["Full time student checking (Age 22 and under) ", "Customers over age 65", "Below $500.00" ];
var col2 = ["None", "None", "$8.00"];
var TheInnerHTML ="";
for (var j = 0; j < col1.length; j++) {
TheInnerHTML += "<tr><td>"+col1[j]+"</td><td>"+col2[j]+"</td></tr>";
}
document.getElementById("TheBody").innerHTML = TheInnerHTML;});
</script>
</head>
<body>
<table>
<thead>
<tr>
<th>Balance</th>
<th>Fee</th>
</tr>
</thead>
<tbody id="TheBody">
</tbody>
</table>
</body>
Enjoy !
I'm surprised none of these answers used the built in MVC features for this.
I wrote a blog post about this here, which even actually links the labels to the checkbox. I used the EditorTemplate folder to accomplish this in a clean and modular way.
You will simply end up with a new file in the EditorTemplate folder that looks like this:
@model SampleObject
@Html.CheckBoxFor(m => m.IsChecked)
@Html.HiddenFor(m => m.Id)
@Html.LabelFor(m => m.IsChecked, Model.Id)
in your actual view, there will be no need to loop this, simply 1 line of code:
@Html.EditorFor(x => ViewData.Model)
Visit my blog post for more details.
You can add the model error on any property of your model, I suggest if there is nothing related to create a new property.
As an exemple we check if the email is already in use in DB and add the error to the Email property in the action so when I return the view, they know that there's an error and how to show it up by using
<%: Html.ValidationSummary(true)%>
<%: Html.ValidationMessageFor(model => model.Email) %>
and
ModelState.AddModelError("Email", Resources.EmailInUse);
For a line-by-line delta measurement, try gnomon.
A command line utility, a bit like moreutils's ts, to prepend timestamp information to the standard output of another command. Useful for long-running processes where you'd like a historical record of what's taking so long.
You can also use the --high
and/or --medium
options to specify a length threshold in seconds, over which gnomon will highlight the timestamp in red or yellow. And you can do a few other things, too.
With pure JavaScript:
console.log(window.location.href)
Using Angular:
this.router.url
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
template: 'The href is: {{href}}'
/*
Other component settings
*/
})
export class Component {
public href: string = "";
constructor(private router: Router) {}
ngOnInit() {
this.href = this.router.url;
console.log(this.router.url);
}
}
The plunkr is here: https://plnkr.co/edit/0x3pCOKwFjAGRxC4hZMy?p=preview
If you mean you want to sort by date first then by names
SELECT id, name, form_id, DATE(updated_at) as date
FROM wp_frm_items
WHERE user_id = 11 && form_id=9
ORDER BY updated_at DESC,name ASC
This will sort the records by date first, then by names
I wanted to comment, but since my reputation won't qualify for commenting, it had to be an answer. Github will actually let you not only cancel a pull request, but also delete it by simply deleting the fork you are trying to push. Hope this may help some others googling this.
For a 2d numpy
array, simply use imshow()
may help you:
import matplotlib.pyplot as plt
import numpy as np
def heatmap2d(arr: np.ndarray):
plt.imshow(arr, cmap='viridis')
plt.colorbar()
plt.show()
test_array = np.arange(100 * 100).reshape(100, 100)
heatmap2d(test_array)
This code produces a continuous heatmap.
You can choose another built-in colormap
from here.
I think you should try this:
string path = Path.GetRandomFileName();
path = Path.Combine(@"c:\temp", path);
path = Path.ChangeExtension(path, ".tmp");
File.Create(path);
It generates a unique filename and creates a file with that file name at a specified location.
dataGridView1.SelectedRows[0].Index;
Or if you wanted to use LINQ and get the index of all selected rows, you could do:
dataGridView1.SelectedRows.Select(r => r.Index);
would this work?
cat requirements.txt | while read x; do conda install "$x" -p ./lib ;done
or
conda install --file requirements.txt -p ./lib
You can go to the Start Menu and search the Node.js icon and open the shell and then install anything with
install <packagename> -g
You can do this with plain js by using
location.host
, same as document.location.hostname
Is it that
success()
returns earlier thancomplete()
?
Yes; the AJAX success()
method runs before the complete()
method.
Below is a diagram illustrating the process flow:
It is important to note that
The success()
(Local Event) is only called if the request was successful (no errors from the server, no errors with the data).
On the other hand, the complete()
(Local Event) is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.
... more details on AJAX Events here.
Historical Note: This was written at the time of PHP4. This is what we call "legacy code" now.
I have left this answer for historical purposes - but some of the methods are now deprecated, DES encryption method is not a recommended practice, etc.
I have not updated this code for two reasons: 1) I no longer work with encryption methods by hand in PHP, and 2) this code still serves the purpose it was intended for: to demonstrate the minimum, simplistic concept of how encryption can work in PHP.
If you find a similarly simplistic, "PHP encryption for dummies" kind of source that can get people started in 10-20 lines of code or less, let me know in comments.
Beyond that, please enjoy this Classic Episode of early-era PHP4 minimalistic encryption answer.
Ideally you have - or can get - access to the mcrypt PHP library, as its certainly popular and very useful a variety of tasks. Here's a run down of the different kinds of encryption and some example code: Encryption Techniques in PHP
//Listing 3: Encrypting Data Using the mcrypt_ecb Function
<?php
echo("<h3> Symmetric Encryption </h3>");
$key_value = "KEYVALUE";
$plain_text = "PLAINTEXT";
$encrypted_text = mcrypt_ecb(MCRYPT_DES, $key_value, $plain_text, MCRYPT_ENCRYPT);
echo ("<p><b> Text after encryption : </b>");
echo ( $encrypted_text );
$decrypted_text = mcrypt_ecb(MCRYPT_DES, $key_value, $encrypted_text, MCRYPT_DECRYPT);
echo ("<p><b> Text after decryption : </b>");
echo ( $decrypted_text );
?>
A few warnings:
1) Never use reversible, or "symmetric" encryption when a one-way hash will do.
2) If the data is truly sensitive, like credit card or social security numbers, stop; you need more than any simple chunk of code will provide, but rather you need a crypto library designed for this purpose and a significant amount of time to research the methods necessary. Further, the software crypto is probably <10% of security of sensitive data. It's like rewiring a nuclear power station - accept that the task is dangerous and difficult and beyond your knowledge if that's the case. The financial penalties can be immense, so better to use a service and ship responsibility to them.
3) Any sort of easily implementable encryption, as listed here, can reasonably protect mildly important information that you want to keep from prying eyes or limit exposure in the case of accidental/intentional leak. But seeing as how the key is stored in plain text on the web server, if they can get the data they can get the decryption key.
Be that as it may, have fun :)
Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction()
function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!
Very readable code is to use .substring()
with a start set to index of the second character (1) (first character has index 0). Second parameter of the .substring()
method is actually optional, so you don't even need to call .length()
...
str = str.substring(1);
...yes it is that simple...
As @Shaded suggested, just loop this while first character of your string is the "unwanted" character...
var yourString = "0000test";
var unwantedCharacter = "0";
//there is really no need for === check, since we use String's charAt()
while( yourString.charAt(0) == unwantedCharacter ) yourString = yourString.substring(1);
//yourString now contains "test"
.slice()
vs .substring()
vs .substr()
EDIT: substr() is not standardized and should not be used for new JS codes, you may be inclined to use it because of the naming similarity with other languages, e.g. PHP, but even in PHP you should probably use mb_substr()
to be safe in modern world :)
Quote from (and more on that in) What is the difference between String.slice and String.substring?
He also points out that if the parameters to slice are negative, they reference the string from the end. Substring and substr doesn´t.
use typescript for your coding, because it's object oriented, strictly typed and easy to maintain the code ...
for more info about typescipt click here
Here one simple example I have created to share data between two controller using Typescript...
module Demo {
//create only one module for single Applicaiton
angular.module('app', []);
//Create a searvie to share the data
export class CommonService {
sharedData: any;
constructor() {
this.sharedData = "send this data to Controller";
}
}
//add Service to module app
angular.module('app').service('CommonService', CommonService);
//Create One controller for one purpose
export class FirstController {
dataInCtrl1: any;
//Don't forget to inject service to access data from service
static $inject = ['CommonService']
constructor(private commonService: CommonService) { }
public getDataFromService() {
this.dataInCtrl1 = this.commonService.sharedData;
}
}
//add controller to module app
angular.module('app').controller('FirstController', FirstController);
export class SecondController {
dataInCtrl2: any;
static $inject = ['CommonService']
constructor(private commonService: CommonService) { }
public getDataFromService() {
this.dataInCtrl2 = this.commonService.sharedData;
}
}
angular.module('app').controller('SecondController', SecondController);
}
For future readers who need this answer quickly:
2^31-1 = 2.147.483.647 characters
Swift 3
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let editAction = UITableViewRowAction(style: .normal, title: "Edit") { (rowAction, indexPath) in
//TODO: edit the row at indexPath here
}
editAction.backgroundColor = .blue
let deleteAction = UITableViewRowAction(style: .normal, title: "Delete") { (rowAction, indexPath) in
//TODO: Delete the row at indexPath here
}
deleteAction.backgroundColor = .red
return [editAction,deleteAction]
}
Swift 2.1
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let editAction = UITableViewRowAction(style: .Normal, title: "Edit") { (rowAction:UITableViewRowAction, indexPath:NSIndexPath) -> Void in
//TODO: edit the row at indexPath here
}
editAction.backgroundColor = UIColor.blueColor()
let deleteAction = UITableViewRowAction(style: .Normal, title: "Delete") { (rowAction:UITableViewRowAction, indexPath:NSIndexPath) -> Void in
//TODO: Delete the row at indexPath here
}
deleteAction.backgroundColor = UIColor.redColor()
return [editAction,deleteAction]
}
Note: for iOS 8 onwards
An alternative to adding LINQ would be to use this code instead:
List<Pax_Detail> paxList = new List<Pax_Detail>(pax);
It's a pandas data-frame and it's using label base selection tool with df.loc
and in it, there are two inputs, one for the row and the other one for the column, so in the row input it's selecting all those row values where the value saved in the column class
is versicolor
, and in the column input it's selecting the column with label class
, and assigning Iris-versicolor
value to them.
So basically it's replacing all the cells of column class
with value versicolor
with Iris-versicolor
.
Once you've added your listbox item to your form, change DrawMode with OwnerDrawFixed option from the Properties panel. If you forget to do this, none of the codes below will work. Then click DrawItem event from the Events area.
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
// 1. Get the item
string selectedItem = listBox1.Items[e.Index].ToString();
// 2. Choose font
Font font = new Font("Arial", 12);
// 3. Choose colour
SolidBrush solidBrush = new SolidBrush(Color.Red);
// 4. Get bounds
int left = e.Bounds.Left;
int top = e.Bounds.Top;
// 5. Use Draw the background within the bounds
e.DrawBackground();
// 6. Colorize listbox items
e.Graphics.DrawString(selectedItem, font, solidBrush, left, top);
}
Just to complete the answers available:
An input element can be either readonly or disabled (none of them is editable, but there are a couple of differences: focus,...)
Good explanation can be found here:
What's the difference between disabled=“disabled” and readonly=“readonly” for HTML form input fields?
How to use:
<input type="text" value="Example" disabled />
<input type="text" value="Example" readonly />
There are also some solutions to make it through CSS or JavaScript as explained here.
React components expose all the standard Javascript mouse events in their top-level interface. Of course, you can still use :hover
in your CSS, and that may be adequate for some of your needs, but for the more advanced behaviors triggered by a hover you'll need to use the Javascript. So to manage hover interactions, you'll want to use onMouseEnter
and onMouseLeave
. You then attach them to handlers in your component like so:
<ReactComponent
onMouseEnter={() => this.someHandler}
onMouseLeave={() => this.someOtherHandler}
/>
You'll then use some combination of state/props to pass changed state or properties down to your child React components.
If you use the request body in a GET request, you're breaking the REST principle, because your GET request won't be able to be cached, because cache system uses only the URL.
What's worse, your URL can't be bookmarked, because the URL doesn't contain all the information needed to redirect the user to this page.
Use URL or Query parameters instead of request body parameters, e.g.:
/myapp?var1=xxxx&var2=xxxx
/myapp;var1=xxxx/resource;var2=xxxx
In fact, the HTTP RFC 7231 says that:
A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.
For more information take a look here.
Much of the reason that it took > 48 hours to do your inserts is because of your indexes. It is incredibly faster to:
1 - Drop all indexes 2 - Do all inserts 3 - Create indexes again
Ive something to add here which no one mentioned.
The pivot
function works great when the source has 3 columns: One for the aggregate
, one to spread as columns with for
, and one as a pivot for row
distribution. In the product example it's QTY, CUST, PRODUCT
.
However, if you have more columns in the source it will break the results into multiple rows instead of one row per pivot based on unique values per additional column (as Group By
would do in a simple query).
See this example, ive added a timestamp column to the source table:
Now see its impact:
SELECT CUST, MILK
FROM Product
-- FROM (SELECT CUST, Product, QTY FROM PRODUCT) p
PIVOT (
SUM(QTY) FOR PRODUCT IN (MILK)
) AS pvt
ORDER BY CUST
In order to fix this, you can either pull a subquery as a source as everyone has done above - with only 3 columns (this is not always going to work for your scenario, imagine if you need to put a where
condition for the timestamp).
Second solution is to use a group by
and do a sum of the pivoted column values again.
SELECT
CUST,
sum(MILK) t_MILK
FROM Product
PIVOT (
SUM(QTY) FOR PRODUCT IN (MILK)
) AS pvt
GROUP BY CUST
ORDER BY CUST
GO
Easy, type this commands:
rm -rf vendor/
rm -rf composer.lock
php composer install --prefer-dist
Should work for low memory machines
MacPorts is the way to go.
Like @user475443 pointed, MacPorts has many many more packages. With brew you'll find yourself trapped soon because the formula you need doesn't exist.
MacPorts is a native application: C + TCL. You don't need Ruby at all. To install Ruby on Mac OS X you might need MacPorts, so just go with MacPorts and you'll be happy.
MacPorts is really stable, in 8 years I never had a problem with it, and my entire Unix ecosystem relay on it.
If you are a PHP developer you can install the last version of Apache (Mac OS X uses 2.2), PHP and all the extensions you need, then upgrade all with one command. Forget to do the same with Homebrew.
MacPorts support groups.
foo@macpro:~/ port select --summary
Name Selected Options
==== ======== =======
db none db46 none
gcc none gcc42 llvm-gcc42 mp-gcc48 none
llvm none mp-llvm-3.3 none
mysql mysql56 mysql56 none
php php55 php55 php56 none
postgresql postgresql94 postgresql93 postgresql94 none
python none python24 python25-apple python26-apple python27 python27-apple none
If you have both PHP55 and PHP56 installed (with many different extensions), you can swap between them with just one command. All the relative extensions are part of the group and they will be activated within the chosen group: php55 or php56. I'm not sure Homebrew has this feature.
Rubists like to rewrite everything in Ruby, because the only thing they are at ease is Ruby itself.
These days you can use a Media Queries Level 4 feature to check if the device has the ability to 'hover' over elements.
@media (hover: hover) { ... }
Since the ipad has no 'hover' state you can effectively target touch devices like the ipad.
Angular now supports min/max validators by default.
Angular provides the following validators by default. Adding the list here so that new comers can easily get to know what are the current supported default validators and google it further as per their interest.
you will get the complete list Angular validators
How to use min/max validator: From the documentation of Angular -
static min(min: number): ValidatorFn
static max(max: number): ValidatorFn
min()/max() is a static function that accepts a number parameter and returns A validator function that returns an error map with the min/max property if the validation check fails, otherwise null.
use min validator in formControl, (for further info, click here)
const control = new FormControl(9, Validators.min(10));
use max validator in formControl, (for further info, click here)
const control = new FormControl(11, Validators.max(10));
sometimes we need to add validator dynamically. setValidators() is the saviour. you can use it like the following -
const control = new FormControl(10);
control.setValidators([Validators.min(9), Validators.max(11)]);
And another useful command to do this (after git fetch) is:
git log origin/master ^master
This shows the commits that are in origin/master but not in master. You can also do it in opposite when doing git pull, to check what commits will be submitted to remote.