In my opinion one of the worst chosen word's to describe the process, as it is not related to anything in real-life or similar. In general the word "queue" is very bad as if pronounced, it sounds like the English character "q". See the inefficiency here?
enqueue: to place something into a queue; to add an element to the tail of a queue;
dequeue to take something out of a queue; to remove the first available element from the head of a queue
To answer the title-question:
DateTime d1 = ...;
DateTime d2 = ...;
TimeSpan diff = d2 - d1;
int millisceonds = (int) diff.TotalMilliseconds;
You can use this to set a Timer:
timer1.interval = millisceonds;
timer1.Enabled = true;
Don't forget to disable the timer when handling the tick.
But if you want an event at 12:03, just substitute DateTime.Now for d1
.
But it is not clear what the exact function of textBox1 and textBox2 are.
In windows,
This works fine in LINQPad4:
Console.WriteLine(DateTime.Parse("2010-08-20T15:00:00Z"));
Console.WriteLine(DateTime.Parse("2010-08-20T15:00:00"));
Console.WriteLine(DateTime.Parse("2010-08-20 15:00:00"));
In SQL server, a cursor is used when you need Instead of the T-SQL commands that operate on all the rows in the result set one at a time, we use a cursor when we need to update records in a database table in a singleton fashion, in other words row by row.to fetch one row at a time or row by row.
Working with cursors consists of several steps:
Declare - Declare is used to define a new cursor. Open - A Cursor is opened and populated by executing the SQL statement defined by the cursor. Fetch - When the cursor is opened, rows can be retrieved from the cursor one by one. Close - After data operations, we should close the cursor explicitly. Deallocate - Finally, we need to delete the cursor definition and release all the system resources associated with the cursor. Syntax
DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ] [ FORWARD_ONLY | SCROLL ] [ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ] [ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ] [ TYPE_WARNING] FOR select_statement [FOR UPDATE [ OF column_name [ ,...n ] ] ] [;]
here is the example using Pure JavaScript
function scrollpage() { _x000D_
function f() _x000D_
{_x000D_
window.scrollTo(0,i);_x000D_
if(status==0) {_x000D_
i=i+40;_x000D_
if(i>=Height){ status=1; } _x000D_
} else {_x000D_
i=i-40;_x000D_
if(i<=1){ status=0; } // if you don't want continue scroll then remove this line_x000D_
}_x000D_
setTimeout( f, 0.01 );_x000D_
}f();_x000D_
}_x000D_
var Height=document.documentElement.scrollHeight;_x000D_
var i=1,j=Height,status=0;_x000D_
scrollpage();_x000D_
</script>
_x000D_
<style type="text/css">_x000D_
_x000D_
#top { border: 1px solid black; height: 20000px; }_x000D_
#bottom { border: 1px solid red; }_x000D_
_x000D_
</style>
_x000D_
<div id="top">top</div>_x000D_
<div id="bottom">bottom</div>
_x000D_
Here is working code:
=QUERY(Sheet1!$A1:$B581, "select B where A = '"&A1&"'")
In this scenario I needed the interval to stay fixed and the reference value to change when I drag it.
What is the potential damage if it was possible to invoke
wait()
outside a synchronized block, retaining it's semantics - suspending the caller thread?
Let's illustrate what issues we would run into if wait()
could be called outside of a synchronized block with a concrete example.
Suppose we were to implement a blocking queue (I know, there is already one in the API :)
A first attempt (without synchronization) could look something along the lines below
class BlockingQueue {
Queue<String> buffer = new LinkedList<String>();
public void give(String data) {
buffer.add(data);
notify(); // Since someone may be waiting in take!
}
public String take() throws InterruptedException {
while (buffer.isEmpty()) // don't use "if" due to spurious wakeups.
wait();
return buffer.remove();
}
}
This is what could potentially happen:
A consumer thread calls take()
and sees that the buffer.isEmpty()
.
Before the consumer thread goes on to call wait()
, a producer thread comes along and invokes a full give()
, that is, buffer.add(data); notify();
The consumer thread will now call wait()
(and miss the notify()
that was just called).
If unlucky, the producer thread won't produce more give()
as a result of the fact that the consumer thread never wakes up, and we have a dead-lock.
Once you understand the issue, the solution is obvious: Use synchronized
to make sure notify
is never called between isEmpty
and wait
.
Without going into details: This synchronization issue is universal. As Michael Borgwardt points out, wait/notify is all about communication between threads, so you'll always end up with a race condition similar to the one described above. This is why the "only wait inside synchronized" rule is enforced.
A paragraph from the link posted by @Willie summarizes it quite well:
You need an absolute guarantee that the waiter and the notifier agree about the state of the predicate. The waiter checks the state of the predicate at some point slightly BEFORE it goes to sleep, but it depends for correctness on the predicate being true WHEN it goes to sleep. There's a period of vulnerability between those two events, which can break the program.
The predicate that the producer and consumer need to agree upon is in the above example buffer.isEmpty()
. And the agreement is resolved by ensuring that the wait and notify are performed in synchronized
blocks.
This post has been rewritten as an article here: Java: Why wait must be called in a synchronized block
When connecting to postgres from command line, don't forget to add -h localhost
as command line parameter. If not, postgres will try to connect using PEER authentication mode.
The below shows a reset of the password, a failed login with PEER authentication and a successful login using a TCP connection.
# sudo -u postgres psql
could not change directory to "/root"
psql (9.1.11)
Type "help" for help.
postgres=# \password
Enter new password:
Enter it again:
postgres=# \q
Failing:
# psql -U postgres -W
Password for user postgres:
psql: FATAL: Peer authentication failed for user "postgres"
Working with -h localhost
:
# psql -U postgres -W -h localhost
Password for user postgres:
psql (9.1.11)
SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256)
Type "help" for help.
postgres=#
=VLOOKUP(LARGE(A1:A10,ROW()),A1:B10,2,0)
Type this formula in first row of your sheet then drag down till fifth row...
its a simple vlookup
, which finds the large
value in array (A1:A10)
, the ROW()
function gives the row number (first row = 1, second row =2 and so on) and further is the lookup criteria.
Note: You can replace the ROW()
to 1,2,3,4,5 as requried...if you have this formula in other than the 1st row, then make sure you subtract some numbers from the row()
to get accurate results.
EDIT: TO check tie results
This is possible, you need to add a helper column to the sheet, here is the link. Do let me know in case things seems to be messy....
If you have Pillow
installed with scipy
and it is still giving you error then check your scipy
version because it has been removed from scipy since 1.3.0rc1
.
rather install scipy 1.1.0
by :
pip install scipy==1.1.0
check https://github.com/scipy/scipy/issues/6212
The method imread
in scipy.misc
requires the forked package of PIL
named Pillow
. If you are having problem installing the right version of PIL try using imread
in other packages:
from matplotlib.pyplot import imread
im = imread(image.png)
To read jpg
images without PIL
use:
import cv2 as cv
im = cv.imread(image.jpg)
You can try
from scipy.misc.pilutil import imread
instead of from scipy.misc import imread
Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.
In-case if you unable to install specific package directly using PIP.
You can download a specific .whl
(wheel) package from - https://www.lfd.uci.edu/~gohlke/pythonlibs/
CD (Change directory) to that downloaded package and install it manually by -
pip install PACKAGENAME.whl
ex:
pip install ad3-2.1-cp27-cp27m-win32.whl
If you are considering using multidimensional arrays, then there is one additional difference between std::array and std::vector. A multidimensional std::array will have the elements packed in memory in all dimensions, just as a c style array is. A multidimensional std::vector will not be packed in all dimensions.
Given the following declarations:
int cConc[3][5];
std::array<std::array<int, 5>, 3> aConc;
int **ptrConc; // initialized to [3][5] via new and destructed via delete
std::vector<std::vector<int>> vConc; // initialized to [3][5]
A pointer to the first element in the c-style array (cConc) or the std::array (aConc) can be iterated through the entire array by adding 1 to each preceding element. They are tightly packed.
A pointer to the first element in the vector array (vConc) or the pointer array (ptrConc) can only be iterated through the first 5 (in this case) elements, and then there are 12 bytes (on my system) of overhead for the next vector.
This means that a std::vector> array initialized as a [3][1000] array will be much smaller in memory than one initialized as a [1000][3] array, and both will be larger in memory than a std:array allocated either way.
This also means that you can't simply pass a multidimensional vector (or pointer) array to, say, openGL without accounting for the memory overhead, but you can naively pass a multidimensional std::array to openGL and have it work out.
Usually this is caused by shell initialization files. Search for PATH=... entries.
You can also re-add RVM to your profile by running: rvm get stable --auto-dotfiles
To fix it temporarily in this shell session run: rvm use ruby-2.6.5
To ignore this error add "rvm_silence_path_mismatch_check_flag=1" to your "~/.rvmrc" file.
That question solved a quite similar question for me and I thought I should share :
In raw python you can use sum()
to count True
values in a list
:
>>> sum([True,True,True,False,False])
3
But this won't work :
>>> sum([[False, False, True], [True, False, True]])
TypeError...
In case of windows, I experienced a new stuff... stopping tomcat from /bin folder will immediately not releasing the port 8080. It takes around 5-10 mins to release the port. After 10 mins again if i try to run my project Run-> Run on server .. it allows to run.
I'm unsure whether my understanding is correct!
If you're doing a very simple GUI and you're already using Visual Studio then it may make sense to just go with MFC. You can just use the Visual Studio MFC wizard to create a dialog based application, drop two controls on it and away you go.
MFC is dated and has its fair share of annoyances, but it will certainly do the job for you if you're just talking about a button and a text box.
I don't have any experience with Qt, so I can't compare the two.
I use this function ... part of the regex comes from prestashop but I added some more bot to it.
public function isBot()
{
$bot_regex = '/BotLink|bingbot|AhrefsBot|ahoy|AlkalineBOT|anthill|appie|arale|araneo|AraybOt|ariadne|arks|ATN_Worldwide|Atomz|bbot|Bjaaland|Ukonline|borg\-bot\/0\.9|boxseabot|bspider|calif|christcrawler|CMC\/0\.01|combine|confuzzledbot|CoolBot|cosmos|Internet Cruiser Robot|cusco|cyberspyder|cydralspider|desertrealm, desert realm|digger|DIIbot|grabber|downloadexpress|DragonBot|dwcp|ecollector|ebiness|elfinbot|esculapio|esther|fastcrawler|FDSE|FELIX IDE|ESI|fido|H?m?h?kki|KIT\-Fireball|fouineur|Freecrawl|gammaSpider|gazz|gcreep|golem|googlebot|griffon|Gromit|gulliver|gulper|hambot|havIndex|hotwired|htdig|iajabot|INGRID\/0\.1|Informant|InfoSpiders|inspectorwww|irobot|Iron33|JBot|jcrawler|Teoma|Jeeves|jobo|image\.kapsi\.net|KDD\-Explorer|ko_yappo_robot|label\-grabber|larbin|legs|Linkidator|linkwalker|Lockon|logo_gif_crawler|marvin|mattie|mediafox|MerzScope|NEC\-MeshExplorer|MindCrawler|udmsearch|moget|Motor|msnbot|muncher|muninn|MuscatFerret|MwdSearch|sharp\-info\-agent|WebMechanic|NetScoop|newscan\-online|ObjectsSearch|Occam|Orbsearch\/1\.0|packrat|pageboy|ParaSite|patric|pegasus|perlcrawler|phpdig|piltdownman|Pimptrain|pjspider|PlumtreeWebAccessor|PortalBSpider|psbot|Getterrobo\-Plus|Raven|RHCS|RixBot|roadrunner|Robbie|robi|RoboCrawl|robofox|Scooter|Search\-AU|searchprocess|Senrigan|Shagseeker|sift|SimBot|Site Valet|skymob|SLCrawler\/2\.0|slurp|ESI|snooper|solbot|speedy|spider_monkey|SpiderBot\/1\.0|spiderline|nil|suke|http:\/\/www\.sygol\.com|tach_bw|TechBOT|templeton|titin|topiclink|UdmSearch|urlck|Valkyrie libwww\-perl|verticrawl|Victoria|void\-bot|Voyager|VWbot_K|crawlpaper|wapspider|WebBandit\/1\.0|webcatcher|T\-H\-U\-N\-D\-E\-R\-S\-T\-O\-N\-E|WebMoose|webquest|webreaper|webs|webspider|WebWalker|wget|winona|whowhere|wlm|WOLP|WWWC|none|XGET|Nederland\.zoek|AISearchBot|woriobot|NetSeer|Nutch|YandexBot|YandexMobileBot|SemrushBot|FatBot|MJ12bot|DotBot|AddThis|baiduspider|SeznamBot|mod_pagespeed|CCBot|openstat.ru\/Bot|m2e/i';
$userAgent = empty($_SERVER['HTTP_USER_AGENT']) ? FALSE : $_SERVER['HTTP_USER_AGENT'];
$isBot = !$userAgent || preg_match($bot_regex, $userAgent);
return $isBot;
}
Anyway take care that some bots uses browser like user agent to fake their identity
( I got many russian ip that has this behaviour on my site )
One distinctive feature of most of the bot is that they don't carry any cookie and so no session is attached to them.
( I am not sure how but this is for sure the best way to track them )
For the CTRL+C case, you can use this:
// Tell the system console to handle CTRL+C by calling our method that
// gracefully shuts down.
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
Console.WriteLine("Shutting down...");
// Cleanup here
System.Threading.Thread.Sleep(750);
}
Mr. Alien's answer is perfect, but anyway I don't recommend to use <div class="clear"></div>
because it just a hack which makes your markup dirty. This is useless empty div
in terms of bad structure and semantic, this also makes your code not flexible. In some browsers this div causes additional height and you have to add height: 0;
which even worse. But real troubles begin when you want to add background or border around your floated elements - it just will collapse because web was designed badly. I do recommend to wrap floated elements into container which has clearfix CSS rule. This is hack as well, but beautiful, more flexible to use and readable for human and SEO robots.
This can be done in a very simple way. Instead of setting the adapter using the built-in values (android.R.layout.simple_list_item_1), create your own xml layout for both TextView and DropDown, and use them. In the TextView layout, define Hint text and Hint color. Last step, create and empty item as the first item in the item array defined in Strings.
<string-array name="professional_qualification_array">
<item></item>
<item>B.Pharm</item>
<item>M.Pharm</item>
<item>PharmD</item>
</string-array>
Create XML layout for Spinner TextView (spnr_qualification.xml)
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:hint="Qualification"
android:textColorHint="@color/light_gray"
android:textColor="@color/blue_black" />
Create XML layout for spinner DropDown.(drpdn_qual.xml)
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="?android:attr/spinnerDropDownItemStyle"
android:maxLines="1"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:ellipsize="marquee"
android:textColor="#FFFFFF"/>
Define spinner in the main XML layout
<Spinner
android:id="@+id/spnQualification"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:paddingBottom="5dp"
android:paddingTop="5dp"
/>
And finally in the code, while setting adapter for the spinner, use your custom XML layout.
ArrayAdapter<CharSequence> qual_adapter = ArrayAdapter.createFromResource(this, R.array.professional_qualification_array,R.layout.spnr_qualification);
qual_adapter.setDropDownViewResource(R.layout.drpdn_qual);
spnQualification.setAdapter(qual_adapter)
.col-xs-2{
background:#00f;
color:#FFF;
}
.col-half-offset{
margin-left:4.166666667%
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="row" style="border: 1px solid red">
<div class="col-xs-4" id="p1">One</div>
<div class="col-xs-4 col-half-offset" id="p2">Two</div>
<div class="col-xs-4 col-half-offset" id="p3">Three</div>
<div>Test</div>
</div>
</div>
I faced this problem in a Framework7 & Cordova project. I tried all the solutions above. They did not solve my problem.
In my case, I was using 10+ css animations on the same page with infinite rotation (transform). I had to remove the animations. It is ok now with the lack of some visual features.
If the solutions above do not help you, you may start eliminating some animations.
Send your file as a base64 string.
var element = angular.element('<a/>');
element.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(atob(response.payload)),
target: '_blank',
download: fname
})[0].click();
If attr method not working in Firefox You can also use javaScript setAttribute method
Using "focus" will give keyboard users the same effect that mouse users get when they hover with a mouse. "Active" is needed to get the same effect in Internet Explorer.
The reality is, these states do not work as they should for all users. Not using all three selectors creates accessibility issues for many keyboard-only users who are physically unable to use a mouse. I invite you to take the #nomouse challenge (nomouse dot org).
I would rather keep my watchers a less as possible. My reason is based on my experiences and one might argue it theoretically.
The issue with using watchers is that you can use any property on scope to call any of the methods in any component or service you like.
In a real world project, pretty soon you'll end up with a non-tracable (better said hard to trace) chain of methods being called and values being changed which specially makes the on-boarding process tragic.
If using inline-blocks is an option I would recommend this approach:
.container {
/* fixed position a zero-height full width container */
position: fixed;
top: 0; /* or whatever position is desired */
left: 0;
right: 0;
height: 0;
/* center all inline content */
text-align: center;
}
.container > div {
/* make the block inline */
display: inline-block;
/* reset container's center alignment */
text-align: left;
}
I wrote a short post on this here: http://salomvary.github.com/position-fixed-horizontally-centered.html
That's because you're using a non-blocking
socket and the output buffer is full.
From the send()
man page
When the message does not fit into the send buffer of the socket,
send() normally blocks, unless the socket has been placed in non-block-
ing I/O mode. In non-blocking mode it would return EAGAIN in this
case.
EAGAIN is the error code tied to "Resource temporarily unavailable"
Consider using select()
to get a better control of this behaviours
in php
echo '<a href="' . $folder_path . '">Link text</a>';
or
<a href="<?=$folder_path?>">Link text</a>;
or
<a href="<?php echo $folder_path ?>">Link text</a>;
Assuming that your original dataset is similar to the one you created (i.e. with NA
as character
. You could specify na.strings
while reading the data using read.table
. But, I guess NAs would be detected automatically.
The price
column is factor
which needs to be converted to numeric
class. When you use as.numeric
, all the non-numeric elements (i.e. "NA"
, FALSE) gets coerced to NA
) with a warning.
library(dplyr)
df %>%
mutate(price=as.numeric(as.character(price))) %>%
group_by(company, year, product) %>%
summarise(total.count=n(),
count=sum(is.na(price)),
avg.price=mean(price,na.rm=TRUE),
max.price=max(price, na.rm=TRUE))
I am using the same dataset
(except the ...
row) that was showed.
df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
"Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
"7.12", "12.99", "10.99", "NA",FALSE)))
Try changing the second parameter in the SaveAs call to Excel.XlFileFormat.xlWorkbookDefault.
When I did that, I generated an xlsx file that I was able to successfully open. (Before making the change, I could produce an xlsx file, but I was unable to open it.)
Also, I'm not sure if it matters or not, but I'm using the Excel 12.0 object library.
There are many solutions, here's a few I've come up with:
int main(int nArgs, char ** vArgs)
{
vector<int> *v = new vector<int>(10);
v->at(2); //Retrieve using pointer to member
v->operator[](2); //Retrieve using pointer to operator member
v->size(); //Retrieve size
vector<int> &vr = *v; //Create a reference
vr[2]; //Normal access through reference
delete &vr; //Delete the reference. You could do the same with
//a pointer (but not both!)
}
You should implement the Comparator
interface.
example:
public class CustomComparator implements Comparator<CustomObject>
{
@Override
public int compare(CustomObject o1, CustomObject o2) {
return o1.getId().compareTo(o2.getId());
}
}
Then you can use the Collections classes Collections.sort()
method:
Collections.sort(list, new CustomComparator());
I managed to get the desired result, but with a slightly different approach. In the Dropdownlist i used the Model and then referenced it. Not sure if this was what you were looking for.
@Html.DropDownList("Example", new SelectList(Model.FeeStructures, "Id", "NameOfFeeStructure", Model.Matters.FeeStructures))
Model.Matters.FeeStructures in above is my id, which could be your value of the item that should be selected.
According to Microsoft's MSDN, the lock is equivalent to:
object __lockObj = x;
bool __lockWasTaken = false;
try
{
System.Threading.Monitor.Enter(__lockObj, ref __lockWasTaken);
// Your code...
}
finally
{
if (__lockWasTaken) System.Threading.Monitor.Exit(__lockObj);
}
If you need to create locks in runtime, you can use open source DynaLock. You can create new locks in run-time and specify boundaries to the locks with context concept.
DynaLock is open-source and source code is available at GitHub
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
This solution works for me (I was using 2.2 before). Also, I am using Java Based Configuration for Servlet 3.0 and no need to have web.xml file.
Yes, on Arrays.asList
, returning a fixed-size list.
Other than using a linked list, simply use addAll
method list.
Example:
String idList = "123,222,333,444";
List<String> parentRecepeIdList = new ArrayList<String>();
parentRecepeIdList.addAll(Arrays.asList(idList.split(",")));
parentRecepeIdList.add("555");
Go to preferences(settings) : click on Build,Execution,Deployment .....then select : Instant Run ......and uncheck its topmost checkbox (i.e Disable Instant Run)
It should probably be mentioned, that there are ways to omit bundle exec
(they are all stated in chapter 3.6.1 of Michael Hartls Ruby on Rails Tutorial book).
The simplest is to just use a sufficiently up-to-date version of RVM (>= 1.11.x).
If you're restricted to an earlier version of RVM, you can always use this method also mentioned by calasyr:
$ rvm get head && rvm reload
$ chmod +x $rvm_path/hooks/after_cd_bundler
$ bundle install --binstubs=./bundler_stubs
The bundler_stubs
directory should then also be added to the .gitignore
file.
A third option is to use the rubygems-bundler
gem if you're not using RVM:
$ gem install rubygems-bundler
$ gem regenerate_binstubs
In your concrete example the problem is that you don't use this construct correctly:
@JsonSubTypes({ @JsonSubTypes.Type(value = MyAbstractClass.class, name = "MyAbstractClass") })
@JsonSubTypes.Type
should contain the actual non-abstract subtypes of your abstract class.
Therefore if you have:
abstract class Parent
and the concrete subclasses
Ch1 extends Parent
and
Ch2 extends Parent
Then your annotation should look like:
@JsonSubTypes({
@JsonSubTypes.Type(value = Ch1.class, name = "ch1"),
@JsonSubTypes.Type(value = Ch2.class, name = "ch2")
})
Here name
should match the value of your 'discriminator':
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.WRAPPER_OBJECT,
property = "type")
in the property
field, here it is equal to type
. So type
will be the key and the value you set in name
will be the value.
Therefore, when the json string comes if it has this form:
{
"type": "ch1",
"other":"fields"
}
Jackson will automatically convert this to a Ch1
class.
If you send this:
{
"type": "ch2",
"other":"fields"
}
You would get a Ch2
instance.
I had been facing the similar problem in Windows 7 and got the below problems while running the android-studio shortcut from my start programs menu for the first time.
Solution : Run As Administrator
The problem was due to the write permission in Windows C:
drive and the Access is Denied
message is displayed. Running the program as administrator downloads all the necessary components and now I can start Android Studio IDE.
Update:
These permission issues doesn't seem to exist in Android Studio latest versions(checked in 1.3.2 in Windows 10) and works without the "Run as administrator" commands. If you still have the problem with the old/latest versions then it might be your firewall and proxy issues. In that case check out the other answers.
If you don't call the favicon, favicon.ico
, you can use that tag to specify the actual path (incase you have it in an images/
directory). The browser/webpage looks for favicon.ico
in the root directory by default.
Based on answer by @Cici I give here a more generic solution:
=SUM(INDIRECT(CONCATENATE(B1,C1)):INDIRECT(CONCATENATE(B2,C2)))
In Italian version of Excel:
=SOMMA(INDIRETTO(CONCATENA(B1;C1)):INDIRETTO(CONCATENA(B2;C2)))
Where B1-C2 cells hold these values:
You can change these valuese to change the final range at wish.
Splitting the formula in parts:
Hence:
=SUM(INDIRECT(CONCATENATE(B1,C1)):INDIRECT(CONCATENATE(B2,C2)))
results in
=SUM(A1:A5)
I'll write down here a couple of SEO keywords for Italian users:
Con la formula indicata qui sopra basta scrivere nelle caselle da B1 a C2 gli estremi dell'intervallo per vedelo cambiare dentro la formula stessa.
What you are trying to do can be simplified down to this.
$('input:text').bind('focus blur', function() {_x000D_
$(this).toggleClass('red');_x000D_
});
_x000D_
input{_x000D_
background:#FFFFEE;_x000D_
}_x000D_
.red{_x000D_
background-color:red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<form>_x000D_
<input class="calc_input" type="text" name="start_date" id="start_date" />_x000D_
<input class="calc_input" type="text" name="end_date" id="end_date" />_x000D_
<input class="calc_input" size="8" type="text" name="leap_year" id="leap_year" />_x000D_
</form>
_x000D_
For e.g. when a user has login.Now lets say the user want to create a forum topic, How will I know that the user is already logged in?
Think about it - there must be some handshake that tells your "Create Forum" API that this current request is from an authenticated user. Since REST APIs are typically stateless, the state must be persisted somewhere. Your client consuming the REST APIs is responsible for maintaining that state. Usually, it is in the form of some token that gets passed around since the time the user was logged in. If the token is good, your request is good.
Check how Amazon AWS does authentications. That's a perfect example of "passing the buck" around from one API to another.
*I thought of adding some practical response to my previous answer. Try Apache Shiro (or any authentication/authorization library). Bottom line, try and avoid custom coding. Once you have integrated your favorite library (I use Apache Shiro, btw) you can then do the following:
/api/v1/login
and api/v1/logout
JSESSIONID
) that is sent back to the client (web, mobile, whatever)/api/v1/findUser
That's all. Hope this helps.
If you use Fedora, in order to generate core dump file in the same directory of binary file:
echo "core.%e.%p" > /proc/sys/kernel/core_pattern
And
ulimit -c unlimited
Without make validation patterns, You can easily trim begin and end spaces using these modules.Try this.
https://www.npmjs.com/package/ngx-trim-directive https://www.npmjs.com/package/ng2-trim-directive
Thank you.
Select JoiningDate ,Dateadd (day , 30 , JoiningDate)
from Emp
Select JoiningDate ,DateAdd (month , 10 , JoiningDate)
from Emp
Select JoiningDate ,DateAdd (year , 10 , JoiningDate )
from Emp
Select DateAdd(Hour, 10 , JoiningDate )
from emp
Select dateadd (hour , 10 , getdate()), getdate()
Select dateadd (hour , 10 , joiningDate)
from Emp
Select DateAdd (Second , 120 , JoiningDate ) , JoiningDate
From EMP
According to the official documentation:
Optional target for this fragment. This may be used, for example, if this fragment is being started by another, and when done wants to give a result back to the first. The target set here is retained across instances via FragmentManager#putFragment.
Return the target fragment set by setTargetFragment(Fragment, int).
So you can do this:
// In your fragment
public class MyFragment extends Fragment implements OnClickListener {
private void showDialog() {
DialogFragment dialogFrag = MyDialogFragment.newInstance(this);
// Add this
dialogFrag.setTargetFragment(this, 0);
dialogFrag.show(getFragmentManager, null);
}
...
}
// then
public class MyialogFragment extends DialogFragment {
@Override
public void onAttach(Context context) {
super.onAttach(context);
// Then get it
Fragment fragment = getTargetFragment();
if (fragment instanceof OnClickListener) {
listener = (OnClickListener) fragment;
} else {
throw new RuntimeException("you must implement OnClickListener");
}
}
...
}
Set the method attribute to POST because file content can't be put inside a URL parameter using a form.
Set the value of enctype to multipart/form-data because the data will be split into multiple parts, one for each file plus one for the text of the form body that may be sent with them.
I believe that the dates have to be specified in the current culture of the application. You might want to experiment with setting CultureInvariantValues to true and see if that solves your problem. Otherwise you may need to change the DateTimeFormat for the current culture (or the culture itself) to get what you want.
jquery - Get the value in an input text box
<script type="text/javascript">
jQuery(document).ready(function(){
var classValues = jQuery(".cart tr").find("td.product-name").text();
classValues = classValues.replace(/[_\W]+/g, " ")
jQuery('input[name=your-p-name]').val(classValues);
//alert(classValues);
});
</script>
You can remove a specific event handler that was attached by on
, using off
$("#ID").on ("eventName", additionalCss, handlerFunction);
// to remove the specific handler
$("#ID").off ("eventName", additionalCss, handlerFunction);
Using this, you will remove only handlerFunction
Another good practice, is to set a nameSpace for multiple attached events
$("#ID").on ("eventName1.nameSpace", additionalCss, handlerFunction1);
$("#ID").on ("eventName2.nameSpace", additionalCss, handlerFunction2);
// ...
$("#ID").on ("eventNameN.nameSpace", additionalCss, handlerFunctionN);
// and to remove handlerFunction from 1 to N, just use this
$("#ID").off(".nameSpace");
You can do it on Internet explorer with OCX component and on chrome browser using a chrome extension chrome document in any case need additional settings on the client system!
Important part of chrome extension source:
var port = chrome.runtime.connectNative("your.app.id");
port.onMessage.addListener(onNativeMessage);
port.onDisconnect.addListener(onDisconnected);
port.postMessage("send some data to STDIO");
permission file:
{
"name": "your.app.id",
"description": "Name of your extension",
"path": "myapp.exe",
"type": "stdio",
"allowed_origins": [
"chrome-extension://IDOFYOUREXTENSION_lokldaeplkmh/"
]
}
and windows registry settings:
HKEY_CURRENT_USER\Software\Google\Chrome\NativeMessagingHosts\your.app.id
REG_EXPAND_SZ : c:\permissionsettings.json
re.search('<title>(.*)</title>', s, re.IGNORECASE).group(1)
netstat -ano | findstr :3010
taskkill /F /PID
But it won't work for me
then I tried taskkill -PID <processorid> -F
Example:- taskkill -PID 33192 -F
Here 33192 is the processorid and it works
Having the following XML:
<node>Text1<subnode/>text2</node>
How do I select either the first or the second text node via XPath?
Use:
/node/text()
This selects all text-node children of the top element (named "node") of the XML document.
/node/text()[1]
This selects the first text-node child of the top element (named "node") of the XML document.
/node/text()[2]
This selects the second text-node child of the top element (named "node") of the XML document.
/node/text()[someInteger]
This selects the someInteger-th text-node child of the top element (named "node") of the XML document. It is equivalent to the following XPath expression:
/node/text()[position() = someInteger]
Set the CommandText
as well, and call Fill
on the SqlAdapter
to retrieve the results in a DataSet
:
var con = new SqlConnection();
con.ConnectionString = "connection string";
var com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "sp_returnTable";
var adapt = new SqlDataAdapter();
adapt.SelectCommand = com;
var dataset = new DataSet();
adapt.Fill(dataset);
(Example is using parameterless constructors for clarity; can be shortened by using other constructors.)
Fast way to get External ip without any connection Actualy no need any Http connection for that
first you must add NATUPNPLib.dll on Referance And select it from referances and check from properties window Embed Interop Type to False
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NATUPNPLib; // Add this dll from referance and chande Embed Interop Interop to false from properties panel on visual studio
using System.Net;
namespace Client
{
class NATTRAVERSAL
{
//This is code for get external ip
private void NAT_TRAVERSAL_ACT()
{
UPnPNATClass uPnP = new UPnPNATClass();
IStaticPortMappingCollection map = uPnP.StaticPortMappingCollection;
foreach (IStaticPortMapping item in map)
{
Debug.Print(item.ExternalIPAddress); //This line will give you external ip as string
break;
}
}
}
}
This should work:
// Gets linearlayout
LinearLayout layout = findViewById(R.id.numberPadLayout);
// Gets the layout params that will allow you to resize the layout
LayoutParams params = layout.getLayoutParams();
// Changes the height and width to the specified *pixels*
params.height = 100;
params.width = 100;
layout.setLayoutParams(params);
If you want to convert dip to pixels, use this:
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, <HEIGHT>, getResources().getDisplayMetrics());
I had the same problem a few weeks ago like yours; but I invented a brilliant solution for exchanging variables between PHP and JavaScript. It worked for me well:
Create a hidden form on a HTML page
Create a Textbox or Textarea in that hidden form
After all of your code written in the script, store the final value of your variable in that textbox
Use $_REQUEST['textbox name'] line in your PHP to gain access to value of your JavaScript variable.
I hope this trick works for you.
Based on this answer and this answer. I've created a public gist
How it can be used
let boolean: Bool = UIDevice.isDevice(ofType: .iPhoneX)
// true or false
let specificDevice: DeviceModel.Model = UIDevice.modelType
// iPhone6s, iPhoneX, iPad etc...
let model: DeviceModel = UIDevice.model
// .simulator(let specificDevice), .real(let specificDevice),
// .unrecognizedSimulator(let string), .unrecognized(let string)
let modelName: String = UIDevice.model.name
// iPhone 6, iPhone X, etc...
This is the code inside the gist
public extension UIDevice {
public static var modelCode: String {
if let simulatorModelIdentifier = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] { return simulatorModelIdentifier }
var systemInfo = utsname()
uname(&systemInfo)
return withUnsafeMutablePointer(to: &systemInfo.machine) {
ptr in String(cString: UnsafeRawPointer(ptr).assumingMemoryBound(to: CChar.self))
}
}
public static var model: DeviceModel {
// Thanks https://stackoverflow.com/a/26962452/5928180
var systemInfo = utsname()
uname(&systemInfo)
let modelCode = withUnsafeMutablePointer(to: &systemInfo.machine) {
ptr in String(cString: UnsafeRawPointer(ptr).assumingMemoryBound(to: CChar.self))
}
// Thanks https://stackoverflow.com/a/33495869/5928180
if modelCode == "i386" || modelCode == "x86_64" {
if let simulatorModelCode = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"], let model = DeviceModel.Model(modelCode: simulatorModelCode) {
return DeviceModel.simulator(model)
} else if let simulatorModelCode = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] {
return DeviceModel.unrecognizedSimulator(simulatorModelCode)
} else {
return DeviceModel.unrecognized(modelCode)
}
} else if let model = DeviceModel.Model(modelCode: modelCode) {
return DeviceModel.real(model)
} else {
return DeviceModel.unrecognized(modelCode)
}
}
public static var modelType: DeviceModel.Model? {
return UIDevice.model.model
}
public static func isDevice(ofType model: DeviceModel.Model) -> Bool {
return UIDevice.modelType == model
}
}
public enum DeviceModel {
case simulator(Model)
case unrecognizedSimulator(String)
case real(Model)
case unrecognized(String)
public enum Model: String {
case iPod1 = "iPod 1"
case iPod2 = "iPod 2"
case iPod3 = "iPod 3"
case iPod4 = "iPod 4"
case iPod5 = "iPod 5"
case iPad2 = "iPad 2"
case iPad3 = "iPad 3"
case iPad4 = "iPad 4"
case iPhone4 = "iPhone 4"
case iPhone4S = "iPhone 4S"
case iPhone5 = "iPhone 5"
case iPhone5S = "iPhone 5S"
case iPhone5C = "iPhone 5C"
case iPadMini1 = "iPad Mini 1"
case iPadMini2 = "iPad Mini 2"
case iPadMini3 = "iPad Mini 3"
case iPadAir1 = "iPad Air 1"
case iPadAir2 = "iPad Air 2"
case iPadPro9_7 = "iPad Pro 9.7\""
case iPadPro9_7_cell = "iPad Pro 9.7\" cellular"
case iPadPro10_5 = "iPad Pro 10.5\""
case iPadPro10_5_cell = "iPad Pro 10.5\" cellular"
case iPadPro12_9 = "iPad Pro 12.9\""
case iPadPro12_9_cell = "iPad Pro 12.9\" cellular"
case iPhone6 = "iPhone 6"
case iPhone6plus = "iPhone 6 Plus"
case iPhone6S = "iPhone 6S"
case iPhone6Splus = "iPhone 6S Plus"
case iPhoneSE = "iPhone SE"
case iPhone7 = "iPhone 7"
case iPhone7plus = "iPhone 7 Plus"
case iPhone8 = "iPhone 8"
case iPhone8plus = "iPhone 8 Plus"
case iPhoneX = "iPhone X"
init?(modelCode: String) {
switch modelCode {
case "iPod1,1": self = .iPod1
case "iPod2,1": self = .iPod2
case "iPod3,1": self = .iPod3
case "iPod4,1": self = .iPod4
case "iPod5,1": self = .iPod5
case "iPad2,1": self = .iPad2
case "iPad2,2": self = .iPad2
case "iPad2,3": self = .iPad2
case "iPad2,4": self = .iPad2
case "iPad2,5": self = .iPadMini1
case "iPad2,6": self = .iPadMini1
case "iPad2,7": self = .iPadMini1
case "iPhone3,1": self = .iPhone4
case "iPhone3,2": self = .iPhone4
case "iPhone3,3": self = .iPhone4
case "iPhone4,1": self = .iPhone4S
case "iPhone5,1": self = .iPhone5
case "iPhone5,2": self = .iPhone5
case "iPhone5,3": self = .iPhone5C
case "iPhone5,4": self = .iPhone5C
case "iPad3,1": self = .iPad3
case "iPad3,2": self = .iPad3
case "iPad3,3": self = .iPad3
case "iPad3,4": self = .iPad4
case "iPad3,5": self = .iPad4
case "iPad3,6": self = .iPad4
case "iPhone6,1": self = .iPhone5S
case "iPhone6,2": self = .iPhone5S
case "iPad4,1": self = .iPadAir1
case "iPad4,2": self = .iPadAir2
case "iPad4,4": self = .iPadMini2
case "iPad4,5": self = .iPadMini2
case "iPad4,6": self = .iPadMini2
case "iPad4,7": self = .iPadMini3
case "iPad4,8": self = .iPadMini3
case "iPad4,9": self = .iPadMini3
case "iPad6,3": self = .iPadPro9_7
case "iPad6,11": self = .iPadPro9_7
case "iPad6,4": self = .iPadPro9_7_cell
case "iPad6,12": self = .iPadPro9_7_cell
case "iPad6,7": self = .iPadPro12_9
case "iPad6,8": self = .iPadPro12_9_cell
case "iPad7,3": self = .iPadPro10_5
case "iPad7,4": self = .iPadPro10_5_cell
case "iPhone7,1": self = .iPhone6plus
case "iPhone7,2": self = .iPhone6
case "iPhone8,1": self = .iPhone6S
case "iPhone8,2": self = .iPhone6Splus
case "iPhone8,4": self = .iPhoneSE
case "iPhone9,1": self = .iPhone7
case "iPhone9,2": self = .iPhone7plus
case "iPhone9,3": self = .iPhone7
case "iPhone9,4": self = .iPhone7plus
case "iPhone10,1": self = .iPhone8
case "iPhone10,2": self = .iPhone8plus
case "iPhone10,3": self = .iPhoneX
case "iPhone10,6": self = .iPhoneX
default: return nil
}
}
}
public var name: String {
switch self {
case .simulator(let model): return "Simulator[\(model.rawValue)]"
case .unrecognizedSimulator(let s): return "UnrecognizedSimulator[\(s)]"
case .real(let model): return model.rawValue
case .unrecognized(let s): return "Unrecognized[\(s)]"
}
}
public var model: DeviceModel.Model? {
switch self {
case .simulator(let model): return model
case .real(let model): return model
case .unrecognizedSimulator(_): return nil
case .unrecognized(_): return nil
}
}
}
In my case the form (which I cannot modify) was always sending POST.
While in my Web Service I tried to implement GET method (due to lack of documentation I expected that both are allowed).
Thus, it was failing as "Not allowed", since there was no method with POST type on my end.
Changing @GET
to @POST
above my WS method fixed the issue.
At the bottommost right look at the blue line where Ln, Col, Spaces, UTF, CRLF,..... here the language is specified. Check that your language and the language specified there are the same. In my case, it was Django Python while I was trying to use HTML.
You may try like this:
import java.applet.Applet;
import java.awt.*;
public class Rect1 extends Applet {
public void paint (Graphics g) {
g.drawRect (x, y, width, height); //can use either of the two//
g.fillRect (x, y, width, height);
g.setColor(color);
}
}
where x is x co-ordinate y is y cordinate color=the color you want to use eg Color.blue
if you want to use rectangle object you could do it like this:
import java.applet.Applet;
import java.awt.*;
public class Rect1 extends Applet {
public void paint (Graphics g) {
Rectangle r = new Rectangle(arg,arg1,arg2,arg3);
g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());
g.setColor(color);
}
}
You can try df.column_name = df.column_name.astype(float)
. As for the NaN
values, you need to specify how they should be converted, but you can use the .fillna
method to do it.
Example:
In [12]: df
Out[12]:
a b
0 0.1 0.2
1 NaN 0.3
2 0.4 0.5
In [13]: df.a.values
Out[13]: array(['0.1', nan, '0.4'], dtype=object)
In [14]: df.a = df.a.astype(float).fillna(0.0)
In [15]: df
Out[15]:
a b
0 0.1 0.2
1 0.0 0.3
2 0.4 0.5
In [16]: df.a.values
Out[16]: array([ 0.1, 0. , 0.4])
A simple method: enable logging in recent versions of Requests (1.x and higher.)
Requests uses the http.client
and logging
module configuration to control logging verbosity, as described here.
Code excerpted from the linked documentation:
import requests
import logging
# These two lines enable debugging at httplib level (requests->urllib3->http.client)
# You will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.
# The only thing missing will be the response.body which is not logged.
try:
import http.client as http_client
except ImportError:
# Python 2
import httplib as http_client
http_client.HTTPConnection.debuglevel = 1
# You must initialize logging, otherwise you'll not see debug output.
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
requests.get('https://httpbin.org/headers')
$ python requests-logging.py
INFO:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): httpbin.org
send: 'GET /headers HTTP/1.1\r\nHost: httpbin.org\r\nAccept-Encoding: gzip, deflate, compress\r\nAccept: */*\r\nUser-Agent: python-requests/1.2.0 CPython/2.7.3 Linux/3.2.0-48-generic\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Content-Type: application/json
header: Date: Sat, 29 Jun 2013 11:19:34 GMT
header: Server: gunicorn/0.17.4
header: Content-Length: 226
header: Connection: keep-alive
DEBUG:requests.packages.urllib3.connectionpool:"GET /headers HTTP/1.1" 200 226
Here is another seamless approach to convert JSON to Datatable using Cinchoo ETL - an open source library
Sample below shows how to convert
string json = @"[
{""id"":""10"",""name"":""User"",""add"":false,""edit"":true,""authorize"":true,""view"":true},
{ ""id"":""11"",""name"":""Group"",""add"":true,""edit"":false,""authorize"":false,""view"":true},
{ ""id"":""12"",""name"":""Permission"",""add"":true,""edit"":true,""authorize"":true,""view"":true}
]";
using (var r = ChoJSONReader.LoadText(json))
{
var dt = r.AsDataTable();
}
Hope it helps.
Look at the types of those properties:
In [1]: import datetime
In [2]: d = datetime.date.today()
In [3]: type(d.month)
Out[3]: <type 'int'>
In [4]: type(d.day)
Out[4]: <type 'int'>
Both are integers. So there is no automatic way to do what you want. So in the narrow sense, the answer to your question is no.
If you want leading zeroes, you'll have to format them one way or another. For that you have several options:
In [5]: '{:02d}'.format(d.month)
Out[5]: '03'
In [6]: '%02d' % d.month
Out[6]: '03'
In [7]: d.strftime('%m')
Out[7]: '03'
In [8]: f'{d.month:02d}'
Out[8]: '03'
Eclipse is a runtime environment for plugins. Virtually everything you see in Eclipse is the result of plugins installed on Eclipse, rather than Eclipse itself.
The .project
file is maintained by the core Eclipse platform, and its goal is to describe the project from a generic, plugin-independent Eclipse view. What's the project's name? what other projects in the workspace does it refer to? What are the builders that are used in order to build the project? (remember, the concept of "build" doesn't pertain specifically to Java projects, but also to other types of projects)
The .classpath
file is maintained by Eclipse's JDT feature (feature = set of plugins). JDT holds multiple such "meta" files in the project (see the .settings
directory inside the project); the .classpath
file is just one of them. Specifically, the .classpath
file contains information that the JDT feature needs in order to properly compile the project: the project's source folders (that is, what to compile); the output folders (where to compile to); and classpath entries (such as other projects in the workspace, arbitrary JAR files on the file system, and so forth).
Blindly copying such files from one machine to another may be risky. For example, if arbitrary JAR files are placed on the classpath (that is, JAR files that are located outside the workspace and are referred-to by absolute path naming), the .classpath
file is rendered non-portable and must be modified in order to be portable. There are certain best practices that can be followed to guarantee .classpath
file portability.
Use setMaxDate()
.
For example, replace return new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay)
statement with something like this:
DatePickerDialog dialog = new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
dialog.getDatePicker().setMaxDate(new Date().getTime());
return dialog;
There are several details you need to 'match up' with for a particular CRC implementation - even using the same polynomial there can be different results because of minor differences in how data bits are handled, using a particular initial value for the CRC (sometimes it's zero, sometimes 0xffff), and/or inverting the bits of the CRC. For example, sometimes one implementation will work from the low order bits of the data bytes up, while sometimes they'll work from the high order bits down (as yours currently does).
Also, you need to 'push out' the last bits of the CRC after you've run all the data bits through.
Keep in mind that CRC algorithms were designed to be implemented in hardware, so some of how bit ordering is handled may not make so much sense from a software point of view.
If you want to match the CRC16 with polynomial 0x8005 as shown on the lammertbies.nl CRC calculator page, you need to make the following changes to your CRC function:
So, your function might look like:
#define CRC16 0x8005
uint16_t gen_crc16(const uint8_t *data, uint16_t size)
{
uint16_t out = 0;
int bits_read = 0, bit_flag;
/* Sanity check: */
if(data == NULL)
return 0;
while(size > 0)
{
bit_flag = out >> 15;
/* Get next bit: */
out <<= 1;
out |= (*data >> bits_read) & 1; // item a) work from the least significant bits
/* Increment bit counter: */
bits_read++;
if(bits_read > 7)
{
bits_read = 0;
data++;
size--;
}
/* Cycle check: */
if(bit_flag)
out ^= CRC16;
}
// item b) "push out" the last 16 bits
int i;
for (i = 0; i < 16; ++i) {
bit_flag = out >> 15;
out <<= 1;
if(bit_flag)
out ^= CRC16;
}
// item c) reverse the bits
uint16_t crc = 0;
i = 0x8000;
int j = 0x0001;
for (; i != 0; i >>=1, j <<= 1) {
if (i & out) crc |= j;
}
return crc;
}
That function returns 0xbb3d
for me when I pass in "123456789"
.
The Issue is with pip --version or python --version.
try solving issue with pip2.7 uninstall Django
command
If you are not able to uninstall using the above command then for sure your pip2.7 version is not installed so you can follow the below steps:
1)which pip2.7
it should give you an output like this :
/usr/local/bin/pip2.7
2) If you have not got this output please install pip using following commands
$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python2.7 get-pip.py
3) Now check your pip version : which pip2.7
Now you will get
/usr/local/bin/pip2.7 as output
4) uninstall Django using pip2.7 uninstall Django
command.
Problem can also be related to Python version. I had a similar problem, this is how I uninstalled Django.
Issue occurred because I had multiple python installed in my virtual environment.
$ ls
activate activate_this.py easy_install-3.4 pip2.7 python python3 wheel
activate.csh easy_install pip pip3 python2 python3.4
activate.fish easy_install-2.7 pip2 pip3.4 python2.7 python-config
Now when I tried to un-install using pip uninstall Django
Django got uninstalled from python 2.7 but not from python 3.4 so I followed the following steps to resolve the issue :
1)alias python=/usr/bin/python3
2) Now check your python version using python -V
command
3) If you have switched to your required python version now you can simply uninstall Django using pip3 uninstall Django
command
Hope this answer helps.
img {
max-width:100%;
}
div {
width:100px;
}
with this snippet you can do it in a more efficient way
Try using the not-null assertion operator...
queue.add(left!!)
There's a faster way to do that:
Arrays.hashCode(arr1) == Arrays.hashCode(arr2)
This is my LDAP Java login test application supporting LDAP:// and LDAPS:// self-signed test certificate. Code is taken from few SO posts, simplified implementation and removed legacy sun.java.* imports.
Usage
I have run this in Windows7 and Linux machines against WinAD directory service. Application prints username and member groups.
$ java -cp classes test.LoginLDAP url=ldap://1.2.3.4:389 [email protected] password=mypwd
$ java -cp classes test.LoginLDAP url=ldaps://1.2.3.4:636 [email protected] password=mypwd
Test application supports temporary self-signed test certificates for ldaps:// protocol, this DummySSLFactory accepts any server cert so man-in-the-middle is possible. Real life installation should import server certificate to a local JKS keystore file and not using dummy factory.
Application uses enduser's username+password for initial context and ldap queries, it works for WinAD but don't know if can be used for all ldap server implementations. You could create context with internal username+pwd then run queries to see if given enduser is found.
LoginLDAP.java
package test;
import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;
public class LoginLDAP {
public static void main(String[] args) throws Exception {
Map<String,String> params = createParams(args);
String url = params.get("url"); // ldap://1.2.3.4:389 or ldaps://1.2.3.4:636
String principalName = params.get("username"); // [email protected]
String domainName = params.get("domain"); // mydomain.com or empty
if (domainName==null || "".equals(domainName)) {
int delim = principalName.indexOf('@');
domainName = principalName.substring(delim+1);
}
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, url);
props.put(Context.SECURITY_PRINCIPAL, principalName);
props.put(Context.SECURITY_CREDENTIALS, params.get("password")); // secretpwd
if (url.toUpperCase().startsWith("LDAPS://")) {
props.put(Context.SECURITY_PROTOCOL, "ssl");
props.put(Context.SECURITY_AUTHENTICATION, "simple");
props.put("java.naming.ldap.factory.socket", "test.DummySSLSocketFactory");
}
InitialDirContext context = new InitialDirContext(props);
try {
SearchControls ctrls = new SearchControls();
ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> results = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", ctrls);
if(!results.hasMore())
throw new AuthenticationException("Principal name not found");
SearchResult result = results.next();
System.out.println("distinguisedName: " + result.getNameInNamespace() ); // CN=Firstname Lastname,OU=Mycity,DC=mydomain,DC=com
Attribute memberOf = result.getAttributes().get("memberOf");
if(memberOf!=null) {
for(int idx=0; idx<memberOf.size(); idx++) {
System.out.println("memberOf: " + memberOf.get(idx).toString() ); // CN=Mygroup,CN=Users,DC=mydomain,DC=com
//Attribute att = context.getAttributes(memberOf.get(idx).toString(), new String[]{"CN"}).get("CN");
//System.out.println( att.get().toString() ); // CN part of groupname
}
}
} finally {
try { context.close(); } catch(Exception ex) { }
}
}
/**
* Create "DC=sub,DC=mydomain,DC=com" string
* @param domainName sub.mydomain.com
* @return
*/
private static String toDC(String domainName) {
StringBuilder buf = new StringBuilder();
for (String token : domainName.split("\\.")) {
if(token.length()==0) continue;
if(buf.length()>0) buf.append(",");
buf.append("DC=").append(token);
}
return buf.toString();
}
private static Map<String,String> createParams(String[] args) {
Map<String,String> params = new HashMap<String,String>();
for(String str : args) {
int delim = str.indexOf('=');
if (delim>0) params.put(str.substring(0, delim).trim(), str.substring(delim+1).trim());
else if (delim==0) params.put("", str.substring(1).trim());
else params.put(str, null);
}
return params;
}
}
And SSL helper class.
package test;
import java.io.*;
import java.net.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.*;
import javax.net.ssl.*;
public class DummySSLSocketFactory extends SSLSocketFactory {
private SSLSocketFactory socketFactory;
public DummySSLSocketFactory() {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{ new DummyTrustManager()}, new SecureRandom());
socketFactory = ctx.getSocketFactory();
} catch ( Exception ex ){ throw new IllegalArgumentException(ex); }
}
public static SocketFactory getDefault() { return new DummySSLSocketFactory(); }
@Override public String[] getDefaultCipherSuites() { return socketFactory.getDefaultCipherSuites(); }
@Override public String[] getSupportedCipherSuites() { return socketFactory.getSupportedCipherSuites(); }
@Override public Socket createSocket(Socket socket, String string, int i, boolean bln) throws IOException {
return socketFactory.createSocket(socket, string, i, bln);
}
@Override public Socket createSocket(String string, int i) throws IOException, UnknownHostException {
return socketFactory.createSocket(string, i);
}
@Override public Socket createSocket(String string, int i, InetAddress ia, int i1) throws IOException, UnknownHostException {
return socketFactory.createSocket(string, i, ia, i1);
}
@Override public Socket createSocket(InetAddress ia, int i) throws IOException {
return socketFactory.createSocket(ia, i);
}
@Override public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException {
return socketFactory.createSocket(ia, i, ia1, i1);
}
}
class DummyTrustManager implements X509TrustManager {
@Override public void checkClientTrusted(X509Certificate[] xcs, String str) {
// do nothing
}
@Override public void checkServerTrusted(X509Certificate[] xcs, String str) {
/*System.out.println("checkServerTrusted for authType: " + str); // RSA
for(int idx=0; idx<xcs.length; idx++) {
X509Certificate cert = xcs[idx];
System.out.println("X500Principal: " + cert.getSubjectX500Principal().getName());
}*/
}
@Override public X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
}
Your Ubuntu definitely has a sufficiently recent version of g++
. The flag to use is -std=c++0x
.
in public static void main(String args[]) args is an array of console line argument whose data type is String. in this array, you can store various string arguments by invoking them at the command line as shown below: java myProgram Shaan Royal then Shaan and Royal will be stored in the array as arg[0]="Shaan"; arg[1]="Royal"; you can do this manually also inside the program, when you don't call them at the command line.
systeminfo
is a command that will output system information, including available memory
I was tryng to rename
the folder within the visual studio community 2019 and could not find it.
However, I figured out that while the code is running you can not change the name of the folder
.
The answer is:
rename
name will be there.Conceptually there are the two "domains" classes and interfaces. Inside these domains you are always extending, only a class implements an interface, which is kind of "crossing the border". So basically "extends" for interfaces mirrors the behavior for classes. At least I think this is the logic behind. It seems than not everybody agrees with this kind of logic (I find it a little bit contrived myself), and in fact there is no technical reason to have two different keywords at all.
Easiest solution for this to remove the index.php code which is allocated on
xammp-> htdocs-> index.php
you can delete the code of this page to solution your problem but have another way which is .htaccss file. Some time you show this problem because of have some issue or miss code on .htaccss file thas way yo saw the xammp dashboard every time. Hop it will resolve your problem. Happy Coding and Good Luck
If you just want to change alignment of text just make a classes
.left {
text-align: left;
}
and span that class through the text
<span class='left'>aligned left</span>
How was the database exported?
If it was exported using exp
and a full schema was exported, then
Create the user:
create user <username> identified by <password> default tablespace <tablespacename> quota unlimited on <tablespacename>;
Grant the rights:
grant connect, create session, imp_full_database to <username>;
Start the import with imp
:
imp <username>/<password>@<hostname> file=<filename>.dmp log=<filename>.log full=y;
If it was exported using expdp
, then start the import with impdp
:
impdp <username>/<password> directory=<directoryname> dumpfile=<filename>.dmp logfile=<filename>.log full=y;
Looking at the error log, it seems you have not specified the directory, so Oracle tries to find the dmp
file in the default directory (i.e., E:\app\Vensi\admin\oratest\dpdump\
).
Either move the export file to the above path or create a directory object to pointing to the path where the dmp
file is present and pass the object name to the impdp
command above.
In addition to what have been said, the bind()
method allows an object to borrow a method from another object without making a copy of that method. This is known as function borrowing in JavaScript.
import (the name of the file without the extension)
Installing modules usually requires you to run an sql script that is included with the database installation.
Assuming linux-like OS
find / -name dblink.sql
Verify the location and run it
For me, eclipse was looking in the wrong place for the SDK Manager. To fix this I did
NOTE: The SDK manager tells you what dir it is using near the top of the UI.
I had installed a new version of eclipse that has the ADT bundled up from the Android developer site, but when I opened eclipse it was looking at the old SDK.exe location.
hth
For some odd reason this part
$el.empty(); // remove old options
from CMS solution didn't work for me, so instead of that I've simply used this
el.html(' ');
And it's works. So my working code now looks like that:
var newOptions = {
"Option 1":"option-1",
"Option 2":"option-2"
};
var $el = $('.selectClass');
$el.html(' ');
$.each(newOptions, function(key, value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
This is how I solved it:
Vagrantfile
(this is the config file)This solved my problem, I found out, that the firewall blocked all IPs from local networks like 192.168.x.x and 10.x.x.x
Adding a rule in /etc/iptables.d/199-allow-wan
to allow all connections from wan:
ip46tables -A wan-input -j ACCEPT
(ip46tables is an alias) see this commit in my Vagrant example Freifunk community
This works in Linux & Windows:
Python 3.x
>>> import sys
>>> print(sys.executable)
C:\path\to\python.exe
Python 2.x
>>> import sys
>>> print sys.executable
/usr/bin/python
Reserved.objects.filter(client=client_id).earliest('check_in')
Or alternatively
Reserved.objects.filter(client=client_id).latest('-check_in')
Here is the documentations for earliest()
and latest()
The correct answer is increasing fastcgi_read_timeout in your Nginx configuration.
Simple as that!
Another alternative to do the same thing is to filter on type=checkbox attribute:
$('input[type="checkbox"]').removeAttr('checked');
or
$('input[type="checkbox"]').prop('checked' , false);
Remeber that The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.
Know more...
find . -type f -name '*php' -o -name '*js' -o -name '*html' |\
xargs grep -liE 'document\.cookie|setcookie'
This works fine for me:
NB I'm using BEM/OCSS SCSS Syntax
#navigation{
li{
&:after{
content: '|'; // use content for box-sizing
text-indent: -999999px; // Hide the content
display: block;
float: right; // Position
width: 1px;
height: 100%; // The 100% of parent (li)
background: black; // The color
margin: {
left: 5px;
right: 5px;
}
}
&:last-child{
&:after{
content: none;
}
}
}
}
use pd.to_numeric()
df["DateColumn"] = pd.to_numeric(df["DateColumn"])
simple and clean
Just another alternative if anyone cares.
You can also use the to_set
method of an array which converts the Array into a Set and by definition, set elements are unique.
[1,2,3,4,5,5,5,6].to_set => [1,2,3,4,5,6]
In addition to what Tichodroma said, you might end up using this syntax:
outputString=$(python myPythonScript arg1 arg2 arg3)
Using np.ix_
is the most convenient way to do it (as answered by others), but here is another interesting way to do it:
>>> rows = [0, 1, 3]
>>> cols = [0, 2]
>>> a[rows].T[cols].T
array([[ 0, 2],
[ 4, 6],
[12, 14]])
If you have multiple subplots, i.e.
fig, ax = plt.subplots(4, 2)
You can use the same y limits for all of them. It gets limits of y ax from first plot.
plt.setp(ax, ylim=ax[0,0].get_ylim())
Try This below method code to get the distance in meter between two location, hope it will help for you
public static double distance(LatLng start, LatLng end){
try {
Location location1 = new Location("locationA");
location1.setLatitude(start.latitude);
location1.setLongitude(start.longitude);
Location location2 = new Location("locationB");
location2.setLatitude(end.latitude);
location2.setLongitude(end.longitude);
double distance = location1.distanceTo(location2);
return distance;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
You should leave out the domain http://example.com
in ProxyPass and ProxyPassReverse and leave it as /
. Additionally, you need to leave the /
at the end of example/
to where it is redirecting. Also, I had some trouble with http://example.com
vs. http://www.example.com
- only the www worked until I made the ServerName www.example.com, and the ServerAlias example.com. Give the following a go.
<VirtualHost *:80>
ProxyPreserveHost On
ProxyRequests Off
ServerName www.example.com
ServerAlias example.com
ProxyPass / http://localhost:8080/example/
ProxyPassReverse / http://localhost:8080/example/
</VirtualHost>
After you make these changes, add the needed modules and restart apache
sudo a2enmod proxy && sudo a2enmod proxy_http && sudo service apache2 restart
Add second parameter
You need to pass additional parameter to your function:
function parts($site_url, $part) {
$structure = 'http://' . $site_url . 'content/';
echo $structure . $part . '.php';
}
In case of closures
If you'd rather use closures then you can import variable to the current scope (the use
keyword):
$parts = function($part) use ($site_url) {
$structure = 'http://' . $site_url . 'content/';
echo $structure . $part . '.php';
};
global
- a bad practice
This post is frequently read, so something needs to be clarified about global
. Using it is considered a bad practice (refer to this and this).
For the completeness sake here is the solution using global
:
function parts($part) {
global $site_url;
$structure = 'http://' . $site_url . 'content/';
echo($structure . $part . '.php');
}
It works because you have to tell interpreter that you want to use a global variable, now it thinks it's a local variable (within your function).
Suggested reading:
You can use the following time conversion within SQL like this:
--Convert Time to Integer (Minutes)
DECLARE @timeNow datetime = '14:47'
SELECT DATEDIFF(mi,CONVERT(datetime,'00:00',108), CONVERT(datetime, RIGHT(CONVERT(varchar, @timeNow, 100),7),108))
--Convert Minutes to Time
DECLARE @intTime int = (SELECT DATEDIFF(mi,CONVERT(datetime,'00:00',108), CONVERT(datetime, RIGHT(CONVERT(varchar, @timeNow, 100),7),108)))
SELECT DATEADD(minute, @intTime, '')
Result: 887 <- Time in minutes and 1900-01-01 14:47:00.000 <-- Minutes to time
When thread tA call tB.join() its causes not only waits for tB to die or tA be interrupted itself but create happens-before relation between last statement in tB and next statement after tB.join() in tA thread.
It means program
class App {
// shared, not synchronized variable = bad practice
static int sharedVar = 0;
public static void main(String[] args) throws Exception {
Thread threadB = new Thread(() -> {sharedVar = 1;});
threadB.start();
threadB.join();
while (true)
System.out.print(sharedVar);
}
}
Always print
>> 1111111111111111111111111 ...
But program
class App {
// shared, not synchronized variable = bad practice
static int sharedVar = 0;
public static void main(String[] args) throws Exception {
Thread threadB = new Thread(() -> {sharedVar = 1;});
threadB.start();
// threadB.join(); COMMENT JOIN
while (true)
System.out.print(sharedVar);
}
}
Can print not only
>> 0000000000 ... 000000111111111111111111111111 ...
But
>> 00000000000000000000000000000000000000000000 ...
Always only '0'.
Because Java Memory Model don't require 'transfering' new value of 'sharedVar' from threadB to main thread without heppens-before relation (thread start, thread join, usage of 'synchonized' keyword, usage of AtomicXXX variables, etc).
this is a solution using mshtml
IHTMLDocument2 doc = new HTMLDocumentClass();
doc.write(new object[] { File.ReadAllText(filePath) });
doc.close();
IHTMLElement head = (IHTMLElement)((IHTMLElementCollection)doc.all.tags("head")).item(null, 0);
IHTMLScriptElement scriptObject = (IHTMLScriptElement)doc.createElement("script");
scriptObject.type = @"text/javascript";
scriptObject.text = @"function btn1_OnClick(str){
alert('you clicked' + str);
}";
((HTMLHeadElementClass)head).appendChild((IHTMLDOMNode)scriptObject);
I know this question is old, but I wanted to offer an extension by adding this to all objects. I know people tend to frown on using the Object prototype for extended object functionality, but I don't find anything easier than doing this. Plus, it's now allowed for with the Object.defineProperty method.
Object.defineProperty( Object.prototype, "has", { value: function( needle ) {
var obj = this;
var needles = needle.split( "." );
for( var i = 0; i<needles.length; i++ ) {
if( !obj.hasOwnProperty(needles[i])) {
return false;
}
obj = obj[needles[i]];
}
return true;
}});
Now, in order to test for any property in any object you can simply do:
if( obj.has("some.deep.nested.object.somewhere") )
Here's a jsfiddle to test it out, and in particular it includes some jQuery that breaks if you modify the Object.prototype directly because of the property becoming enumerable. This should work fine with 3rd party libraries.
Here's a variant of the solution from @JoshuaUlrich that uses the correct size instead of a hard-coded size:
fileName <- 'foo.txt'
readChar(fileName, file.info(fileName)$size)
Note that readChar allocates space for the number of bytes you specify, so readChar(fileName, .Machine$integer.max)
does not work well...
You would need to use Javascript for this. You can set the style of the background-image
for the body like so.
var body = document.getElementsByTagName('body')[0];
body.style.backgroundImage = 'url(http://localhost/background.png)';
Just make sure you replace the URL with the actual URL.
I used the Visual Studio 2008 Uninstall tool and it worked fine for me.
You can use this tool to uninstall Visual Studio 2008 official release and Visual Studio 2008 Release candidate (Only English version).
Found here, on the MSDN Forum: MSDN forum topic.
I found this answer here
Be sure you run the tool with admin-rights.
Answer for PyCharm 2016.1 on OSX: (This is an update to the answer by @GeorgeWilliams993's answer above, but I don't have the rep yet to make comments.)
Go to Pycharm menu --> Preferences --> Project: (projectname) --> Project Interpreter
At the top is a popup for "Project Interpreter," and to the right of it is a button with ellipses (...) - click on this button for a different popup and choose "More" (or, as it turns out, click on the main popup and choose "Show All").
This shows a list of interpreters, with one selected. At the bottom of the screen are a set of tools... pick the rightmost one:
Now you should see all the paths pycharm is searching to find imports, and you can use the "+" button at the bottom to add a new path.
I think the most significant difference from @GeorgeWilliams993's answer is that the gear button has been replaced by a set of ellipses. That threw me off.
Paste my contains
example here:
//table[contains(@class, "EC_result")]/tbody
From the PHP manual:
This is only called on reading/writing inaccessible properties. Your property however is public, which means it is accessible. Changing the access modifier to protected solves the issue.
I also had problem with proximity sensor (I shattered screen in that region on my Nexus 6, Android Marshmallow) and none of proposed solutions / third party apps worked when I tried to disable proximity sensor. What worked for me was to calibrate the sensor using Proximity Sensor Reset/Repair. You have to follow the instruction in app (cover sensor and uncover it) and then restart your phone. Although my sensor is no longer behind the glass, it still showed slightly different results when covered / uncovered and recalibration did the job.
What I tried and didn't work? Proximity Screen Off Lite, Macrodroid and KinScreen.
What would've I tried had it still not worked?[XPOSED] Sensor Disabler, but it requires you to be rooted and have Xposed Framework, so I'm really glad I've found the easier way.
Here's how I do file upload in react using axios
import React from 'react'
import axios, { post } from 'axios';
class SimpleReactFileUpload extends React.Component {
constructor(props) {
super(props);
this.state ={
file:null
}
this.onFormSubmit = this.onFormSubmit.bind(this)
this.onChange = this.onChange.bind(this)
this.fileUpload = this.fileUpload.bind(this)
}
onFormSubmit(e){
e.preventDefault() // Stop form submit
this.fileUpload(this.state.file).then((response)=>{
console.log(response.data);
})
}
onChange(e) {
this.setState({file:e.target.files[0]})
}
fileUpload(file){
const url = 'http://example.com/file-upload';
const formData = new FormData();
formData.append('file',file)
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
return post(url, formData,config)
}
render() {
return (
<form onSubmit={this.onFormSubmit}>
<h1>File Upload</h1>
<input type="file" onChange={this.onChange} />
<button type="submit">Upload</button>
</form>
)
}
}
export default SimpleReactFileUpload
Run
rake db:migrate:down VERSION=<version>
Where <version>
is the version number of your migration file you want to revert.
Example:-
rake db:migrate:down VERSION=3846656238
You should know that it is not possible to directly run a DDL statement like you do for DML from a PL/SQL block because PL/SQL does not support late binding directly it only support compile time binding which is fine for DML. hence to overcome this type of problem oracle has provided a dynamic SQL approach which can be used to execute the DDL statements.The dynamic sql approach is about parsing and binding of sql string at the runtime. Also you should rememder that DDL statements are by default auto commit hence you should be careful about any of the DDL statement using the dynamic SQL approach incase if you have some DML (which needs to be commited explicitly using TCL) before executing the DDL in the stored proc/function.
You can use any of the following dynamic sql approach to execute a DDL statement from a pl/sql block.
1) Execute immediate
2) DBMS_SQL package
3) DBMS_UTILITY.EXEC_DDL_STATEMENT (parse_string IN VARCHAR2);
Hope this answers your question with explanation.
I have used the extremely handy app_offline.htm trick to shut down/update sites in the past without any issues.
Be sure that you are actually placing the "app_offline.htm" file in the "root" of the website that you have configured within IIS.
Also ensure that the file is named exactly as it should be: app_offline.htm
Other than that, there should be no other changes to IIS that you should need to make since the processing of this file (with this specific name) is handled by the ASP.NET runtime rather than IIS itself (for IIS v6).
Be aware, however, that although placing this file in the root of your site will force the application to "shut down" and display the content of the "app_offline.htm" file itself, any existing requests will still get the real website served up to them. Only new requests will get the app_offline.htm content.
If you're still having issues, try the following links for further info:
App_Offline.htm and working around the "IE Friendly Errors" feature
Will app_offline.htm stop current requests or just new requests?
When sure that the object is a user-defined one, the easiest way to determine if UDO is empty, would be the following code:
isEmpty=
/*b.b Troy III p.a.e*/
function(x,p){for(p in x)return!1;return!0};
Even though this method is (by nature) a deductive one, - it's the quickest, and fastest possible.
a={};
isEmpty(a) >> true
a.b=1
isEmpty(a) >> false
p.s.: !don't use it on browser-defined objects.
I'm trying to sort of get my head around what's going on over there. Is there anything IN your "example" folder? Git doesn't track empty folders.
If you branched and switched to your new branch then made a new folder and left it empty, and then did "git commit -a", you wouldn't get that new folder in the commit.
Which means it's untracked, which means checking out a different branch wouldn't remove it.
Following is a simple code to read from SQL database. Database names is "database1". Table name is "table1". It contain two columns "uname" and "pass". Dont forget to add "sqljdbc4.jar" to your project. Download sqljdbc4.jar
public class NewClass {
public static void main(String[] args) {
Connection conn = null;
String dbName = "database1";
String serverip="192.168.100.100";
String serverport="1433";
String url = "jdbc:sqlserver://"+serverip+"\\SQLEXPRESS:"+serverport+";databaseName="+dbName+"";
Statement stmt = null;
ResultSet result = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String databaseUserName = "admin";
String databasePassword = "root";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url, databaseUserName, databasePassword);
stmt = conn.createStatement();
result = null;
String pa,us;
result = stmt.executeQuery("select * from table1 ");
while (result.next()) {
us=result.getString("uname");
pa = result.getString("pass");
System.out.println(us+" "+pa);
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can get SVN command-line tools with TortoiseSVN 1.7 or later or get a 6.5mb standalone package from VisualSVN.
Starting with TortoiseSVN 1.7, its installer provides you with an option to install the command-line tools.
It also makes sense to check the Apache Subversion "Binary Packages" page. xD
The simplest way to do so:
maxlength="5"
So.. Adding this attribute to your control:
<input type="text"
id="sessionNo"
name="sessionNum"
onkeypress="return isNumberKey(event)"
maxlength="5" />
Shameless self plug: you could always use https://github.com/amoerie/jstreams
Works on Java 6 and up, a perfect fit for Android development.
It looks a lot like Scala operators, lodash, C# LINQ, etc.
You can use path
to maneuver.
var MYPATH = '/User/HELLO/WORLD/FILENAME.js';
var MYEXT = '.js';
var fileName = path.basename(MYPATH, MYEXT);
var filePath = path.dirname(MYPATH) + '/' + fileName;
Output
> filePath
'/User/HELLO/WORLD/FILENAME'
> fileName
'FILENAME'
> MYPATH
'/User/HELLO/WORLD/FILENAME.js'
Unlike C/C++ Long in Python have unlimited precision. Refer the section Numeric Types in python for more information.To determine the max value of integer you can just refer sys.maxint
. You can get more details from the documentation of sys.
With the last update of Androd Studio I have two versions of the IDE's launcher
One is called studio.exe and the other studio64.exe they are both on:
C:\Users\myUserName\AppData\Local\Android\android-studio\bin
You have to launch the one that matches your Java version 64 or 32 bit
If you have access to SQL Server 2016, you can use the FOR JSON (with INCLUDE_NULL_VALUES) option to get JSON output from a select statement. Copy the output, then in Visual Studio, paste special -> paste JSON as class.
Kind of a budget solution, but might save some time.
I was using View.INVISIBLE
and View.VISIBLE
and the ProgressBar
would slowly flash instead of constantly being visible, switched to View.GONE
and View.VISIBLE
and it works perfectly
#include <stdio.h>
#define QUOTEME(x) #x
#ifndef TEST_FUN
# define TEST_FUN func_name
# define TEST_FUN_NAME QUOTEME(TEST_FUN)
#endif
int main(void)
{
puts(TEST_FUN_NAME);
return 0;
}
Reference: Wikipedia's C preprocessor page
In the Gregorian calendar, three conditions are used to identify leap years:
This means that in the Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years. source
def is_leap(year):
leap = False
if year % 4 == 0:
leap = True
if year % 4 == 0 and year % 100 == 0:
leap = False
if year % 400 == 0:
leap = True
return leap
year = int(input())
leap = is_leap(year)
if leap:
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
Command + K will clear previous output.
To clear entered text, first jump left with Command + A and then clear the text to the right of the pointer with Control + K.
Visual examples:
var phone = '2124771000',
formatted = phone.substr(0, 3) + '-' + phone.substr(3, 3) + '-' + phone.substr(6,4)
As already stated in earlier answers, ng-pristine
is for indicating that the field has not been modified, whereas ng-dirty
is for telling it has been modified. Why need both?
Let's say we've got a form with phone and e-mail address among the fields. Either phone or e-mail is required, and you also have to notify the user when they've got invalid data in each field. This can be accomplished by using ng-dirty
and ng-pristine
together:
<form name="myForm">
<input name="email" ng-model="data.email" ng-required="!data.phone">
<div class="error"
ng-show="myForm.email.$invalid &&
myForm.email.$pristine &&
myForm.phone.$pristine">Phone or e-mail required</div>
<div class="error"
ng-show="myForm.email.$invalid && myForm.email.$dirty">
E-mail is invalid
</div>
<input name="phone" ng-model="data.phone" ng-required="!data.email">
<div class="error"
ng-show="myForm.phone.$invalid &&
myForm.email.$pristine &&
myForm.phone.$pristine">Phone or e-mail required</div>
<div class="error"
ng-show="myForm.phone.$invalid && myForm.phone.$dirty">
Phone is invalid
</div>
</form>
What I want is a way to merge my stashed changes with the current changes
Here is another option to do it:
git stash show -p|git apply
git stash drop
git stash show -p
will show the patch of last saved stash. git apply
will apply it. After the merge is done, merged stash can be dropped with git stash drop
.
- Each time you append or do any modification with it, it creates a new String
object.
- So use append()
method of StringBuilder
(If thread safety is not important), else use StringBuffer
(If thread safety is important.), that will be efficient way to do it.
New Operator for lambda expression added in java 8
Lambda expression is the short way of method writing.
It is indirectly used to implement functional interface
Primary Syntax : (parameters) -> { statements; }
There are some basic rules for effective lambda expressions writting which you should konw.
Go to Menu-Tab -> Project -> Build -> Automatically(check this option). and than reopen a new project.
Try to replace 'w' for 'iw'. For example:
SELECT to_char(to_date(TRANSDATE, 'dd-mm-yyyy'), 'iw') as weeknumber from YOUR_TABLE;
This worked much better in my case.
HTML in PHP: <a href=".$link_address.">Link</a>
In Java 8+ you can create a max priority queue via one of these methods:
Method 1:
PriorityQueue<Integer> maxPQ = new PriorityQueue<>(Collections.reverseOrder());
Method 2:
PriorityQueue<Integer> maxPQ = new PriorityQueue<>((a,b) -> b - a);
Method 3:
PriorityQueue<Integer> maxPQ = new PriorityQueue<>((a,b) -> b.compareTo(a));
A few comments:
analog=True
in the call to butter
, and you should use scipy.signal.freqz
(not freqs
) to generate the frequency response.Here's my modified version of your script, followed by the plot that it generates.
import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt
def butter_lowpass(cutoff, fs, order=5):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='low', analog=False)
return b, a
def butter_lowpass_filter(data, cutoff, fs, order=5):
b, a = butter_lowpass(cutoff, fs, order=order)
y = lfilter(b, a, data)
return y
# Filter requirements.
order = 6
fs = 30.0 # sample rate, Hz
cutoff = 3.667 # desired cutoff frequency of the filter, Hz
# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)
# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()
# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0 # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data. We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)
# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)
plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()
plt.subplots_adjust(hspace=0.35)
plt.show()
Let's say that you have a folder named "contollers".
In your app.js you can put this code:
console.log("Loading controllers....");
var controllers = {};
var controllers_path = process.cwd() + '/controllers'
fs.readdirSync(controllers_path).forEach(function (file) {
if (file.indexOf('.js') != -1) {
controllers[file.split('.')[0]] = require(controllers_path + '/' + file)
}
});
console.log("Controllers loaded..............[ok]");
... and ...
router.get('/ping', controllers.ping.pinging);
in your controllers forlder you will have the file "ping.js" with this code:
exports.pinging = function(req, res, next){
console.log("ping ...");
}
And this is it....
Move Your log4j.properties file into the src folder. Open Windows explorer, browse to the directory where your project resides in. Browse to bin directory and delete all the folders with in it.
Now in eclipse click project---->clean---->OK
This would force it to build the project again,all the contents delete from bin directory will be recreated.
I took while to figure this out. At times directly clicking clean doesn't work
There may already be a function to do what you're looking for, but I don't know about it (yet?). In the meantime, I would suggess using:
ran_floats = numpy.random.rand(50) * (13.3-0.5) + 0.5
This will produce an array of shape (50,) with a uniform distribution between 0.5 and 13.3.
You could also define a function:
def random_uniform_range(shape=[1,],low=0,high=1):
"""
Random uniform range
Produces a random uniform distribution of specified shape, with arbitrary max and
min values. Default shape is [1], and default range is [0,1].
"""
return numpy.random.rand(shape) * (high - min) + min
EDIT: Hmm, yeah, so I missed it, there is numpy.random.uniform() with the same exact call you want!
Try import numpy; help(numpy.random.uniform)
for more information.
add async defer at the begining of map api key call.
The Tkinter library in the Python standard library is an interactive tool which you can import. Basically, you can create buttons and boxes and popups and stuff that appear as windows which you manipulate with code.
If you use Tkinter, do not use time.sleep()
, because it will muck up your program. This happened to me. Instead, use root.after()
and replace the values for however many seconds, with a milliseconds. For example, time.sleep(1)
is equivalent to root.after(1000)
in Tkinter.
Otherwise, time.sleep()
, which many answers have pointed out, which is the way to go.
It's been a while, but last time I had something similar:
ROLLBACK TRAN
or trying to
COMMIT
what had allready been done free'd everything up so I was able to clear things out and start again.
Here is Federico Ramponi's answer in Go. Note: no error-checking :(
import (
"math"
)
// Semi-axes of WGS-84 geoidal reference
const (
// Major semiaxis (meters)
WGS84A = 6378137.0
// Minor semiaxis (meters)
WGS84B = 6356752.3
)
// BoundingBox represents the geo-polygon that encompasses the given point and radius
type BoundingBox struct {
LatMin float64
LatMax float64
LonMin float64
LonMax float64
}
// Convert a degree value to radians
func deg2Rad(deg float64) float64 {
return math.Pi * deg / 180.0
}
// Convert a radian value to degrees
func rad2Deg(rad float64) float64 {
return 180.0 * rad / math.Pi
}
// Get the Earth's radius in meters at a given latitude based on the WGS84 ellipsoid
func getWgs84EarthRadius(lat float64) float64 {
an := WGS84A * WGS84A * math.Cos(lat)
bn := WGS84B * WGS84B * math.Sin(lat)
ad := WGS84A * math.Cos(lat)
bd := WGS84B * math.Sin(lat)
return math.Sqrt((an*an + bn*bn) / (ad*ad + bd*bd))
}
// GetBoundingBox returns a BoundingBox encompassing the given lat/long point and radius
func GetBoundingBox(latDeg float64, longDeg float64, radiusKm float64) BoundingBox {
lat := deg2Rad(latDeg)
lon := deg2Rad(longDeg)
halfSide := 1000 * radiusKm
// Radius of Earth at given latitude
radius := getWgs84EarthRadius(lat)
pradius := radius * math.Cos(lat)
latMin := lat - halfSide/radius
latMax := lat + halfSide/radius
lonMin := lon - halfSide/pradius
lonMax := lon + halfSide/pradius
return BoundingBox{
LatMin: rad2Deg(latMin),
LatMax: rad2Deg(latMax),
LonMin: rad2Deg(lonMin),
LonMax: rad2Deg(lonMax),
}
}
when you want to write a 1D Array in a Excel sheet you have to transpose it and you don't have to create a 2D array with 1 column ([n, 1]) as I read above! Here is a example of code :
wSheet.Cells(RowIndex, colIndex).Resize(RowsCount, ).Value = _excel.Application.transpose(My1DArray)
Have a good day, Gilles
The URI is encoded as UTF-8, but Tomcat is decoding them as ISO-8859-1. You need to edit the connector settings in the server.xml and add the URIEncoding="UTF-8" attribute.
or edit this parameter on your application.properties
server.tomcat.uri-encoding=utf-8
From the OP:
I finally reinstalled it from Java for OS X 2013-005. It solved this issue.
For those using an ImageButton
here is how you do it:
In style.xml:
<style name="BlueImageButton" parent="Base.Widget.AppCompat.ImageButton">
<item name="colorButtonNormal">@color/primary</item>
<item name="android:tint">@color/white</item>
</style>
in v21/style.xml:
<style name="BlueImageButton" parent="Widget.AppCompat.ImageButton">
<item name="android:colorButtonNormal">@color/primary</item>
<item name="android:tint">@color/white</item>
</style>
Then in your layout file:
<android.support.v7.widget.AppCompatImageButton
android:id="@+id/my_button"
android:theme="@style/BlueImageButton"
android:layout_width="42dp"
android:layout_height="42dp"
android:layout_gravity="center_vertical"
android:src="@drawable/ic_check_black_24dp"
/>
You can try in a simple way:
Install zip-dir
:
npm install zip-dir
and use it
var zipdir = require('zip-dir');
let foldername = src_path.split('/').pop()
zipdir(<<src_path>>, { saveTo: 'demo.zip' }, function (err, buffer) {
});
To call a .bat
file within a .bat
file, use
call foo.bat
(Yes, this is silly, it would make more sense if you could call it with foo.bat
, like you could from the command prompt, but the correct way is to use call
.)
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script>
<script type="text/javascript" src="jquery-2.1.0.js"></script>
<script type="text/javascript" >
function openOnImageClick()
{
//alert("Jai Sh Raam");
// document.getElementById("images").src = "fruits.jpg";
var img = document.createElement('img');
img.setAttribute('src', 'tiger.jpg');
img.setAttribute('width', '200');
img.setAttribute('height', '150');
document.getElementById("images").appendChild(img);
}
</script>
</head>
<body>
<h1>Screen Shot View</h1>
<p>Click the Tiger to display the Image</p>
<div id="images" >
</div>
<img src="tiger.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick()" />
<img src="Logo1.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick()" />
</body>
</html>
You can check for empty string (when stderr is empty)
- name: Check script
shell: . {{ venv_name }}/bin/activate && myscritp.py
args:
chdir: "{{ home }}"
sudo_user: "{{ user }}"
register: test_myscript
- debug: msg='myscritp is Ok'
when: test_myscript.stderr == ""
If you want to check for fail:
- debug: msg='myscritp has error: {{test_myscript.stderr}}'
when: test_myscript.stderr != ""
Also look at this stackoverflow question
React hooks are a new way (still being developed) to access the core features of react such as state
without having to use classes, in your example if you want to increment a counter directly in the handler function without specifying it directly in the onClick
prop, you could do something like:
...
const [count, setCounter] = useState(0);
const [moreStuff, setMoreStuff] = useState(...);
...
const setCount = () => {
setCounter(count + 1);
setMoreStuff(...);
...
};
and onClick:
<button onClick={setCount}>
Click me
</button>
Let's quickly explain what is going on in this line:
const [count, setCounter] = useState(0);
useState(0)
returns a tuple where the first parameter count
is the current state of the counter and setCounter
is the method that will allow us to update the counter's state. We can use the setCounter
method to update the state of count
anywhere - In this case we are using it inside of the setCount
function where we can do more things; the idea with hooks is that we are able to keep our code more functional and avoid class based components if not desired/needed.
I wrote a complete article about hooks with multiple examples (including counters) such as this codepen, I made use of useState
, useEffect
, useContext
, and custom hooks. I could get into more details about how hooks work on this answer but the documentation does a very good job explaining the state hook and other hooks in detail, hope it helps.
update: Hooks are not longer a proposal, since version 16.8 they're now available to be used, there is a section in React's site that answers some of the FAQ.
This problem is happend because of php.ini defined limit was exided but have lot's of solution for this but simple one is to find your local servers folder and on that find the php folder and in that folder have php.ini file which have all declaration of these type setups. You just need to find one and change that value. But in this situation have one big problem once you change in your localhost file but what about server when you want to put your site on server it again produce same problem and you again follow the same for server. But you also know about .htaccess file this is one of the best and single place to do a lot's of things without changing core files. Like you change www routing, removing .php or other extentions from url or add one. Same like that you also difine default values of php.ini here like this - First you need to open the .htaccess file from your root directory or if you don't have this file so create one on root directory of your site and paste this code on it -
php_value upload_max_filesize 1000M
php_value post_max_size 99500M
php_value memory_limit 500M
php_value max_execution_time 300
after changes if you want to check the changes just run the php code
<?php phpinfo(); ?>
it will show you the php cofigrations all details. So you find your changes.
Note: for defining unlimited just add -1 like php_value memory_limit -1 It's not good and most of the time slow down your server. But if you like to be limit less then this one option is also fit for you. If after refresh your page changes will not reflect you must restart your local server once for changes.
Good Luck. Hope it will help. Want to download the .htaccess file click this.
Use %p
, for "pointer", and don't use anything else*. You aren't guaranteed by the standard that you are allowed to treat a pointer like any particular type of integer, so you'd actually get undefined behaviour with the integral formats. (For instance, %u
expects an unsigned int
, but what if void*
has a different size or alignment requirement than unsigned int
?)
*) [See Jonathan's fine answer!] Alternatively to %p
, you can use pointer-specific macros from <inttypes.h>
, added in C99.
All object pointers are implicitly convertible to void*
in C, but in order to pass the pointer as a variadic argument, you have to cast it explicitly (since arbitrary object pointers are only convertible, but not identical to void pointers):
printf("x lives at %p.\n", (void*)&x);
I was recently dealing with an issue when I was trying to get past authentication while making a REST call from Java, and while the answers in this thread (and other threads) helped, there was still a bit of trial and error involved in getting it working.
What worked for me was encoding credentials in Base64
and adding them as Basic Authorization headers. I then added them as an HttpEntity
to restTemplate.postForEntity
, which gave me the response I needed.
Here's the class I wrote for this in full (extending RestTemplate):
public class AuthorizedRestTemplate extends RestTemplate{
private String username;
private String password;
public AuthorizedRestTemplate(String username, String password){
this.username = username;
this.password = password;
}
public String getForObject(String url, Object... urlVariables){
return authorizedRestCall(this, url, urlVariables);
}
private String authorizedRestCall(RestTemplate restTemplate,
String url, Object... urlVariables){
HttpEntity<String> request = getRequest();
ResponseEntity<String> entity = restTemplate.postForEntity(url,
request, String.class, urlVariables);
return entity.getBody();
}
private HttpEntity<String> getRequest(){
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + getBase64Credentials());
return new HttpEntity<String>(headers);
}
private String getBase64Credentials(){
String plainCreds = username + ":" + password;
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
return new String(base64CredsBytes);
}
}
int x = 4<5;
Completely portable. Standard conformant. bool
to int
conversion is implicit!
§4.7/4 from the C++ Standard says (Integral Conversion)
If the source type is bool, the value
false
is converted to zero and the valuetrue
is converted to one.
As for C, as far as I know there is no bool
in C. (before 1999) So bool
to int
conversion is relevant in C++ only. In C, 4<5
evaluates to int
value, in this case the value is 1
, 4>5
would evaluate to 0
.
EDIT: Jens in the comment said, C99 has _Bool
type. bool
is a macro defined in stdbool.h
header file. true
and false
are also macro defined in stdbool.h
.
§7.16 from C99 says,
The macro
bool
expands to _Bool.[..]
true
which expands to the integer constant1
,false
which expands to the integer constant0
,[..]
Use the strtotime
function:
Example:
$date = "25 december 2009";
$my_date = date('m/d/y', strtotime($date));
echo $my_date;
getElementById("id").removeAttribute("style");
if you are using jQuery then
$("#id").removeClass("classname");
If you use the following to change the port or host:
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
use the following code to start the server (my main entrance for flask is app.py):
python app.py
instead of using:
flask run
If the transfer mode is Buffered then make sure that the values of MaxReceivedMessageSize and MaxBufferSize is same. I just resolved the faulted state issue this way after grappling with it for hours and thought i'll post it here if it helps someone.
assuming certain column names...
INSERT one
newToner = Toner(toner_id = 1,
toner_color = 'blue',
toner_hex = '#0F85FF')
dbsession.add(newToner)
dbsession.commit()
INSERT multiple
newToner1 = Toner(toner_id = 1,
toner_color = 'blue',
toner_hex = '#0F85FF')
newToner2 = Toner(toner_id = 2,
toner_color = 'red',
toner_hex = '#F01731')
dbsession.add_all([newToner1, newToner2])
dbsession.commit()
UPDATE
q = dbsession.query(Toner)
q = q.filter(Toner.toner_id==1)
record = q.one()
record.toner_color = 'Azure Radiance'
dbsession.commit()
or using a fancy one-liner using MERGE
record = dbsession.merge(Toner( **kwargs))
So this isn't what the requester was asking for but it is the answer to "SQL selecting rows by most recent date".
Modified from http://wiki.lessthandot.com/index.php/Returning_The_Maximum_Value_For_A_Row
SELECT t.chargeId, t.chargeType, t.serviceMonth FROM(
SELECT chargeId,MAX(serviceMonth) AS serviceMonth
FROM invoice
GROUP BY chargeId) x
JOIN invoice t ON x.chargeId =t.chargeId
AND x.serviceMonth = t.serviceMonth
According to the pytest docs, pytest --capture=sys
should work. If you want to capture standard out inside a test, refer to the capsys fixture.
The exec
family of functions make your process execute a different program, replacing the old program it was running. I.e., if you call
execl("/bin/ls", "ls", NULL);
then the ls
program is executed with the process id, current working dir and user/group (access rights) of the process that called execl
. Afterwards, the original program is not running anymore.
To start a new process, the fork
system call is used. To execute a program without replacing the original, you need to fork
, then exec
.
Use os.path.join
to concatenate the directory and file name:
for path, subdirs, files in os.walk(root):
for name in files:
print(os.path.join(path, name))
Note the usage of path
and not root
in the concatenation, since using root
would be incorrect.
In Python 3.4, the pathlib module was added for easier path manipulations. So the equivalent to os.path.join
would be:
pathlib.PurePath(path, name)
The advantage of pathlib
is that you can use a variety of useful methods on paths. If you use the concrete Path
variant you can also do actual OS calls through them, like changing into a directory, deleting the path, opening the file it points to and much more.
origin/master
is an entity (since it is not a physical branch) representing the state of the master
branch on the remote origin
.
origin master
is the branch master
on the remote origin
.
So we have these:
Example (in local branch master
):
git fetch # get current state of remote repository
git merge origin/master # merge state of remote master branch into local branch
git push origin master # push local branch master to remote branch master
I run into this problem on a regular basis and often use the "add a method" solution. However, there are definitely cases where "add a method" or "compute it in the view" don't work (or don't work well). E.g. when you are caching template fragments and need some non-trivial DB computation to produce it. You don't want to do the DB work unless you need to, but you won't know if you need to until you are deep in the template logic.
Some other possible solutions:
Use the {% expr <expression> as <var_name> %} template tag found at http://www.djangosnippets.org/snippets/9/ The expression is any legal Python expression with your template's Context as your local scope.
Change your template processor. Jinja2 (http://jinja.pocoo.org/2/) has syntax that is almost identical to the Django template language, but with full Python power available. It's also faster. You can do this wholesale, or you might limit its use to templates that you are working on, but use Django's "safer" templates for designer-maintained pages.
In the case of HashMap
, it replaces the old value with the new one.
In the case of HashSet
, the item isn't inserted.
If you are having 112 columns in one single table and you would like to insert data from source table, you could do as
create table employees as select * from source_employees where employee_id=100;
Or from sqlplus do as
copy from source_schema/password insert employees using select * from
source_employees where employee_id=100;
If you use Hue, you can browse the table in the Metastore App and then click on 'View file location': that will open the HDFS File Browser in its directory.
There are no values that will cause the checkbox to be unchecked. If the checked
attribute exists, the checkbox will be checked regardless of what value you set it to.
<input type="checkbox" checked />_x000D_
<input type="checkbox" checked="" />_x000D_
<input type="checkbox" checked="checked" />_x000D_
<input type="checkbox" checked="unchecked" />_x000D_
<input type="checkbox" checked="true" />_x000D_
<input type="checkbox" checked="false" />_x000D_
<input type="checkbox" checked="on" />_x000D_
<input type="checkbox" checked="off" />_x000D_
<input type="checkbox" checked="1" />_x000D_
<input type="checkbox" checked="0" />_x000D_
<input type="checkbox" checked="yes" />_x000D_
<input type="checkbox" checked="no" />_x000D_
<input type="checkbox" checked="y" />_x000D_
<input type="checkbox" checked="n" />
_x000D_
Renders everything checked in all modern browsers (FF3.6, Chrome 10, IE8).
You can try this:
<form action="/home">_x000D_
_x000D_
<input type="submit" value="cancel">_x000D_
_x000D_
<input type="submit" value="login" formaction="/login">_x000D_
<input type="submit" value="signup" formaction="/signup">_x000D_
_x000D_
</form>
_x000D_
Arrays.asList
returns a fixed-size List
backed by the array. If you want a normal mutable java.util.ArrayList
you need to do this:
List<String> list = new ArrayList<String>(Arrays.asList(string.split(" , ")));
Or, using Guava:
List<String> list = Lists.newArrayList(Splitter.on(" , ").split(string));
Using a Splitter
gives you more flexibility in how you split the string and gives you the ability to, for example, skip empty strings in the results and trim results. It also has less weird behavior than String.split
as well as not requiring you to split by regex (that's just one option).
In most of the cases, StringUtils.isBlank(str)
from apache commons library would solve it. But if there is case, where input string being checked has null value within quotes, it fails to check such cases.
Take an example where I have an input object which was converted into string using String.valueOf(obj)
API. In case obj reference is null, String.valueOf returns "null" instead of null.
When you attempt to use, StringUtils.isBlank("null")
, API fails miserably, you may have to check for such use cases as well to make sure your validation is proper.
You can also use a conditional lookup using .loc
as seen here:
df.loc[df[<some_column_name>] == <condition>, [<another_column_name>]] = <value_to_add>
where <some_column_name
is the column you want to check the <condition>
variable against and <another_column_name>
is the column you want to add to (can be a new column or one that already exists). <value_to_add>
is the value you want to add to that column/row.
This example doesn't work precisely with the question at hand, but it might be useful for someone wants to add a specific value based on a condition.
I think that CONTAINS
took longer and used Merge
because you had a dash("-") in your query adventure-works.com
.
The dash is a break word so the CONTAINS
searched the full-text index for adventure
and than it searched for works.com
and merged the results.
It's trying to run it as a shell script, which interprets your <?php
token as bash, which is a syntax error. Just use include()
or one of its friends:
For example, in a.php
put:
<?php
print "one";
include 'b.php';
print "three";
?>
In b.php
put:
<?php
print "two";
?>
Prints:
eric@dev ~ $ php a.php
onetwothree
Easy as pie, allowing a transparent bg:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="0"
android:startColor="#f00"
android:centerColor="@android:color/transparent"
android:centerX="0.01" />
</shape>
Change the angle to change border location:
If you're calling native apps, you need to worry about [Environment]::CurrentDirectory
not about PowerShell's $PWD
current directory. For various reasons, PowerShell does not set the process' current working directory when you Set-Location or Push-Location, so you need to make sure you do so if you're running applications (or cmdlets) that expect it to be set.
In a script, you can do this:
$CWD = [Environment]::CurrentDirectory
Push-Location $MyInvocation.MyCommand.Path
[Environment]::CurrentDirectory = $PWD
## Your script code calling a native executable
Pop-Location
# Consider whether you really want to set it back:
# What if another runspace has set it in-between calls?
[Environment]::CurrentDirectory = $CWD
There's no foolproof alternative to this. Many of us put a line in our prompt function to set [Environment]::CurrentDirectory ... but that doesn't help you when you're changing the location within a script.
Two notes about the reason why this is not set by PowerShell automatically:
$PWD
present working directory, but there's only one process, and only one Environment.$PWD
isn't always a legal CurrentDirectory (you might CD into the registry provider for instance).If you want to put it into your prompt (which would only run in the main runspace, single-threaded), you need to use:
[Environment]::CurrentDirectory = Get-Location -PSProvider FileSystem
I was trying to make a simple solution for a simple issue. Above posts are good but so complicated for a simple issue. So i made a simple thing. Just added a close button. Its perfect for me.
$(".popover-link").click(function(){
$(".mypopover").hide();
$(this).parent().find(".mypopover").show();
})
$('.close').click(function(){
$(this).parents('.mypopover').css('display','none');
});
<div class="popover-content">
<i class="fa fa-times close"></i>
<h3 class="popover-title">Title here</h3>
your other content here
</div>
.popover-content {
position:relative;
}
.close {
position:absolute;
color:#CCC;
right:5px;
top:5px;
cursor:pointer;
}
git branch -f <branch-name> [<new-tip-commit>]
If new-tip-commit
is omitted it defaults to the current commit.
You can't, Print Preview is a feature of a browser, and therefore should be protected from being called by JavaScript as it would be a security risk.
That's why your example uses Active X, which bypasses the JavaScript security issues.
So instead use the print stylesheet that you already should have and show it for media=screen,print instead of media=print.
Read Alist Apart: Going to Print for a good article on the subject of print stylesheets.
Use ECMAScript 2015's Template String Literals, if applicable.
There is no direct way to do it, as per ECMAScript 5 specifications, but ECMAScript 6 has template strings, which were also known as quasi-literals during the drafting of the spec. Use them like this:
> var n = 42;
undefined
> `foo${n}bar`
'foo42bar'
You can use any valid JavaScript expression inside the {}
. For example:
> `foo${{name: 'Google'}.name}bar`
'fooGooglebar'
> `foo${1 + 3}bar`
'foo4bar'
The other important thing is, you don't have to worry about multi-line strings anymore. You can write them simply as
> `foo
... bar`
'foo\n bar'
Note: I used io.js v2.4.0 to evaluate all the template strings shown above. You can also use the latest Chrome to test the above shown examples.
Note: ES6 Specifications are now finalized, but have yet to be implemented by all major browsers.
According to the Mozilla Developer Network pages, this will be implemented for basic support starting in the following versions: Firefox 34, Chrome 41, Internet Explorer 12. If you're an Opera, Safari, or Internet Explorer user and are curious about this now, this test bed can be used to play around until everyone gets support for this.
With regard to bootstrap, the correct answer is using spacing utilities as mentioned by loopasam in a previous comment. Following is an example of using padding for both left and right.
<a href="#" class="nav-item nav-link px-3">Blog</a>
I faced a similar problem. I tried everything with ports, hosts and config files.But nothing helped.
I checked apache error logs. They showed the following error
(OS 10038)An operation was attempted on something that is not a socket. : AH00332: winnt_accept: getsockname error on listening socket, is IPv6 available?
Finally this is what solved my problem.
1) Goto command prompt and run it in administrative mode. In windows 7 you can do it by typing cmd
in run and then pressing ctrl+shift+enter
2) run the following command:
netsh winsock reset
3) Restart the system
Tab as Enter: create a user control which inherits textbox, override the KeyPress
method. If the user presses enter you can either call SendKeys.Send("{TAB}")
or System.Windows.Forms.Control.SelectNextControl()
. Note you can achieve the same using the KeyPress
event.
Focus Entire text: Again, via override or events, target the GotFocus
event and then call TextBox.Select
method.
According to my experience
ref: https://en.wikipedia.org/wiki/Scrum_(software_development)
To link the entire row, you need to define onclick
function on your row, which is <tr>
element and define a mouse hover
in the CSS for tr
element to make the mouse pointer to a typical click-hand in web:
In table:
<tr onclick="location.href='http://www.google.com'">
<td>blah</td>
<td>blah</td>
<td><strong>Text</strong></td>
</tr>
In related CSS:
tr:hover {
cursor: pointer;
}
If you are using PyCharm IDE, then you can run that individual test or all tests using Run toolbar. The Run tool window displays output generated by your application and you can see all the print statements in there as part of test output.
You need to use v-bind:
or its alias :
. For example,
<a v-bind:href="'/job/'+ r.id">
or
<a :href="'/job/' + r.id">
The MediaStore API is probably throwing away the alpha channel (i.e. decoding to RGB565). If you have a file path, just use BitmapFactory directly, but tell it to use a format that preserves alpha:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
selected_photo.setImageBitmap(bitmap);
or
http://mihaifonoage.blogspot.com/2009/09/displaying-images-from-sd-card-in.html