Just change the class container to container-fullwidth like this :
<div class="container-fullwidth">
Try fully qualifying the filenames in the arguments - I notice you're specifying the path in the FileName part, so it's possible that the process is being started elsewhere, then not finding the arguments and causing an error.
If that works, then setting the WorkingDirectory property on the StartInfo may be of use.
Actually, according to the link
The WorkingDirectory property must be set if UserName and Password are provided. If the property is not set, the default working directory is %SYSTEMROOT%\system32.
Simplest left to right swipe detector:
In your activity class add following attributes:
private float x1,x2;
static final int MIN_DISTANCE = 150;
and override onTouchEvent()
method:
@Override
public boolean onTouchEvent(MotionEvent event)
{
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
x1 = event.getX();
break;
case MotionEvent.ACTION_UP:
x2 = event.getX();
float deltaX = x2 - x1;
if (Math.abs(deltaX) > MIN_DISTANCE)
{
Toast.makeText(this, "left2right swipe", Toast.LENGTH_SHORT).show ();
}
else
{
// consider as something else - a screen tap for example
}
break;
}
return super.onTouchEvent(event);
}
In the particular situation outlined in the question,
typeof window.console === "undefined"
is identical to
window.console === undefined
I prefer the latter since it's shorter.
Please note that we look up for console
only in global scope (which is a window
object in all browsers). In this particular situation it's desirable. We don't want console
defined elsewhere.
@BrianKelley in his great answer explains technical details. I've only added lacking conclusion and digested it into something easier to read.
Another option I have working, in a linux server with Postfix:
First, configure CI email to use your server's email system: eg, in email.php
, for example
# alias to postfix in a typical Postfix server
$config['protocol'] = 'sendmail';
$config['mailpath'] = '/usr/sbin/sendmail';
Then configure your postfix to relay the mail to google (perhaps depending on the sender address). You'll probably need to put you user-password settings in /etc/postfix/sasl_passwd
(docs)
This is much simpler (and less fragmente) if you have a linux box, already configured to send some/all of its outgoing emails to Google.
Well, it's part of BitBucket philosophy and workflow:
i.e you can't (in usual case) commit into foreign repo under own credentials.
You have two possible solutions:
Between array_key_exists
and isset
, though both are very fast [O(1)]
, isset
is significantly faster. If this check is happening many thousands of times, you'd want to use isset
.
It should be noted that they are not identical, though -- when the array key exists but the value is null
, isset
will return false
and array_key_exists
will return true
. If the value may be null
, you need to use array_key_exists
.
As noted in comments, if your value may be null
, the fast choice is:
isset($foo[$key]) || array_key_exists($key, $foo)
Here is a sample tokenizer class that might do what you want
//Header file
class Tokenizer
{
public:
static const std::string DELIMITERS;
Tokenizer(const std::string& str);
Tokenizer(const std::string& str, const std::string& delimiters);
bool NextToken();
bool NextToken(const std::string& delimiters);
const std::string GetToken() const;
void Reset();
protected:
size_t m_offset;
const std::string m_string;
std::string m_token;
std::string m_delimiters;
};
//CPP file
const std::string Tokenizer::DELIMITERS(" \t\n\r");
Tokenizer::Tokenizer(const std::string& s) :
m_string(s),
m_offset(0),
m_delimiters(DELIMITERS) {}
Tokenizer::Tokenizer(const std::string& s, const std::string& delimiters) :
m_string(s),
m_offset(0),
m_delimiters(delimiters) {}
bool Tokenizer::NextToken()
{
return NextToken(m_delimiters);
}
bool Tokenizer::NextToken(const std::string& delimiters)
{
size_t i = m_string.find_first_not_of(delimiters, m_offset);
if (std::string::npos == i)
{
m_offset = m_string.length();
return false;
}
size_t j = m_string.find_first_of(delimiters, i);
if (std::string::npos == j)
{
m_token = m_string.substr(i);
m_offset = m_string.length();
return true;
}
m_token = m_string.substr(i, j - i);
m_offset = j;
return true;
}
Example:
std::vector <std::string> v;
Tokenizer s("split this string", " ");
while (s.NextToken())
{
v.push_back(s.GetToken());
}
If you're using .NET 4.0 or later:
In the case where you need sorting then use SortedSet<T>
. Otherwise if you don't, then use HashSet<T>
since it's O(1)
for search and manipulate operations. Whereas SortedSet<T>
is O(log n)
for search and manipulate operations.
It seems that you catch not the exception you wanna catch out there :)
if the s
is a socket.socket()
object, then the right way to call .connect
would be:
import socket
s = socket.socket()
address = '127.0.0.1'
port = 80 # port number is a number, not string
try:
s.connect((address, port))
# originally, it was
# except Exception, e:
# but this syntax is not supported anymore.
except Exception as e:
print("something's wrong with %s:%d. Exception is %s" % (address, port, e))
finally:
s.close()
Always try to see what kind of exception is what you're catching in a try-except loop.
You can check what types of exceptions in a socket module represent what kind of errors (timeout, unable to resolve address, etc) and make separate except
statement for each one of them - this way you'll be able to react differently for different kind of problems.
Python functions always return a unique value. The comma operator is the constructor of tuples so self.first_name, self.last_name
evaluates to a tuple and that tuple is the actual value the function is returning.
You should not call .get() directly. Optional<>, that Stream::max
returns, was designed to benefit from .orElse... inline handling.
If you are sure your arguments have their size of 2+:
list.stream()
.map(u -> u.date)
.max(Date::compareTo)
.orElseThrow(() -> new IllegalArgumentException("Expected 'list' to be of size: >= 2. Was: 0"));
If you support empty lists, then return some default value, for example:
list.stream()
.map(u -> u.date)
.max(Date::compareTo)
.orElse(new Date(Long.MIN_VALUE));
CREDITS to: @JimmyGeers, @assylias from the accepted answer.
Just Change in build.gradle file
classpath 'com.android.tools.build:gradle:1.3.0'
To
classpath 'com.android.tools.build:gradle:2.0.0'
Now GoTo
-> menu choose File
-> Invalidate Caches/Restart
...
Choose first option: Invalidate and Restart
Android Studio would restart.
After this, it should work normally.
The best way to do this is to surround your tree in the triple backticks to denote a code block. For more info, see the markdown docs: http://daringfireball.net/projects/markdown/syntax#code
Convert hashmap to a ArrayList with a pair class
Hashmap<Object,Object> items = new HashMap<>();
to
List<Pair<Object,Object>> items = new ArrayList<>();
so you can sort it as you want, or list sorted by adding order.
If you want to "wrap around" and effectively rotate the list to start with Monday (rather than just chop off the items prior to Monday):
dayNames = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday', ]
startDayName = 'Monday'
startIndex = dayNames.index( startDayName )
print ( startIndex )
rotatedDayNames = dayNames[ startIndex: ] + dayNames [ :startIndex ]
for x in rotatedDayNames:
print ( x )
The python shutil.copytree method its a mess. I've done one that works correctly:
def copydirectorykut(src, dst):
os.chdir(dst)
list=os.listdir(src)
nom= src+'.txt'
fitx= open(nom, 'w')
for item in list:
fitx.write("%s\n" % item)
fitx.close()
f = open(nom,'r')
for line in f.readlines():
if "." in line:
shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
else:
if not os.path.exists(dst+'/'+line[:-1]):
os.makedirs(dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
f.close()
os.remove(nom)
os.chdir('..')
You could do this (ugly but it works):
INSERT INTO dbo.MyTable (ID, Name)
select * from
(
select 123, 'Timmy'
union all
select 124, 'Jonny'
union all
select 125, 'Sally'
...
) x
I have toyed with this for forever, and finally found something that seems to always work!
textField = new JTextField() {
public void addNotify() {
super.addNotify();
requestFocus();
}
};
Use facebook feed dialog instead of share dialog.
Example:
I've found that using the recipients real first and last name in the body is a sure fire way of getting through a spam filter.
if you want to read in lots of data and work on each line separately you could use something like this:
cat myFile | while read x ; do echo $x ; done
if you want to split the lines up into multiple words you can use multiple variables in place of x like this:
cat myFile | while read x y ; do echo $y $x ; done
alternatively:
while read x y ; do echo $y $x ; done < myFile
But as soon as you start to want to do anything really clever with this sort of thing you're better going for some scripting language like perl where you could try something like this:
perl -ane 'print "$F[0]\n"' < myFile
There's a fairly steep learning curve with perl (or I guess any of these languages) but you'll find it a lot easier in the long run if you want to do anything but the simplest of scripts. I'd recommend the Perl Cookbook and, of course, The Perl Programming Language by Larry Wall et al.
To use vertical-align
properly, you should do it on table
tag. But there is a way to make other html tags to behave as a table by assigning them a css of display:table
to your parent, and display:table-cell
on your child. Then vertical-align:bottom
will work on that child.
HTML:
??????<div class="parent">
<div class="child">
This text is vertically aligned to bottom.
</div>
</div>????????????????????????
CSS:
?.parent {
width: 300px;
height: 50px;
display:? table;
border: 1px solid red;
}
.child {
display: table-cell;
vertical-align: bottom;
}?
Here is a live example: link demo
There are two ways for this:
If you are using ui-router or $stateProvider
, do it as:
$state.go('stateName'); //remember to add $state service in the controller
if you are using angular-router or $routeProvider
, do it as:
$location.path('routeName'); //similarily include $location service in your controller
Since a ThreadLocal
is a reference to data within a given Thread
, you can end up with classloading leaks when using ThreadLocal
s in application servers using thread pools. You need to be very careful about cleaning up any ThreadLocal
s you get()
or set()
by using the ThreadLocal
's remove()
method.
If you do not clean up when you're done, any references it holds to classes loaded as part of a deployed webapp will remain in the permanent heap and will never get garbage collected. Redeploying/undeploying the webapp will not clean up each Thread
's reference to your webapp's class(es) since the Thread
is not something owned by your webapp. Each successive deployment will create a new instance of the class which will never be garbage collected.
You will end up with out of memory exceptions due to java.lang.OutOfMemoryError: PermGen space
and after some googling will probably just increase -XX:MaxPermSize
instead of fixing the bug.
If you do end up experiencing these problems, you can determine which thread and class is retaining these references by using Eclipse's Memory Analyzer and/or by following Frank Kieviet's guide and followup.
Update: Re-discovered Alex Vasseur's blog entry that helped me track down some ThreadLocal
issues I was having.
generally smtp servers name are smtp.yourdomain.com or mail.yourdomain.com open command prompt try to run following two commands
>ping smtp.yourdomain.com
>ping mail.yourdomain.com
you will most probably get response from any one from the above two commands.and that will be your smtp server
If this doesn't work open your cpanel --> go to your mailing accounts -- > click on configure mail account -- > there somewhere in the page you will get the information about your smtp server
it will be written like this way may be :
Incoming Server: mail.yourdomain.com
IMAP Port: ---
POP3 Port: ---
Outgoing Server: mail.yourdomain.com
SMTP Port: ---
If you develop browser extensions you can try browser.cookies.getAll()
I'm using a workaround by returning a function with an object of my global variables:
function globalVariables(){
var variables = {
sheetName: 'Sheet1',
variable1: 1,
variable2: 2
};
return variables;
}
function functionThatUsesVariable (){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(globalVariables().sheetName);
}
str.copy(cstr, str.length()+1); // since C++11
cstr[str.copy(cstr, str.length())] = '\0'; // before C++11
cstr[str.copy(cstr, sizeof(cstr)-1)] = '\0'; // before C++11 (safe)
It's a better practice to avoid C in C++, so std::string::copy should be the choice instead of strcpy.
Suppose your hex string is something like
>>> hex_string = "deadbeef"
>>> hex_data = hex_string.decode("hex")
>>> hex_data
"\xde\xad\xbe\xef"
>>> bytes.fromhex(hex_string) # Python = 3
b'\xde\xad\xbe\xef'
>>> bytearray.fromhex(hex_string)
bytearray(b'\xde\xad\xbe\xef')
Note that bytes
is an immutable version of bytearray
.
From command prompt as admin run:
netsh interface ip delete destinationcache
Works on Win7.
In my case I had to use
import androidx.annotation...
instead of
import android.annotation...
I migrated to AndroidX and forgot to change that.
We can do that using @lru_cache
decorator and setrecursionlimit()
method:
import sys
from functools import lru_cache
sys.setrecursionlimit(15000)
@lru_cache(128)
def fib(n: int) -> int:
if n == 0:
return 0
if n == 1:
return 1
return fib(n - 2) + fib(n - 1)
print(fib(14000))
3002468761178461090995494179715025648692747937490792943468375429502230242942284835863402333575216217865811638730389352239181342307756720414619391217798542575996541081060501905302157019002614964717310808809478675602711440361241500732699145834377856326394037071666274321657305320804055307021019793251762830816701587386994888032362232198219843549865275880699612359275125243457132496772854886508703396643365042454333009802006384286859581649296390803003232654898464561589234445139863242606285711591746222880807391057211912655818499798720987302540712067959840802106849776547522247429904618357394771725653253559346195282601285019169360207355179223814857106405285007997547692546378757062999581657867188420995770650565521377874333085963123444258953052751461206977615079511435862879678439081175536265576977106865074099512897235100538241196445815568291377846656352979228098911566675956525644182645608178603837172227838896725425605719942300037650526231486881066037397866942013838296769284745527778439272995067231492069369130289154753132313883294398593507873555667211005422003204156154859031529462152953119957597195735953686798871131148255050140450845034240095305094449911578598539658855704158240221809528010179414493499583473568873253067921639513996596738275817909624857593693291980841303291145613566466575233283651420134915764961372875933822262953420444548349180436583183291944875599477240814774580187144637965487250578134990402443365677985388481961492444981994523034245619781853365476552719460960795929666883665704293897310201276011658074359194189359660792496027472226428571547971602259808697441435358578480589837766911684200275636889192254762678512597000452676191374475932796663842865744658264924913771676415404179920096074751516422872997665425047457428327276230059296132722787915300105002019006293320082955378715908263653377755031155794063450515731009402407584683132870206376994025920790298591144213659942668622062191441346200098342943955169522532574271644954360217472458521489671859465232568419404182043966092211744372699797375966048010775453444600153524772238401414789562651410289808994960533132759532092895779406940925252906166612153699850759933762897947175972147868784008320247586210378556711332739463277940255289047962323306946068381887446046387745247925675240182981190836264964640612069909458682443392729946084099312047752966806439331403663934969942958022237945205992581178803606156982034385347182766573351768749665172549908638337611953199808161937885366709285043276595726484068138091188914698151703122773726725261370542355162118164302728812259192476428938730724109825922331973256105091200551566581350508061922762910078528219869913214146575557249199263634241165352226570749618907050553115468306669184485910269806225894530809823102279231750061652042560772530576713148647858705369649642907780603247428680176236527220826640665659902650188140474762163503557640566711903907798932853656216227739411210513756695569391593763704981001125
I met the same problem. I found the solution in the solution from kb.vmware.com.
It works for me by adding
usb.quirks.device0 = "0xvid:0xpid skip-refresh"
Detail as below:
vmx | USB: Found device [name:Apple\ IR\ Receiver vid:05ac pid:8240 path:13/7/2 speed:full family:hid]
The line has the name of the USB device and its vid and pid information. Make a note of the vid and pid values.
usb.quirks.device0 = "0xvid:0xpid skip-reset"
For example, for the Apple device found in step 2, this line is:
usb.quirks.device0 = "0x05ac:0x8240 skip-reset"
usb.quirks.device0 = "0xvid:0xpid skip-refresh"
usb.quirks.device0 = "0xvid:0xpid skip-setconfig"
usb.quirks.device0 = "0xvid:0xpid skip-reset, skip-refresh, skip-setconfig"
Notes:
Refer this to see in detail.
Here is the jQuery function I use:
function isExists(var elemId){
return jQuery('#'+elemId).length > 0;
}
This will return a boolean value. If element exists, it returns true.
If you want to select element by class name, just replace #
with .
Evidence that std::unordered_map
uses a hash map in GCC stdlibc++ 6.4
This was mentioned at: https://stackoverflow.com/a/3578247/895245 but in the following answer: What data structure is inside std::map in C++? I have given further evidence of such for the GCC stdlibc++ 6.4 implementation by:
Here is a preview of the performance characteristic graph described in that answer:
How to use a custom class and hash function with unordered_map
This answer nails it: C++ unordered_map using a custom class type as the key
Excerpt: equality:
struct Key
{
std::string first;
std::string second;
int third;
bool operator==(const Key &other) const
{ return (first == other.first
&& second == other.second
&& third == other.third);
}
};
Hash function:
namespace std {
template <>
struct hash<Key>
{
std::size_t operator()(const Key& k) const
{
using std::size_t;
using std::hash;
using std::string;
// Compute individual hash values for first,
// second and third and combine them using XOR
// and bit shifting:
return ((hash<string>()(k.first)
^ (hash<string>()(k.second) << 1)) >> 1)
^ (hash<int>()(k.third) << 1);
}
};
}
Make sure you have MainActivity
and .ScanActivity
into your AndroidManifest.xml
file:
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ScanActivity">
</activity>
You can create a custom collector that convert a stream to array.
public static <T> Collector<T, ?, T[]> toArray( IntFunction<T[]> converter )
{
return Collectors.collectingAndThen(
Collectors.toList(),
list ->list.toArray( converter.apply( list.size() ) ) );
}
and a quick use
List<String> input = Arrays.asList( ..... );
String[] result = input.stream().
.collect( CustomCollectors.**toArray**( String[]::new ) );
This will print the data in columns and comes to new line once last column is reached.
ResultSetMetaData resultSetMetaData = res.getMetaData();
int columnCount = resultSetMetaData.getColumnCount();
for(int i =1; i<=columnCount; i++){
if(!(i==columnCount)){
System.out.print(res.getString(i)+"\t");
}
else{
System.out.println(res.getString(i));
}
}
This splits the Seatblocks by space and gives each its own row.
In [43]: df
Out[43]:
CustNum CustomerName ItemQty Item Seatblocks ItemExt
0 32363 McCartney, Paul 3 F04 2:218:10:4,6 60
1 31316 Lennon, John 25 F01 1:13:36:1,12 1:13:37:1,13 300
In [44]: s = df['Seatblocks'].str.split(' ').apply(Series, 1).stack()
In [45]: s.index = s.index.droplevel(-1) # to line up with df's index
In [46]: s.name = 'Seatblocks' # needs a name to join
In [47]: s
Out[47]:
0 2:218:10:4,6
1 1:13:36:1,12
1 1:13:37:1,13
Name: Seatblocks, dtype: object
In [48]: del df['Seatblocks']
In [49]: df.join(s)
Out[49]:
CustNum CustomerName ItemQty Item ItemExt Seatblocks
0 32363 McCartney, Paul 3 F04 60 2:218:10:4,6
1 31316 Lennon, John 25 F01 300 1:13:36:1,12
1 31316 Lennon, John 25 F01 300 1:13:37:1,13
Or, to give each colon-separated string in its own column:
In [50]: df.join(s.apply(lambda x: Series(x.split(':'))))
Out[50]:
CustNum CustomerName ItemQty Item ItemExt 0 1 2 3
0 32363 McCartney, Paul 3 F04 60 2 218 10 4,6
1 31316 Lennon, John 25 F01 300 1 13 36 1,12
1 31316 Lennon, John 25 F01 300 1 13 37 1,13
This is a little ugly, but maybe someone will chime in with a prettier solution.
.vs
folder..vs
folder, you will see a config
folder in it. Delete its content.File
menu.I do not recommend deleting IIS Express folder or messing with the config file in it.
Here's the final solution for the case in update section (with the help of Google Collections):
Collections2.transform (fooCollection, new Function<Foo, Bar>() {
public Bar apply (Foo foo) {
return new Bar (foo);
}
}).toArray (new Bar[fooCollection.size()]);
But, the key approach here was mentioned in the doublep's answer (I forgot for toArray
method).
FWIW I just hit this on a slightly different use case. I scoured and scoured my code looking for where I might've used a 'str' variable, but could not find it. I started to suspect that maybe one of the modules I imported was the culprit... but alas, it was a missing '%' character in a formatted print statement.
Here's an example:
x=5
y=6
print("x as a string is: %s. y as a string is: %s" (str(x) , str(y)) )
This will result in the output:
TypeError: 'str' object is not callable
The correction is:
x=5
y=6
print("x as a string is: %s. y as a string is: %s" % (str(x) , str(y)) )
Resulting in our expected output:
x as a string is: 5. y as a string is: 6
if you just run the main.py
under the app
, just import like
from mymodule import myclass
if you want to call main.py
on other folder, use:
from .mymodule import myclass
for example:
+-- app
¦ +-- __init__.py
¦ +-- main.py
¦ +-- mymodule.py
+-- __init__.py
+-- run.py
main.py
from .mymodule import myclass
run.py
from app import main
print(main.myclass)
So I think the main question of you is how to call app.main
.
Use PHP DOM to parse and add <br/>
in it. Like this:
$html = '<textarea> put returns between paragraphs
for linebreak add 2 spaces at end
indent code by 4 spaces
quote by placing > at start of line
</textarea>';
//parsing begins here:
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('textarea');
//get text and add <br/> then remove last <br/>
$lines = $nodes->item(0)->nodeValue;
//split it by newlines
$lines = explode("\n", $lines);
//add <br/> at end of each line
foreach($lines as $line)
$output .= $line . "<br/>";
//remove last <br/>
$output = rtrim($output, "<br/>");
//display it
var_dump($output);
This outputs:
string ' put returns between paragraphs
<br/>for linebreak add 2 spaces at end
<br/>indent code by 4 spaces
<br/>quote by placing > at start of line
' (length=141)
Pretty much the same way that you always have, with "Modules" instead of classes and just use "Public" instead of the old "Global" keyword:
Public Module Module1
Public Foo As Integer
End Module
The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.
as a single line:
long value_ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now()).time_since_epoch()).count();
define class in models.py and a function in it.
class all_products(models.Model):
def get_all_products():
items = []
with open('EXACT FILE PATH OF YOUR CSV FILE','r') as fp:
# You can also put the relative path of csv file
# with respect to the manage.py file
reader1 = csv.reader(fp, delimiter=';')
for value in reader1:
items.append(value)
return items
You can access ith element in the list as items[i]
<table id="table1"></table>
<table id="table2"></table>
or
<table class="table1"></table>
<table class="table2"></table>
The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:
try:
assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
print 'Houston, we have a problem.'
raise
Which gives the following output that includes the offending statement and line number:
Houston, we have a problem.
Traceback (most recent call last):
File "/tmp/poop.py", line 2, in <module>
assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie
Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):
import logging
try:
assert False == True
except AssertionError:
logging.error("Nothing is real but I can't quit...", exc_info=True)
I had this problem and the issue was that I had the package loaded in another R instance. Simply closing all R instances and installing on a fresh instance allowed for the package to be installed.
Generally, you can also install if every remaining instance has never loaded the package as well (even if it installed an old version).
The other answers here clearly explained what does it mean.I like to explain its use.
You can select an element in the elements
tab and switch to console
tab in chrome. Just type $0 or $1
or whatever number and press enter and the element will be displayed in the console for your use.
$gcc -o program program.c -l <library_to_resolve_program.c's_unresolved_symbols>
A good description of why the placement of -l dl matters
But there's also a pretty succinct explanation in the docs From $man gcc
-llibrary -l library Search the library named library when linking. (The second alternative with the library as a separate argument is only for POSIX compliance and is not recommended.)
It makes a difference where in the command you write this option; the
linker searches and processes libraries and object files in the order
they are specified. Thus, foo.o -lz bar.o searches library z after
file foo.o but before bar.o. If bar.o refers to functions in z,
those functions may not be loaded.
On linux, if you can afford the run time cost (for debugging), you can use valgrind with the massif tool:
http://valgrind.org/docs/manual/ms-manual.html
It is heavy weight, but very useful.
I'm not aware of a tool that does this well but I've seen a variety of homegrown solutions. The common thread of these is to minimise the binary data under version control and maximise textual data to leverage the power of conventional scc systems. To do this:
The answer provided by PointedEars is everything most of us need. But by following Mathias Bynens's answer, I went on a Wikipedia trip and found this: https://en.wikipedia.org/wiki/Newline.
The following is a drop-in function that implements everything the above Wiki page considers "new line" at the time of this answer.
If something doesn't fit your case, just remove it. Also, if you're looking for performance this might not be it, but for a quick tool that does the job in any case, this should be useful.
// replaces all "new line" characters contained in `someString` with the given `replacementString`
const replaceNewLineChars = ((someString, replacementString = ``) => { // defaults to just removing
const LF = `\u{000a}`; // Line Feed (\n)
const VT = `\u{000b}`; // Vertical Tab
const FF = `\u{000c}`; // Form Feed
const CR = `\u{000d}`; // Carriage Return (\r)
const CRLF = `${CR}${LF}`; // (\r\n)
const NEL = `\u{0085}`; // Next Line
const LS = `\u{2028}`; // Line Separator
const PS = `\u{2029}`; // Paragraph Separator
const lineTerminators = [LF, VT, FF, CR, CRLF, NEL, LS, PS]; // all Unicode `lineTerminators`
let finalString = someString.normalize(`NFD`); // better safe than sorry? Or is it?
for (let lineTerminator of lineTerminators) {
if (finalString.includes(lineTerminator)) { // check if the string contains the current `lineTerminator`
let regex = new RegExp(lineTerminator.normalize(`NFD`), `gu`); // create the `regex` for the current `lineTerminator`
finalString = finalString.replace(regex, replacementString); // perform the replacement
};
};
return finalString.normalize(`NFC`); // return the `finalString` (without any Unicode `lineTerminators`)
});
To get RHEL 7 64-bit to compile gcc 4.8 32-bit programs, you'll need to do two things.
Make sure all the 32-bit gcc 4.8 development tools are completely installed:
sudo yum install glibc-devel.i686 libgcc.i686 libstdc++-devel.i686 ncurses-devel.i686
Compile programs using the -m32 flag
gcc pgm.c -m32 -o pgm
stolen from here : How to Compile 32-bit Apps on 64-bit RHEL? - I only had to do step 1.
In general, when you need a character that is "special" in regexes, just prefix it with a \
. So a literal [
would be \[
.
fcntl()
or ioctl()
are used to set the properties for file streams. When you use this function to make a socket non-blocking, function like accept()
, recv()
and etc, which are blocking in nature will return error and errno
would be set to EWOULDBLOCK
. You can poll file descriptor sets to poll on sockets.
I'm not 100% on why (actually came here to search for the answer), but this also works, and doesn't require replacing all nan values.
import pandas as pd
import numpy as np
df = pd.DataFrame([["foo1"], ["foo2"], ["bar"], [np.nan]], columns=['a'])
newdf = df.loc[df['a'].str.contains('foo') == True]
Works with or without .loc
.
I have no idea why this works, as I understand it when you're indexing with brackets pandas evaluates whatever's inside the bracket as either True
or False
. I can't tell why making the phrase inside the brackets 'extra boolean' has any effect at all.
If that's all what you want to do, you don't need to convert it into an array. You can just access it as:
string myData=yourDataTable.Rows[0][1].ToString();//Gives you USA
The absolute path to the directory where
./manage.py collectstatic
will collect static files for deployment. Example:STATIC_ROOT="/var/www/example.com/static/"
now the command ./manage.py collectstatic
will copy all the static files(ie in static folder in your apps, static files in all paths) to the directory /var/www/example.com/static/
. now you only need to serve this directory on apache or nginx..etc.
The
URL
of which the static files inSTATIC_ROOT
directory are served(by Apache or nginx..etc). Example:/static/
orhttp://static.example.com/
If you set STATIC_URL = 'http://static.example.com/'
, then you must serve the STATIC_ROOT
folder (ie "/var/www/example.com/static/"
) by apache or nginx at url 'http://static.example.com/'
(so that you can refer the static file '/var/www/example.com/static/jquery.js'
with 'http://static.example.com/jquery.js'
)
Now in your django-templates, you can refer it by:
{% load static %}
<script src="{% static "jquery.js" %}"></script>
which will render:
<script src="http://static.example.com/jquery.js"></script>
It would return NULL but if taken as BIGINT would show the number
They're essentially the same... They both use swig for templating, they both use karma and mocha for tests, passport integration, nodemon, etc.
Why so similar? Mean.js is a fork of Mean.io and both initiatives were started by the same guy... Mean.io is now under the umbrella of the company Linnovate and looks like the guy (Amos Haviv) stopped his collaboration with this company and started Mean.js. You can read more about the reasons here.
Now... main (or little) differences you can see right now are:
SCAFFOLDING AND BOILERPLATE GENERATION
Mean.io uses a custom cli tool named 'mean'
Mean.js uses Yeoman Generators
MODULARITY
Mean.io uses a more self-contained node packages modularity with client and server files inside the modules.
Mean.js uses modules just in the front-end (for angular), and connects them with Express. Although they were working on vertical modules as well...
BUILD SYSTEM
Mean.io has recently moved to gulp
Mean.js uses grunt
DEPLOYMENT
Both have Dockerfiles in their respective repos, and Mean.io has one-click install on Google Compute Engine, while Mean.js can also be deployed with one-click install on Digital Ocean.
DOCUMENTATION
Mean.io has ok docs
Mean.js has AWESOME docs
COMMUNITY
Mean.io has a bigger community since it was the original boilerplate
Mean.js has less momentum but steady growth
On a personal level, I like more the philosophy and openness of MeanJS and more the traction and modules/packages approach of MeanIO. Both are nice, and you'll end probably modifying them, so you can't really go wrong picking one or the other. Just take them as starting point and as a learning exercise.
MEAN is a generic way (coined by Valeri Karpov) to describe a boilerplate/framework that takes "Mongo + Express + Angular + Node" as the base of the stack. You can find frameworks with this stack that use other denomination, some of them really good for RAD (Rapid Application Development) and building SPAs. Eg:
You also have Hackathon Starter. It doesn't have A of MEAN (it is 'MEN'), but it rocks..
Have fun!
No need to use the command line.
If you FILE-> "Export Android Application" in the ADK then it will allow you to create a key and then produce your .apk file.
background-image
instead of background
This works in Opera : http://jsfiddle.net/ZNsbU/5/
But it doesn't work in FF5 nor IE8. (yay for outdated browsers :D )
body {
background:url(http://www.google.com/intl/en_com/images/srpr/logo3w.png) 400px 200px / 600px 400px no-repeat;
}
You could do it like this :
body {
background:url(http://www.google.com/intl/en_com/images/srpr/logo3w.png) 400px 400px no-repeat;
background-size:20px 20px
}
Which works in FF5 and Opera but not in IE8.
A workaround is to transpose the DataFrame
and iterate over the rows.
for column_name, column in df.transpose().iterrows():
print column_name
The NoSuchMethodError javadoc says this:
Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.
Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.
In your case, this Error is a strong indication that your webapp is using the wrong version of the JAR defining the org.objectweb.asm.*
classes.
final keyword in the method input parameter is not needed. Java creates a copy of the reference to the object, so putting final on it doesn't make the object final but just the reference, which doesn't make sense
Declare a variable for active window
var activeInfoWindow;
and bind this code in marker listener
marker.addListener('click', function () {
if (activeInfoWindow) { activeInfoWindow.close();}
infowindow.open(map, marker);
activeInfoWindow = infowindow;
});
Go into task manager and see if you have any Microsoft Excel Processes running in the background. I closed my excel background processes and my code worked again.
You can fix this issue without opening the storyboard as a source. This warning is triggered by UILabels if numberOfLines !=1 and deployment target is < 8.0
HOW TO FIND IT?
Why not something like this?
//is q a rotation of p?
bool isRotation(string p, string q) {
string table = q + q;
return table.IndexOf(p) != -1;
}
Of course, you could write your own IndexOf() function; I'm not sure if .NET uses a naive way or a faster way.
Naive:
int IndexOf(string s) {
for (int i = 0; i < this.Length - s.Length; i++)
if (this.Substring(i, s.Length) == s) return i;
return -1;
}
Faster:
int IndexOf(string s) {
int count = 0;
for (int i = 0; i < this.Length; i++) {
if (this[i] == s[count])
count++;
else
count = 0;
if (count == s.Length)
return i - s.Length;
}
return -1;
}
Edit: I might have some off-by-one problems; don't feel like checking. ;)
it might be nice toggling in one line of code:
let video = $('video')[0];_x000D_
video[video.paused ? 'play' : 'pause']();
_x000D_
<View
style={{
flexDirection: 'row',
padding: 10,
}}
>
<Text numberOfLines={5} style={{flex:1}}>
This is a very long text that will overflow on a small device This is a very
long text that will overflow on a small deviceThis is a very long text that
will overflow on a small deviceThis is a very long text that will overflow
on a small device
</Text>
</View>
var text = "http://example.com";
text = "'"+text+"'";
Would attach the single quotes (') to the front and the back of the string.
Here's my solution, i would love anyone's opinion on this, it's simple for beginners
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.Scanner;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
public class Cryptography {
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
Encoder encoder = Base64.getUrlEncoder().withoutPadding();
System.out.print("Password: ");
String strPassword = new Scanner(System.in).nextLine();
byte[] bSalt = Salt();
String strSalt = encoder.encodeToString(bSalt); // Byte to String
System.out.println("Salt: " + strSalt);
System.out.println("String to be hashed: " + strPassword + strSalt);
String strHash = encoder.encodeToString(Hash(strPassword, bSalt)); // Byte to String
System.out.println("Hashed value (Password + Salt value): " + strHash);
}
private static byte[] Salt() {
SecureRandom random = new SecureRandom();
byte salt[] = new byte[6];
random.nextBytes(salt);
return salt;
}
private static byte[] Hash(String password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] hash = factory.generateSecret(spec).getEncoded();
return hash;
}
}
You can validate by just decoding the strSalt
and using the same hash
method:
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
Encoder encoder = Base64.getUrlEncoder().withoutPadding();
Decoder decoder = Base64.getUrlDecoder();
System.out.print("Password: ");
String strPassword = new Scanner(System.in).nextLine();
String strSalt = "Your Salt String Here";
byte[] bSalt = decoder.decode(strSalt); // String to Byte
System.out.println("Salt: " + strSalt);
System.out.println("String to be hashed: " + strPassword + strSalt);
String strHash = encoder.encodeToString(Hash(strPassword, bSalt)); // Byte to String
System.out.println("Hashed value (Password + Salt value): " + strHash);
}
Include the System.DirectoryServices.dll, then use the code below:
DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName);
string userNames="Users: ";
foreach (DirectoryEntry child in directoryEntry.Children)
{
if (child.SchemaClassName == "User")
{
userNames += child.Name + Environment.NewLine ;
}
}
MessageBox.Show(userNames);
Also try changing from this:
SELECT * FROM table WHERE Contains(Column, "test") > 0;
To this:
SELECT * FROM table WHERE Contains(Column, '"*test*"') > 0;
The former will find records with values like "this is a test" and "a test-case is the plan".
The latter will also find records with values like "i am testing this" and "this is the greatest".
The JavaDoc explains it very well:
With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
SO_TIMEOUT
is the timeout that a read()
call will block. If the timeout is reached, a java.net.SocketTimeoutException will be thrown. If you want to block forever put this option to zero (the default value), then the read()
call will block until at least 1 byte could be read.
I'm attempting to address both the question and the current bounty with this question.
The bounty requires that the caller be obtained in strict mode, and the only way I can see this done is by referring to a function declared outside of strict mode.
For example, the following is non-standard but has been tested with previous (29/03/2016) and current (1st August 2018) versions of Chrome, Edge and Firefox.
function caller()_x000D_
{_x000D_
return caller.caller.caller;_x000D_
}_x000D_
_x000D_
'use strict';_x000D_
function main()_x000D_
{_x000D_
// Original question:_x000D_
Hello();_x000D_
// Bounty question:_x000D_
(function() { console.log('Anonymous function called by ' + caller().name); })();_x000D_
}_x000D_
_x000D_
function Hello()_x000D_
{_x000D_
// How do you find out the caller function is 'main'?_x000D_
console.log('Hello called by ' + caller().name);_x000D_
}_x000D_
_x000D_
main();
_x000D_
Refer to this link :https://gis.stackexchange.com/questions/84885/whats-the-difference-between-vincenty-and-great-circle-distance-calculations
this actually gives two ways of getting distance. They are Haversine and Vincentys. From my research I came to know that Vincentys is relatively accurate. Also use import statement to make the implementation.
You can use Date.getTime()
function, or the Date
object itself which when divided returns the time in milliseconds.
var d = new Date();
d/1000
> 1510329641.84
d.getTime()/1000
> 1510329641.84
import * as utils from './utils.js';
If you do the above, you will be able to use functions in utils.js as
utils.someFunction()
Just for completion: All the answers above are going for a shallow copy - keeping the reference of the original objects. I you want a deep copy, your (reference-) class in the list have to implement a clone / copy method, which provides a deep copy of a single object. Then you can use:
newList.addAll(oldList.stream().map(s->s.clone()).collect(Collectors.toList()));
Here is another solution
Set a hidden scope variable in your html then you can use it from your controller:
<span style="display:none" >{{ formValid = myForm.$valid}}</span>
Here is the full working example:
angular.module('App', [])_x000D_
.controller('myController', function($scope) {_x000D_
$scope.userType = 'guest';_x000D_
$scope.formValid = false;_x000D_
console.info('Ctrl init, no form.');_x000D_
_x000D_
$scope.$watch('myForm', function() {_x000D_
console.info('myForm watch');_x000D_
console.log($scope.formValid);_x000D_
});_x000D_
_x000D_
$scope.isFormValid = function() {_x000D_
//test the new scope variable_x000D_
console.log('form valid?: ', $scope.formValid);_x000D_
};_x000D_
});
_x000D_
<!doctype html>_x000D_
<html ng-app="App">_x000D_
<head>_x000D_
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<form name="myForm" ng-controller="myController">_x000D_
userType: <input name="input" ng-model="userType" required>_x000D_
<span class="error" ng-show="myForm.input.$error.required">Required!</span><br>_x000D_
<tt>userType = {{userType}}</tt><br>_x000D_
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>_x000D_
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>_x000D_
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>_x000D_
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>_x000D_
_x000D_
_x000D_
/*-- Hidden Variable formValid to use in your controller --*/_x000D_
<span style="display:none" >{{ formValid = myForm.$valid}}</span>_x000D_
_x000D_
_x000D_
<br/>_x000D_
<button ng-click="isFormValid()">Check Valid</button>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
You need to add the original repository (the one that you forked) as a remote.
git remote add github (clone url for the orignal repository)
Then you need to bring in the changes to your local repository
git fetch github
Now you will have all the branches of the original repository in your local one. For example, the master branch will be github/master
. With these branches you can do what you will. Merge them into your branches etc
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
// Assume x, y, and diameter are instance variables.
Ellipse2D.Double circle = new Ellipse2D.Double(x, y, diameter, diameter);
g2d.fill(circle);
...
}
Here are some docs about paintComponent (link).
You should override that method in your JPanel and do something similar to the code snippet above.
In your ActionListener you should specify x, y, diameter
and call repaint()
.
Instead of using array you can use the ArrayList
directly and can use the contains method to check the value which u have passes with the ArrayList
.
Had the same problem. Here's how I solved it: Go to Package Explorer. Right click on JRE System Library and go to Properties. In the Classpath Container > Select JRE for the project build path select the third option (Workspace default JRE).
It seems that you have a bunch of describe
s that never have end
s keywords, starting with describe "when email format is invalid" do
until describe "when email address is already taken" do
Put an end on those guys and you're probably done =)
Agile is the practice and Scrum is the process to following this practice same as eXtreme Programming (XP) and Kanban are the alternative process to following Agile development practice.
Here's a safe way:
using (var transitron = ctx.Database.BeginTransaction())
{
try
{
var employer = new Employ { Id = 1 };
ctx.Entry(employer).State = EntityState.Deleted;
ctx.SaveChanges();
transitron.Commit();
}
catch (Exception ex)
{
transitron.Rollback();
//capture exception like: entity does not exist, Id property does not exist, etc...
}
}
Here you can pile up all the changes you want, so you can do a series of deletion before the SaveChanges and Commit, so they will be applied only if they are all successful.
You can use laravel MessageBag to add our own messages to existing messages.
To use MessageBag you need to use:
use Illuminate\Support\MessageBag;
In the controller:
MessageBag $message_bag
$message_bag->add('message', trans('auth.confirmation-success'));
return redirect('login')->withSuccess($message_bag);
Hope it will help some one.
Use below code..
$('#globalCheckbox').click(function(){
if($(this).prop("checked")) {
$(".checkBox").prop("checked", true);
} else {
$(".checkBox").prop("checked", false);
}
});
$('.checkBox').click(function(){
if($(".checkBox").length == $(".checkBox:checked").length) {
//if the length is same then untick
$("#globalCheckbox").prop("checked", false);
}else {
//vise versa
$("#globalCheckbox").prop("checked", true);
}
});
Missing Context file location in configuration can cause this, one approach to solve this:
like:
@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })
More details
@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })
public class UserServiceTest extends AbstractJUnit4SpringContextTests {}
Reference:Thanks to @Xstian
Execute this at the terminal to see conflicting configurations listening to the same port:
grep -R default_server /etc/nginx
You can use the following code:
dateForButton = dateForButton.Subtract(TimeSpan.FromDays(1));
on your Promise response you requested
response.json()
but this works well if your server sends json response in return especially if you're using Node Js on the server side
So check again and make sure your server sends json as response as said if its NodeJS the response could be
res.json(YOUR-DATA-RESPONSE)
java.util.Deque
has descendingIterator()
- if your List
is a Deque
, you can use that.
Using just awk you could do (I also shortened some of your piping):
strings -a libAddressDoctor5.so | awk '/EngineVersion/ { if(NR==2) { gsub("\"",""); print $2 } }'
I can't verify it for you because I don't know your exact input, but the following works:
echo "Blah EngineVersion=\"123\"" | awk '/EngineVersion/ { gsub("\"",""); print $2 }'
See also this question on removing single quotes.
According to @Data description you can use:
All generated getters and setters will be public. To override the access level, annotate the field or class with an explicit @Setter and/or @Getter annotation. You can also use this annotation (by combining it with AccessLevel.NONE) to suppress generating a getter and/or setter altogether.
This is my "one-line" solution:
$.postJSON = function(url, data, func) { $.post(url+(url.indexOf("?") == -1 ? "?" : "&")+"callback=?", data, func, "json"); }
In order to use jsonp, and POST method, this function adds the "callback" GET parameter to the URL. This is the way to use it:
$.postJSON("http://example.com/json.php",{ id : 287 }, function (data) {
console.log(data.name);
});
The server must be prepared to handle the callback GET parameter and return the json string as:
jsonp000000 ({"name":"John", "age": 25});
in which "jsonp000000" is the callback GET value.
In PHP the implementation would be like:
print_r($_GET['callback']."(".json_encode($myarr).");");
I made some cross-domain tests and it seems to work. Still need more testing though.
It's important to note that once you generate a core file you'll need to use the gdb tool to look at it. For gdb to make sense of your core file, you must tell gcc to instrument the binary with debugging symbols: to do this, you compile with the -g flag:
$ g++ -g prog.cpp -o prog
Then, you can either set "ulimit -c unlimited" to let it dump a core, or just run your program inside gdb. I like the second approach more:
$ gdb ./prog
... gdb startup output ...
(gdb) run
... program runs and crashes ...
(gdb) where
... gdb outputs your stack trace ...
I hope this helps.
I was having a similar problem. I was not using the ACL stuff, so I didn't need s3:PutObjectAcl
.
In my case, I was doing (in Serverless Framework YML):
- Effect: Allow
Action:
- s3:PutObject
Resource: "arn:aws:s3:::MyBucketName"
Instead of:
- Effect: Allow
Action:
- s3:PutObject
Resource: "arn:aws:s3:::MyBucketName/*"
Which adds a /*
to the end of the bucket ARN.
Hope this helps.
So far we have three competing alternatives for how to do this:
Console.Write("\r{0} ", value); // Option 1: carriage return
Console.Write("\b\b\b\b\b{0}", value); // Option 2: backspace
{ // Option 3 in two parts:
Console.SetCursorPosition(0, Console.CursorTop); // - Move cursor
Console.Write(value); // - Rewrite
}
I've always used Console.CursorLeft = 0
, a variation on the third option, so I decided to do some tests. Here's the code I used:
public static void CursorTest()
{
int testsize = 1000000;
Console.WriteLine("Testing cursor position");
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < testsize; i++)
{
Console.Write("\rCounting: {0} ", i);
}
sw.Stop();
Console.WriteLine("\nTime using \\r: {0}", sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
int top = Console.CursorTop;
for (int i = 0; i < testsize; i++)
{
Console.SetCursorPosition(0, top);
Console.Write("Counting: {0} ", i);
}
sw.Stop();
Console.WriteLine("\nTime using CursorLeft: {0}", sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
Console.Write("Counting: ");
for (int i = 0; i < testsize; i++)
{
Console.Write("\b\b\b\b\b\b\b\b{0,8}", i);
}
sw.Stop();
Console.WriteLine("\nTime using \\b: {0}", sw.ElapsedMilliseconds);
}
On my machine, I get the following results:
Additionally, SetCursorPosition
caused noticeable flicker that I didn't observe with either of the alternatives. So, the moral is to use backspaces or carriage returns when possible, and thanks for teaching me a faster way to do this, SO!
Update: In the comments, Joel suggests that SetCursorPosition is constant with respect to the distance moved while the other methods are linear. Further testing confirms that this is the case, however constant time and slow is still slow. In my tests, writing a long string of backspaces to the console is faster than SetCursorPosition until somewhere around 60 characters. So backspace is faster for replacing portions of the line shorter than 60 characters (or so), and it doesn't flicker, so I'm going to stand by my initial endorsement of \b over \r and SetCursorPosition
.
From MSDN
$0 - "Substitutes the last substring matched by group number number (decimal)."
In .NET Regular expressions group 0 is always the entire match. For a literal $ you need to
string value = Regex.Replace("%PolicyAmount%", "%PolicyAmount%", @"$$0", RegexOptions.IgnoreCase);
def previous_line(self, opened_file):
opened_file.seek(0, os.SEEK_END)
position = opened_file.tell()
buffer = bytearray()
while position >= 0:
opened_file.seek(position)
position -= 1
new_byte = opened_file.read(1)
if new_byte == self.NEW_LINE:
parsed_string = buffer.decode()
yield parsed_string
buffer = bytearray()
elif new_byte == self.EMPTY_BYTE:
continue
else:
new_byte_array = bytearray(new_byte)
new_byte_array.extend(buffer)
buffer = new_byte_array
yield None
to use:
opened_file = open(filepath, "rb")
iterator = self.previous_line(opened_file)
line = next(iterator) #one step
close(opened_file)
If you need to do this on the backend you can use the following URL structure:
https://maps.googleapis.com/maps/api/geocode/json?address=[STREET_ADDRESS]&key=[YOUR_API_KEY]
Sample PHP code using curl:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://maps.googleapis.com/maps/api/geocode/json?address=' . rawurlencode($address) . '&key=' . $api_key);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
$json = curl_exec($curl);
curl_close ($curl);
$obj = json_decode($json);
See additional documentation for more details and expected json response.
The docs provide sample output and will assist you in getting your own API key in order to be able to make requests to the Google Maps Geocoding API.
You can also simply create ONLY a UIView in Interface builder and drag & drop the ImageView and UILabel (to make it look like your desired header) and then use that.
Once your UIView looks like the way you want it too, you can programmatically initialize it from the XIB and add to your UITableView. In other words, you dont have to design the ENTIRE table in IB. Just the headerView (this way the header view can be reused in other tables as well)
For example I have a custom UIView for one of my table headers. The view is managed by a xib file called "CustomHeaderView" and it is loaded into the table header using the following code in my UITableViewController subclass:
-(UIView *) customHeaderView {
if (!customHeaderView) {
[[NSBundle mainBundle] loadNibNamed:@"CustomHeaderView" owner:self options:nil];
}
return customHeaderView;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Set the CustomerHeaderView as the tables header view
self.tableView.tableHeaderView = self.customHeaderView;
}
h2.myClass
refers to all h2
with class="myClass"
.
.myClass h2
refers to all h2
that are children of (i.e. nested in) elements with class="myClass"
.
If you want the h2
in your HTML to appear blue, change the CSS to the following:
.myClass h2 {
color: blue;
}
If you want to be able to reference that h2
by a class rather than its tag, you should leave the CSS as it is and give the h2
a class in the HTML:
<h2 class="myClass">This header should be BLUE to match the element.class selector</h2>
function
getValue(input){
var value = input.value ? parseInt(input.value) : 0;
let min = input.min;
let max = input.max;
if(value < min)
return parseInt(min);
else if(value > max)
return parseInt(max);
else return value;
}
Usages
changeDotColor = (event) => {
let value = this.getValue(event.target) //value will be always number
console.log(value)
console.log(typeof value)
}
For windows users: if git config
or set http_proxy=
doesn't work, this answer may help:
replace the git://
protocol of the git repository with http://
. Note, you'll have to set the http_proxy
first, anyways.
I had also similar problem. In my case brokerUrl was not configured properly. So that's way I received following Error:
Cause: Error While attempting to add new Connection to the pool: nested exception is javax.jms.JMSException: Could not connect to broker URL : tcp://localhost:61616. Reason: java.net.ConnectException: Connection refused
& I resolved it following way.
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
connectionFactory.setBrokerURL("tcp://hostname:61616");
connectionFactory.setUserName("admin");
connectionFactory.setPassword("admin");
Just use TeX ! This works :
title(r"""\Huge{Big title !} \newline \tiny{Small subtitle !}""")
EDIT: To enable TeX processing, you need to add the "usetex = True" line to matplotlib parameters:
fig_size = [12.,7.5]
params = {'axes.labelsize': 8,
'text.fontsize': 6,
'legend.fontsize': 7,
'xtick.labelsize': 6,
'ytick.labelsize': 6,
'text.usetex': True, # <-- There
'figure.figsize': fig_size,
}
rcParams.update(params)
I guess you also need a working TeX distribution on your computer. All details are given at this page:
Check out api.hotelsbase.org - its a free xml hotel api No images as of yet though
public static List<Fragment> pullToBackStack() {
List<Fragment> fragments = new ArrayList<>();
List<Map.Entry<String, Fragment>> entryList = new ArrayList<>(backMap.entrySet());
int size = entryList.size();
if (size > 0) {
for (int i = size - 1; i >= 0; i--) {// last Fragments
fragments.add(entryList.get(i).getValue());
backMap.remove(entryList.get(i).getKey());
}
return fragments;
}
return null;
}
You can use the CONCAT
function like this:
SELECT CONCAT(`SUBJECT`, ' ', `YEAR`) FROM `table`
Update:
To get that result you can try this:
SET @rn := 0;
SELECT CONCAT(`SUBJECT`,'-',`YEAR`,'-',LPAD(@rn := @rn+1,3,'0'))
FROM `table`
You can (should) declare it as extern
in a header file, and define it in exactly 1 .c file.
Note that that .c file should also use the header and that the standard pattern looks like:
// file.h
extern int x; // declaration
// file.c
#include "file.h"
int x = 1; // definition and re-declaration
Found this on HTML table: keep the same width for columns
If you set the style table-layout: fixed; on your table, you can override the browser's automatic column resizing. The browser will then set column widths based on the width of cells in the first row of the table. Change your to and remove the inside of it, and then set fixed widths for the cells in .
There's a simpler way to do this:
$(newHtml).appendTo('#myDiv').effects(...);
This turns things around by first creating newHtml
with jQuery(html [, ownerDocument ])
, and then using appendTo(target)
(note the "To
" bit) to add that it to the end of #mydiv
.
Because you now start with $(newHtml)
the end result of appendTo('#myDiv')
is that new bit of html, and the .effects(...)
call will be on that new bit of html too.
ShareDialog shareDialog = new ShareDialog(this);
if(ShareDialog.canShow(ShareLinkContent.class)) {
ShareLinkContent linkContent = new ShareLinkContent.Builder().setContentTitle(strTitle).setContentDescription(strDescription)
.setContentUrl(Uri.parse(strNewsHtmlUrl))
.build();
shareDialog.show(linkContent);
}
There are several ways to intercept the initialization process in Spring. If you have to initialize all beans and autowire/inject them there are at least two ways that I know of that will ensure this. I have only testet the second one but I belive both work the same.
If you are using @Bean you can reference by initMethod, like this.
@Configuration
public class BeanConfiguration {
@Bean(initMethod="init")
public BeanA beanA() {
return new BeanA();
}
}
public class BeanA {
// method to be initialized after context is ready
public void init() {
}
}
If you are using @Component you can annotate with @EventListener like this.
@Component
public class BeanB {
@EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {
}
}
In my case I have a legacy system where I am now taking use of IoC/DI where Spring Boot is the choosen framework. The old system brings many circular dependencies to the table and I therefore must use setter-dependency a lot. That gave me some headaches since I could not trust @PostConstruct since autowiring/injection by setter was not yet done. The order is constructor, @PostConstruct then autowired setters. I solved it with @EventListener annotation which wil run last and at the "same" time for all beans. The example shows implementation of InitializingBean aswell.
I have two classes (@Component) with dependency to each other. The classes looks the same for the purpose of this example displaying only one of them.
@Component
public class BeanA implements InitializingBean {
private BeanB beanB;
public BeanA() {
log.debug("Created...");
}
@PostConstruct
private void postConstruct() {
log.debug("@PostConstruct");
}
@Autowired
public void setBeanB(BeanB beanB) {
log.debug("@Autowired beanB");
this.beanB = beanB;
}
@Override
public void afterPropertiesSet() throws Exception {
log.debug("afterPropertiesSet()");
}
@EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {
log.debug("@EventListener");
}
}
This is the log output showing the order of the calls when the container starts.
2018-11-30 18:29:30.504 DEBUG 3624 --- [ main] com.example.demo.BeanA : Created...
2018-11-30 18:29:30.509 DEBUG 3624 --- [ main] com.example.demo.BeanB : Created...
2018-11-30 18:29:30.517 DEBUG 3624 --- [ main] com.example.demo.BeanB : @Autowired beanA
2018-11-30 18:29:30.518 DEBUG 3624 --- [ main] com.example.demo.BeanB : @PostConstruct
2018-11-30 18:29:30.518 DEBUG 3624 --- [ main] com.example.demo.BeanB : afterPropertiesSet()
2018-11-30 18:29:30.518 DEBUG 3624 --- [ main] com.example.demo.BeanA : @Autowired beanB
2018-11-30 18:29:30.518 DEBUG 3624 --- [ main] com.example.demo.BeanA : @PostConstruct
2018-11-30 18:29:30.518 DEBUG 3624 --- [ main] com.example.demo.BeanA : afterPropertiesSet()
2018-11-30 18:29:30.607 DEBUG 3624 --- [ main] com.example.demo.BeanA : @EventListener
2018-11-30 18:29:30.607 DEBUG 3624 --- [ main] com.example.demo.BeanB : @EventListener
As you can see @EventListener is run last after everything is ready and configured.
This is because the className
value which you are passing as argument for
forName(String className)
method is not found or doesn't exists, or you a re passing the wrong value as the class name. Here is also a link which could help you.
1.
https://docs.oracle.com/javase/7/docs/api/java/lang/ClassNotFoundException.html
2.
https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#forName(java.lang.String)
Update
Module not specified
According to the snapshot you have provided this problem is because you have not determined the app module of your project, so I suggest you to choose the app module from configuration. For example:
This worked for me:
Dim binding As New WebHttpBinding(WebHttpSecurityMode.Transport)
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None
binding.MaxBufferSize = Integer.MaxValue
binding.MaxReceivedMessageSize = Integer.MaxValue
binding.MaxBufferPoolSize = Integer.MaxValue
The built-in submodule os.path has a function for that very task.
import os
os.path.dirname('T:\Data\DBDesign\DBDesign_93_v141b.mdb')
To me it sounds like the simplest way to expose your git repository on the server (which seems to be a Windows machine) would be to share it as a network resource.
Right click the folder "MY_GIT_REPOSITORY" and select "Sharing". This will give you the ability to share your git repository as a network resource on your local network. Make sure you give the correct users the ability to write to that share (will be needed when you and your co-workers push to the repository).
The URL for the remote that you want to configure would probably end up looking something like
file://\\\\189.14.666.666\MY_GIT_REPOSITORY
If you wish to use any other protocol (e.g. HTTP, SSH) you'll have to install additional server software that includes servers for these protocols. In lieu of these the file sharing method is probably the easiest in your case right now.
Add PresentationCore.dll
to your references. This dll url in my pc - C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\PresentationCore.dll
In our case what caused the issue is that the private key we were trying to use was encrypted with a passphrase.
We had to decrypt the private key using ssh-keygen -p
before we could use the private key with the openssl command line tool.
For some reason, this was not working
<p:column headerText="" width="25px" sortBy="#{row.key}">
But this worked:
<p:column headerText="" width="25" sortBy="#{row.key}">
Starting from Oracle 12c R1 (12.1), there is a row limiting clause. It does not use familiar LIMIT
syntax, but it can do the job better with more options. You can find the full syntax here. (Also read more on how this works internally in Oracle in this answer).
To answer the original question, here's the query:
SELECT *
FROM sometable
ORDER BY name
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;
(For earlier Oracle versions, please refer to other answers in this question)
Following examples were quoted from linked page, in the hope of preventing link rot.
CREATE TABLE rownum_order_test (
val NUMBER
);
INSERT ALL
INTO rownum_order_test
SELECT level
FROM dual
CONNECT BY level <= 10;
COMMIT;
SELECT val
FROM rownum_order_test
ORDER BY val;
VAL
----------
1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9
10
10
20 rows selected.
N
rowsSELECT val
FROM rownum_order_test
ORDER BY val DESC
FETCH FIRST 5 ROWS ONLY;
VAL
----------
10
10
9
9
8
5 rows selected.
N
rows, if N
th row has ties, get all the tied rowsSELECT val
FROM rownum_order_test
ORDER BY val DESC
FETCH FIRST 5 ROWS WITH TIES;
VAL
----------
10
10
9
9
8
8
6 rows selected.
x
% of rowsSELECT val
FROM rownum_order_test
ORDER BY val
FETCH FIRST 20 PERCENT ROWS ONLY;
VAL
----------
1
1
2
2
4 rows selected.
SELECT val
FROM rownum_order_test
ORDER BY val
OFFSET 4 ROWS FETCH NEXT 4 ROWS ONLY;
VAL
----------
3
3
4
4
4 rows selected.
SELECT val
FROM rownum_order_test
ORDER BY val
OFFSET 4 ROWS FETCH NEXT 20 PERCENT ROWS ONLY;
VAL
----------
3
3
4
4
4 rows selected.
If it were an "ordered factor" things would be different. Which is not to say I like "ordered factors", I don't, only to say that some relationships are defined for 'ordered factors' that are not defined for "factors". Factors are thought of as ordinary categorical variables. You are seeing the natural sort order of factors which is alphabetical lexical order for your locale. If you want to get an automatic coercion to "numeric" for every column, ... dates and factors and all, then try:
sapply(df, function(x) max(as.numeric(x)) ) # not generally a useful result
Or if you want to test for factors first and return as you expect then:
sapply( df, function(x) if("factor" %in% class(x) ) {
max(as.numeric(as.character(x)))
} else { max(x) } )
@Darrens comment does work better:
sapply(df, function(x) max(as.character(x)) )
max
does succeed with character vectors.
Array.filter is not implemented in many browsers,It is better to define this function if it does not exist.
The source code for Array.prototype is posted in MDN
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp */)
{
"use strict";
if (this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in t)
{
var val = t[i]; // in case fun mutates this
if (fun.call(thisp, val, i, t))
res.push(val);
}
}
return res;
};
}
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for more details
I had this problem, the mistake was actually very silly. I had specified the wrong location for the .dll file, after changing the location to correct location the loading happened correctly (answering so someone else don't make this mistake).
Write the following method:
public boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} // try
catch (Exception e) {
return false;
} // catch
}
Now, you can check whether alert is present or not by using the method written above as below:
if (isAlertPresent()) {
driver.switchTo().alert();
driver.switchTo().alert().accept();
driver.switchTo().defaultContent();
}
I also came to this page after searching "js, when to use 'return false;' Among the other search results was a page I found far more useful and straightforward, on Chris Coyier's CSS-Tricks site: The difference between ‘return false;’ and ‘e.preventDefault();’
The gist of his article is:
function() { return false; }
// IS EQUAL TO
function(e) { e.preventDefault(); e.stopPropagation(); }
though I would still recommend reading the whole article.
Update: After arguing the merits of using return false; as a replacement for e.preventDefault(); & e.stopPropagation(); one of my co-workers pointed out that return false also stops callback execution, as outlined in this article: jQuery Events: Stop (Mis)Using Return False.
These days, many site owners are using CDN services which pulls data from CDN server. If that's your case then you are left with two options:
Create a subdomain and edit DNS by Adding a CNAME record
Don't create a subdomain but only create a CNAME record pointing back to your temporary DNS URL.
This solution only implies to pulling code from CDN which will show that it's fetching data from cdn.sitename.com but practically its pulling from your CDN host.
You may also want to set the button size.
QPixmap pixmap("image_path");
QIcon ButtonIcon(pixmap);
button->setIcon(ButtonIcon);
button->setIconSize(pixmap.rect().size());
button->setFixedSize(pixmap.rect().size());
I have to disagree with the other answers: the built in json
library (in Python 2.7) is not necessarily slower than simplejson
. It also doesn't have this annoying unicode bug.
Here is a simple benchmark:
import json
import simplejson
from timeit import repeat
NUMBER = 100000
REPEAT = 10
def compare_json_and_simplejson(data):
"""Compare json and simplejson - dumps and loads"""
compare_json_and_simplejson.data = data
compare_json_and_simplejson.dump = json.dumps(data)
assert json.dumps(data) == simplejson.dumps(data)
result = min(repeat("json.dumps(compare_json_and_simplejson.data)", "from __main__ import json, compare_json_and_simplejson",
repeat = REPEAT, number = NUMBER))
print " json dumps {} seconds".format(result)
result = min(repeat("simplejson.dumps(compare_json_and_simplejson.data)", "from __main__ import simplejson, compare_json_and_simplejson",
repeat = REPEAT, number = NUMBER))
print "simplejson dumps {} seconds".format(result)
assert json.loads(compare_json_and_simplejson.dump) == data
result = min(repeat("json.loads(compare_json_and_simplejson.dump)", "from __main__ import json, compare_json_and_simplejson",
repeat = REPEAT, number = NUMBER))
print " json loads {} seconds".format(result)
result = min(repeat("simplejson.loads(compare_json_and_simplejson.dump)", "from __main__ import simplejson, compare_json_and_simplejson",
repeat = REPEAT, number = NUMBER))
print "simplejson loads {} seconds".format(result)
print "Complex real world data:"
COMPLEX_DATA = {'status': 1, 'timestamp': 1362323499.23, 'site_code': 'testing123', 'remote_address': '212.179.220.18', 'input_text': u'ny monday for less than \u20aa123', 'locale_value': 'UK', 'eva_version': 'v1.0.3286', 'message': 'Successful Parse', 'muuid1': '11e2-8414-a5e9e0fd-95a6-12313913cc26', 'api_reply': {"api_reply": {"Money": {"Currency": "ILS", "Amount": "123", "Restriction": "Less"}, "ProcessedText": "ny monday for less than \\u20aa123", "Locations": [{"Index": 0, "Derived From": "Default", "Home": "Default", "Departure": {"Date": "2013-03-04"}, "Next": 10}, {"Arrival": {"Date": "2013-03-04", "Calculated": True}, "Index": 10, "All Airports Code": "NYC", "Airports": "EWR,JFK,LGA,PHL", "Name": "New York City, New York, United States (GID=5128581)", "Latitude": 40.71427, "Country": "US", "Type": "City", "Geoid": 5128581, "Longitude": -74.00597}]}}}
compare_json_and_simplejson(COMPLEX_DATA)
print "\nSimple data:"
SIMPLE_DATA = [1, 2, 3, "asasd", {'a':'b'}]
compare_json_and_simplejson(SIMPLE_DATA)
And the results on my system (Python 2.7.4, Linux 64-bit):
Complex real world data:
json dumps 1.56666707993 seconds
simplejson dumps 2.25638604164 seconds
json loads 2.71256899834 seconds
simplejson loads 1.29233884811 secondsSimple data:
json dumps 0.370109081268 seconds
simplejson dumps 0.574181079865 seconds
json loads 0.422876119614 seconds
simplejson loads 0.270955085754 seconds
For dumping, json
is faster than simplejson
.
For loading, simplejson
is faster.
Since I am currently building a web service, dumps()
is more important—and using a standard library is always preferred.
Also, cjson
was not updated in the past 4 years, so I wouldn't touch it.
For all the collections including map use: isEmpty
method which is there on these collection objects. But you have to do a null check before:
Map<String, String> map;
........
if(map!=null && !map.isEmpty())
......
String inputStreamToString(InputStream inputStream, Charset charset) throws IOException {
try (
final StringWriter writer = new StringWriter();
final InputStreamReader reader = new InputStreamReader(inputStream, charset)
) {
reader.transferTo(writer);
return writer.toString();
}
}
foreach (DataRow dr in ds.Tables[0].Rows)
{
//your code here
}
The database must have a name (example DB1), try this one:
OracleConnection con = new OracleConnection("data source=DB1;user id=fastecit;password=fastecit");
In case the TNS is not defined you can also try this one:
OracleConnection con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=DB1)));
User Id=fastecit;Password=fastecit");
You can only delete with your time field, which is a number.
Delete from <measurement> where time=123456
will work. Remember not to give single quotes or double quotes. Its a number.
just add display: inline-block; property and removed width.
Subscribing to the IUS Community Project Repository
cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh
Run the script:
sudo bash setup-ius.sh
Upgrading mod_php with Apache
This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.
Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.
sudo yum remove php-cli mod_php php-common
Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.
sudo yum install mod_php70u php70u-cli php70u-mysqlnd
Finally, restart Apache to load the new version of mod_php:
sudo apachectl restart
You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:
systemctl status httpd
I had this issue after upgrading to the Eclipse 2019-12 release. Somehow the command line to launch the JVM got too long and I had to enable the jar-classpath option in the run configuration (right click on file -> run as -> run configs).
Did you import the packages for the file reading stuff.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
also here
cfiltering(numberOfUsers, numberOfMovies);
Are you trying to create an object or calling a method?
also another thing:
user_movie_matrix[userNo][movieNo]=rating;
you are assigning a value to a member of an instance as if it was a static variable
also remove the Th
in
private int user_movie_matrix[][];Th
Hope this helps.
Intervention Image is an open source PHP image handling and manipulation library http://image.intervention.io/
This library provides a lot of useful features:
Basic Examples
// open an image file
$img = Image::make('public/foo.jpg');
// now you are able to resize the instance
$img->resize(320, 240);
// and insert a watermark for example
$img->insert('public/watermark.png');
// finally we save the image as a new file
$img->save('public/bar.jpg');
Method chaining:
$img = Image::make('public/foo.jpg')->resize(320, 240)->insert('public/watermark.png');
Tips: (In your case) https://laracasts.com/discuss/channels/laravel/file-upload-isvalid-returns-false
Tips 1:
// Tell the validator input file should be an image & check this validation
$rules = array(
'image' => 'mimes:jpeg,jpg,png,gif,svg // allowed type
|required // is required field
|max:2048' // max 2MB
|min:1024 // min 1MB
);
// validator Rules
$validator = Validator::make($request->only('image'), $rules);
// Check validation (fail or pass)
if ($validator->fails())
{
//Error do your staff
} else
{
//Success do your staff
};
Tips 2:
$this->validate($request, [
'input_img' =>
'required
|image
|mimes:jpeg,png,jpg,gif,svg
|max:1024',
]);
Function:
function imageUpload(Request $request) {
if ($request->hasFile('input_img')) { //check the file present or not
$image = $request->file('input_img'); //get the file
$name = "//what every you want concatenate".'.'.$image->getClientOriginalExtension(); //get the file extention
$destinationPath = public_path('/images'); //public path folder dir
$image->move($destinationPath, $name); //mve to destination you mentioned
$image->save(); //
}
}
Write a function that takes a number as an argument and prints the Fibonacci series till that number
def Series(n):
a = 0
b = 1
print(a)
print(b)
S = 0
for i in range(0,n):
if S <= n-1:
S = a + b
print(S)
a = b
b = S
I do not like java type names in query strings and handle it with a specific constructor. Spring JPA implicitly calls constructor with query result in HashMap parameter:
@Getter
public class SurveyAnswerStatistics {
public static final String PROP_ANSWER = "answer";
public static final String PROP_CNT = "cnt";
private String answer;
private Long cnt;
public SurveyAnswerStatistics(HashMap<String, Object> values) {
this.answer = (String) values.get(PROP_ANSWER);
this.count = (Long) values.get(PROP_CNT);
}
}
@Query("SELECT v.answer as "+PROP_ANSWER+", count(v) as "+PROP_CNT+" FROM Survey v GROUP BY v.answer")
List<SurveyAnswerStatistics> findSurveyCount();
Code needs Lombok for resolving @Getter
I am using Jenkins with .net projects and had troubles with MVC 4 references.
I finallys solved my issue by using a .Net reference search engine functionality based on the registry using :
"HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft.NETFramework\v2.0.50727\AssemblyFoldersEx"
You can create subkey et set the default key to "c:\myreferenceedir" for example.
It saved me with MVC versions and also ASP.net Web pages.
Usefull to add references to the "Add Reference Dialog"
tabs = {}
def new_tab():
global browser
hpos = browser.window_handles.index(browser.current_window_handle)
browser.execute_script("window.open('');")
browser.switch_to.window(browser.window_handles[hpos + 1])
return(browser.current_window_handle)
def switch_tab(name):
global tabs
global browser
if not name in tabs.keys():
tabs[name] = {'window_handle': new_tab(), 'url': url+name}
browser.get(tabs[name]['url'])
else:
browser.switch_to.window(tabs[name]['window_handle'])
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Employee> criteriaQuery = criteriaBuilder.createQuery(Employee.class);
Root<Employee> empleoyeeRoot = criteriaQuery.from(Employee.class);
Subquery<Project> projectSubquery = criteriaQuery.subquery(Project.class);
Root<Project> projectRoot = projectSubquery.from(Project.class);
projectSubquery.select(projectRoot);
Expression<String> stringExpression = empleoyeeRoot.get(Employee_.ID);
Predicate predicateIn = stringExpression.in(projectSubquery);
criteriaQuery.select(criteriaBuilder.count(empleoyeeRoot)).where(predicateIn);
Ctrl+Shift+F formats the selected line(s) or the whole source code if you haven't selected any line(s) as per the formatter specified in your Eclipse, while Ctrl+I gives proper indent to the selected line(s) or the current line if you haven't selected any line(s).
Fustigador answer was great, but I found some device (Like Samsung Galaxy Note V) cannot reach 0, have 2 point left, after the calculation. I suggest to add a little buffer like below:
@Override
public void onScrollChanged(ScrollViewExt scrollView, int x, int y, int oldx, int oldy) {
// We take the last son in the scrollview
View view = (View) scrollView.getChildAt(scrollView.getChildCount() - 1);
int diff = (view.getBottom() - (scrollView.getHeight() + scrollView.getScrollY()));
// if diff is zero, then the bottom has been reached
if (diff <= 10) {
// do stuff
}
}
With the Entity Framework most of the time SaveChanges()
is sufficient. This creates a transaction, or enlists in any ambient transaction, and does all the necessary work in that transaction.
Sometimes though the SaveChanges(false) + AcceptAllChanges()
pairing is useful.
The most useful place for this is in situations where you want to do a distributed transaction across two different Contexts.
I.e. something like this (bad):
using (TransactionScope scope = new TransactionScope())
{
//Do something with context1
//Do something with context2
//Save and discard changes
context1.SaveChanges();
//Save and discard changes
context2.SaveChanges();
//if we get here things are looking good.
scope.Complete();
}
If context1.SaveChanges()
succeeds but context2.SaveChanges()
fails the whole distributed transaction is aborted. But unfortunately the Entity Framework has already discarded the changes on context1
, so you can't replay or effectively log the failure.
But if you change your code to look like this:
using (TransactionScope scope = new TransactionScope())
{
//Do something with context1
//Do something with context2
//Save Changes but don't discard yet
context1.SaveChanges(false);
//Save Changes but don't discard yet
context2.SaveChanges(false);
//if we get here things are looking good.
scope.Complete();
context1.AcceptAllChanges();
context2.AcceptAllChanges();
}
While the call to SaveChanges(false)
sends the necessary commands to the database, the context itself is not changed, so you can do it again if necessary, or you can interrogate the ObjectStateManager
if you want.
This means if the transaction actually throws an exception you can compensate, by either re-trying or logging state of each contexts ObjectStateManager
somewhere.
I had the same problem.please do the following it may help you: By Default List View Threshold set at only 5,000 items this is because of Sharepoint server performance.
To Change the LVT:
Click OK to save it.
This limit is indeed not specified, however their TOS mentions that: "FOR EXAMPLE, WE DON’T MAKE ANY COMMITMENTS ABOUT THE CONTENT WITHIN THE SERVICES, THE SPECIFIC FUNCTIONS OF THE SERVICES, OR THEIR RELIABILITY, AVAILABILITY, OR ABILITY TO MEET YOUR NEEDS. WE PROVIDE THE SERVICES “AS IS”. "
This means to me that the download limit is calculated based on a set of factors that describe the user and is subject to change from one to another.
Maybe using the TOR network may help you do your job.
1) PYTHONPATH
is an environment variable which you can set to add additional directories where python will look for modules and packages. e.g.:
# make python look in the foo subdirectory of your home directory for
# modules and packages
export PYTHONPATH=${PYTHONPATH}:${HOME}/foo
Here I use the sh
syntax. For other shells (e.g. csh
,tcsh
), the syntax would be slightly different. To make it permanent, set the variable in your shell's init file (usually ~/.bashrc).
2) Ubuntu comes with python already installed. There may be reasons for installing other (independent) python versions, but I've found that to be rarely necessary.
3) The folder where your modules live is dependent on PYTHONPATH
and where the directories were set up when python was installed. For the most part, the installed stuff you shouldn't care about where it lives -- Python knows where it is and it can find the modules. Sort of like issuing the command ls
-- where does ls
live? /usr/bin
? /bin
? 99% of the time, you don't need to care -- Just use ls
and be happy that it lives somewhere on your PATH
so the shell can find it.
4) I'm not sure I understand the question. 3rd party modules usually come with install instructions. If you follow the instructions, python should be able to find the module and you shouldn't have to care about where it got installed.
5) Configure PYTHONPATH
to include the directory where your module resides and python will be able to find your module.
In VBA (and VB.NET) the line terminator (carriage return) is used to signal the end of a statement. To break long statements into several lines, you need to
Use the line-continuation character, which is an underscore (_), at the point at which you want the line to break. The underscore must be immediately preceded by a space and immediately followed by a line terminator (carriage return).
In other words: Whenever the interpreter encounters the sequence <space>
_
<line terminator>
, it is ignored and parsing continues on the next line. Note, that even when ignored, the line continuation still acts as a token separator, so it cannot be used in the middle of a variable name, for example. You also cannot continue a comment by using a line-continuation character.
To break the statement in your question into several lines you could do the following:
U_matrix(i, j, n + 1) = _
k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
(k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))
(Leading whitespaces are ignored.)
Solution to allow Apache 2 to host websites outside of htdocs:
Underneath the "DocumentRoot" directive in httpd.conf, you should see a directory block. Replace this directory block with:
<Directory />
Options FollowSymLinks
AllowOverride All
Allow from all
</Directory>
REMEMBER NOT TO USE THIS CONFIGURATION IN A REAL ENVIRONMENT
This has been discussed on SO multiple times. Here are a few links to get you started:
SO: Capturing image from webcam in java?
openCVF applet: http://www.colorfulwolf.com/blog/2011/07/05/accessing-the-webcam-from-inside-a-java-applet/
config: http://ganeshtiwaridotcomdotnp.blogspot.in/2011/12/opencv-javacv-eclipse-project.html
this will unhide all files and folders on your computer
attrib -r -s -h /S /D
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
It's now called rounded-circle
as explained here in the BS4 docs
<img src="img/gallery2.JPG" class="rounded-circle">
While the rules in C++03 about when you need typename
and template
are largely reasonable, there is one annoying disadvantage of its formulation
template<typename T>
struct A {
typedef int result_type;
void f() {
// error, "this" is dependent, "template" keyword needed
this->g<float>();
// OK
g<float>();
// error, "A<T>" is dependent, "typename" keyword needed
A<T>::result_type n1;
// OK
result_type n2;
}
template<typename U>
void g();
};
As can be seen, we need the disambiguation keyword even if the compiler could perfectly figure out itself that A::result_type
can only be int
(and is hence a type), and this->g
can only be the member template g
declared later (even if A
is explicitly specialized somewhere, that would not affect the code within that template, so its meaning cannot be affected by a later specialization of A
!).
To improve the situation, in C++11 the language tracks when a type refers to the enclosing template. To know that, the type must have been formed by using a certain form of name, which is its own name (in the above, A
, A<T>
, ::A<T>
). A type referenced by such a name is known to be the current instantiation. There may be multiple types that are all the current instantiation if the type from which the name is formed is a member/nested class (then, A::NestedClass
and A
are both current instantiations).
Based on this notion, the language says that CurrentInstantiation::Foo
, Foo
and CurrentInstantiationTyped->Foo
(such as A *a = this; a->Foo
) are all member of the current instantiation if they are found to be members of a class that is the current instantiation or one of its non-dependent base classes (by just doing the name lookup immediately).
The keywords typename
and template
are now not required anymore if the qualifier is a member of the current instantiation. A keypoint here to remember is that A<T>
is still a type-dependent name (after all T
is also type dependent). But A<T>::result_type
is known to be a type - the compiler will "magically" look into this kind of dependent types to figure this out.
struct B {
typedef int result_type;
};
template<typename T>
struct C { }; // could be specialized!
template<typename T>
struct D : B, C<T> {
void f() {
// OK, member of current instantiation!
// A::result_type is not dependent: int
D::result_type r1;
// error, not a member of the current instantiation
D::questionable_type r2;
// OK for now - relying on C<T> to provide it
// But not a member of the current instantiation
typename D::questionable_type r3;
}
};
That's impressive, but can we do better? The language even goes further and requires that an implementation again looks up D::result_type
when instantiating D::f
(even if it found its meaning already at definition time). When now the lookup result differs or results in ambiguity, the program is ill-formed and a diagnostic must be given. Imagine what happens if we defined C
like this
template<>
struct C<int> {
typedef bool result_type;
typedef int questionable_type;
};
A compiler is required to catch the error when instantiating D<int>::f
. So you get the best of the two worlds: "Delayed" lookup protecting you if you could get in trouble with dependent base classes, and also "Immediate" lookup that frees you from typename
and template
.
In the code of D
, the name typename D::questionable_type
is not a member of the current instantiation. Instead the language marks it as a member of an unknown specialization. In particular, this is always the case when you are doing DependentTypeName::Foo
or DependentTypedName->Foo
and either the dependent type is not the current instantiation (in which case the compiler can give up and say "we will look later what Foo
is) or it is the current instantiation and the name was not found in it or its non-dependent base classes and there are also dependent base classes.
Imagine what happens if we had a member function h
within the above defined A
class template
void h() {
typename A<T>::questionable_type x;
}
In C++03, the language allowed to catch this error because there could never be a valid way to instantiate A<T>::h
(whatever argument you give to T
). In C++11, the language now has a further check to give more reason for compilers to implement this rule. Since A
has no dependent base classes, and A
declares no member questionable_type
, the name A<T>::questionable_type
is neither a member of the current instantiation nor a member of an unknown specialization. In that case, there should be no way that that code could validly compile at instantiation time, so the language forbids a name where the qualifier is the current instantiation to be neither a member of an unknown specialization nor a member of the current instantiation (however, this violation is still not required to be diagnosed).
You can try this knowledge on this answer and see whether the above definitions make sense for you on a real-world example (they are repeated slightly less detailed in that answer).
The C++11 rules make the following valid C++03 code ill-formed (which was not intended by the C++ committee, but will probably not be fixed)
struct B { void f(); };
struct A : virtual B { void f(); };
template<typename T>
struct C : virtual B, T {
void g() { this->f(); }
};
int main() {
C<A> c; c.g();
}
This valid C++03 code would bind this->f
to A::f
at instantiation time and everything is fine. C++11 however immediately binds it to B::f
and requires a double-check when instantiating, checking whether the lookup still matches. However when instantiating C<A>::g
, the Dominance Rule applies and lookup will find A::f
instead.
It is not the most efficient in the world, but this should work:
get-content $file |
select -Skip 1 |
set-content "$file-temp"
move "$file-temp" $file -Force
Here are some ways to do it:
grep --color 'pattern\|$' file
grep --color -E 'pattern|$' file
egrep --color 'pattern|$' file
The |
symbol is the OR operator. Either escape it using \
or tell grep that the search text has to be interpreted as regular expressions by adding -E or using the egrep
command instead of grep
.
The search text "pattern|$" is actually a trick, it will match lines that have pattern
OR lines that have an end. Because all lines have an end, all lines are matched, but the end of a line isn't actually any characters, so it won't be colored.
In your example, the point of piping the output of find to xargs is that the standard behavior of find's -exec option is to execute the command once for each found file. If you're using find, and you want its standard behavior, then the answer is simple - don't use xargs to begin with.
This is a modern and simple ES6 way to do it that is also very flexible. It lets you specify multiple arrays as the arrays to compare the subject array to, and can work in both inclusive and exclusive mode.
// =======================================
// The function
// =======================================
function assoc(subjectArray, otherArrays, { mustBeInAll = true } = {}) {
return subjectArray.filter((subjectItem) => {
if (mustBeInAll) {
return otherArrays.every((otherArray) =>
otherArray.includes(subjectItem)
);
} else {
return otherArrays.some((otherArray) => otherArray.includes(subjectItem));
}
});
}
// =======================================
// The usage
// =======================================
const cheeseList = ["stilton", "edam", "cheddar", "brie"];
const foodListCollection = [
["cakes", "ham", "stilton"],
["juice", "wine", "brie", "bread", "stilton"]
];
// Output will be: ['stilton', 'brie']
const inclusive = assoc(cheeseList, foodListCollection, { mustBeInAll: false }),
// Output will be: ['stilton']
const exclusive = assoc(cheeseList, foodListCollection, { mustBeInAll: true })
Live example: https://codesandbox.io/s/zealous-butterfly-h7dgf?fontsize=14&hidenavigation=1&theme=dark
Look at the ToLookup
and/or ToDictionary
extension methods.
rum[order(rum$T1, -rum$T2 ), ]
If you get code behind, use some like this
MyCustomObject myObject = new MyCustomObject();
myObject.name='try';
//OBJECT -> JSON
var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string myObjectJson = javaScriptSerializer.Serialize(myObject);
//return JSON
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(myObjectJson );
Response.End();
So you return a json object serialized with all attributes of MyCustomObject.
I had similar problems. I removed the property="og:image:secure_url" and now it will scrub with just og:image. Sometimes, less is more
You can get your result by simply use substr():
Syntax substr(string,start,length)
Example
<?php
$myStr = "HelloWordl";
echo substr($myStr,0,5);
?>
Output :
Hello
You can use this simple method after setting up your connection:
private void getAgentInfo(string key)//"key" is your search paramter inside database
{
con.Open();
string sqlquery = "SELECT * FROM TableName WHERE firstname = @fName";
SqlCommand command = new SqlCommand(sqlquery, con);
SqlDataReader sReader;
command.Parameters.Clear();
command.Parameters.AddWithValue("@fName", key);
sReader = command.ExecuteReader();
while (sReader.Read())
{
textBoxLastName.Text = sReader["Lastname"].ToString(); //SqlDataReader
//["LastName"] the name of your column you want to retrieve from DB
textBoxAge.Text = sReader["age"].ToString();
//["age"] another column you want to retrieve
}
con.Close();
}
Now you can pass the key to this method by your textBoxFirstName like:
getAgentInfo(textBoxFirstName.Text);
There's no need for Prototype here: JavaScript has for..in
loops. If you're not sure that no one messed with Object.prototype
, check hasOwnProperty()
as well, ie
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
doSomethingWith(obj[prop]);
}
There are two types of variable in SQL-plus: substitution and bind.
This is substitution (substitution variables can replace SQL*Plus command options or other hard-coded text):
define a = 1;
select &a from dual;
undefine a;
This is bind (bind variables store data values for SQL and PL/SQL statements executed in the RDBMS; they can hold single values or complete result sets):
var x number;
exec :x := 10;
select :x from dual;
exec select count(*) into :x from dual;
exec print x;
SQL Developer supports substitution variables, but when you execute a query with bind :var
syntax you are prompted for the binding (in a dialog box).
Reference:
UPDATE substitution variables are a bit tricky to use, look:
define phone = '+38097666666';
select &phone from dual; -- plus is stripped as it is a number
select '&phone' from dual; -- plus is preserved as it is a string
It means parent/child
example:
html>body
that's saying that body is a child of html
Check out: Selectors
If you strictly want to stick to using button,Then simply create an open window function as follows:
<script>
function myfunction() {
window.open("mynewpage.html");
}
</script>
Then in your html do the following with your button:
Join
So you would have something like this:
<body>
<script>
function joinfunction() {
window.open("mynewpage.html");
}
</script>
<button onclick="myfunction()" type="button" class="btn btn-default subs-btn">Join</button>
function fetch_comments($ticket_id){
$this->db->select('tbl_tickets_replies.comments,
tbl_users.username,tbl_roles.role_name');
$this->db->where('tbl_tickets_replies.ticket_id',$ticket_id);
$this->db->join('tbl_users','tbl_users.id = tbl_tickets_replies.user_id');
$this->db->join('tbl_roles','tbl_roles.role_id=tbl_tickets_replies.role_id');
return $this->db->get('tbl_tickets_replies');
}
public static T Clone<T>(T obj)
{
DataContractSerializer dcSer = new DataContractSerializer(obj.GetType());
MemoryStream memoryStream = new MemoryStream();
dcSer.WriteObject(memoryStream, obj);
memoryStream.Position = 0;
T newObject = (T)dcSer.ReadObject(memoryStream);
return newObject;
}
On windows 10 insert at beggining this:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
Strange, but it work for me!(Together with input() at the end, of course)
List is an interface. You need a specific class in the end so either try
List l = new ArrayList();
or
List l = new LinkedList();
Whichever suit your needs.
Access from Windows by Git Bash console:
scp root@ip:/etc/../your-file "C:/Users/XXX/Download"
I noticed that problem because of AdBlock Extension, I turned off AdBlock extension the issue got resolve.
Also You Can Use Server.Execute
You may want to check C++ REST SDK (codename "Casablanca"). http://msdn.microsoft.com/en-us/library/jj950081.aspx
With the C++ REST SDK, you can more easily connect to HTTP servers from your C++ app.
Usage example:
#include <iostream>
#include <cpprest/http_client.h>
using namespace web::http; // Common HTTP functionality
using namespace web::http::client; // HTTP client features
int main(int argc, char** argv) {
http_client client("http://httpbin.org/");
http_response response;
// ordinary `get` request
response = client.request(methods::GET, "/get").get();
std::cout << response.extract_string().get() << "\n";
// working with json
response = client.request(methods::GET, "/get").get();
std::cout << "url: " << response.extract_json().get()[U("url")] << "\n";
}
The C++ REST SDK is a Microsoft project for cloud-based client-server communication in native code using a modern asynchronous C++ API design.
private lateinit var runnable: Runnable
override fun onCreate(savedInstanceState: Bundle?) {
val handler = Handler()
runnable = Runnable {
// do your work
handler.postDelayed(runnable, 2000)
}
handler.postDelayed(runnable, 2000)
}
Runnable runnable;
Handler handler;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
// do your work
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
}
The second parameter of findBy
is for ORDER.
$ens = $em->getRepository('AcmeBinBundle:Marks')
->findBy(
array('type'=> 'C12'),
array('id' => 'ASC')
);
for jQuery 1.6 or higher:
if ($('input.checkbox_check').prop('checked')) {
//blah blah
}
the cross-browser-compatible way to determine if a checkbox is checked is to use the property https://api.jquery.com/prop/
Use router.go(0)
if you use Typescript, and it's asking arguments for the go method.
This can also be achieved with jsp:include. Chad Darby explains well here in this video https://www.youtube.com/watch?v=EWbYj0qoNHo
Some ideas in the following answer:
Steps in creating a web service using Axis2 - The client code
Gives an example of a Groovy client invoking the ADB classes generated from the WSDL.
There are lots of web service frameworks out there...