I searched for a simple solution and this works well for me:
//input data
view = new Uint8Array(data);
//output string
serialString = ua2text(view);
//convert UTF8 to string
function ua2text(ua) {
s = "";
for (var i = 0; i < ua.length; i++) {
s += String.fromCharCode(ua[i]);
}
return s;
}
Only issue I have is sometimes I get one character at a time. This might be by design with my source of the arraybuffer. I'm using https://github.com/xseignard/cordovarduino to read serial data on an android device.
JVM heap size can be growable and shrinkable by the Garbage-Collection mechanism. But, it can't allocate over maximum memory size: Runtime.maxMemory. This is the meaning of maximum memory. Total memory means the allocated heap size. And free memory means the available size in total memory.
example) java -Xms20M -Xmn10M -Xmx50M ~~~. This means that jvm should allocate heap 20M on start(ms). In this case, total memory is 20M. free memory is 20M-used size. If more heap is needed, JVM allocate more but can't over 50M(mx). In the case of maximum, total memory is 50M, and free size is 50M-used size. As for minumum size(mn), if heap is not used much, jvm can shrink heap size to 10M.
This mechanism is for efficiency of memory. If small java program run on huge fixed size heap memory, so much memory may be wasteful.
You have to do a result.next() before you can access the result. It's a very common idiom to do
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
int foo = rs.getInt(1);
...
}
The integer passed to the constructor represents its initial capacity, i.e., the number of elements it can hold before it needs to resize its internal array (and has nothing to do with the initial number of elements in the list).
To initialize an list with 60 zeros you do:
List<Integer> list = new ArrayList<Integer>(Collections.nCopies(60, 0));
If you want to create a list with 60 different objects, you could use the Stream API with a Supplier
as follows:
List<Person> persons = Stream.generate(Person::new)
.limit(60)
.collect(Collectors.toList());
Don't forget DataFrame.tail
! e.g. df1.tail(10)
BufferedReader
can't wrap an InputStream
directly. It wraps another Reader
. In this case you'd want to do something like:
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
If the string is empty, comboBox.getSelectedItem().toString()
will give a NullPointerException
. So better to typecast by (String)
.
By keys()
and values()
methods of dictionary and zip
.
zip
will return a list of tuples which acts like an ordered dictionary.
Demo:
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> zip(d.keys(), d.values())
[('a', 1), ('c', 3), ('b', 2)]
>>> zip(d.values(), d.keys())
[(1, 'a'), (3, 'c'), (2, 'b')]
first get the current address
var url = window.location.href
Then just parse that string
var arr = url.split("/");
your url is:
var result = arr[0] + "//" + arr[2]
Hope this helps
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
#top, #bottom {
height: 100px;
width: 100%;
position: relative;
}
#container {
overflow: hidden;
position: relative;
width: 100%;
}
#container .left {
height: 550px;
width: 55%;
position: relative;
float: left;
background-color: #3399FF;
}
#container .right {
height: 100%;
position: absolute;
right: 0;
left: 55%;
bottom: 0px;
top: 0px;
background-color: #3366CC;
}
</style>
</head>
<body>
<div id="top"></div>
<div id="container">
<div class="left"></div>
<div class="right"></div>
</div>
<div id="bottom"></div>
</body>
</html>
Maybe you mean like this? I like to make an object and use Format-Table:
> $array = @()
> $object = New-Object -TypeName PSObject
> $object | Add-Member -Name 'Name' -MemberType Noteproperty -Value 'Joe'
> $object | Add-Member -Name 'Age' -MemberType Noteproperty -Value 32
> $object | Add-Member -Name 'Info' -MemberType Noteproperty -Value 'something about him'
> $array += $object
> $array | Format-Table
Name Age Info
---- --- ----
Joe 32 something about him
This will put all objects you have in the array in columns according to their properties.
Tip: Using -auto
sizes the table better
> $array | Format-Table -Auto
Name Age Info
---- --- ----
Joe 32 something about him
You can also specify which properties you want in the table. Just separate each property name with a comma:
> $array | Format-Table Name, Age -Auto
Name Age
---- ---
Joe 32
Use vertical-align:top; for the element you want at the top, as I have demonstrated on your jsfiddle.
import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))
if you want to sort x in-place, you can also:
x.sort(key=operator.attrgetter('score'))
I have other solution, my application need to be started when new object of MyApp is created, so it looks like:
function MyApp(objId){
this.init=function(){
//.........
}
this.run=function(){
if(!document || !document.body || !window[objId]){
window.setTimeout(objId+".run();",100);
return;
}
this.init();
};
this.run();
}
//and i am starting it
var app=new MyApp('app');
it is working on all browsers, that i know.
You can use this to get a perfect count, it calculates the mode a particular column
df['name'].value_counts()
Also something important to add here, in order to set default values for arrays and objects we must use the default function for props:
propE: {
type: Object,
// Object or array defaults must be returned from
// a factory function
default: function () {
return { message: 'hello' }
}
},
Use attribute binding syntax instead
<ol class="viewer-nav"><li *ngFor="let section of sections"
[attr.data-sectionvalue]="section.value">{{ section.text }}</li>
</ol>
or
<ol class="viewer-nav"><li *ngFor="let section of sections"
attr.data-sectionvalue="{{section.value}}">{{ section.text }}</li>
</ol>
for (Object key : meMap.keySet()) {
String value=(String)meMap.get(key);
Toast.makeText(ctx, "Key: "+key+" Value: "+value, Toast.LENGTH_LONG).show();
}
Android Studio (Preview) sometimes recommends updating to a Gradle Plugin that is not available yet (did Google forget to publish it?). Such as today with
'com.android.tools.build:gradle:3.1.0-beta1'
I found I can see current versions of com.android.tools.build:gradle here, and then I just pick the newest:
https://dl.google.com/dl/android/maven2/index.html
I just found this beta1 gradle bug in the Android Bug Tracker. I also just learned Android Studio > Help Menu > Submit Feedback brought me to the bug tracker.
Found temporary solution at androiddev reddit for the 3.1.0-beta1 problem: Either roll back to Preview Canary 8, or switch to gradle plugin 3.0.1 until Canary 10 is released shortly.
there's this manual, and kinda cute way too:
double d1 = 1.1;
double d2 = 1.5;
double d3 = 1.9;
int i1 = (int)(d1 + 0.5);
int i2 = (int)(d2 + 0.5);
int i3 = (int)(d3 + 0.5);
simply add 0.5 to any number, and cast it to int (or floor it) and it will be mathematically correctly rounded :D
Return values are almost always the right choice when the method doesn't have anything else to return. (In fact, I can't think of any cases where I'd ever want a void method with an out
parameter, if I had the choice. C# 7's Deconstruct
methods for language-supported deconstruction acts as a very, very rare exception to this rule.)
Aside from anything else, it stops the caller from having to declare the variable separately:
int foo;
GetValue(out foo);
vs
int foo = GetValue();
Out values also prevent method chaining like this:
Console.WriteLine(GetValue().ToString("g"));
(Indeed, that's one of the problems with property setters as well, and it's why the builder pattern uses methods which return the builder, e.g. myStringBuilder.Append(xxx).Append(yyy)
.)
Additionally, out parameters are slightly harder to use with reflection and usually make testing harder too. (More effort is usually put into making it easy to mock return values than out parameters). Basically there's nothing I can think of that they make easier...
Return values FTW.
EDIT: In terms of what's going on...
Basically when you pass in an argument for an "out" parameter, you have to pass in a variable. (Array elements are classified as variables too.) The method you call doesn't have a "new" variable on its stack for the parameter - it uses your variable for storage. Any changes in the variable are immediately visible. Here's an example showing the difference:
using System;
class Test
{
static int value;
static void ShowValue(string description)
{
Console.WriteLine(description + value);
}
static void Main()
{
Console.WriteLine("Return value test...");
value = 5;
value = ReturnValue();
ShowValue("Value after ReturnValue(): ");
value = 5;
Console.WriteLine("Out parameter test...");
OutParameter(out value);
ShowValue("Value after OutParameter(): ");
}
static int ReturnValue()
{
ShowValue("ReturnValue (pre): ");
int tmp = 10;
ShowValue("ReturnValue (post): ");
return tmp;
}
static void OutParameter(out int tmp)
{
ShowValue("OutParameter (pre): ");
tmp = 10;
ShowValue("OutParameter (post): ");
}
}
Results:
Return value test...
ReturnValue (pre): 5
ReturnValue (post): 5
Value after ReturnValue(): 10
Out parameter test...
OutParameter (pre): 5
OutParameter (post): 10
Value after OutParameter(): 10
The difference is at the "post" step - i.e. after the local variable or parameter has been changed. In the ReturnValue test, this makes no difference to the static value
variable. In the OutParameter test, the value
variable is changed by the line tmp = 10;
Frankly, pretty much everything that we've encountered works just fine w/ the JAXP version, so we always exclude xml-apis
and xercesImpl
.
You can use this code:
<select id="menu" name="links" size="1" onchange="window.location.href=this.value;">
<option value="URL">Book</option>
<option value="URL">Pen</option>
<option value="URL">Read</option>
<option value="URL">Apple</option>
</select>
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;
These are deprecated use the following..
// Connects to your Database
$link = mysqli_connect("localhost", "root", "", "");
and to insert data use the following
$sql = "INSERT INTO Table-Name (Column-Name)
VALUES ('$filename')" ;
In Access VBA I've used this to turn off all the dialogs when running a bunch of updates:
DoCmd.SetWarnings False
After running all the updates, the last step in my VBA script is:
DoCmd.SetWarnings True
Hope this helps.
def my_string = "some string"
println "here: " + my_string
Not quite sure why the answer above needs to go into benchmarks, string buffers, tests, etc.
If U want to delete more than one characters, say comma and dots you can write
<script type="text/javascript">
var mystring = "It,is,a,test.string,of.mine"
mystring = mystring.replace(/[,.]/g , '');
alert( mystring);
</script>
According to pywin32 github you must run
pip install pywin32
and after that, you must run
python Scripts/pywin32_postinstall.py -install
I know I'm reviving an old thread, but I just had this problem and this was the only way to solve it.
Tips:
You can try to use
ctx.getSystemService("phone_msim")
instead of
ctx.getSystemService(Context.TELEPHONY_SERVICE)
If you have already tried Vaibhav's answer and telephony.getClass().getMethod()
fails, above is what works for my Qualcomm mobile.
I'm using Batik for this. The complete Delphi code:
procedure ExecNewProcess(ProgramName : String; Wait: Boolean);
var
StartInfo : TStartupInfo;
ProcInfo : TProcessInformation;
CreateOK : Boolean;
begin
FillChar(StartInfo, SizeOf(TStartupInfo), #0);
FillChar(ProcInfo, SizeOf(TProcessInformation), #0);
StartInfo.cb := SizeOf(TStartupInfo);
CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil, False,
CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS,
nil, nil, StartInfo, ProcInfo);
if CreateOK then begin
//may or may not be needed. Usually wait for child processes
if Wait then
WaitForSingleObject(ProcInfo.hProcess, INFINITE);
end else
ShowMessage('Unable to run ' + ProgramName);
CloseHandle(ProcInfo.hProcess);
CloseHandle(ProcInfo.hThread);
end;
procedure ConvertSVGtoPNG(aFilename: String);
const
ExecLine = 'c:\windows\system32\java.exe -jar C:\Apps\batik-1.7\batik-rasterizer.jar ';
begin
ExecNewProcess(ExecLine + aFilename, True);
end;
here is the best way in a similar function
function cart_stats($cart_id){
$sql = "select sum(price) sum_bids, count(*) total_bids from carts_bids where cart_id = '$cart_id'";
$rs = mysql_query($sql);
$row = mysql_fetch_object($rs);
$total_bids = $row->total_bids;
$sum_bids = $row->sum_bids;
$avarage = $sum_bids/$total_bids;
$array["total_bids"] = "$total_bids";
$array["avarage"] = " $avarage";
return $array;
}
and you get the array data like this
$data = cart_stats($_GET['id']);
<?=$data['total_bids']?>
You are asking a lot of questions that you could answer yourself by reading the documentation, so I'll give you a general advice: read it and experiment in the python shell. You'll see that itemgetter
returns a callable:
>>> func = operator.itemgetter(1)
>>> func(a)
['Paul', 22, 'Car Dealer']
>>> func(a[0])
8
To do it in a different way, you can use lambda
:
a.sort(key=lambda x: x[1])
And reverse it:
a.sort(key=operator.itemgetter(1), reverse=True)
Sort by more than one column:
a.sort(key=operator.itemgetter(1,2))
See the sorting How To.
You can use the dictionary type of formatting:
s='arbit'
string='%(key)s hello world %(key)s hello world %(key)s' % {'key': s,}
As your output results a double you should cast either completed variable or total variable or both to double while dividing.
So, the correct implmentation will be:
System.out.println((double)completed/total);
my situation is that the mysql in the /etc/ directory is renamed mysql_bk, just copy mysql_bk
sudo cp -r /etc/mysql_bk/ /etc/mysql/
then
service mysql restart
This doesn't show the filenames, but at least you get a feel of the repository.
cat .git/refs/tags/*
Each file in that directory contains a commit SHA pointing to a commit.
Padding aligns structure members to "natural" address boundaries - say, int
members would have offsets, which are mod(4) == 0
on 32-bit platform. Padding is on by default. It inserts the following "gaps" into your first structure:
struct mystruct_A {
char a;
char gap_0[3]; /* inserted by compiler: for alignment of b */
int b;
char c;
char gap_1[3]; /* -"-: for alignment of the whole struct in an array */
} x;
Packing, on the other hand prevents compiler from doing padding - this has to be explicitly requested - under GCC it's __attribute__((__packed__))
, so the following:
struct __attribute__((__packed__)) mystruct_A {
char a;
int b;
char c;
};
would produce structure of size 6
on a 32-bit architecture.
A note though - unaligned memory access is slower on architectures that allow it (like x86 and amd64), and is explicitly prohibited on strict alignment architectures like SPARC.
for i in $(seq 1 $END); do echo $i; done
edit: I prefer seq
over the other methods because I can actually remember it ;)
On Ubuntu, the recommended way of changing the default library path for a user, is to set the R_LIBS_USER
variable in the ~/.Renviron
file.
touch ~/.Renviron
echo "R_LIBS_USER=/custom/path/in/absolute/form" >> ~/.Renviron
You can call qApp.exit();
. I always use that and never had a problem with it.
If you application is a command line application, you might indeed want to return an exit code. It's completely up to you what the code is.
I had the same problem and wanted to change the product key to another. Unfortunate it's not as easy as it was on VS2010.
The following steps work:
Remove the registry key containing the license information: HKEY_CLASSES_ROOT\Licenses\77550D6B-6352-4E77-9DA3-537419DF564B
If you can't find the key, use sysinternals ProcessMonitor to check the registry access of VS2012 to locate the correct key which is always in HKEY_CLASSES_ROOT\Licenses
After you remove this key, VS2012 will tell you that it's license information is incorrect. Go to "Programs and features" and repair VS2012.
After the repair, VS2012 is reverted to a 30 day trial and you can enter a new product key. This could also be used to stay in a trial version loop and never enter a producy key.
Simplest solution:
df.set_index('id').T.to_dict('records')
Example:
df= pd.DataFrame([['a',1],['a',2],['b',3]], columns=['id','value'])
df.set_index('id').T.to_dict('records')
If you have multiple values, like val1, val2, val3,etc and u want them as lists, then use the below code:
df.set_index('id').T.to_dict('list')
To find which library is being used you could run
$ /sbin/ldconfig -p | grep stdc++
libstdc++.so.6 (libc6) => /usr/lib/libstdc++.so.6
The list of compatible versions for libstdc++ version 3.4.0 and above is provided by
$ strings /usr/lib/libstdc++.so.6 | grep LIBCXX
GLIBCXX_3.4
GLIBCXX_3.4.1
GLIBCXX_3.4.2
...
For earlier versions the symbol GLIBCPP
is defined.
The date stamp of the library is defined in a macro __GLIBCXX__
or __GLIBCPP__
depending on the version:
// libdatestamp.cxx
#include <cstdio>
int main(int argc, char* argv[]){
#ifdef __GLIBCPP__
std::printf("GLIBCPP: %d\n",__GLIBCPP__);
#endif
#ifdef __GLIBCXX__
std::printf("GLIBCXX: %d\n",__GLIBCXX__);
#endif
return 0;
}
$ g++ libdatestamp.cxx -o libdatestamp
$ ./libdatestamp
GLIBCXX: 20101208
The table of datestamps of libstdc++ versions is listed in the documentation:
Yes, you can find out element by data attribute.
element = $('a[data-item-id="stand-out"]');
In C++ you can overload operator<<
for ostream
and your custom class:
class A {
public:
int i;
};
std::ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << a.i << ")";
}
This way you can output instances of your class on streams:
A x = ...;
std::cout << x << std::endl;
In case your operator<<
wants to print out internals of class A
and really needs access to its private and protected members you could also declare it as a friend function:
class A {
private:
friend std::ostream& operator<<(std::ostream&, const A&);
int j;
};
std::ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << a.j << ")";
}
Position the cursor inside the class, then press ALT + Ins and select Getters and Setters
from the contextual menu.
Use:
#import <QuartzCore/QuartzCore.h>
.......
[myView.layer removeAllAnimations];
Use os.rename
. But you have to pass full path of both files to the function. If I have a file a.txt
on my desktop so I will do and also I have to give full of renamed file too.
os.rename('C:\\Users\\Desktop\\a.txt', 'C:\\Users\\Desktop\\b.kml')
Yes, the function is querySelectorAll
(or querySelector
for a single element), which allows you to use CSS selectors to find elements.
document.querySelectorAll('[property]'); // All with attribute named "property"
document.querySelectorAll('[property="value"]'); // All with "property" set to "value" exactly.
(Complete list of attribute selectors on MDN.)
This finds all elements with the attribute property. It would be better to specify a tag name if possible:
document.querySelectorAll('span[property]');
You can work around this if necessary by looping through all the elements on the page to see whether they have the attribute set:
var withProperty = [],
els = document.getElementsByTagName('span'), // or '*' for all types of element
i = 0;
for (i = 0; i < els.length; i++) {
if (els[i].hasAttribute('property')) {
withProperty.push(els[i]);
}
}
Libraries such as jQuery handle this for you; it's probably a good idea to let them do the heavy lifting.
For anyone dealing with ancient browsers, note that querySelectorAll
was introduced to Internet Explorer in v8 (2009) and fully supported in IE9. All modern browsers support it.
The time.Parse
function does not do Unix timestamps. Instead you can use strconv.ParseInt
to parse the string to int64
and create the timestamp with time.Unix
:
package main
import (
"fmt"
"time"
"strconv"
)
func main() {
i, err := strconv.ParseInt("1405544146", 10, 64)
if err != nil {
panic(err)
}
tm := time.Unix(i, 0)
fmt.Println(tm)
}
Output:
2014-07-16 20:55:46 +0000 UTC
Playground: http://play.golang.org/p/v_j6UIro7a
Edit:
Changed from strconv.Atoi
to strconv.ParseInt
to avoid int overflows on 32 bit systems.
No, there is nothing like this in CSS. You can, however, use JavaScript to calculate the number of children and apply styles.
I have a very well working solution for tables of max-width: 100%
.
Just use word-break: break-all;
for the table cells (except heading cells) to break all long text into several lines:
<!DOCTYPE html>
<html>
<head>
<style>
table {
max-width: 100%;
}
table td {
word-break: break-all;
}
</style>
</head>
<body>
<table border="1">
<tr>
<th><strong>Input</strong></th>
<th><strong>Output</strong></th>
</tr>
<tr>
<td>some text</td>
<td>12b6459fc6b4cabb4b1990be1a78e4dc5fa79c3a0fe9aa9f0386d673cfb762171a4aaa363b8dac4c33e0ad23e4830888</td>
</tr>
</table>
</body>
</html>
This will render like this (when the screen width is limited):
If you have access to the server, the most reliable way of doing this is to do it on the server itself, in IIS. Go in to IIS HTTP Response Headers. Add
Name: X-UA-Compatible
Value: IE=edge
This will override your browser and your code.
if(str.matches(".*\\d.*")){
// contains a number
} else{
// does not contain a number
}
Previous suggested solution, which does not work, but brought back because of @Eng.Fouad's request/suggestion.
String strWithNumber = "This string has a 1 number";
String strWithoutNumber = "This string does not have a number";
System.out.println(strWithNumber.contains("\d"));
System.out.println(strWithoutNumber.contains("\d"));
String strWithNumber = "This string has a 1 number";
if(strWithNumber.matches(".*\\d.*")){
System.out.println("'"+strWithNumber+"' contains digit");
} else{
System.out.println("'"+strWithNumber+"' does not contain a digit");
}
String strWithoutNumber = "This string does not have a number";
if(strWithoutNumber.matches(".*\\d.*")){
System.out.println("'"+strWithoutNumber+"' contains digit");
} else{
System.out.println("'"+strWithoutNumber+"' does not contain a digit");
}
Output
'This string has a 1 number' contains digit
'This string does not have a number' does not contain a digit
Assuming the image data is already in the format you want, you don't need image ImageIO
at all - you just need to write the data to the file:
// Note preferred way of declaring an array variable
byte[] data = Base64.decodeBase64(crntImage);
try (OutputStream stream = new FileOutputStream("c:/decode/abc.bmp")) {
stream.write(data);
}
(I'm assuming you're using Java 7 here - if not, you'll need to write a manual try/finally statement to close the stream.)
If the image data isn't in the format you want, you'll need to give more details.
lst *= 0
has the same effect as
lst[:] = []
It's a little simpler and maybe easier to remember. Other than that there's not much to say
The efficiency seems to be about the same
This questions is already answered here. Just put height: 100%
in both the div
and the container td
.
Im not sure you can do this, however you can try these additions in your gitconfig file.
Try to replace the kdiff3 from these values to point to visual studio code executable.
[merge]
tool = kdiff3
[mergetool "kdiff3"]
path = C:/Program Files/KDiff3/kdiff3.exe
keepBackup = false
trustExitCode = false
You have mentioned Wrong id
alert(document.getElementById("name").value);
if you want to use name
attribute then
alert(document.getElementsByName("username")[0].value);
Updates:
input type="text" id="name" name="username"
id is different from name
Because I have yet to see an example that works for my use case, here is the most full-proof solution that I was able to realize.
dd {_x000D_
margin: 0;_x000D_
}_x000D_
dd::after {_x000D_
content: '\A';_x000D_
white-space: pre-line;_x000D_
}_x000D_
dd:last-of-type::after {_x000D_
content: '';_x000D_
}_x000D_
dd, dt {_x000D_
display: inline;_x000D_
}_x000D_
dd, dt, .address {_x000D_
vertical-align: middle;_x000D_
}_x000D_
dt {_x000D_
font-weight: bolder;_x000D_
}_x000D_
dt::after {_x000D_
content: ': ';_x000D_
}_x000D_
.address {_x000D_
display: inline-block;_x000D_
white-space: pre;_x000D_
}
_x000D_
Surrounding_x000D_
_x000D_
<dl>_x000D_
<dt>Phone Number</dt>_x000D_
<dd>+1 (800) 555-1234</dd>_x000D_
<dt>Email Address</dt>_x000D_
<dd><a href="#">[email protected]</a></dd>_x000D_
<dt>Postal Address</dt>_x000D_
<dd><div class="address">123 FAKE ST<br />EXAMPLE EX 00000</div></dd>_x000D_
</dl>_x000D_
_x000D_
Text
_x000D_
Strangely enough, it doesn't work with display: inline-block
. I suppose that if you need to set the size of any of the dt
elements or dd
elements, you could set the dl
's display as display: flexbox; display: -webkit-flex; display: flex;
and the flex
shorthand of the dd
elements and the dt
elements as something like flex: 1 1 50%
and display
as display: inline-block
. But I haven't tested that, so approach with caution.
Your sklearn version is too low, model_selection
is imported by 0.18.1, so please update the sklearn version.
Is something as simple as the following not good enough?
return abs(f1 - f2) <= allowed_error
For what it's worth, if you're using NumPy distutils, numpy.distutils.misc_util.Configuration
has a make_svn_version_py()
method that embeds the revision number inside package.__svn_version__
in the variable version
.
git mv oldname newname
so that Git recognizes this is a move, rather than deleting/adding new files).Info.plist
and Product Bundle Identifier
.Info.plist
, update it.Product Bundle Identifier
, unless it is utilizing the ${PRODUCT_NAME} variable. In that case, search for "product" in the settings and update Product Name
. If Product Name
is based on ${TARGET_NAME}, click on the actual target item in the TARGETS list on the left of the settings pane and edit it, and all related settings will update immediately.Prefix Header
's path is also updated to the new name.Use:
SELECT *
FROM `table`
WHERE INSTR(`column`, '{$needle}') > 0
Reference:
It's safe to just delete the source directory and compiled package file. Find the source directory under $GOPATH/src
and the package file under $GOPATH/pkg/<architecture>
, for example: $GOPATH/pkg/windows_amd64
.
I have referred this post, it worked like charm , except it did not hide the arrow in IE browser.
However adding following hides the arrow in IE:
&::-ms-expand {_x000D_
display: none;_x000D_
}
_x000D_
Complete solution ( sass )
$select-border-color: #ccc;_x000D_
$select-focus-color: green;_x000D_
_x000D_
select {_x000D_
_x000D_
cursor: pointer;_x000D_
/* styling */_x000D_
background-color: white;_x000D_
border: 1px solid $select-border-color;_x000D_
border-radius: 4px;_x000D_
display: inline-block;_x000D_
font: inherit;_x000D_
line-height: 1.5em;_x000D_
padding: 0.5em 3.5em 0.5em 1em;_x000D_
_x000D_
/* reset */_x000D_
margin: 0;_x000D_
-webkit-box-sizing: border-box;_x000D_
-moz-box-sizing: border-box;_x000D_
box-sizing: border-box;_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
_x000D_
background-image: linear-gradient(45deg, transparent 50%, $select-border-color 50%),_x000D_
linear-gradient(135deg, $select-border-color 50%, transparent 50%),_x000D_
linear-gradient(to right, $select-border-color, $select-border-color);_x000D_
background-position: calc(100% - 20px) calc(1em + 2px),_x000D_
calc(100% - 15px) calc(1em + 2px), calc(100% - 2.5em) 0.5em;_x000D_
background-size: 5px 5px, 5px 5px, 1px 1.5em;_x000D_
background-repeat: no-repeat;_x000D_
_x000D_
/* Very imp: hide arrow in IE */_x000D_
&::-ms-expand {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
&:-moz-focusring {_x000D_
color: transparent;_x000D_
text-shadow: none;_x000D_
}_x000D_
_x000D_
&:focus {_x000D_
background-image: linear-gradient(45deg, $select-focus-color 50%, transparent 50%),_x000D_
linear-gradient(135deg, transparent 50%, $select-focus-color 50%), linear-gradient(to right, $select-focus-color, $select-focus-color);_x000D_
background-position: calc(100% - 15px) 1em, calc(100% - 20px) 1em, calc(100% - 2.5em) 0.5em;_x000D_
background-size: 5px 5px, 5px 5px, 1px 1.5em;_x000D_
background-repeat: no-repeat;_x000D_
border-color: $select-focus-color;_x000D_
outline: 0;_x000D_
}_x000D_
}
_x000D_
.val()
always works with textarea
elements.
.text()
works sometimes and fails other times! It's not reliable (tested in Chrome 33)
What's best is that .val()
works seamlessly with other form elements too (like input
) whereas .text()
fails.
NuGet > Microsoft.AspNet.WebApi.Client package
I recently had this problem as I was moving from Putty for Linux to Remmina for Linux. So I have a lot of PPK files for Putty in my .putty
directory as I've been using it's for 8 years. For this I used a simple for
command for bash shell to do all files:
cd ~/.putty
for X in *.ppk; do puttygen $X -L > ~/.ssh/$(echo $X | sed 's,./,,' | sed 's/.ppk//g').pub; puttygen $X -O private-openssh -o ~/.ssh/$(echo $X | sed 's,./,,' | sed 's/.ppk//g').pvk; done;
Very quick and to the point, got the job done for all files that putty had. If it finds a key with a password it will stop and ask for the password for that key first and then continue.
If you are willing to change your uri, you could also use PathVariable
.
@RequestMapping(value="/mapping/foo/{foo}/{bar}", method=RequestMethod.GET)
public String process(@PathVariable String foo,@PathVariable String bar) {
//Perform logic with foo and bar
}
NB: The first foo is part of the path, the second one is the PathVariable
RUN
- command triggers while we build the docker image.
CMD
- command triggers while we launch the created docker image.
SELECT company
, workflow
, MIN(date)
FROM workflowTable
GROUP BY company
, workflow
Also pay attention to the object type of your numpy array, converting it using .astype('uint8')
resolved the issue for me.
this is a working copy of my code check it, how to retrive day name from date in sql
CREATE Procedure [dbo].[proc_GetProjectDeploymentTimeSheetData]
@FromDate date,
@ToDate date
As
Begin
select p.ProjectName + ' ( ' + st.Time +' '+'-'+' '+et.Time +' )' as ProjectDeatils,
datename(dw,pts.StartDate) as 'Day'
from
ProjectTimeSheet pts
join Projects p on pts.ProjectID=p.ID
join Timing st on pts.StartTimingId=st.Id
join Timing et on pts.EndTimingId=et.Id
where pts.StartDate >= @FromDate
and pts.StartDate <= @ToDate
END
Generally to count distinct values in single column, you can use Series.value_counts
:
df.domain.value_counts()
#'vk.com' 5
#'twitter.com' 2
#'facebook.com' 1
#'google.com' 1
#Name: domain, dtype: int64
To see how many unique values in a column, use Series.nunique
:
df.domain.nunique()
# 4
To get all these distinct values, you can use unique
or drop_duplicates
, the slight difference between the two functions is that unique
return a numpy.array
while drop_duplicates
returns a pandas.Series
:
df.domain.unique()
# array(["'vk.com'", "'twitter.com'", "'facebook.com'", "'google.com'"], dtype=object)
df.domain.drop_duplicates()
#0 'vk.com'
#2 'twitter.com'
#4 'facebook.com'
#6 'google.com'
#Name: domain, dtype: object
As for this specific problem, since you'd like to count distinct value with respect to another variable, besides groupby
method provided by other answers here, you can also simply drop duplicates firstly and then do value_counts()
:
import pandas as pd
df.drop_duplicates().domain.value_counts()
# 'vk.com' 3
# 'twitter.com' 2
# 'facebook.com' 1
# 'google.com' 1
# Name: domain, dtype: int64
In my case I had to remove some files that were created by gradle at some point in my study to make things work. So, cleaning up after messing up and then it ran fine ...
If you experienced this issue in a git project, do git status
and remove the unrevisioned files. (For me elasticsearch
had a problem with plugins/analysis-icu
).
Gradle Version
: 5.1.1
Answer 1 : Yes it called upcasting but the way you do it is not modern way. Upcasting can be performed implicitly you don't need any conversion. So just writing Employee emp = mgr; is enough for upcasting.
Answer 2 : If you create object of Manager class we can say that manager is an employee. Because class Manager : Employee depicts Is-A relationship between Employee Class and Manager Class. So we can say that every manager is an employee.
But if we create object of Employee class we can not say that this employee is manager because class Employee is a class which is not inheriting any other class. So you can not directly downcast that Employee Class object to Manager Class object.
So answer is, if you want to downcast from Employee Class object to Manager Class object, first you must have object of Manager Class first then you can upcast it and then you can downcast it.
Inspired by the answers from @thegauraw and @Brian Woodward, here's a bit I pulled together for JQuery users, including a custom validation error message:
$cbx_group = $("input:checkbox[name^='group']");
$cbx_group.on("click", function() {
if ($cbx_group.is(":checked")) {
// checkboxes become unrequired as long as one is checked
$cbx_group.prop("required", false).each(function() {
this.setCustomValidity("");
});
} else {
// require checkboxes and set custom validation error message
$cbx_group.prop("required", true).each(function() {
this.setCustomValidity("Please select at least one checkbox.");
});
}
});
Note that my form has some checkboxes checked by default.
Maybe some of you JavaScript/JQuery wizards could tighten that up even more?
pax> echo a.b.js | sed 's/\.[^.]*$//'
a.b
pax> echo a.b.js | sed 's/^.*\.//'
js
works fine, so you can just use:
pax> FILE=a.b.js
pax> NAME=$(echo "$FILE" | sed 's/\.[^.]*$//')
pax> EXTENSION=$(echo "$FILE" | sed 's/^.*\.//')
pax> echo $NAME
a.b
pax> echo $EXTENSION
js
The commands, by the way, work as follows.
The command for NAME
substitutes a "."
character followed by any number of non-"."
characters up to the end of the line, with nothing (i.e., it removes everything from the final "."
to the end of the line, inclusive). This is basically a non-greedy substitution using regex trickery.
The command for EXTENSION
substitutes a any number of characters followed by a "."
character at the start of the line, with nothing (i.e., it removes everything from the start of the line to the final dot, inclusive). This is a greedy substitution which is the default action.
var otherInput = $(this).closest('.row').find('.inputQty');
That goes up to a row level, then back down to .inputQty
.
If you are getting a JS based date String
then first use the new Date(String)
constructor and then pass the Date
object to the moment
method. Like:
var dateString = 'Thu Jul 15 2016 19:31:44 GMT+0200 (CEST)';
var dateObj = new Date(dateString);
var momentObj = moment(dateObj);
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15
In case dateString
is 15-07-2016
, then you should use the moment(date:String, format:String)
method
var dateString = '07-15-2016';
var momentObj = moment(dateString, 'MM-DD-YYYY');
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15
Just studied the topic, look for the examples in the thread and try to make my version:
from collections import defaultdict
# from pprint import pprint
import re
def gen_primes(limit=None):
"""Sieve of Eratosthenes"""
not_prime = defaultdict(list)
num = 2
while limit is None or num <= limit:
if num in not_prime:
for prime in not_prime[num]:
not_prime[prime + num].append(prime)
del not_prime[num]
else: # Prime number
yield num
not_prime[num * num] = [num]
# It's amazing to debug it this way:
# pprint([num, dict(not_prime)], width=1)
# input()
num += 1
def is_prime(num):
"""Check if number is prime based on Sieve of Eratosthenes"""
return num > 1 and list(gen_primes(limit=num)).pop() == num
def oneliner_is_prime(num):
"""Simple check if number is prime"""
return num > 1 and not any([num % x == 0 for x in range(2, num)])
def regex_is_prime(num):
return re.compile(r'^1?$|^(11+)\1+$').match('1' * num) is None
def simple_is_prime(num):
"""Simple check if number is prime
More efficient than oneliner_is_prime as it breaks the loop
"""
for x in range(2, num):
if num % x == 0:
return False
return num > 1
def simple_gen_primes(limit=None):
"""Prime number generator based on simple gen"""
num = 2
while limit is None or num <= limit:
if simple_is_prime(num):
yield num
num += 1
if __name__ == "__main__":
less1000primes = list(gen_primes(limit=1000))
assert less1000primes == list(simple_gen_primes(limit=1000))
for num in range(1000):
assert (
(num in less1000primes)
== is_prime(num)
== oneliner_is_prime(num)
== regex_is_prime(num)
== simple_is_prime(num)
)
print("Primes less than 1000:")
print(less1000primes)
from timeit import timeit
print("\nTimeit:")
print(
"gen_primes:",
timeit(
"list(gen_primes(limit=1000))",
setup="from __main__ import gen_primes",
number=1000,
),
)
print(
"simple_gen_primes:",
timeit(
"list(simple_gen_primes(limit=1000))",
setup="from __main__ import simple_gen_primes",
number=1000,
),
)
print(
"is_prime:",
timeit(
"[is_prime(num) for num in range(2, 1000)]",
setup="from __main__ import is_prime",
number=100,
),
)
print(
"oneliner_is_prime:",
timeit(
"[oneliner_is_prime(num) for num in range(2, 1000)]",
setup="from __main__ import oneliner_is_prime",
number=100,
),
)
print(
"regex_is_prime:",
timeit(
"[regex_is_prime(num) for num in range(2, 1000)]",
setup="from __main__ import regex_is_prime",
number=100,
),
)
print(
"simple_is_prime:",
timeit(
"[simple_is_prime(num) for num in range(2, 1000)]",
setup="from __main__ import simple_is_prime",
number=100,
),
)
The result of running this code show interesting results:
$ python prime_time.py
Primes less than 1000:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
Timeit:
gen_primes: 0.6738066330144648
simple_gen_primes: 4.738092333020177
is_prime: 31.83770858097705
oneliner_is_prime: 3.3708438930043485
regex_is_prime: 8.692703998007346
simple_is_prime: 0.4686249239894096
So I can see that we have right answers for different questions here; for a prime number generator gen_primes
looks like the right answer; but for a prime number check, the simple_is_prime
function is better suited.
This works, but I am always open to better ways to make is_prime
function.
Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.
You should read Working with Auto Layout Programmatically and Visual Format Language.
You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.
Some links i found:
What is the difference?
From the documentation:
- - (Boolean)
instance_of?(class)
- Returns
true
ifobj
is an instance of the given class.
and:
- - (Boolean)
is_a?(class)
- (Boolean)kind_of?(class)
- Returns
true
ifclass
is the class ofobj
, or ifclass
is one of the superclasses ofobj
or modules included inobj
.
If that is unclear, it would be nice to know what exactly is unclear, so that the documentation can be improved.
When should I use which?
Never. Use polymorphism instead.
Why are there so many of them?
I wouldn't call two "many". There are two of them, because they do two different things.
Use:
List<String> x = new ArrayList<>(Arrays.asList("xyz", "abc"));
If you don't want to add new elements to the list later, you can also use (Arrays.asList returns a fixed-size list):
List<String> x = Arrays.asList("xyz", "abc");
Note: you can also use a static import if you like, then it looks like this:
import static java.util.Arrays.asList;
...
List<String> x = new ArrayList<>(asList("xyz", "abc"));
or
List<String> x = asList("xyz", "abc");
According to the below article:
http://tools.ietf.org/html/rfc3696 (Page 6, Section 3)
It's mentioned that:
"There is a length limit on email addresses. That limit is a maximum of 64 characters (octets) in the "local part" (before the "@") and a maximum of 255 characters (octets) in the domain part (after the "@") for a total length of 320 characters. Systems that handle email should be prepared to process addresses which are that long, even though they are rarely encountered."
So, the maximum total length for an email address is 320 characters ("local part": 64 + "@": 1 + "domain part": 255 which sums to 320)
echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'
Sorry, you can't view or download this file at this time is an error message that you may get when you try to download files on Google Drive.
Bandwidth limits
Limit Per hour Per day
Download via web client 750 MB 1250 MB
Upload via web client 300 MB 500 MB
The explanation for the error message is simple: while users are free to share files publicly, or with a large number of users, quotas are in effect that limit availability.
If too many users view or download a file, it may be locked for a 24 hour period before the quota is reset. The period that a file is locked may be shorter according to Google.
If a file is particularly popular, it may take days or even longer before you manage to download it to your computer or place it on your Drive storage.
It could be a solution:
Locate the "uc" part of the address, and replace it with "open", so that the beginning of the URL reads * https:// drive.google.com/open?*
Load the address again once you have replaced uc with open in the address.
This loads a new screen with controls at the top.
Click on the "add to my drive" icon at the top right.
Click on "add to my drive" again to open your Google Drive storage in a new tab in the browser.
You should see the locked file on your drive now.
Select it with a right-click, and then the "make a copy" option from the menu.
8.Select the copy of the file with a right-click, and there download to download the file to your local system.
Basically, what this does is create a copy of the file on your own Drive account. Since you are the owner of the copied file, you may download it to your local system this way.
Please note that this works only if you are signed in to a Google Account. Also note that you are the owner of the copied file and will be held responsible for policy violations or other issues linked to the file.
Another option is: Any public folder in Drive can host files and provide direct links to the files.
How to create the hosting URL: https:// googledrive.com/host/FolderID (your id file)
This will provide a folder that will give direct links to files inside the folder. Note: hosting view will not display files created in Google Docs.
My solution:
I had the same problem, so I made a JSON file in Google Drive but the URL file (.mp3) is in Dropbox. It is working fantastic even though I have 40,000 active user. I used this solution because I did not have time to search too much! I wrote you the Dropbox Limits anyway but I did not get problems with it
Traffic limits DROPBOX
Links and file requests are automatically banned if they generate unusually large amounts of traffic.
Dropbox Basic (free) accounts:
20 GB per day: The total amount of traffic that all of your links and file requests combined can generate without getting banned 100,000 downloads per day: The total number of downloads that all of your links combined can generate
Dropbox Plus and Business accounts: About 200 GB per day: The total amount of traffic that all of your links and file requests combined can generate without getting banned There's no daily limit to the number of downloads that your links can generate If your account hits our limit, we'll send a message to the email address registered to your account. Your links will be temporarily disabled, and anyone who tries to access them will see an error page instead of your files.
P.S. If you need more information about my files and how did it and How to make the URL File from Dropbox, I hope help to the people is reading this! (I posted it before but Someone deleted my last post)!
I would use something like this for fixed length, like hashes:
md5sum = String.format("%032x", new BigInteger(1, md.digest()));
This can also be due to environment variable CATALINA_HOME in your system. In our organization there were several cases where JNLP applications just refused to start without logging anything and emptying CATALINA_HOME solved the issue.
I had the environment variable set in the command prompt and it didn't appear in GUI. I'm not sure if setx command or register removal commands did the trick. Restart seems to be necessary after removing the variable.
Because the designers of CSS didn't have the foresight to imagine the flexibility this would bring. There are plenty of reasons to expand the content area of a box without affecting its relationship to neighbouring elements. If you think it's not possible, put some long nowrap
'd text in a box, set a width on the box, and watch how the overflowed content does nothing to the layout.
Yes, this is still relevant with CSS3 in 2019; case in point: flexbox layouts. Flexbox items' margins do not collapse, so in order to space them evenly and align them with the visual edge of the container, one must subtract the items' margins from their container's padding. If any result is < 0, you must use a negative margin on the container, or sum that negative with the existing margin. I.e. the content of the element effects how one defines the margins for it, which is backwards. Summing doesn't work cleanly when flex elements' content have margins defined in different units or are affected by a different font-size, etc.
The example below should, ideally have aligned and evenly spaced grey boxes but, sadly they aren't.
body {_x000D_
font-family: sans-serif;_x000D_
margin: 2rem;_x000D_
}_x000D_
body > * {_x000D_
margin: 2rem 0 0;_x000D_
}_x000D_
body > :first-child {_x000D_
margin-top: 0;_x000D_
}_x000D_
h1,_x000D_
li,_x000D_
p {_x000D_
padding: 10px;_x000D_
background: lightgray;_x000D_
}_x000D_
ul {_x000D_
list-style: none;_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
padding: 0;/* just to reset */_x000D_
padding: -5px;/* would allow correct alignment */_x000D_
}_x000D_
li {_x000D_
flex: 1 1 auto;_x000D_
margin: 5px;_x000D_
}
_x000D_
<h1>Cras facilisis orci ligula</h1>_x000D_
_x000D_
<ul>_x000D_
<li>a lacinia purus porttitor eget</li>_x000D_
<li>donec ut nunc lorem</li>_x000D_
<li>duis in est dictum</li>_x000D_
<li>tempor metus non</li>_x000D_
<li>dapibus sapien</li>_x000D_
<li>phasellus bibendum tincidunt</li>_x000D_
<li>quam vitae accumsan</li>_x000D_
<li>ut interdum eget nisl in eleifend</li>_x000D_
<li>maecenas sodales interdum quam sed accumsan</li>_x000D_
</ul>_x000D_
_x000D_
<p>Fusce convallis, arcu vel elementum pulvinar, diam arcu tempus dolor, nec venenatis sapien diam non dui. Nulla mollis velit dapibus magna pellentesque, at tempor sapien blandit. Sed consectetur nec orci ac lobortis.</p>_x000D_
_x000D_
<p>Integer nibh purus, convallis eget tincidunt id, eleifend id lectus. Vivamus tristique orci finibus, feugiat eros id, semper augue.</p>
_x000D_
I have encountered enough of these little issues over the years where a little negative padding would have gone a long way, but instead I'm forced to add non-semantic markup, use calc()
, or CSS preprocessors which only work when the units are the same, etc.
As for "obnoxious try/catch blocks":
d = {}
d.setdefault('key',{}).setdefault('inner key',{})['inner inner key'] = 'value'
print d
yields
{'key': {'inner key': {'inner inner key': 'value'}}}
You can use this to convert from your flat dictionary format to structured format:
fd = {('new jersey', 'mercer county', 'plumbers'): 3,
('new jersey', 'mercer county', 'programmers'): 81,
('new jersey', 'middlesex county', 'programmers'): 81,
('new jersey', 'middlesex county', 'salesmen'): 62,
('new york', 'queens county', 'plumbers'): 9,
('new york', 'queens county', 'salesmen'): 36}
for (k1,k2,k3), v in fd.iteritems():
d.setdefault(k1, {}).setdefault(k2, {})[k3] = v
From MDSN article, Controlling Transactions (Database Engine).
If a run-time statement error (such as a constraint violation) occurs in a batch, the default behavior in the Database Engine is to roll back only the statement that generated the error. You can change this behavior using the SET XACT_ABORT statement. After SET XACT_ABORT ON is executed, any run-time statement error causes an automatic rollback of the current transaction. Compile errors, such as syntax errors, are not affected by SET XACT_ABORT. For more information, see SET XACT_ABORT (Transact-SQL).
In your case it will rollback the complete transaction when any of inserts fail.
There is another cause for this type of problem what I would like to share, because I struggle in this problem for some time and I could't find any answer on SO.
In a repository like:
@Repository
public interface UserEntityDao extends CrudRepository<UserEntity, Long>{
}
If your entity UserEntity
does not have the @Entity
annotation on the class, you will have the same error.
This error is confusing for this case, because you focus on trying to resolve the problem about Spring not found the Repository but the problem is the entity. And if you came to this answer trying to test your Repository, this answer may help you.
My way to effectively work with multiple files is to use tmux.
It allows you to split windows vertically and horizontally, as in:
I have it working this way on both my mac and linux machines and I find it better than the native window pane switching mechanism that's provided (on Macs). I find the switching easier and only with tmux have I been able to get the 'new page at the same current directory' working on my mac (despite the fact that there seems to be options to open new panes in the same directory) which is a surprisingly critical piece. An instant new pane at the current location is amazingly useful. A method that does new panes with the same key combos for both OS's is critical for me and a bonus for all for future personal compatibility. Aside from multiple tmux panes, I've also tried using multiple tabs, e.g. and multiple new windows, e.g. and ultimately I've found that multiple tmux panes to be the most useful for me. I am very 'visual' and like to keep my various contexts right in front of me, connected together as panes.
tmux also support horizontal and vertical panes which the older screen
didn't (though mac's iterm2 seems to support it, but again, the current directory setting didn't work for me). tmux 1.8
You simply cannot get PowerShell to ommit those pesky newlines. There is no script or cmdlet that does this.
Of course Write-Host is absolute nonsense because you can't redirect/pipe from it! You simply have to write your own:
using System;
namespace WriteToStdout
{
class Program
{
static void Main(string[] args)
{
if (args != null)
{
Console.Write(string.Join(" ", args));
}
}
}
}
E.g.
PS C:\> writetostdout finally I can write to stdout like echo -n
finally I can write to stdout like echo -nPS C:\>
I do not have a Mac OSx machine to test this on but in bash on Linux I use something like the following to chmod only directories:
find . -type d -exec chmod 755 {} \+
but this also does the same thing:
chmod 755 `find . -type d`
and so does this:
chmod 755 $(find . -type d)
The last two are using different forms of subcommands. The first is using backticks (older and depreciated) and the other the $() subcommand syntax.
So I think in your case that the following will do what you want.
chmod 777 $(find "/Users/Test/Desktop/PATH")
I was just searching for something similar:
I want to sum every odd row column.
SUMIF
has TWO possible ranges, the range to sum from, and a range to consider criteria in.
SUMIF(B1:B1000,1,A1:A1000)
This function will consider if a cell in the B range is "=1", it will sum the corresponding A cell only if it is.
To get "=1" to return in the B range I put this in B:
=MOD(ROWNUM(B1),2)
Then auto fill down to get the modulus to fill, you could put and calculatable criteria here to get the SUMIF or SUMIFS conditions you need to loop through each cell.
Easier than ARRAY stuff and hides the back-end of loops!
If you want to do it the way the calculator actually does it, use the Babylonian technique. It is explained here and here.
Suppose you want to calculate the square root of 2:
a=2
a1 = (a/2)+1
b1 = a/a1
aminus1 = a1
bminus1 = b1
while (aminus1-bminus1 > 0):
an = 0.5 * (aminus1 + bminus1)
bn = a / an
aminus1 = an
bminus1 = bn
print(an,bn,an-bn)
a bit late to the party but in light of iOS 8.0 out there this might be relevant:
if you can avoid using
[[UIDevice currentDevice] systemVersion]
Instead check for existence of of a method/class/whatever else.
if ([self.yourClassInstance respondsToSelector:@selector(<yourMethod>)])
{
//do stuff
}
I found it to be useful for location manager where I have to call requestWhenInUseAuthorization for iOS 8.0 but the method is not available for iOS < 8
You can find every content type here: http://www.iana.org/assignments/media-types/media-types.xhtml
The most common type are:
Type application
application/java-archive
application/EDI-X12
application/EDIFACT
application/javascript
application/octet-stream
application/ogg
application/pdf
application/xhtml+xml
application/x-shockwave-flash
application/json
application/ld+json
application/xml
application/zip
application/x-www-form-urlencoded
Type audio
audio/mpeg
audio/x-ms-wma
audio/vnd.rn-realaudio
audio/x-wav
Type image
image/gif
image/jpeg
image/png
image/tiff
image/vnd.microsoft.icon
image/x-icon
image/vnd.djvu
image/svg+xml
Type multipart
multipart/mixed
multipart/alternative
multipart/related (using by MHTML (HTML mail).)
multipart/form-data
Type text
text/css
text/csv
text/html
text/javascript (obsolete)
text/plain
text/xml
Type video
video/mpeg
video/mp4
video/quicktime
video/x-ms-wmv
video/x-msvideo
video/x-flv
video/webm
Type vnd :
application/vnd.android.package-archive
application/vnd.oasis.opendocument.text
application/vnd.oasis.opendocument.spreadsheet
application/vnd.oasis.opendocument.presentation
application/vnd.oasis.opendocument.graphics
application/vnd.ms-excel
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.ms-powerpoint
application/vnd.openxmlformats-officedocument.presentationml.presentation
application/msword
application/vnd.openxmlformats-officedocument.wordprocessingml.document
application/vnd.mozilla.xul+xml
In interface Builder set table view separator "None"
and those separator lines which are shown after the last cell can be remove by following approach. Best approach is to assign Empty View to tableView FooterView in viewDidLoad
self.tableView.tableFooterView = UIView()
I know that this question is from a while ago, but I wanted to add an answer that I believe expands upon the original question. The addendum to this question was to write the mode method without relying upon a preset range (in this case, 0 through 100). I have written a version for mode that uses the range of values in the original array to generate the count array.
public static int mode(int[] list) {
//Initialize max and min value variable as first value of list
int maxValue = list[0];
int minValue = list[0];
//Finds maximum and minimum values in list
for (int i = 1; i < list.length; i++) {
if (list[i] > maxValue) {
maxValue = list[i];
}
if (list[i] < minValue) {
minValue = list[i];
}
}
//Initialize count array with (maxValue - minValue + 1) elements
int[] count = new int[maxValue - minValue + 1];
//Tally counts of values from list, store in array count
for (int i = 0; i < list.length; i++) {
count[list[i] - minValue]++; //Increment counter index for current value of list[i] - minValue
}
//Find max value in count array
int max = count[0]; //Initialize max variable as first value of count
for (int i = 1; i < count.length; i++) {
if (count[i] > max) {
max = count[i];
}
}
//Find first instance where max occurs in count array
for (int i = 0; i < count.length; i++) {
if (count[i] == max) {
return i + minValue; //Returns index of count adjusted for min/max list values - this is the mode value in list
}
}
return -1; //Only here to force compilation, never actually used
}
I've created an API to create an Excel file more easier.
Create Excel - Creating Excel from Template
Just set the required values upon instantiation then invoke execute(), it will be created based on your desired output directory.
But before you use this, you must have an Excel Template which will be use as a template of the newly created Excel file.
Also, you need Apache POI in your project's class path.
Be aware that the function File.GetLastWriteTime does not always work as expected, the values are sometimes not instantaneously updated by the OS. You may get an old Timestamp, even if the file has been modified right before.
The behaviour may vary between OS versions. For example, this unit test worked well every time on my developer machine, but it always fails on our build server.
[TestMethod]
public void TestLastModifiedTimeStamps()
{
var tempFile = Path.GetTempFileName();
var lastModified = File.GetLastWriteTime(tempFile);
using (new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
}
Assert.AreNotEqual(lastModified, File.GetLastWriteTime(tempFile));
}
See File.GetLastWriteTime seems to be returning 'out of date' value
Your options:
a) live with the occasional omissions.
b) Build up an active component realising the observer pattern (eg. a tcp server client structure), communicating the changes directly instead of writing / reading files. Fast and flexible, but another dependency and a possible point of failure (and some work, of course).
c) Ensure the signalling process by replacing the content of a dedicated signal file that other processes regularly read. It´s not that smart as it´s a polling procedure and has a greater overhead than calling File.GetLastWriteTime, but if not checking the content from too many places too often, it will do the work.
/// <summary>
/// type to set signals or check for them using a central file
/// </summary>
public class FileSignal
{
/// <summary>
/// path to the central file for signal control
/// </summary>
public string FilePath { get; private set; }
/// <summary>
/// numbers of retries when not able to retrieve (exclusive) file access
/// </summary>
public int MaxCollisions { get; private set; }
/// <summary>
/// timespan to wait until next try
/// </summary>
public TimeSpan SleepOnCollisionInterval { get; private set; }
/// <summary>
/// Timestamp of the last signal
/// </summary>
public DateTime LastSignal { get; private set; }
/// <summary>
/// constructor
/// </summary>
/// <param name="filePath">path to the central file for signal control</param>
/// <param name="maxCollisions">numbers of retries when not able to retrieve (exclusive) file access</param>
/// <param name="sleepOnCollisionInterval">timespan to wait until next try </param>
public FileSignal(string filePath, int maxCollisions, TimeSpan sleepOnCollisionInterval)
{
FilePath = filePath;
MaxCollisions = maxCollisions;
SleepOnCollisionInterval = sleepOnCollisionInterval;
LastSignal = GetSignalTimeStamp();
}
/// <summary>
/// constructor using a default value of 50 ms for sleepOnCollisionInterval
/// </summary>
/// <param name="filePath">path to the central file for signal control</param>
/// <param name="maxCollisions">numbers of retries when not able to retrieve (exclusive) file access</param>
public FileSignal(string filePath, int maxCollisions): this (filePath, maxCollisions, TimeSpan.FromMilliseconds(50))
{
}
/// <summary>
/// constructor using a default value of 50 ms for sleepOnCollisionInterval and a default value of 10 for maxCollisions
/// </summary>
/// <param name="filePath">path to the central file for signal control</param>
public FileSignal(string filePath) : this(filePath, 10)
{
}
private Stream GetFileStream(FileAccess fileAccess)
{
var i = 0;
while (true)
{
try
{
return new FileStream(FilePath, FileMode.Create, fileAccess, FileShare.None);
}
catch (Exception e)
{
i++;
if (i >= MaxCollisions)
{
throw e;
}
Thread.Sleep(SleepOnCollisionInterval);
};
};
}
private DateTime GetSignalTimeStamp()
{
if (!File.Exists(FilePath))
{
return DateTime.MinValue;
}
using (var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.None))
{
if(stream.Length == 0)
{
return DateTime.MinValue;
}
using (var reader = new BinaryReader(stream))
{
return DateTime.FromBinary(reader.ReadInt64());
};
}
}
/// <summary>
/// overwrites the existing central file and writes the current time into it.
/// </summary>
public void Signal()
{
LastSignal = DateTime.Now;
using (var stream = new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (var writer = new BinaryWriter(stream))
{
writer.Write(LastSignal.ToBinary());
}
}
}
/// <summary>
/// returns true if the file signal has changed, otherwise false.
/// </summary>
public bool CheckIfSignalled()
{
var signal = GetSignalTimeStamp();
var signalTimestampChanged = LastSignal != signal;
LastSignal = signal;
return signalTimestampChanged;
}
}
Some tests for it:
[TestMethod]
public void TestSignal()
{
var fileSignal = new FileSignal(Path.GetTempFileName());
var fileSignal2 = new FileSignal(fileSignal.FilePath);
Assert.IsFalse(fileSignal.CheckIfSignalled());
Assert.IsFalse(fileSignal2.CheckIfSignalled());
Assert.AreEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
fileSignal.Signal();
Assert.IsFalse(fileSignal.CheckIfSignalled());
Assert.AreNotEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
Assert.IsTrue(fileSignal2.CheckIfSignalled());
Assert.AreEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
Assert.IsFalse(fileSignal2.CheckIfSignalled());
}
Arduino sketches are written in C++.
Here is a typical construct you'll encounter:
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
...
lcd.begin(16, 2);
lcd.print("Hello, World!");
That's C++, not C.
Hence do yourself a favor and learn C++. There are plenty of books and online resources available.
Remove the servlet-api.jar from build path and just add it on web-inf lib folder and then export the WAR file..it'll work...cheers..!!!
I like the solution from realcrowd the best.
HTML:
<form role="form" id="form" name="form" autocomplete="off" novalidate rc-submit="signup()">
<div class="form-group" ng-class="{'has-error': rc.form.hasError(form.firstName)}">
<label for="firstName">Your First Name</label>
<input type="text" id="firstName" name="firstName" class="form-control input-sm" placeholder="First Name" ng-maxlength="40" required="required" ng-model="owner.name.first"/>
<div class="help-block" ng-show="rc.form.hasError(form.firstName)">{{rc.form.getErrMsg(form.firstName)}}</div>
</div>
</form>
javascript:
//define custom submit directive
var rcSubmitDirective = {
'rcSubmit': ['$parse', function ($parse) {
return {
restrict: 'A',
require: ['rcSubmit', '?form'],
controller: ['$scope', function ($scope) {
this.attempted = false;
var formController = null;
this.setAttempted = function() {
this.attempted = true;
};
this.setFormController = function(controller) {
formController = controller;
};
this.hasError = function (fieldModelController) {
if (!formController) return false;
if (fieldModelController) {
return fieldModelController.$invalid && this.attempted;
} else {
return formController && formController.$invalid && this.attempted;
}
};
this.getErrMsg=function(ctrl){
var e=ctrl.$error;
var errMsg;
if (e.required){
errMsg='Please enter a value';
}
return errMsg;
}
}],
compile: function(cElement, cAttributes, transclude) {
return {
pre: function(scope, formElement, attributes, controllers) {
var submitController = controllers[0];
var formController = (controllers.length > 1) ? controllers[1] : null;
submitController.setFormController(formController);
scope.rc = scope.rc || {};
scope.rc[attributes.name] = submitController;
},
post: function(scope, formElement, attributes, controllers) {
var submitController = controllers[0];
var formController = (controllers.length > 1) ? controllers[1] : null;
var fn = $parse(attributes.rcSubmit);
formElement.bind('submit', function (event) {
submitController.setAttempted();
if (!scope.$$phase) scope.$apply();
if (!formController.$valid) return false;
scope.$apply(function() {
fn(scope, {$event:event});
});
});
}
};
}
};
}]
};
app.directive(rcSubmitDirective);
Unfortunately INFORMATION_SCHEMA
doesn't contain info about the system procs.
SELECT *
FROM sys.objects
WHERE objectproperty(object_id, N'IsMSShipped') = 0
AND objectproperty(object_id, N'IsProcedure') = 1
It supports lists, but not as a separate data structure (ignoring arrays for the moment).
The for
loop iterates over a list (in the generic sense) of white-space separated values, regardless of how that list is created, whether literally:
for i in 1 2 3; do
echo "$i"
done
or via parameter expansion:
listVar="1 2 3"
for i in $listVar; do
echo "$i"
done
or command substitution:
for i in $(echo 1; echo 2; echo 3); do
echo "$i"
done
An array is just a special parameter which can contain a more structured list of value, where each element can itself contain whitespace. Compare the difference:
array=("item 1" "item 2" "item 3")
for i in "${array[@]}"; do # The quotes are necessary here
echo "$i"
done
list='"item 1" "item 2" "item 3"'
for i in $list; do
echo $i
done
for i in "$list"; do
echo $i
done
for i in ${array[@]}; do
echo $i
done
Create a class for maintain hit counters
public static class Counter
{
private static long hit;
public static void HitCounter()
{
hit++;
}
public static long GetCounter()
{
return hit;
}
}
Increment the value of counter at page load event
protected void Page_Load(object sender, EventArgs e)
{
Counter.HitCounter(); // call static function of static class Counter to increment the counter value
}
Redirect the page on itself and display the counter value on button click
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write(Request.RawUrl.ToString()); // redirect on itself
Response.Write("<br /> Counter =" + Counter.GetCounter() ); // display counter value
}
What you ask is quite complex topic - not easily answerable. Other answers are ok, but they covered just a small part of all the things you need to do.
As seen in comments, it is not possible to fix hardware problems 100%, however it is possible with high probabily to reduce or catch them using various techniques.
If I was you, I would create the software of the highest Safety integrity level level (SIL-4). Get the IEC 61513 document (for the nuclear industry) and follow it.
This is very possible; you define the URI scheme in your AndroidManifest.xml, using the <data>
element. You setup an intent filter with the <data>
element filled out, and you'll be able to create your own scheme. (More on intent filters and intent resolution here.)
Here's a short example:
<activity android:name=".MyUriActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="myapp" android:host="path" />
</intent-filter>
</activity>
As per how implicit intents work, you need to define at least one action and one category as well; here I picked VIEW as the action (though it could be anything), and made sure to add the DEFAULT category (as this is required for all implicit intents). Also notice how I added the category BROWSABLE - this is not necessary, but it will allow your URIs to be openable from the browser (a nifty feature).
In the spirit of @Chris W, just try to replicate the exact error you are getting. An example would have helped but maybe you're doing:
x <- c(1,2)
y <- c("a","b","c")
names(x) <- y
Error in names(x) <- y :
'names' attribute [3] must be the same length as the vector [2]
I suspect you're trying to give names to a vector (x
) that is shorter than your vector of names (y
).
Use pathed from gtools.
It does things in an intuitive way. For example:
pathed /REMOVE "c:\my\folder"
pathed /APPEND "c:\my\folder"
It shows results without the need to spawn a new cmd!
This very helpful feature is now available starting at version 1.1.2 of AngularJS. It's considered unstable but I have used it (1.1.3) and it works fine.
Basically you can use a function to generate a templateUrl string. The function is passed the route parameters that you can use to build and return the templateUrl string.
var app = angular.module('app',[]);
app.config(
function($routeProvider) {
$routeProvider.
when('/', {templateUrl:'/home'}).
when('/users/:user_id',
{
controller:UserView,
templateUrl: function(params){ return '/users/view/' + params.user_id; }
}
).
otherwise({redirectTo:'/'});
}
);
Many thanks to https://github.com/lrlopez for the pull request.
To restate your problem in a way that's easier to express as a regular expression:
Get the substring of characters that is contained between zero or one leading double-quotes and zero or one trailing double-quotes.
Here's the regexp that does that:
var regexp = /^"?(.+?)"?$/;
var newStr = str.replace(/^"?(.+?)"?$/,'$1');
Breaking down the regexp:
^"?
a greedy match for zero or one leading double-quotes"?$
a greedy match for zero or one trailing double-quotes(.+?)
, which will contain the target as $1
.This will return delimited "string" here
for:
str = "delimited "string" here" // ...
str = '"delimited "string" here"' // ...
str = 'delimited "string" here"' // ... and
str = '"delimited "string" here'
Note that SimpleDateFormat format pattern Z is for RFC 822 time zone and pattern X is for ISO 8601 (this standard supports single letter time zone names like Z for Zulu).
So new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX")
produces a format that can parse both "2013-03-11T01:38:18.309Z"
and "2013-03-11T01:38:18.309+0000"
and will give you the same result.
Unfortunately, as far as I can tell, you can't get this format to generate the Z for Zulu version, which is annoying.
I actually have more trouble on the JavaScript side to deal with both formats.
I just want to add something to these great answers. If your DOM
element ins't loading in time. You can still set the value.
let Ctrl = $('#mySelectElement');
...
Ctrl.attr('value', myValue);
after that most DOM
elements that accept a value attribute should populate correctly.
To read the content of .hdf5 file as an array, you can do something as follow
> import numpy as np
> myarray = np.fromfile('file.hdf5', dtype=float)
> print(myarray)
Yup, serialize/unserialize is what I've seen the most in many open source projects.
The best way is to use simple math
>>> a = 8
>>> a**(1./3.)
2.0
EDIT
For Negative numbers
>>> a = -8
>>> -(-a)**(1./3.)
-2.0
Complete Program for all the requirements as specified
x = int(input("Enter an integer: "))
if x>0:
ans = x**(1./3.)
if ans ** 3 != abs(x):
print x, 'is not a perfect cube!'
else:
ans = -((-x)**(1./3.))
if ans ** 3 != -abs(x):
print x, 'is not a perfect cube!'
print 'Cube root of ' + str(x) + ' is ' + str(ans)
Here is what worked for me in similar case.
After you finish writing into the Servlet
OutputStream
just call response.sendRedirect("yourPage.jsp");
. That would cause initiation of a new request from the browser, therefore avoid writing into the same output stream.
If you are working in some IDE like Eclipse or NetBeans, you should have that a.txt
file in the root directory of your project. (and not in the folder where your .class
files are built or anywhere else)
If not, you should specify the absolute path to that file.
Edit:
You would put the .txt
file in the same place with the .class
(usually also the .java
file because you compile in the same folder) compiled files if you compile it by hand with javac
. This is because it uses the relative path and the path tells the JVM the path where the executable file is located.
If you use some IDE, it will generate the compiled files for you using a Makefile or something similar for Windows and will consider it's default file structure, so he knows that the relative path begins from the root folder of the project.
The ONESHELL directive allows to write multiple line recipes to be executed in the same shell invocation.
all: foo
SOURCE_FILES = $(shell find . -name '*.c')
.ONESHELL:
foo: ${SOURCE_FILES}
FILES=()
for F in $^; do
FILES+=($${F})
done
gcc "$${FILES[@]}" -o $@
There is a drawback though : special prefix characters (‘@’, ‘-’, and ‘+’) are interpreted differently.
https://www.gnu.org/software/make/manual/html_node/One-Shell.html
Above solutions will work only if its a string. Input type date, gives you output in javascript date object in some cases like if you use angular or so. That's why some people are getting error like "TypeError: str.split is not a function". It's a date object, so you should use functions of Date object in javascript to manipulate it. Example here:
var date = $scope.dateObj ;
//dateObj is data bind to the ng-modal of input type dat.
console.log(date.getFullYear()); //this will give you full year eg : 1990
console.log(date.getDate()); //gives you the date from 1 to 31
console.log(date.getMonth() + 1); //getMonth will give month from 0 to 11
Check the following link for reference:
Want to add a difference:
Trying to acess a inexistent key gives runtime error in Dictionary but no problem in hashtable as it returns null instead of error.
e.g.
//No strict type declaration
Hashtable hash = new Hashtable();
hash.Add(1, "One");
hash.Add(2, "Two");
hash.Add(3, "Three");
hash.Add(4, "Four");
hash.Add(5, "Five");
hash.Add(6, "Six");
hash.Add(7, "Seven");
hash.Add(8, "Eight");
hash.Add(9, "Nine");
hash.Add("Ten", 10);// No error as no strict type
for(int i=0;i<=hash.Count;i++)//=>No error for index 0
{
//Can be accessed through indexers
Console.WriteLine(hash[i]);
}
Console.WriteLine(hash["Ten"]);//=> No error in Has Table
here no error for key 0 & also for key "ten"(note: t is small)
//Strict type declaration
Dictionary<int,string> dictionary= new Dictionary<int, string>();
dictionary.Add(1, "One");
dictionary.Add(2, "Two");
dictionary.Add(3, "Three");
dictionary.Add(4, "Four");
dictionary.Add(5, "Five");
dictionary.Add(6, "Six");
dictionary.Add(7, "Seven");
dictionary.Add(8, "Eight");
dictionary.Add(9, "Nine");
//dictionary.Add("Ten", 10);// error as only key, value pair of type int, string can be added
//for i=0, key doesn't exist error
for (int i = 1; i <= dictionary.Count; i++)
{
//Can be accessed through indexers
Console.WriteLine(dictionary[i]);
}
//Error : The given key was not present in the dictionary.
//Console.WriteLine(dictionary[10]);
here error for key 0 & also for key 10 as both are inexistent in dictionary, runtime error, while try to acess.
int(n**0.5)
is the floor value of sqrt(n) which you confused with power 2 of n (n**2)
. If n
is not prime, there must be two numbers 1 < i <= j < n
such that: i * j = n
.
Now, since sqrt(n) * sqrt(n) = n
assuming one of i,j
is bigger than (or equals to) sqrt(n)
- it means that the other one has to be smaller than (or equals to) sqrt(n)
.
Since that is the case, it's good enough to iterate the integer numbers in the range [2, sqrt(n)]
. And that's exactly what the code that was posted is doing.
If you want to come out as a real smartass, use the following one-liner function:
import re
def is_prime(n):
return not re.match(r'^1?$|^(11+?)\1+$',n*'1')
An explanation for the "magic regex" can be found here
Your password seems to be incorrect. Recheck your credentials.
Simply use the on click event for tab shown.
$(document).on('shown.bs.tab', 'a[href="#tab"]', function (){
});
As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:
TSKILL processName
or
TSKILL PID
Have on mind that processName
should not have the .exe
suffix and is limited to 18 characters.
Another option is WMIC
:
wmic Path win32_process Where "Caption Like 'MyProcess%.exe'" Call Terminate
wmic offer even more flexibility than taskkill with its SQL-like matchers .With wmic Path win32_process get
you can see the available fileds you can filter (and %
can be used as a wildcard).
In my case the issue revealed to be chrome blocking the CORS request from localhost:4200 to facebook api website. Running Chrome with this setting: "YOUR_PATH_TO_CHROME\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="c:/chrome worked like a charm while developing. Even with no localhost added to facebook app's settings.
Here is a complete solution using the Collections.shuffle
approach:
public static void shuffleArray(int[] array) {
List<Integer> list = new ArrayList<>();
for (int i : array) {
list.add(i);
}
Collections.shuffle(list);
for (int i = 0; i < list.size(); i++) {
array[i] = list.get(i);
}
}
Note that it suffers due to Java's inability to smoothly translate between int[]
and Integer[]
(and thus int[]
and List<Integer>
).
There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml
. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml
mediatype.
You can use the magic of Spring's ReflectionTestUtils.setField
in order to avoid making any modifications whatsoever to your code.
The comment from Michal Stochmal provides an example:
use
ReflectionTestUtils.setField(bean, "fieldName", "value");
before invoking yourbean
method during test.
Check out this tutorial for even more information, although you probably won't need it since the method is very easy to use
UPDATE
Since the introduction of Spring 4.2.RC1 it is now possible to set a static field without having to supply an instance of the class. See this part of the documentation and this commit.
<div id="video_box">
<div id="video_overlays"></div>
<div>
<video id="player" src="http://video.webmfiles.org/big-buck-bunny_trailer.webm" type="video/webm" onclick="this.play();">Your browser does not support this streaming content.</video>
</div>
</div>
for this you need to just add css like this:
#video_overlays {
position: absolute;
background-color: rgba(0, 0, 0, 0.46);
z-index: 2;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
#video_box{position: relative;}
i guess the simplest way which doesn't require any operators is
if($_GET){
//do something if $_GET is set
}
if(!$_GET){
//do something if $_GET is NOT set
}
A simple example to calculate the memory usage of a block of codes / function using memory_profile, while returning result of the function:
import memory_profiler as mp
def fun(n):
tmp = []
for i in range(n):
tmp.extend(list(range(i*i)))
return "XXXXX"
calculate memory usage before running the code then calculate max usage during the code:
start_mem = mp.memory_usage(max_usage=True)
res = mp.memory_usage(proc=(fun, [100]), max_usage=True, retval=True)
print('start mem', start_mem)
print('max mem', res[0][0])
print('used mem', res[0][0]-start_mem)
print('fun output', res[1])
calculate usage in sampling points while running function:
res = mp.memory_usage((fun, [100]), interval=.001, retval=True)
print('min mem', min(res[0]))
print('max mem', max(res[0]))
print('used mem', max(res[0])-min(res[0]))
print('fun output', res[1])
Credits: @skeept
Actually, you don't need to downgrade – if you need to use older version in some projects, just specify the version that you need to use after pod
command.
pod _0.37.2_ setup
cell1.innerHTML="<?php echo $customerDESC; ?>";
cell2.innerHTML="<?php echo $comm; ?>";
cell3.innerHTML="<?php echo $expressFEE; ?>";
cell4.innerHTML="<?php echo $totao_unit_price; ?>";
it is working like a charm, the javascript is inside a php while loop
If you want to export your last n amount of records into a file, you can run the following:
mysqldump -u user -p -h localhost --where "1=1 ORDER BY id DESC LIMIT 100" database table > export_file.sql
The above will save the last 100 records into export_file.sql, assuming the table you're exporting from has an auto-incremented id column.
You will need to alter the user, localhost, database and table values. You may optionally alter the id column and export file name.
In case of a list of dictionaries, the full list comprehension solution works while the set
solution raises
TypeError: unhashable type: 'dict'
def diff(a, b):
return [aa for aa in a if aa not in b]
d1 = {"a":1, "b":1}
d2 = {"a":2, "b":2}
d3 = {"a":3, "b":3}
>>> diff([d1, d2, d3], [d2, d3])
[{'a': 1, 'b': 1}]
>>> diff([d1, d2, d3], [d1])
[{'a': 2, 'b': 2}, {'a': 3, 'b': 3}]
You're thinking too complicated. It's actually just $('#'+openaddress)
.
I know the ask is to count a particular letter. I am writing here generic code without using any method.
sentence1 =" Mary had a little lamb"
count = {}
for i in sentence1:
if i in count:
count[i.lower()] = count[i.lower()] + 1
else:
count[i.lower()] = 1
print(count)
output
{' ': 5, 'm': 2, 'a': 4, 'r': 1, 'y': 1, 'h': 1, 'd': 1, 'l': 3, 'i': 1, 't': 2, 'e': 1, 'b': 1}
Now if you want any particular letter frequency, you can print like below.
print(count['m'])
2
Just as another option if you want to print only the key (doesn't write the .env file) you can use:
php artisan key:generate --show
Maybe you should try
^[#;].*$
^
matches the beggining, $
the end.
It says that it should be a 64-bit JDK. I have a feeling that you installed (at a previous time) a 32-bit version of Java. The path for all 32-bit applications in Windows 7 and Vista is:
C:\Program Files (x86)\
You were setting the JAVA_HOME
variable to the 32-bit version of Java. Set your JAVA_HOME
variable to the following:
C:\Program Files\Java\jdk1.7.0_45
If that does not work, check that the JDK version is 1.7.0_45. If not, change the JAVA_HOME
variable to (with JAVAVERSION
as the Java version number:
C:\Program Files\Java\jdkJAVAVERSION
follow this two step 1) adb kill-server 2) adb start-server
this is work for me
Declaration
A prototype for a function which takes a function parameter looks like the following:
void func ( void (*f)(int) );
This states that the parameter f
will be a pointer to a function which has a void
return type and which takes a single int
parameter. The following function (print
) is an example of a function which could be passed to func
as a parameter because it is the proper type:
void print ( int x ) {
printf("%d\n", x);
}
Function Call
When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:
func(print);
would call func
, passing the print function to it.
Function Body
As with any parameter, func
can now use the parameter's name in the function body to access the value of the parameter. Let's say that func
will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
print(ctr);
}
Since func
's parameter declaration says that f
is the name for a pointer to the desired function, we recall first that if f
is a pointer then *f
is the thing that f
points to (i.e. the function print
in this case). As a result, just replace every occurrence of print in the loop above with *f
:
void func ( void (*f)(int) ) {
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
(*f)(ctr);
}
}
this is what it worked for me:
select * from table
where column
BETWEEN STR_TO_DATE('29/01/15', '%d/%m/%Y')
AND STR_TO_DATE('07/10/15', '%d/%m/%Y')
Please, note that I had to change STR_TO_DATE(column, '%d/%m/%Y') from previous solutions, as it was taking ages to load
You should set a TimeZone in your DateFormat, otherwise it will use the default one (depending on the settings of the computer).
I sorted it out with [DeploymentItem] on my assembly initializing class
namespace MyTests
{
/// <summary>
/// Summary description for AssemblyTestInit
/// </summary>
[TestClass]
[DeploymentItem("EntityFramework.SqlServer.dll")]
public class AssemblyTestInit
{
public AssemblyTestInit()
{
}
private TestContext testContextInstance;
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
[AssemblyInitialize()]
public static void DbContextInitialize(TestContext testContext)
{
Database.SetInitializer<TestContext>(new TestContextInitializer());
}
}
}
If any of the above method is not working and you code is perfect then try hard refreshing by pressing Ctrl + F5. It will clear all the chaces and then reload file. It worked for me.
With the introduction of f-strings in Python 3.6, this will also work:
f'{10}' == '10'
It is actually faster than calling str()
, at the cost of readability.
In fact, it's faster than %x
string formatting and .format()
!
The examples above are a bit confusing, and this is probably the best way:
$.ajaxSetup({
headers: {
'Authorization': "Basic " + btoa(USERNAME + ":" + PASSWORD)
}
});
I took the above from a combination of Rico and Yossi's answer.
If statement is used for checking just one condition quickly.
When you have multiple options, use <xsl:choose>
as illustrated below:
<xsl:choose>
<xsl:when test="$CreatedDate > $IDAppendedDate">
<h2>mooooooooooooo</h2>
</xsl:when>
<xsl:otherwise>
<h2>dooooooooooooo</h2>
</xsl:otherwise>
</xsl:choose>
Also, you can use multiple <xsl:when>
tags to express If .. Else If
or Switch
patterns as illustrated below:
<xsl:choose>
<xsl:when test="$CreatedDate > $IDAppendedDate">
<h2>mooooooooooooo</h2>
</xsl:when>
<xsl:when test="$CreatedDate = $IDAppendedDate">
<h2>booooooooooooo</h2>
</xsl:when>
<xsl:otherwise>
<h2>dooooooooooooo</h2>
</xsl:otherwise>
</xsl:choose>
The previous example would be equivalent to the pseudocode below:
if ($CreatedDate > $IDAppendedDate)
{
output: <h2>mooooooooooooo</h2>
}
else if ($CreatedDate = $IDAppendedDate)
{
output: <h2>booooooooooooo</h2>
}
else
{
output: <h2>dooooooooooooo</h2>
}
On your aspx page define the HTML Button element with the usual suspects: runat, class, title, etc.
If this element is part of a data bound control (i.e.: grid view, etc.) you may want to use CommandName and possibly CommandArgument as attributes. Add your button's content and closing tag.
<button id="cmdAction"
runat="server" onserverclick="cmdAction_Click()"
class="Button Styles"
title="Does something on the server"
<!-- for databound controls -->
CommandName="cmdname">
CommandArgument="args..."
>
<!-- content -->
<span class="ui-icon ..."></span>
<span class="push">Click Me</span>
</button>
On the code behind page the element would call the handler that would be defined as the element's ID_Click event function.
protected void cmdAction_Click(object sender, EventArgs e)
{
: do something.
}
There are other solutions as in using custom controls, etc. Also note that I am using this live on projects in VS2K8.
Hoping this helps. Enjoy!
You have to replace string line
QString line = in.readLine();
into while:
QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(0, "error", file.errorString());
}
QTextStream in(&file);
while(!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split(",");
model->appendRow(fields);
}
file.close();
dev.copy(png,'path/pngFile.png')
plot(YData ~ XData, data = mydata)
dev.off()
As the recent developed Web Applications are using JavaScript, jQuery, AngularJS, ReactJS etc there is a possibility that to retrieve an attribute of an element through Selenium you have to induce WebDriverWait to synchronize the WebDriver instance with the lagging Web Client i.e. the Web Browser before trying to retrieve any of the attributes.
Some examples:
Python:
To retrieve any attribute form a visible element (e.g. <h1>
tag) you need to use the expected_conditions as visibility_of_element_located(locator)
as follows:
attribute_value = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, "org"))).get_attribute("attribute_name")
To retrieve any attribute form an interactive element (e.g. <input>
tag) you need to use the expected_conditions as element_to_be_clickable(locator)
as follows:
attribute_value = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "org"))).get_attribute("attribute_name")
Below is a list of some attributes often used in HTML
Note: A complete list of all attributes for each HTML element, is listed in: HTML Attribute Reference
If you want SQL Server to try and figure it out, just use CAST CAST('whatever' AS datetime) However that is a bad idea in general. There are issues with international dates that would come up. So as you've found, to avoid those issues, you want to use the ODBC canonical format of the date. That is format number 120, 20 is the format for just two digit years. I don't think SQL Server has a built-in function that allows you to provide a user given format. You can write your own and might even find one if you search online.
Suppose gamma1 and gamma2 are two such columns for which df.isnull().any() gives True value , the following code can be used to print the rows.
bool1 = pd.isnull(df['gamma1'])
bool2 = pd.isnull(df['gamma2'])
df[bool1]
df[bool2]
Try \r\n
where \r
is carriage return. Also ensure that your output do not have new line, because debugger can show you special characters in form of \n
, \r
, \t
etc.
Webkit browsers set the height and width property after the image is loaded. Instead of using timeouts, I'd recommend using an image's onload event. Here's a quick example:
var img = $("img")[0]; // Get my img elem
var pic_real_width, pic_real_height;
$("<img/>") // Make in memory copy of image to avoid css issues
.attr("src", $(img).attr("src"))
.load(function() {
pic_real_width = this.width; // Note: $(this).width() will not
pic_real_height = this.height; // work for in memory images.
});
To avoid any of the effects CSS might have on the image's dimensions, the code above makes an in memory copy of the image. This is a very clever solution suggested by FDisk.
You can also use the naturalHeight
and naturalWidth
HTML5 attributes.
The method based on list comprehension and groupby
, which stores all the split dataframes in a list variable and can be accessed using the index.
Example:
ans = [pd.DataFrame(y) for x, y in DF.groupby('column_name', as_index=False)]***
ans[0]
ans[0].column_name
The csv file might contain very huge fields, therefore increase the field_size_limit
:
import sys
import csv
csv.field_size_limit(sys.maxsize)
sys.maxsize
works for Python 2.x and 3.x. sys.maxint
would only work with Python 2.x (SO: what-is-sys-maxint-in-python-3)
As Geoff pointed out, the code above might result in the following error: OverflowError: Python int too large to convert to C long
.
To circumvent this, you could use the following quick and dirty code (which should work on every system with Python 2 and Python 3):
import sys
import csv
maxInt = sys.maxsize
while True:
# decrease the maxInt value by factor 10
# as long as the OverflowError occurs.
try:
csv.field_size_limit(maxInt)
break
except OverflowError:
maxInt = int(maxInt/10)
You can either use JavaScript or CSS3.
JavaScript solution: Use an absolute positioned <img>
tag and resize it on the page load and whenever the page resizes. Be careful of possible bugs when trying to get the page/window size.
CSS3 solution: Use the CSS3 background-size property. You might use either 100% 100%
or contain
or cover
, depending on how you want the image to resize. Of course, this only works on modern browsers.
If none of the solutions work for you, the handling the post-autoload-dump event returned with error code 1 error can also be caused by using Composer 2
instead of Composer 1
. That can happen when you run the install command manually in something like a Dockerfile, and it installs newest. Just modify your command to install the last 1.x.x stable version with the --1
option:
curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer --1
Or, specify a certain version with --version=x.x.x
:
curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer --version=1.10.17
It might be good to also delete your vendor
directory and composer.lock
file so that nothing stale interferes with the version downgrade, before calling composer install
as usual.
Here comes Linq:
var listItem = list.Single(i => i.Title == title);
It throws an exception if there's no item matching the predicate. Alternatively, there's SingleOrDefault
.
If you want a collection of items matching the title, there's:
var listItems = list.Where(i => i.Title == title);
Another way to do this would to first get row indices, append extra copies of the df, and then order by the indices:
df$index = 1:nrow(df)
df = rbind(df,df)
df = df[order(df$index),][,-ncol(df)]
Although the other solutions may be shorter, this method may be more advantageous in certain situations.
"Not ASCII (neither's ?/?)" needs qualification.
While these characters are not defined in the American Standard Code for Information Interchange as glyphs, their codes WERE commonly used to give a graphical presentation for ASCII codes 24 and 25 (hex 18 and 19, CANcel and EM:End of Medium). Code page 437 (called Extended ASCII by IBM, includes the numeric codes 128 to 255) defined the use of these glyphs as ASCII codes and the ubiquity of these conventions permeated the industry as seen by their deployment as standards by leading companies such as HP, particularly for printers, and IBM, particularly for microcomputers starting with the original PC.
Just as the use of the ASCII codes for CAN and EM was relatively obsolete at the time, justifying their use as glyphs, so has the passage of time made the use of the codes as glyphs obsolete by the current use of UNICODE conventions.
It should be emphasized that the extensions to ASCII made by IBM in Extended ASCII, included not only a larger numeric set for numeric codes 128 to 255, but also extended the use of some numeric control codes, in the ASCII range 0 to 32, from just media transmission control protocols to include glyphs. It is often assumed, incorrectly, that the first 0 to 128 were not "extended" and that IBM was using the glyphs of conventional ASCII for this range. This error is also perpetrated in one of the previous references. This error became so pervasive that it colloquially redefined ASCII subliminally.
You will have to download file from here https://commons.apache.org/proper/commons-io/download_io.cgi and select https://prnt.sc/tk5ewt
Now, Next add this downloaded files into your project:
Right click to your project ->Build path->Configure BuidPath -> https://prnt.sc/tk5d93
If you have just a pair of brackets ( []
) in your string, you can use indexOf()
:
String str = "ABC[ This is the text to be extracted ]";
String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));
For those getting blank/black screens this code worked for me.
let vc = self.storyboard?.instantiateViewController(withIdentifier: myVCID) as! myVCName
self.present(vc, animated: true, completion: nil)
To set the "Identifier" to your VC just go to identity inspector for the VC in the storyboard. Set the 'Storyboard ID' to what ever you want to identifier to be. Look at the image below for reference.
I experienced this today. The value in Config was the updated one but the application would return the older value, stop and starting the solution did nothing.
So I cleared the .Net Temp folder.
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files
It shouldn't create bugs but to be safe close your solution down first. Clear the Temporary ASP.NET Files then load up your solution.
My issue was sorted.
Other type of format :
$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-length: 0';
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);
Technically C# Extension have no equivalent in Java. But if you do want to implement such functions for a cleaner code and maintainability, you have to use Manifold framework.
package extensions.java.lang.String;
import manifold.ext.api.*;
@Extension
public class MyStringExtension {
public static void print(@This String thiz) {
System.out.println(thiz);
}
@Extension
public static String lineSeparator() {
return System.lineSeparator();
}
}
The Easiest way to do it is to have good site structure and write it as a constant.
DEFINE("BACK_ROOT","/var/www/");
in case it helps someone, on amilinux, with php5.6 and php-fpm installed, it's:
sudo /etc/init.d/php-fpm-5.6 status
I had same problem. I just solved it with declaring adapter
public before onCreate
of class.
PostAdapter postAdapter;
after that
postAdapter = new PostAdapter(getActivity(), posts);
recList.setAdapter(postAdapter);
at last I have called:
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// Display the size of your ArrayList
Log.i("TAG", "Size : " + posts.size());
progressBar.setVisibility(View.GONE);
postAdapter.notifyDataSetChanged();
}
May this will helps you.
Yes, you can.
From cplusplus.com:
Because these functions are operator overloading functions, the usual way in which they are called is:
strm >> variable;
Where
strm
is the identifier of a istream object andvariable
is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:strm >> variable1 >> variable2 >> variable3; //...
which is the same as performing successive extractions from the same object
strm
.
Just replace strm
with cin
.
To find the number of days between two dates, you use:
DATEDIFF ( d, startdate , enddate )
Working with a dictionary ->level2 above comes from a dictionary in my case (just in case anybody will find it useful) Trying the first example I stumbled over this error: "This document already has a 'DocumentElement' node." I was inspired by the answer here
and edited my code: (xmlDoc.DocumentElement.AppendChild(body))
//a dictionary:
Dictionary<string, string> Level2Data
{
{"level2", "text"},
{"level2", "other text"},
{"same_level2", "more text"}
}
//xml Decalration:
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDoc.DocumentElement;
xmlDoc.InsertBefore(xmlDeclaration, root);
// add body
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.AppendChild(body);
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.DocumentElement.AppendChild(body); //without DocumentElement ->ERR
foreach (KeyValuePair<string, string> entry in Level2Data)
{
//write to xml: - it works version 1.
XmlNode keyNode = xmlDoc.CreateElement(entry.Key); //open TAB
keyNode.InnerText = entry.Value;
body.AppendChild(keyNode); //close TAB
//Write to xmml verdion 2: (uncomment the next 4 lines and comment the above 3 - version 1
//XmlElement key = xmlDoc.CreateElement(string.Empty, entry.Key, string.Empty);
//XmlText value = xmlDoc.CreateTextNode(entry.Value);
//key.AppendChild(value);
//body.AppendChild(key);
}
Both versions (1 and 2 inside foreach loop) give the output:
<?xml version="1.0" encoding="UTF-8"?>
<body>
<level1>
<level2>text</level2>
<level2>ther text</level2>
<same_level2>more text</same_level2>
</level1>
</body>
(Note: third line "same level2" in dictionary can be also level2 as the others but I wanted to ilustrate the advantage of the dictionary - in my case I needed level2 with different names.
You can also get it by
string(//bookstore/book[1]/title/@lang)
string(//bookstore/book[2]/title/@lang)
although if you are using XMLDOM with JavaScript you can code something like
var n1 = uXmlDoc.selectSingleNode("//bookstore/book[1]/title/@lang");
and n1.text
will give you the value "eng"
If you are having trouble tracing the definitions, you can use the preprocessed output of the compiler which will tell you all you need to know. E.g.
$ cat test.c
#include <stdio.h>
$ cc -E test.c | grep off_t
typedef long int __off_t;
typedef __off64_t __loff_t;
__off_t __pos;
__off_t _old_offset;
typedef __off_t off_t;
extern int fseeko (FILE *__stream, __off_t __off, int __whence);
extern __off_t ftello (FILE *__stream) ;
If you look at the complete output you can even see the exact header file location and line number where it was defined:
# 132 "/usr/include/bits/types.h" 2 3 4
typedef unsigned long int __dev_t;
typedef unsigned int __uid_t;
typedef unsigned int __gid_t;
typedef unsigned long int __ino_t;
typedef unsigned long int __ino64_t;
typedef unsigned int __mode_t;
typedef unsigned long int __nlink_t;
typedef long int __off_t;
typedef long int __off64_t;
...
# 91 "/usr/include/stdio.h" 3 4
typedef __off_t off_t;
Both NSQueueOperations and GCD allow executing heavy computation task in the background on separate threads by freeing the UI Application Main Tread.
Well, based previous post we see NSOperations has addDependency so that you can queue your operation one after another sequentially.
But I also read about GCD serial Queues you can create run your operations in the queue using dispatch_queue_create. This will allow running a set of operations one after another in a sequential manner.
NSQueueOperation Advantages over GCD:
It allows to add dependency and allows you to remove dependency so for one transaction you can run sequential using dependency and for other transaction run concurrently while GCD doesn't allow to run this way.
It is easy to cancel an operation if it is in the queue it can be stopped if it is running.
You can define the maximum number of concurrent operations.
You can suspend operation which they are in Queue
You can find how many pending operations are there in queue.
d*
means that it should match zero or more "d
" characters. So any string is a valid match. Try d+
instead!
In order to have support for wildcard patterns I would replace the wildcards with the RegEx equivalents. Like *
becomes .*
and ?
becomes .?
. Then your expression above becomes d.*
When you float sub-left
and sub-right
they no longer take up any space within sub-title
. You need to add another div with style = "clear: both"
beneath them to expand the containing div or they appear below it.
HTML:
<div id="sub-title">
<div id="sub-left">
sub-left
</div>
<div id="sub-right">
sub-right
</div>
<div class="clear-both"></div>
</div>
CSS:
#sub-left {
float: left;
}
#sub-right {
float: right;
}
.clear-both {
clear: both;
}
Do it like this. This approach lets you search a file of any size (big size won't crash the script) and will return ALL lines that match the string you want.
<?php
$searchthis = "mystring";
$matches = array();
$handle = @fopen("path/to/inputfile.txt", "r");
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
if(strpos($buffer, $searchthis) !== FALSE)
$matches[] = $buffer;
}
fclose($handle);
}
//show results:
print_r($matches);
?>
Note the way strpos
is used with !==
operator.
Classes
Structs
Interfaces
Events
Properties
Delegates
Expressions
Statements
Attributes
Literals
Dispose in foreach
foreach over string specialization
C# 2 - Visual Studio 2005
Generics
Partial types
Anonymous methods
Iterators
Nullable types
Getter/setter separate accessibility
Method group conversions (delegates)
Static classes
Delegate inference
Implicitly typed local variables
Object and collection initializers
Auto-Implemented properties
Anonymous types
Extension methods
Query expressions
Lambda expression
Expression trees
Partial methods
Dynamic binding
Named and optional arguments
Co- and Contra-variance for generic delegates and interfaces
Embedded interop types ("NoPIA")
Asynchronous methods
Caller info attributes
Draft Specification online
Compiler-as-a-service (Roslyn)
Import of static type members into namespace
Exception filters
Await in catch/finally blocks
Auto property initializers
Default values for getter-only properties
Expression-bodied members
Null propagator (null-conditional operator, succinct null checking)
String interpolation
nameof operator
Dictionary initializer
Out variables
Pattern matching
Tuples
Deconstruction
Discards
Local Functions
Binary Literals
Digit Separators
Ref returns and locals
Generalized async return types
More expression-bodied members
Throw expressions
Async main
Default expressions
Reference assemblies
Inferred tuple element names
Pattern-matching with generics
Span and ref-like types
In parameters and readonly references
Ref conditional
Non-trailing named arguments
Private protected accessibility
Digit separator after base specifier
System.Enum, System.Delegate and unmanaged constraints.
Ref local re-assignment: Ref locals and ref parameters can now be reassigned with the ref assignment operator (= ref).
Stackalloc initializers: Stack-allocated arrays can now be initialized, e.g. Span<int> x = stackalloc[] { 1, 2, 3 };.
Indexing movable fixed buffers: Fixed buffers can be indexed into without first being pinned.
Custom fixed statement: Types that implement a suitable GetPinnableReference can be used in a fixed statement.
Improved overload candidates: Some overload resolution candidates can be ruled out early, thus reducing ambiguities.
Expression variables in initializers and queries: Expression variables like out var and pattern variables are allowed in field initializers, constructor initializers and LINQ queries.
Tuple comparison: Tuples can now be compared with == and !=.
Attributes on backing fields: Allows [field: …] attributes on an auto-implemented property to target its backing field.
Nullable reference types: express nullability intent on reference types with ?, notnull constraint and annotations attributes in APIs, the compiler will use those to try and detect possible null values being dereferenced or passed to unsuitable APIs.
Default interface members: interfaces can now have members with default implementations, as well as static/private/protected/internal members except for state (ie. no fields).
Recursive patterns: positional and property patterns allow testing deeper into an object, and switch expressions allow for testing multiple patterns and producing corresponding results in a compact fashion.
Async streams: await foreach and await using allow for asynchronous enumeration and disposal of IAsyncEnumerable<T> collections and IAsyncDisposable resources, and async-iterator methods allow convenient implementation of such asynchronous streams.
Enhanced using: a using declaration is added with an implicit scope and using statements and declarations allow disposal of ref structs using a pattern.
Ranges and indexes: the i..j syntax allows constructing System.Range instances, the ^k syntax allows constructing System.Index instances, and those can be used to index/slice collections.
Null-coalescing assignment: ??= allows conditionally assigning when the value is null.
Static local functions: local functions modified with static cannot capture this or local variables, and local function parameters now shadow locals in parent scopes.
Unmanaged generic structs: generic struct types that only have unmanaged fields are now considered unmanaged (ie. they satisfy the unmanaged constraint).
Readonly members: individual members can now be marked as readonly to indicate and enforce that they do not modify instance state.
Stackalloc in nested contexts: stackalloc expressions are now allowed in more expression contexts.
Alternative interpolated verbatim strings: @$"..." strings are recognized as interpolated verbatim strings just like $@"...".
Obsolete on property accessors: property accessors can now be individually marked as obsolete.
Permit t is null on unconstrained type parameter
[source] : https://github.com/dotnet/csharplang/blob/master/Language-Version-History.md
app.component.html
<div>
<h5 style="color:#ffffff;">{{myDate | date:'fullDate'}}</h5>
</div>
app.component.ts
export class AppComponent implements OnInit {
myDate = Date.now(); //date
If you want to send as Cc using MimeMessageHelper
List<String> emails= new ArrayList();
email.add("email1");
email.add("email2");
for (String string : emails) {
message.addCc(string);
}
Same you can use to add multiple recipient.
The &
means that the function accepts the address (or reference) to a variable, instead of the value of the variable.
For example, note the difference between this:
void af(int& g)
{
g++;
cout<<g;
}
int main()
{
int g = 123;
cout << g;
af(g);
cout << g;
return 0;
}
And this (without the &
):
void af(int g)
{
g++;
cout<<g;
}
int main()
{
int g = 123;
cout << g;
af(g);
cout << g;
return 0;
}
The answers and the documentation provided by MSDN is the best, but I would like to add one typical case that I use a lot which requires the use of #pragma comment
to send a command to the linker at link time for example
#pragma comment(linker,"/ENTRY:Entry")
tell the linker to change the entry point form WinMain()
to Entry()
after that the CRTStartup
going to transfer controll to Entry()
It is confusing in the beginning. But it helps in the situations below :
class SomeAction implements Action {
}
// Later in the code.
Class<Action> actionClass = Class.forName("SomeAction");
Action action = actionClass.newInstance();
// Notice you get an Action instance, there was no need to cast.
I know this is a bit old, but instead of looping through the array with a for loop, it would be much easier to use the method <array>.indexOf(<element>[, fromIndex])
It loops through an array, finding and returning the first index of a value. If the value is not contained in the array, it returns -1.
<array>
is the array to look through, <element>
is the value you are looking for, and [fromIndex]
is the index to start from (defaults to 0).
I hope this helps reduce the size of your code!