You need to pass a function to setTimeout
$(window).load(function () {
window.setTimeout(function () {
window.location.href = "https://www.google.co.in";
}, 5000)
});
Using reshape2
and dplyr
. Your data:
df <- read.table(text=
"tea coke beer water gender
14.55 26.50793651 22.53968254 40 1
24.92997199 24.50980392 26.05042017 24.50980393 2
23.03732304 30.63063063 25.41827542 20.91377091 1
225.51781276 24.6064623 24.85501243 50.80645161 1
24.53662842 26.03706973 25.24271845 24.18358341 2", header=TRUE)
Getting data into correct form:
library(reshape2)
library(dplyr)
df.melt <- melt(df, id="gender")
bar <- group_by(df.melt, variable, gender)%.%summarise(mean=mean(value))
Plotting:
library(ggplot2)
ggplot(bar, aes(x=variable, y=mean, fill=factor(gender)))+
geom_bar(position="dodge", stat="identity")
Both are similar in functionality because they both return type information, however I personally prefer instanceof
because it's comparing actual types rather than strings. Type comparison is less prone to human error, and it's technically faster since it's comparing pointers in memory rather than doing whole string comparisons.
You want a semantic linebreak?
Then consider using <br>
. W3Schools may suggest you that BR
is just for writing poems (mine is coming soon) but you can change the style so it behaves as a 100% width block element that will push your content to the next line. If 'br' suggests a break then it seems more appropriate to me than using hr
or a 100% div
and makes the html more readable.
Insert the <br>
where you need linebreaks and style it like this.
// Use `>` to avoid styling `<br>` inside your boxes
.container > br
{
width: 100%;
content: '';
}
You can disable <br>
with media queries, by setting display:
to block
or none
as appropriate (I've included an example of this but left it commented out).
You can use order:
to set the order if needed too.
And you can put as many as you want, with different classes or names :-)
.container {_x000D_
background: tomato;_x000D_
display: flex;_x000D_
flex-flow: row wrap;_x000D_
justify-content: space-between;_x000D_
}_x000D_
.item {_x000D_
width: 100px;_x000D_
background: gold;_x000D_
height: 100px;_x000D_
border: 1px solid black;_x000D_
font-size: 30px;_x000D_
line-height: 100px;_x000D_
text-align: center;_x000D_
margin: 10px_x000D_
}_x000D_
_x000D_
.container > br_x000D_
{_x000D_
width: 100%;_x000D_
content: '';_x000D_
}_x000D_
_x000D_
// .linebreak1 _x000D_
// { _x000D_
// display: none;_x000D_
// }_x000D_
_x000D_
// @media (min-width: 768px) _x000D_
// {_x000D_
// .linebreak1_x000D_
// {_x000D_
// display: block;_x000D_
// }_x000D_
// }
_x000D_
<div class="container">_x000D_
<div class="item">1</div>_x000D_
<div class="item">2</div>_x000D_
<br class="linebreak1"/>_x000D_
<div class="item">3</div>_x000D_
<div class="item">4</div>_x000D_
<div class="item">5</div>_x000D_
<div class="item">6</div>_x000D_
<div class="item">7</div>_x000D_
<div class="item">8</div>_x000D_
<div class="item">9</div>_x000D_
<div class="item">10</div>_x000D_
</div>
_x000D_
No need to limit yourself to what W3Schools says:
According to the very popular WWDC 2015 talk Protocol Oriented Programming in Swift (video, transcript), Swift provides a number of features that make structs better than classes in many circumstances.
Structs are preferable if they are relatively small and copiable because copying is way safer than having multiple references to the same instance as happens with classes. This is especially important when passing around a variable to many classes and/or in a multithreaded environment. If you can always send a copy of your variable to other places, you never have to worry about that other place changing the value of your variable underneath you.
With Structs, there is much less need to worry about memory leaks or multiple threads racing to access/modify a single instance of a variable. (For the more technically minded, the exception to that is when capturing a struct inside a closure because then it is actually capturing a reference to the instance unless you explicitly mark it to be copied).
Classes can also become bloated because a class can only inherit from a single superclass. That encourages us to create huge superclasses that encompass many different abilities that are only loosely related. Using protocols, especially with protocol extensions where you can provide implementations to protocols, allows you to eliminate the need for classes to achieve this sort of behavior.
The talk lays out these scenarios where classes are preferred:
- Copying or comparing instances doesn't make sense (e.g., Window)
- Instance lifetime is tied to external effects (e.g., TemporaryFile)
- Instances are just "sinks"--write-only conduits to external state (e.g.CGContext)
It implies that structs should be the default and classes should be a fallback.
On the other hand, The Swift Programming Language documentation is somewhat contradictory:
Structure instances are always passed by value, and class instances are always passed by reference. This means that they are suited to different kinds of tasks. As you consider the data constructs and functionality that you need for a project, decide whether each data construct should be defined as a class or as a structure.
As a general guideline, consider creating a structure when one or more of these conditions apply:
- The structure’s primary purpose is to encapsulate a few relatively simple data values.
- It is reasonable to expect that the encapsulated values will be copied rather than referenced when you assign or pass around an instance of that structure.
- Any properties stored by the structure are themselves value types, which would also be expected to be copied rather than referenced.
- The structure does not need to inherit properties or behavior from another existing type.
Examples of good candidates for structures include:
- The size of a geometric shape, perhaps encapsulating a width property and a height property, both of type Double.
- A way to refer to ranges within a series, perhaps encapsulating a start property and a length property, both of type Int.
- A point in a 3D coordinate system, perhaps encapsulating x, y and z properties, each of type Double.
In all other cases, define a class, and create instances of that class to be managed and passed by reference. In practice, this means that most custom data constructs should be classes, not structures.
Here it is claiming that we should default to using classes and use structures only in specific circumstances. Ultimately, you need to understand the real world implication of value types vs. reference types and then you can make an informed decision about when to use structs or classes. Also, keep in mind that these concepts are always evolving and The Swift Programming Language documentation was written before the Protocol Oriented Programming talk was given.
Here's one way:
Stream myStream = null;
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = theDialog.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
Modified from here:MSDN OpenFileDialog.OpenFile
EDIT Here's another way more suited to your needs:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
string filename = theDialog.FileName;
string[] filelines = File.ReadAllLines(filename);
List<Employee> employeeList = new List<Employee>();
int linesPerEmployee = 4;
int currEmployeeLine = 0;
//parse line by line into instance of employee class
Employee employee = new Employee();
for (int a = 0; a < filelines.Length; a++)
{
//check if to move to next employee
if (a != 0 && a % linesPerEmployee == 0)
{
employeeList.Add(employee);
employee = new Employee();
currEmployeeLine = 1;
}
else
{
currEmployeeLine++;
}
switch (currEmployeeLine)
{
case 1:
employee.EmployeeNum = Convert.ToInt32(filelines[a].Trim());
break;
case 2:
employee.Name = filelines[a].Trim();
break;
case 3:
employee.Address = filelines[a].Trim();
break;
case 4:
string[] splitLines = filelines[a].Split(' ');
employee.Wage = Convert.ToDouble(splitLines[0].Trim());
employee.Hours = Convert.ToDouble(splitLines[1].Trim());
break;
}
}
//Test to see if it works
foreach (Employee emp in employeeList)
{
MessageBox.Show(emp.EmployeeNum + Environment.NewLine +
emp.Name + Environment.NewLine +
emp.Address + Environment.NewLine +
emp.Wage + Environment.NewLine +
emp.Hours + Environment.NewLine);
}
}
}
You can do it programmatically:
ddlColor.DataSource = from p in db.ProductTypes
where p.ProductID == pID
orderby p.Color
select new { p.Color };
ddlColor.DataTextField = "Color";
ddlColor.DataBind();
ddlColor.Items.Insert(0, new ListItem("Select", "NA"));
Or add it in markup as:
<asp:DropDownList .. AppendDataBoundItems="true">
<Items>
<asp:ListItem Text="Select" Value="" />
</Items>
</asp:DropDownList>
It checks to see whether the specific object is contained in the list.
You might be better using the Find method on the list.
Here's an example
List<CartProduct> lst = new List<CartProduct>();
CartProduct objBeer;
objBeer = lst.Find(x => (x.Name == "Beer"));
Hope that helps
You should also look at LinQ - overkill for this perhaps, but a useful tool nonetheless...
This my batch file
C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe C:\Projects\testPublish\testPublish.csproj /p:DeployOnBuild=true /property:Configuration=Release
if exist "C:\PublishDirectory" rd /q /s "C:\PublishDirectory"
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_compiler.exe -v / -p C:\Projects\testPublish\obj\Release\Package\PackageTmp -c C:\PublishDirectory
cd C:\PublishDirectory\bin
del *.xml
del *.pdb
Try this one:
class test {
public function newTest(){
$this->bigTest();
$this->smallTest();
}
private function bigTest(){
//Big Test Here
}
private function smallTest(){
//Small Test Here
}
public function scoreTest(){
//Scoring code here;
}
}
$testObject = new test();
$testObject->newTest();
$testObject->scoreTest();
This one shows SQL that is currently "ACTIVE":-
select S.USERNAME, s.sid, s.osuser, t.sql_id, sql_text
from v$sqltext_with_newlines t,V$SESSION s
where t.address =s.sql_address
and t.hash_value = s.sql_hash_value
and s.status = 'ACTIVE'
and s.username <> 'SYSTEM'
order by s.sid,t.piece
/
This shows locks. Sometimes things are going slow, but it's because it is blocked waiting for a lock:
select
object_name,
object_type,
session_id,
type, -- Type or system/user lock
lmode, -- lock mode in which session holds lock
request,
block,
ctime -- Time since current mode was granted
from
v$locked_object, all_objects, v$lock
where
v$locked_object.object_id = all_objects.object_id AND
v$lock.id1 = all_objects.object_id AND
v$lock.sid = v$locked_object.session_id
order by
session_id, ctime desc, object_name
/
This is a good one for finding long operations (e.g. full table scans). If it is because of lots of short operations, nothing will show up.
COLUMN percent FORMAT 999.99
SELECT sid, to_char(start_time,'hh24:mi:ss') stime,
message,( sofar/totalwork)* 100 percent
FROM v$session_longops
WHERE sofar/totalwork < 1
/
Try this:
printf '\n%s\n' 'I want this on a new line!'
That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.
quantity=38; price=142.15; description='advanced widget'
$ printf '%8d%10.2f %s\n' "$quantity" "$price" "$description"
38 142.15 advanced widget
Not really - but I don't see how git fetch
would hurt as it won't change any of your local branches.
You can use:
((count = FIRSTV - SECONDV))
to avoid invoking a separate process, as per the following transcript:
pax:~$ FIRSTV=7
pax:~$ SECONDV=2
pax:~$ ((count = FIRSTV - SECONDV))
pax:~$ echo $count
5
function Palindrome(str) {
let forwardStr = str.toLowerCase().replace(/[\W_]/g, '');
let reversedStr = forwardStr.split('').reverse().join();
return forwardStr === reversedStr;
}
console.log(Palindrome('madam'));
For large numbers of events this might help:
var element = document.getElementById("myId");
var myEvents = "click touchstart touchend".split(" ");
var handler = function (e) {
do something
};
for (var i=0, len = myEvents.length; i < len; i++) {
element.addEventListener(myEvents[i], handler, false);
}
Update 06/2017:
Now that new language features are more widely available you could simplify adding a limited list of events that share one listener.
const element = document.querySelector("#myId");
function handleEvent(e) {
// do something
}
// I prefer string.split because it makes editing the event list slightly easier
"click touchstart touchend touchmove".split(" ")
.map(name => element.addEventListener(name, handleEvent, false));
If you want to handle lots of events and have different requirements per listener you can also pass an object which most people tend to forget.
const el = document.querySelector("#myId");
const eventHandler = {
// called for each event on this element
handleEvent(evt) {
switch (evt.type) {
case "click":
case "touchstart":
// click and touchstart share click handler
this.handleClick(e);
break;
case "touchend":
this.handleTouchend(e);
break;
default:
this.handleDefault(e);
}
},
handleClick(e) {
// do something
},
handleTouchend(e) {
// do something different
},
handleDefault(e) {
console.log("unhandled event: %s", e.type);
}
}
el.addEventListener(eventHandler);
Update 05/2019:
const el = document.querySelector("#myId");
const eventHandler = {
handlers: {
click(e) {
// do something
},
touchend(e) {
// do something different
},
default(e) {
console.log("unhandled event: %s", e.type);
}
},
// called for each event on this element
handleEvent(evt) {
switch (evt.type) {
case "click":
case "touchstart":
// click and touchstart share click handler
this.handlers.click(e);
break;
case "touchend":
this.handlers.touchend(e);
break;
default:
this.handlers.default(e);
}
}
}
Object.keys(eventHandler.handlers)
.map(eventName => el.addEventListener(eventName, eventHandler))
typedef enum state {DEAD,ALIVE} State;
| | | | | |^ terminating semicolon, required!
| | | type specifier | | |
| | | | ^^^^^ declarator (simple name)
| | | |
| | ^^^^^^^^^^^^^^^^^^^^^^^
| |
^^^^^^^-- storage class specifier (in this case typedef)
The typedef
keyword is a pseudo-storage-class specifier. Syntactically, it is used in the same place where a storage class specifier like extern
or static
is used. It doesn't have anything to do with storage. It means that the declaration doesn't introduce the existence of named objects, but rather, it introduces names which are type aliases.
After the above declaration, the State
identifier becomes an alias for the type enum state {DEAD,ALIVE}
. The declaration also provides that type itself. However that isn't typedef
doing it. Any declaration in which enum state {DEAD,ALIVE}
appears as a type specifier introduces that type into the scope:
enum state {DEAD, ALIVE} stateVariable;
If enum state
has previously been introduced the typedef
has to be written like this:
typedef enum state State;
otherwise the enum
is being redefined, which is an error.
Like other declarations (except function parameter declarations), the typedef
declaration can have multiple declarators, separated by a comma. Moreover, they can be derived declarators, not only simple names:
typedef unsigned long ulong, *ulongptr;
| | | | | 1 | | 2 |
| | | | | | ^^^^^^^^^--- "pointer to" declarator
| | | | ^^^^^^------------- simple declarator
| | ^^^^^^^^^^^^^-------------------- specifier-qualifier list
^^^^^^^---------------------------------- storage class specifier
This typedef
introduces two type names ulong
and ulongptr
, based on the unsigned long
type given in the specifier-qualifier list. ulong
is just a straight alias for that type. ulongptr
is declared as a pointer to unsigned long
, thanks to the *
syntax, which in this role is a kind of type construction operator which deliberately mimics the unary *
for pointer dereferencing used in expressions. In other words ulongptr
is an alias for the "pointer to unsigned long
" type.
Alias means that ulongptr
is not a distinct type from unsigned long *
. This is valid code, requiring no diagnostic:
unsigned long *p = 0;
ulongptr q = p;
The variables q
and p
have exactly the same type.
The aliasing of typedef
isn't textual. For instance if user_id_t
is a typedef
name for the type int
, we may not simply do this:
unsigned user_id_t uid; // error! programmer hoped for "unsigned int uid".
This is an invalid type specifier list, combining unsigned
with a typedef name. The above can be done using the C preprocessor:
#define user_id_t int
unsigned user_id_t uid;
whereby user_id_t
is macro-expanded to the token int
prior to syntax analysis and translation. While this may seem like an advantage, it is a false one; avoid this in new programs.
Among the disadvantages that it doesn't work well for derived types:
#define silly_macro int *
silly_macro not, what, you, think;
This declaration doesn't declare what
, you
and think
as being of type "pointer to int" because the macro-expansion is:
int * not, what, you, think;
The type specifier is int
, and the declarators are *not
, what
, you
and think
. So not
has the expected pointer type, but the remaining identifiers do not.
And that's probably 99% of everything about typedef
and type aliasing in C.
I've always just used git status
.
can add awk
at the end to get just the file names
git status -s | grep ^U | awk '{print $2}'
<video style="min-width: 100%; min-height: 100%; " id="vid" width="auto" height="auto" controls autoplay="true" loop="loop" preload="auto" muted="muted">
<source src="video/sample.mp4" type="video/mp4">
<source src="video/sample.ogg" type="video/ogg">
</video>
<script>
$(document).ready(function(){
document.getElementById('vid').play(); });
</script>
The variable is captured by the inline functions defined in the method. this
in the function will refer to another object. This way, you can make the function hold a reference to the this
in the outer scope.
Your main problem is thinking that the variable you declared outside of the template is the same variable being "set" inside the choose statement. This is not how XSLT works, the variable cannot be reassigned. This is something more like what you want:
<xsl:template match="class">
<xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
<xsl:variable name="subexists">
<xsl:choose>
<xsl:when test="joined-subclass">true</xsl:when>
<xsl:otherwise>false</xsl:otherwise>
</xsl:choose>
</xsl:variable>
subexists: <xsl:value-of select="$subexists" />
</xsl:template>
And if you need the variable to have "global" scope then declare it outside of the template:
<xsl:variable name="subexists">
<xsl:choose>
<xsl:when test="/path/to/node/joined-subclass">true</xsl:when>
<xsl:otherwise>false</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:template match="class">
subexists: <xsl:value-of select="$subexists" />
</xsl:template>
Also made a little script using RDFa (you can also use microdata or other formats) Check it out on google This script also keeps in mind your site structure.
function breadcrumbs($text = 'You are here: ', $sep = ' » ', $home = 'Home') {
//Use RDFa breadcrumb, can also be used for microformats etc.
$bc = '<div xmlns:v="http://rdf.data-vocabulary.org/#" id="crums">'.$text;
//Get the website:
$site = 'http://'.$_SERVER['HTTP_HOST'];
//Get all vars en skip the empty ones
$crumbs = array_filter( explode("/",$_SERVER["REQUEST_URI"]) );
//Create the home breadcrumb
$bc .= '<span typeof="v:Breadcrumb"><a href="'.$site.'" rel="v:url" property="v:title">'.$home.'</a>'.$sep.'</span>';
//Count all not empty breadcrumbs
$nm = count($crumbs);
$i = 1;
//Loop the crumbs
foreach($crumbs as $crumb){
//Make the link look nice
$link = ucfirst( str_replace( array(".php","-","_"), array(""," "," ") ,$crumb) );
//Loose the last seperator
$sep = $i==$nm?'':$sep;
//Add crumbs to the root
$site .= '/'.$crumb;
//Make the next crumb
$bc .= '<span typeof="v:Breadcrumb"><a href="'.$site.'" rel="v:url" property="v:title">'.$link.'</a>'.$sep.'</span>';
$i++;
}
$bc .= '</div>';
//Return the result
return $bc;}
please check the below edited code:-
#!/bin/bash
export num1=(3.17648*e-22)
export num2=1.5
st=$((`echo "$num1 < $num2"| bc`))
if [ $st -eq 1 ]
then
echo -e "$num1 < $num2"
else
echo -e "$num1 >= $num2"
fi
this works well.
If you have a look at the documentation for Html.fromHtml(text)
you'll see it says:
Any
<img>
tags in the HTML will display as a generic replacement image which your program can then go through and replace with real images.
If you don't want to do this replacement yourself you can use the other Html.fromHtml()
method which takes an Html.TagHandler
and an Html.ImageGetter
as arguments as well as the text to parse.
In your case you could parse null
as for the Html.TagHandler
but you'd need to implement your own Html.ImageGetter
as there isn't a default implementation.
However, the problem you're going to have is that the Html.ImageGetter
needs to run synchronously and if you're downloading images from the web you'll probably want to do that asynchronously. If you can add any images you want to display as resources in your application the your ImageGetter
implementation becomes a lot simpler. You could get away with something like:
private class ImageGetter implements Html.ImageGetter {
public Drawable getDrawable(String source) {
int id;
if (source.equals("stack.jpg")) {
id = R.drawable.stack;
}
else if (source.equals("overflow.jpg")) {
id = R.drawable.overflow;
}
else {
return null;
}
Drawable d = getResources().getDrawable(id);
d.setBounds(0,0,d.getIntrinsicWidth(),d.getIntrinsicHeight());
return d;
}
};
You'd probably want to figure out something smarter for mapping source strings to resource IDs though.
To import all the builtin functions you can use:
app.jinja_env.globals.update(__builtins__)
Add .__dict__
after __builtins__
if this doesn't work.
Based on John32323's answer.
If you are using Bash, then use:
command >/dev/null |& grep "something"
http://www.gnu.org/software/bash/manual/bashref.html#Pipelines
function go(type, pageCount) {
if ((type == 2 && pageCount == 0) || (type == 2 && pageCount == '')) {
pageCount = document.getElementById('<%=hfPageCount.ClientID %>').value;
}
}
Cleaner and an all in one solution :D
//This returns the first IP4 address or null
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);
In Android starting from API level 21, items in the layout file get their Z order both from how they are ordered within the file, as described in correct answer, and from their elevation, a higher elevation value means the item gets a higher Z order.
This can sometimes cause problems, especially with buttons that often appear on top of items that according to the order of the XML should be below them in Z order. To fix this just set the android:elevation
of the the items in your layout XML to match the Z order you want to achieve.
I you set an elevation of an element in the layout it will start to cast a shadow. If you don't want this effect you can remove the shadow with code like so:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
myView.setOutlineProvider(null);
}
I haven't found any way to remove the shadow of a elevated view through the layout xml.
You can also do something like this...
<input @input="myHandler('foo', 'bar', ...arguments)">
Evan You himself recommended this technique in one post on Vue forum. In general some events may emit more than one argument. Also as documentation states internal variable $event is meant for passing original DOM event.
You can do it with pythagoras theorem
If you have two points (x1, y1) and (x2, y2) then you can calculate the difference in x and difference in y, lets call them a and b.
var a = x1 - x2;
var b = y1 - y2;
var c = Math.sqrt( a*a + b*b );
// c is the distance
It's a few less clicks in VS2017, and if the local repo is ahead of the Git clone, click Source control from the pop-up project menu:
This brings up the Team Explorer Changes dialog:
Type in a description- here it's "Stack Overflow Example Commit".
Make a choice of the three options on offer, all of which are explained here.
I have seen something similar before when the account the SQL Server is set to run under does not have the required permission.
Tangentially, once it is installed, a common mistake is to change the login credentials from Windows Services, not from SQL Server Configuration Manager. Although they look the same, the SQL Server tool grants access to some registry keys that the Windows tool does not, which can cause a problem on service startup.
You can run Sysinternals RegMon/Sysinternals ProcessMon while the install is running, filtering by sqlsevr.exe and Failure messages to see if the account credentials are a problem.
Hope this helps
Firstly a warning: you should never tinker with DOM that is managed by React, which you are doing by calling ReactDOM.render(<SampleComponent ... />);
With React, you should use SampleComponent directly in the main App.
var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(<App/>, document.body);
The content of your Component is irrelevant, but it should be used like this:
var App = React.createClass({
render: function() {
return (
<div>
<h1>App main component! </h1>
<SampleComponent name="SomeName"/>
</div>
);
}
});
You can then extend your app component to use a list.
var App = React.createClass({
render: function() {
var componentList = [
<SampleComponent name="SomeName1"/>,
<SampleComponent name="SomeName2"/>
]; // Change this to get the list from props or state
return (
<div>
<h1>App main component! </h1>
{componentList}
</div>
);
}
});
I would really recommend that you look at the React documentation then follow the "Get Started" instructions. The time you spend on that will pay off later.
Another way would be creating a mutable integer:
class MutableInt {
int value = 0;
public void inc () { ++value; }
public int get () { return value; }
}
...
Map<String,MutableInt> map = new HashMap<String,MutableInt> ();
MutableInt value = map.get (key);
if (value == null) {
value = new MutableInt ();
map.put (key, value);
} else {
value.inc ();
}
of course this implies creating an additional object but the overhead in comparison to creating an Integer (even with Integer.valueOf) should not be so much.
You are exceeding the length of int datatype. You can use UNSIGNED attribute to support that value.
SIGNED INT can support till 2147483647 and with UNSIGNED INT allows double than this. After this you still want to save data than use CHAR or VARCHAR with length 10
De-structuring Assignment in ES6 would help here.For Ex:
let [arg1, arg2] = new Promise((resolve, reject) => {
resolve([argument1, argument2]);
});
It's like the COM registry done right, with respect to the physical files as well as their interface and location information. In COM, files were everywhere, with centralised metadata. The GAC centralises the bang shoot.
Enter the following into the result cell and then press Ctrl & Shift while pushing ENTER:
=MIN(If(A1:E1>0,A1:E1))
To check where the core dumps are generated, run:
sysctl kernel.core_pattern
or:
cat /proc/sys/kernel/core_pattern
where %e
is the process name and %t
the system time. You can change it in /etc/sysctl.conf
and reloading by sysctl -p
.
If the core files are not generated (test it by: sleep 10 &
and killall -SIGSEGV sleep
), check the limits by: ulimit -a
.
If your core file size is limited, run:
ulimit -c unlimited
to make it unlimited.
Then test again, if the core dumping is successful, you will see “(core dumped)” after the segmentation fault indication as below:
Segmentation fault: 11 (core dumped)
See also: core dumped - but core file is not in current directory?
In Ubuntu the core dumps are handled by Apport and can be located in /var/crash/
. However, it is disabled by default in stable releases.
For more details, please check: Where do I find the core dump in Ubuntu?.
For macOS, see: How to generate core dumps in Mac OS X?
Assuming you're not using html5 routing, try $location.path("route")
.
This will redirect your browser to #/route
which might be what you want.
I found this on exceljet.net and works for me:
=LEFT(B4,FIND(" ",B4)-1)
There is a LARGE collection of attributes you can't set in IE using .setAttribute() which includes every inline event handler.
See here for details:
http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
@SuppressWarnings("serial")
public class RegisterAction {
public String execute() {
RegisterAction mailBean = new RegisterAction();
String subject="Your username & password ";
String message="Hi," + username;
message+="\n \n Your username is " + email;
message+="\n \n Your password is " + password;
message+="\n \n Please login to the web site with your username and password.";
message+="\n \n Thanks";
message+="\n \n \n Regards";
//Getting FROM_MAIL
String[] recipients = new String[1];
recipients[0] = new String();
recipients[0] = customer.getEmail();
try{
mailBean.sendMail(recipients,subject,message);
return "success";
}catch(Exception e){
System.out.println("Error in sending mail:"+e);
}
return "failure";
}
public void sendMail( String recipients[ ], String subject, String message)
throws MessagingException
{
boolean debug = false;
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.auth", true);
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"[email protected]", "5373273437543");// Specify the Username and the PassWord
}
});
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++)
{
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Optional : You can also set your custom headers in the Email if you Want
//msg.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
//send message
Transport.send(msg);
System.out.println("Message Sent Successfully");
}
}
The problem is that .form-control
class renders like a DIV
element which according to the normal-flow-of-the-page
renders on a new line.
One way of fixing issues like this is to use display:inline
property. So, create a custom CSS
class with display:inline
and attach it to your component with a .form-control
class. You have to have a width
for your component as well.
There are other ways of handling this issue (like arranging your form-control
components inside any of the .col
classes), but the easiest way is to just make your .form-control
an inline
element (the way a span
would render)
The first line of your code returns an array and assigns it to the var comment, when what you want is an element assigned to the var comment...
var comment = document.getElementsByClassName("button");
So you are trying to use the method addEventListener() on the array when you need to use the method addEventListener() on the actual element within the array. You need to return an element not an array by accessing the element within the array so the var comment itself is assigned an element not an array.
Change...
var comment = document.getElementsByClassName("button");
to...
var comment = document.getElementsByClassName("button")[0];
Try this
select convert(varchar,getdate(),100)
third parameter is format, range is from 100
to 114
, any one should work for you.
If you need date in dd/mmm/yyyy
use this:
replace(convert(char(11),getdate(),113),' ','-')
Replace getdate()
with your column name. This worked for me.
Check this page http://www.alanwood.net/unicode/geometric_shapes.html, first is "9650 ? 25B2 BLACK UP-POINTING TRIANGLE (present in WGL4)" and 2nd "9660 ? 25BC BLACK DOWN-POINTING TRIANGLE (present in WGL4)".
It's the #
.
See PowerShell - Special Characters And Tokens for special characters.
Not sure at what version this capability arrived, but you can use something like this to return all the properties of multiple child registry entries in an array:
$InstalledSoftware = Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" | ForEach-Object {Get-ItemProperty "Registry::$_"}
Only adding this as Google brought me here for a relevant reason and I eventually came up with the above one-liner for dredging the registry.
Thanks to all. I had been stuck on standard format strings for some time. I also used a custom function in VB.
Mark Up:-
<asp:Label ID="Label3" runat="server" text='<%# Formatlabel(DataBinder.Eval(Container.DataItem, "psWages1D")) %>'/>
Code behind:-
Public Function fLabel(ByVal tval) As String
fLabel = tval.ToString("#,##0.00%;(#,##0.00%);Zero")
End Function
Java doesn't support the Net Framework. Java has its own Framework. Visual Studio used to support at one time J++ and J#, which were meant for Java developers who wanted to develop with the .Net, but since that has become extinct.
Most people when they want to develop java, they just go ahead and start with Netbeans, Eclipse, or something equivalent. They don't go around asking on sites like this if they could develop Java stuff in Visual Studio.
In my honest opinion, Java would not do very well in Visual Studio. Oracle and Microsoft are two separate entities and they need to remain that way. The only mix of Oracle and Microsoft I want to see is Java for Windows and Java development tools for Windows. I do not want to see Java in Visual Studio. It would get too confusing with C# lingering around the corner.
Here is an easy solution without coding a single line.
This change makes iPad app behavior as expected otherwise the new screen is displaying in the center of the screen as a popup.
In Xcode 8 - Swift 3:
button.setTitle( "entertext" , for: .normal )
As you should know by now, purists say it's forbiden to run ordered tests. That might be true for unit tests. MSTest and other Unit Test frameworks are used to run pure unit test but also UI tests, full integration tests, you name it. Maybe we shouldn't call them Unit Test frameworks, or maybe we should and use them according to our needs. That's what most people do anyway.
I'm running VS2015 and I MUST run tests in a given order because I'm running UI tests (Selenium).
Priority - Doesn't do anything at all This attribute is not used by the test system. It is provided to the user for custom purposes.
orderedtest - it works but I don't recommend it because:
Other suggestions in this thread are interesting but you loose the ability to follow the test progress on Test Explorer.
You are left with the solution that purist will advise against, but in fact is the solution that works: sort by declaration order.
The MSTest executor uses an interop that manages to get the declaration order and this trick will work until Microsoft changes the test executor code.
This means the test method that is declared in the first place executes before the one that is declared in second place, etc.
To make your life easier, the declaration order should match the alphabetical order that is is shown in the Test Explorer.
I strongly suggest some old and tested rules:
VERY IMPORTANT
In order to execute the tests by the declaration order, you must use Run All in the Test Explorer.
Say you have 3 test classes (in my case tests for Chrome, Firefox and Edge). If you select a given class and right click Run Selected Tests it usually starts by executing the method declared in the last place.
Again, as I said before, declared order and listed order should match or else you'll in big trouble in no time.
The curl installed by default in Debian supports HTTPS since a great while back. (a long time ago there were two separate packages, one with and one without SSL but that's not the case anymore)
You can send an OPTIONS request with curl like this:
curl -i -X OPTIONS http://example.org/path
You may also use -v
instead of -i
to see more output.
To send a plain * (instead of the path, see RFC 7231) with the OPTIONS method, you need curl 7.55.0 or later as then you can run a command line like:
curl -i --request-target "*" -X OPTIONS http://example.org
This is not a spring boot tutorial. It's the updated answer to a question on how to run a Maven build within a Docker container.
Question originally posted 4 years ago.
Use the spring initializer to generate a demo app
Extract the zip archive locally
#
# Build stage
#
FROM maven:3.6.0-jdk-11-slim AS build
COPY src /home/app/src
COPY pom.xml /home/app
RUN mvn -f /home/app/pom.xml clean package
#
# Package stage
#
FROM openjdk:11-jre-slim
COPY --from=build /home/app/target/demo-0.0.1-SNAPSHOT.jar /usr/local/lib/demo.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/usr/local/lib/demo.jar"]
Note
docker build -t demo .
$ docker run --rm -it demo:latest
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.3.RELEASE)
2019-02-22 17:18:57.835 INFO 1 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication v0.0.1-SNAPSHOT on f4e67677c9a9 with PID 1 (/usr/local/bin/demo.jar started by root in /)
2019-02-22 17:18:57.837 INFO 1 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2019-02-22 17:18:58.294 INFO 1 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 0.711 seconds (JVM running for 1.035)
Read the Docker hub documentation on how the Maven build can be optimized to use a local repository to cache jars.
This question is now 4 years old and in that time it's fair to say building application using Docker has undergone significant change.
This new style enables you to create more light-weight images that don't encapsulate your build tools and source code.
The example here again uses the official maven base image to run first stage of the build using a desired version of Maven. The second part of the file defines how the built jar is assembled into the final output image.
FROM maven:3.5-jdk-8 AS build
COPY src /usr/src/app/src
COPY pom.xml /usr/src/app
RUN mvn -f /usr/src/app/pom.xml clean package
FROM gcr.io/distroless/java
COPY --from=build /usr/src/app/target/helloworld-1.0.0-SNAPSHOT.jar /usr/app/helloworld-1.0.0-SNAPSHOT.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/usr/app/helloworld-1.0.0-SNAPSHOT.jar"]
Note:
I haven't used this approach but seems worthy of investigation as it enables you to build images without having to create nasty things like Dockerfiles :-)
https://github.com/GoogleContainerTools/jib
The project has a Maven plugin which integrates the packaging of your code directly into your Maven workflow.
Try using the new official images, there's one for Maven
https://registry.hub.docker.com/_/maven/
The image can be used to run Maven at build time to create a compiled application or, as in the following examples, to run a Maven build within a container.
The following command runs your Maven build inside a container:
docker run -it --rm \
-v "$(pwd)":/opt/maven \
-w /opt/maven \
maven:3.2-jdk-7 \
mvn clean install
Notes:
Run the Nexus container
docker run -d -p 8081:8081 --name nexus sonatype/nexus
Create a "settings.xml" file:
<settings>
<mirrors>
<mirror>
<id>nexus</id>
<mirrorOf>*</mirrorOf>
<url>http://nexus:8081/content/groups/public/</url>
</mirror>
</mirrors>
</settings>
Now run Maven linking to the nexus container, so that dependencies will be cached
docker run -it --rm \
-v "$(pwd)":/opt/maven \
-w /opt/maven \
--link nexus:nexus \
maven:3.2-jdk-7 \
mvn -s settings.xml clean install
Notes:
Here is some code I've wrote to automatically turn URL's into links and automatically embed any video urls from youtube. I made it for a chat room I'm working on and it works pretty well. I'm sure it will work just fine for any other purpose as well like a blog for instance.
All you have to do is call the function "autolink()" and pass it the string to be parsed.
For example include the function below and then echo this code.
`
echo '<div id="chat_message">'.autolink($string).'</div>';
/****************Function to include****************/
<?php
function autolink($string){
// force http: on www.
$string = str_ireplace( "www.", "http://www.", $string );
// eliminate duplicates after force
$string = str_ireplace( "http://http://www.", "http://www.", $string );
$string = str_ireplace( "https://http://www.", "https://www.", $string );
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// Check if there is a url in the text
$m = preg_match_all($reg_exUrl, $string, $match);
if ($m) {
$links=$match[0];
for ($j=0;$j<$m;$j++) {
if(substr($links[$j], 0, 18) == 'http://www.youtube'){
$string=str_replace($links[$j],'<a href="'.$links[$j].'" rel="nofollow" target="_blank">'.$links[$j].'</a>',$string).'<br /><iframe title="YouTube video player" class="youtube-player" type="text/html" width="320" height="185" src="http://www.youtube.com/embed/'.substr($links[$j], -11).'" frameborder="0" allowFullScreen></iframe><br />';
}else{
$string=str_replace($links[$j],'<a href="'.$links[$j].'" rel="nofollow" target="_blank">'.$links[$j].'</a>',$string);
}
}
}
return ($string);
}
?>
`
require 'pathname'
Pathname.new('/opt/local/bin/ruby').basename
# => #<Pathname:ruby>
I haven't been a Windows user in a long time, but the Pathname rdoc says it has no issues with directory-name separators on Windows.
If we want to rename a specific key in hash then we can do it as follows:
Suppose my hash is my_hash = {'test' => 'ruby hash demo'}
Now I want to replace 'test' by 'message', then:
my_hash['message'] = my_hash.delete('test')
All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if
to bind them all together in the way I believe you intend.
if you are using boolean variable to bind the radio button. please refer below sample code
<div ng-repeat="book in books">
<input type="radio" ng-checked="book.selected"
ng-click="function($event)">
</div>
if the list contains only integer:
reduce(lambda x,y: x*10+y, list)
Whenever we are trying to connect to URL,
if server at the other site is running on https protocol and is mandating that we should communicate via information provided in certificate then we have following option:
1) ask for the certificate(download the certificate), import this certificate in trustore. Default trustore java uses can be found in \Java\jdk1.6.0_29\jre\lib\security\cacerts, then if we retry to connect to the URL connection would be accepted.
2) In normal business cases, we might be connecting to internal URLS in organizations and we know that they are correct. In such cases, you trust that it is the correct URL, In such cases above, code can be used which will not mandate to store the certificate to connect to particular URL.
for the point no 2 we have to follow below steps :
1) write below method which sets HostnameVerifier for HttpsURLConnection which returns true for all cases meaning we are trusting the trustStore.
// trusting all certificate
public void doTrustToCertificates() throws Exception {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) {
System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
}
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
2) write below method, which calls doTrustToCertificates before trying to connect to URL
// connecting to URL
public void connectToUrl(){
doTrustToCertificates();//
URL url = new URL("https://www.example.com");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
System.out.println("ResponseCode ="+conn.getResponseCode());
}
This call will return response code = 200 means connection is successful.
For more detail and sample example you can refer to URL.
I came across a similar situation while working with DRF, the solution was appending .as_view() method to the View in urls.py
Instead of using the new pragmas, you can also use __attribute__((optimize("O0")))
for your needs. This has the advantage of just applying to a single function and not all functions defined in the same file.
Usage example:
void __attribute__((optimize("O0"))) foo(unsigned char data) {
// unmodifiable compiler code
}
I encountered this error when upgrading from jdk10 to jdk11. Adding the following dependency fixed the problem:
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.25.0-GA</version>
</dependency>
I am doing this for my email in the following way:
git config --global alias.hobbyprofile 'config user.email "[email protected]"'
Then when I clone a new work project, I have only to run git hobbyprofile
and it will be configured to use that email.
The sessions parameter is derived from the processes parameter and changes accordingly when you change the number of max processes. See the Oracle docs for further info.
To get only the info about the sessions:
select current_utilization, limit_value
from v$resource_limit
where resource_name='sessions';
CURRENT_UTILIZATION LIMIT_VALUE ------------------- ----------- 110 792
Try this to show info about both:
select resource_name, current_utilization, max_utilization, limit_value
from v$resource_limit
where resource_name in ('sessions', 'processes');
RESOURCE_NAME CURRENT_UTILIZATION MAX_UTILIZATION LIMIT_VALUE ------------- ------------------- --------------- ----------- processes 96 309 500 sessions 104 323 792
If you want text to be scrolled within the textview, then you can follow the following:
First you should have to subclass textview.
And then use that.
Following is an example of a subclassed textview.
public class AutoScrollableTextView extends TextView {
public AutoScrollableTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setEllipsize(TruncateAt.MARQUEE);
setMarqueeRepeatLimit(-1);
setSingleLine();
setHorizontallyScrolling(true);
}
public AutoScrollableTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setEllipsize(TruncateAt.MARQUEE);
setMarqueeRepeatLimit(-1);
setSingleLine();
setHorizontallyScrolling(true);
}
public AutoScrollableTextView(Context context) {
super(context);
setEllipsize(TruncateAt.MARQUEE);
setMarqueeRepeatLimit(-1);
setSingleLine();
setHorizontallyScrolling(true);
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if(focused)
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
@Override
public void onWindowFocusChanged(boolean focused) {
if(focused)
super.onWindowFocusChanged(focused);
}
@Override
public boolean isFocused() {
return true;
}
}
Now, you have to use that in the XML in this way:
<com.yourpackagename.AutoScrollableTextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is very very long text to be scrolled"
/>
That's it.
In case someone else finds this topic while using localhost
in the file URIs - Internet Explorer acts completely different if the host name is localhost
or 127.0.0.1
- if you use the actual hostname, it works fine (from trusted sites/intranet zone).
Another big difference between IE and FF - IE is fine with uris like file://server/share/file.txt
but FF requires additional slashes file:////server/share/file.txt
.
It's more convenient to use a session, this way you don't have to remember to set headers each time:
session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})
session.get('https://httpbin.org/headers')
By default, session also manages cookies for you. In case you want to disable that, see this question.
--
-- STORED PROCEDURE
-- Name of stored procedure.
--
-- DESCRIPTION
-- Business description of the stored procedure's functionality.
--
-- PARAMETERS
-- @InputParameter1
-- * Description of @InputParameter1 and how it is used.
--
-- RETURN VALUE
-- 0 - No Error.
-- -1000 - Description of cause of non-zero return value.
--
-- PROGRAMMING NOTES
-- Gotchas and other notes for your fellow programmer.
--
-- CHANGE HISTORY
-- 05 May 2009 - Who
-- * More comprehensive description of the change than that included with the
-- source code commit message.
--
xlim
and ylim
don't cut it here. You need to use expand_limits
, scale_x_continuous
, and scale_y_continuous
. Try:
df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for
p + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0))
You may need to adjust things a little to make sure points are not getting cut off (see, for example, the point at x = 5
and y = 5
.
Check this, http://www.hacktrix.com/how-to-delete-svn-folders-from-your-project-on-windows-linux-and-mac
I used with context
//Convert bitmap to drawable
Drawable drawable = new BitmapDrawable(context.getResources(), bitmap);
Try specifying a DC in DomainB using the -Server
property. Ex:
Get-ADUser -Server "dc01.DomainB.local" -Filter {EmailAddress -like "*Smith_Karla*"} -Properties EmailAddress
If you want to rotate a vector you should construct what is known as a rotation matrix.
Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are
x' = x cos ? - y sin ?
y' = x sin ? + y cos ?
To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider
Unit vector along X axis = <1, 0>
x' = 1 cos 90 - 0 sin 90 = 0
y' = 1 sin 90 + 0 cos 90 = 1
New coordinates of the vector, <x', y'> = <0, 1> ? Y-axis
When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is
|cos ? -sin ?| |x| = |x cos ? - y sin ?| = |x'|
|sin ? cos ?| |y| |x sin ? + y cos ?| |y'|
That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be
|cos ? -sin ? 0| |x| |x cos ? - y sin ?| |x'|
|sin ? cos ? 0| |y| = |x sin ? + y cos ?| = |y'|
| 0 0 1| |z| | z | |z'|
around the Y-axis would be
| cos ? 0 sin ?| |x| | x cos ? + z sin ?| |x'|
| 0 1 0| |y| = | y | = |y'|
|-sin ? 0 cos ?| |z| |-x sin ? + z cos ?| |z'|
around the X-axis would be
|1 0 0| |x| | x | |x'|
|0 cos ? -sin ?| |y| = |y cos ? - z sin ?| = |y'|
|0 sin ? cos ?| |z| |y sin ? + z cos ?| |z'|
Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.
Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.
I hope this clarifies basic rotation.
The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.
I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).
A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.
When you run selenium WebDriver, the WebDriver opens a remote server in your computer's local host. Now, this server, called the Selenium Server, is used to interpret your code into actions to run or "drive" the instance of a real browser known as either chromebrowser, ie broser, ff browser, etc.
So, the Selenium Server can interact with different browser properties and hence it has many "capabilities".
Now what capabilities do you desire? Consider a scenario where you are validating if files have been downloaded properly in your app but, however, you do not have a desktop automation tool. In the case where you click the download link and a desktop pop up shows up to ask where to save and/or if you want to download. Your next route to bypass that would be to suppress that pop up. How? Desired Capabilities.
There are other such examples. In summary, Selenium Server can do a lot, use Desired Capabilities to tailor it to your need.
The solution takes two steps!
First, complete the user, domain, and proxy fields in cntlm.ini
. The username and domain should probably be whatever you use to log in to Windows at your office, eg.
Username employee1730
Domain corporate
Proxy proxy.infosys.corp:8080
Then test cntlm with a command such as
cntlm.exe -c cntlm.ini -I -M http://www.bbc.co.uk
It will ask for your password (again whatever you use to log in to Windows_). Hopefully it will print 'http 200 ok' somewhere, and print your some cryptic tokens authentication information. Now add these to cntlm.ini
, eg:
Auth NTLM
PassNT A2A7104B1CE00000000000000007E1E1
PassLM C66000000000000000000000008060C8
Finally, set the http_proxy
environment variable in Windows (assuming you didn't change with the Listen
field which by default is set to 3128
) to the following
http://localhost:3128
I would use regular expression matching to sum over variables with certain pattern names. For example:
df <- df %>% mutate(sum1 = rowSums(.[grep("x[3-5]", names(.))], na.rm = TRUE),
sum_all = rowSums(.[grep("x", names(.))], na.rm = TRUE))
This way you can create more than one variable as a sum of certain group of variables of your data frame.
Use the Database menu and "Set Datasource Location" menu option to change the name or location of each table in a report.
This works for changing the location of a database, changing to a new database, and changing the location or name of an individual table being used in your report.
To change the datasource connection, go the Database menu and click Set Datasource Location.
And try running the report again.
The key is to change the datasource connection first, then any tables you need to update, then the other stuff. The connection won't automatically change the tables underneath. Those tables are like goslings that've imprinted on the first large goose-like animal they see. They'll continue to bypass all reason and logic and go to where they've always gone unless you specifically manually change them.
To make it more convenient, here's a tip: You can "Show SQL Query" in the Database menu, and you'll see table names qualified with the database (like "Sales"."dbo"."Customers") for any tables that go straight to a specific database. That might make the hunting easier if you have a lot of stuff going on. When I tackled this problem I had to change each and every table to point to the new table in the new database.
foo(*ob);
You don't need to cast it because it's the same Object type, you just need to dereference it.
private Cursor getAllFavorites() {
return mDb.query(DocsDsctnContract.DocsDsctnEntry.Description_Table_Name,
null,
null,
null,
null,
null,
DocsDsctnContract.DocsDsctnEntry.COLUMN_Timest);
}
@Override
public void onResume()
{ // After a pause OR at startup
super.onResume();
mAdapter.swapCursor(getAllFavorites());
mAdapter.notifyDataSetChanged();
}
public void swapCursor(Cursor newCursor){
if (mCursor!=null) mCursor.close();
mCursor = newCursor;
if (newCursor != null){
mAdapter.notifyDataSetChanged();
}
}
I just have favorites category so when i click to the item from favorites there appear such information and if i unlike it - this item should be deleted from Favorites : for that i refresh database and set it to adapter(for recyclerview)[I wish you will understand my problem & solution]
*please be sure there is no Ripple at your root layout of list view container
add this line to your list view
android:listSelector="@drawable/background_listview"
here is the "background_listview.xml" file
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/white_background" android:state_pressed="true" />
<item android:drawable="@color/primary_color" android:state_focused="false" /></selector>
the colors that used in the background_listview.xml file :
<color name="primary_color">#cc7e00</color>
<color name="white_background">#ffffffff</color>
after these
(clicked item contain orange color until you click another item)
I solved this issue with commands bellow:
$ sudo apt-get install php7.3-intl
$ sudo /etc/init.d/php7.3-fpm restart
These commands works for me in homestead with php7.3
It's simple with open source 7zip SFX-Packager - easy way to just "Drag & drop" folders onto it, and it creates a portable/self-extracting package.
Only static functions are called with class name.
classname::Staicfunction();
Non static functions have to be called using objects.
classname obj;
obj.Somefunction();
This is exactly what your error means. Since your function is non static you have to use a object reference to invoke it.
What's wrong with using two regexs (or three)? This makes your intentions more clear and may even improve your performance:
if ($string =~ /^(Clinton|Reagan)/i && $string !~ /Bush/i) { ... }
if (($string =~ /^Clinton/i || $string =~ /^Reagan/i)
&& $string !~ /Bush/i) {
print "$string\n"
}
This is because the content of
<p myHighlight>Highlight me!</p>
has not been rendered when the constructor of the HighlightDirective is called so there is no content yet.
If you implement the AfterContentInit hook you will get the element and its content.
import { Directive, ElementRef, AfterContentInit } from '@angular/core';
@Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
constructor(private el: ElementRef) {
//el.nativeElement.style.backgroundColor = 'yellow';
}
ngAfterContentInit(){
//you can get to the element content here
//this.el.nativeElement
}
}
As discussed here, there really isn't such a thing as an HTTP connection and what httplib refers to as the HTTPConnection is really the underlying TCP connection which doesn't really know much about your requests at all. Requests abstracts that away and you won't ever see it.
The newest version of Requests does in fact keep the TCP connection alive after your request.. If you do want your TCP connections to close, you can just configure the requests to not use keep-alive.
s = requests.session()
s.config['keep_alive'] = False
You can get the device screen width via the screen.width property.
Sometimes it's also useful to use window.innerWidth (not typically found on mobile devices) instead of screen width when dealing with desktop browsers where the window size is often less than the device screen size.
Typically, when dealing with mobile devices AND desktop browsers I use the following:
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
You could declare your parameters in the file, like param:
[string]$para1
[string]$param2
And then call the PowerShell file like so .\temp.ps1 para1 para2....para10
, etc.
Short answer: Why not?
Longer answer: The time itself doesn't really matter, as long as everyone who uses it agrees on its value. As 1/1/70 has been in use for so long, using it will make you code as understandable as possible for as many people as possible.
There's no great merit in choosing an arbitrary epoch just to be different.
I ran into this issue when I wanted to temporarily disable the sending of an email while working on another part of the code.
Commenting the use of the service triggered a lot of cascade errors, so instead of commenting I used a condition
if false {
// Technically, svc still be used so no yelling
_, err = svc.SendRawEmail(input)
Check(err)
}
Use first the method OpenTextFile
, and then...
either read the file at once with the method ReadAll
:
Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll
or line by line with the method ReadLine
:
Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
line = file.Readline
dict.Add row, line
row = row + 1
Loop
file.Close
'Loop over it
For Each line in dict.Items
WScript.Echo line
Next
There are two reasons for this error
1) In the array of import if you imported HttpModule twice
2) If you haven't import:
import { HttpModule, JsonpModule } from '@angular/http';
If you want then run:
npm install @angular/http
If you were using AppCompatActivity
and have gone down the path of not using it, because you wanted to not get the automatic ActionBar
that it provides, because you want to separate out the Toolbar
, because of your Material Design needs and CoordinatorLayout
or AppBarLayout
, then, consider this:
You can still use the AppCompatActivity
, you don't need to stop using it just so that you can use a <android.support.v7.widget.Toolbar>
in your xml. Just turn off the action bar style as follows:
First, derive a style from one of the NoActionBar themes that you like in your styles.xml
, I used Theme.AppCompat.Light.NoActionBar
like so:
<style name="SuperCoolAppBarActivity" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/primary</item>
<!-- colorPrimaryDark is used for the status bar -->
<item name="colorPrimaryDark">@color/primary_dark</item>
...
...
</style>
In your App's manifest, choose the child style theme you just defined, like so:
<activity
android:name=".activity.YourSuperCoolActivity"
android:label="@string/super_cool"
android:theme="@style/SuperCoolAppBarActivity">
</activity>
In your Activity Xml, if the toolbar is defined like so:
...
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
/>
...
Then, and this is the important part, you set the support Action bar to the AppCompatActivity that you're extending, so that the toolbar in your xml, becomes the action bar. I feel that this is a better way, because you can simply do the many things that ActionBar allows, like menus, automatic activity title, item selection handling, etc. without resorting to adding custom click handlers, etc.
In your Activity's onCreate override, do the following:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_super_cool);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Your toolbar is now an action bar and you can use it like you always do, for example:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Typically, quicksort is significantly faster in practice than other T(nlogn) algorithms, because its inner loop can be efficiently implemented on most architectures, and in most real-world data, it is possible to make design choices which minimize the probability of requiring quadratic time.
Note that the very low memory requirement is a big plus as well.
Cygwin mount
now support bind method which lets you mount a directory. Hence you can simply add the following line to /etc/fstab
, then restart your shell:
c:/Users /home none bind 0 0
If your code is ES7 based (or upper versions):
channelArray.includes('three'); //will return true or false
If not, for example you are using IE with no babel transpile:
channelArray.indexOf('three') !== -1; //will return true or false
the indexOf
method will return the position the element has into the array, because of that we use !==
different from -1 if the needle is found at the first position.
A slight variation of the nice @liangli's solution that does not require to change the index of existing dataframes:
newdf = df1.drop(df1.join(df2.set_index('Name').index))
Try this. I set the blue box to float right, gave left and right a fixed height, and added a white border on the right of the left div. Also added rounded corners to more match your example (These won't work in ie 8 or less). I also took out the position: relative. You don't need it. Block level elements are set to position relative by default.
See it here: http://jsfiddle.net/ZSgLJ/
#left {
float: left;
width: 44%;
margin: 0;
padding: 0;
border-right: 1px solid white;
height:400px;
}
#right {
position: relative;
float: right;
width: 49%;
margin: 0;
padding: 0;
height:400px;
}
#blue_box {
background-color:blue;
border-radius: 10px;
-moz-border-radius:10px;
-webkit-border-radius: 10px;
width: 45%;
min-width: 400px;
max-width: 600px;
padding: 2%;
float: right;
}
This is my adaptation johnrefling's. This work also in WindowsXP; in my case i start the same application at the end, because i want reopen it with different parametrs. My application is a WindowForm .NET
@echo off
taskkill -im:MyApp.exe
:loop1
tasklist | find /i "MyApp.exe" >nul 2>&1
if errorlevel 1 goto cont1
echo "Waiting termination of process..."
:: timeout /t 1 /nobreak >nul 2>&1 ::this don't work in windows XP
:: from: https://stackoverflow.com/questions/1672338/how-to-sleep-for-five-seconds-in-a-batch-file-cmd/33286113#33286113
typeperf "\System\Processor Queue Length" -si 1 -sc 1 >nul s
goto loop1
:cont1
echo "Process terminated, start new application"
START "<SYMBOLIC-TEXT-NAME>" "<full-path-of-MyApp2.exe>" "MyApp2-param1" "MyApp2-param2"
pause
Use the following:
type file.txt | findstr /v ERROR | findstr /v REFERENCE
This has the advantage of using standard tools in the Windows OS, rather than having to find and install sed/awk/perl and such.
See the following transcript for it in operation:
C:\>type file.txt Good Line of data bad line of C:\Directory\ERROR\myFile.dll Another good line of data bad line: REFERENCE Good line C:\>type file.txt | findstr /v ERROR | findstr /v REFERENCE Good Line of data Another good line of data Good line
I use the following to avoid notices, this checks if the var it's declarated on GET or POST and with the @ prefix you can safely check if is not empty and avoid the notice if the var is not set:
if( isset($_GET['var']) && @$_GET['var']!='' ){
//Is not empty, do something
}
Now we no need to use any third party lib or custom imageView
ShapeableImageView
SAMPLE CODE
First add below
dependencies
in yourbuild.gradle
file
implementation 'com.google.android.material:material:1.2.0-alpha05'
Add ShapeableImageView
in your layout
<com.google.android.material.imageview.ShapeableImageView
android:id="@+id/myShapeableImageView"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/nilesh" />
Kotlin code to make ImageView Circle
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.android.material.shape.CornerFamily
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// <dimen name="image_corner_radius">50dp</dimen>
val radius = resources.getDimension(R.dimen.image_corner_radius)
myShapeableImageView.shapeAppearanceModel = myShapeableImageView.shapeAppearanceModel
.toBuilder()
.setTopRightCorner(CornerFamily.ROUNDED, radius)
.setTopLeftCorner(CornerFamily.ROUNDED, radius)
.setBottomLeftCorner(CornerFamily.ROUNDED, radius)
.setBottomRightCorner(CornerFamily.ROUNDED, radius)
.build()
// or You can use setAllCorners() method
myShapeableImageView.shapeAppearanceModel = myShapeableImageView.shapeAppearanceModel
.toBuilder()
.setAllCorners(CornerFamily.ROUNDED, radius)
.build()
}
}
OUTPUT
First, create a below style in your style.xml
<style name="circleImageViewStyle" >
<item name="cornerFamily">rounded</item>
<item name="cornerSize">50%</item>
</style>
Now use that style in your layout like this
<com.google.android.material.imageview.ShapeableImageView
android:id="@+id/myShapeableImageView"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="20dp"
app:shapeAppearanceOverlay="@style/circleImageViewStyle"
app:srcCompat="@drawable/nilesh" />
OUTPUT
Please find the complete exmaple here how to use ShapeableImageView
Although this issue is quite old, i think this is relevant news / the most recent answer: Microsoft open-sourced XAML Behaviours and posted a blog post how to update to this version: https://devblogs.microsoft.com/dotnet/open-sourcing-xaml-behaviors-for-wpf/
To save you a click, this is the main steps to migrate:
The "proper" LaTeX ways to do it is to use a package which allows you to specify the spacing you want. There are several such package, and these two pages link to lists of them...
In Device Developer option
Check Install Via USB is ON compulsory.
For python 3 it would be like this
n,m,p=map(int,input().split())
You create a new project. The new project is your EAR assembly project which contains your two dependencies for your EJB project and your WAR project.
So you actually have three maven projects here. One EJB. One WAR. One EAR that pulls the two parts together and creates the ear.
Deployment descriptors can be generated by maven, or placed inside the resources directory in the EAR project structure.
The maven-ear-plugin is what you use to configure it, and the documentation is good, but not quite clear if you're still figuring out how maven works in general.
So as an example you might do something like this:
<?xml version="1.0" encoding="utf-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>myEar</artifactId>
<packaging>ear</packaging>
<name>My EAR</name>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<artifactId>maven-ear-plugin</artifactId>
<configuration>
<version>1.4</version>
<modules>
<webModule>
<groupId>com.mycompany</groupId>
<artifactId>myWar</artifactId>
<bundleFileName>myWarNameInTheEar.war</bundleFileName>
<contextRoot>/myWarConext</contextRoot>
</webModule>
<ejbModule>
<groupId>com.mycompany</groupId>
<artifactId>myEjb</artifactId>
<bundleFileName>myEjbNameInTheEar.jar</bundleFileName>
</ejbModule>
</modules>
<displayName>My Ear Name displayed in the App Server</displayName>
<!-- If I want maven to generate the application.xml, set this to true -->
<generateApplicationXml>true</generateApplicationXml>
</configuration>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.3</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
<finalName>myEarName</finalName>
</build>
<!-- Define the versions of your ear components here -->
<dependencies>
<dependency>
<groupId>com.mycompany</groupId>
<artifactId>myWar</artifactId>
<version>1.0-SNAPSHOT</version>
<type>war</type>
</dependency>
<dependency>
<groupId>com.mycompany</groupId>
<artifactId>myEjb</artifactId>
<version>1.0-SNAPSHOT</version>
<type>ejb</type>
</dependency>
</dependencies>
</project>
Seba Illingworth's code, In case you need time in your file name (it gives 2014-02-21_1035)
echo off
cls
echo -- BACKUP DATABASE --
set /p DATABASENAME=Enter database name:
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
:: filename format Name-Date (eg MyDatabase-2009.5.19.bak)
set DATESTAMP=%mydate%_%mytime%
set BACKUPFILENAME=%CD%\%DATABASENAME%-%DATESTAMP%.bak
set SERVERNAME=.
echo.
sqlcmd -E -S %SERVERNAME% -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = N'%BACKUPFILENAME%' WITH INIT , NOUNLOAD , NAME = N'%DATABASENAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.
pause
The best way is to let the Android Studio fix the issue.
I did the below, and it worked fine.
Open your project in Android Studio, errors will be popup, if there is a link given to fix it click on it.
Re-open your project in Android Studio, errors will be popup, there will be a link this time if it's not given in the Step 1, click on the given link to fix it.
Note that both operations took several minutes of time, but fixed all issues.
I eventually figured it out. Place:
import warnings
warnings.filterwarnings('ignore')
inside ~/.ipython/profile_default/startup/disable-warnings.py
. I'm leaving this question and answer for the record in case anyone else comes across the same issue.
Quite often it is useful to see a warning once. This can be set by:
warnings.filterwarnings(action='once')
Or patch your kernel and remove the check.
(Option of last resort, not recommended).
In net/ipv4/af_inet.c
, remove the two lines that read
if (snum && snum < PROT_SOCK && !capable(CAP_NET_BIND_SERVICE))
goto out;
and the kernel won't check privileged ports anymore.
In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198
Shadowbox is your best choice. Check it out.
Ftrujillo's answer works well but if you only have one package to scan this is the shortest form::
@Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("your.package.to.scan");
return marshaller;
}
Had the same exception. In my case, I had to run Command Prompt with Administrator Rights.
From the Start Menu, right click on Command Prompt, select "Run as administrator".
Why do you not want to iterate exactly ? The new Array.prototype.forEach are great for this purpose!
You can use a Binary Search Tree to find via a single method call if you want. This is a neat implementation of BTree and Red black Search tree in JS - https://github.com/vadimg/js_bintrees - but I'm not sure whether you can find the index at the same time.
As said in the documentation:
Must: The clause (query) must appear in matching documents.
Should: The clause (query) should appear in the matching document. In a boolean query with no must clauses, one or more should clauses must match a document. The minimum number of should clauses to match can be set using the minimum_should_match parameter.
In other words, results will have to be matched by all the queries present in the must clause ( or match at least one of the should clauses if there is no must clause.
Since you want your results to satisfy all the queries, you should use must.
You can indeed use filters inside a boolean query.
For make a list, simply do that
colors=(red orange white "light gray")
Technically is an array, but - of course - it has all list features.
Even python list are implemented with array
All of these answers should suffice. However if you don't have a defined width, auto margins will not work.
I have found this nifty little trick to centre some of the more stubborn elements (Particularly images).
.div {
position: absolute;
left: 0;
right: 0;
margin-left: 0;
margin-right: 0;
}
x = float(raw_input("enter number between 0 and 1: "))
p = 0
while ((2**p)*x) %1 != 0:
p += 1
# print p
num = int (x * (2 ** p))
# print num
result = ''
if num == 0:
result = '0'
while num > 0:
result = str(num%2) + result
num = num / 2
for i in range (p - len(result)):
result = '0' + result
result = result[0:-p] + '.' + result[-p:]
print result #this will print result for the decimal portion
Just because memcpy
doesn't have to deal with overlapping regions, doesn't mean it doesn't deal with them correctly. The call with overlapping regions produces undefined behavior. Undefined behavior can work entirely as you expect on one platform; that doesn't mean it's correct or valid.
What follows is an explanation for what is going on, scroll to bottom for code demos.
Passing parameter suppress=True
to function set_printoptions
works only for numbers that fit in the default 8 character space allotted to it, like this:
import numpy as np
np.set_printoptions(suppress=True) #prevent numpy exponential
#notation on print, default False
# tiny med large
a = np.array([1.01e-5, 22, 1.2345678e7]) #notice how index 2 is 8
#digits wide
print(a) #prints [ 0.0000101 22. 12345678. ]
However if you pass in a number greater than 8 characters wide, exponential notation is imposed again, like this:
np.set_printoptions(suppress=True)
a = np.array([1.01e-5, 22, 1.2345678e10]) #notice how index 2 is 10
#digits wide, too wide!
#exponential notation where we've told it not to!
print(a) #prints [1.01000000e-005 2.20000000e+001 1.23456780e+10]
numpy has a choice between chopping your number in half thus misrepresenting it, or forcing exponential notation, it chooses the latter.
Here comes set_printoptions(formatter=...)
to the rescue to specify options for printing and rounding. Tell set_printoptions
to just print bare a bare float:
np.set_printoptions(suppress=True,
formatter={'float_kind':'{:f}'.format})
a = np.array([1.01e-5, 22, 1.2345678e30]) #notice how index 2 is 30
#digits wide.
#Ok good, no exponential notation in the large numbers:
print(a) #prints [0.000010 22.000000 1234567799999999979944197226496.000000]
We've force-suppressed the exponential notation, but it is not rounded or justified, so specify extra formatting options:
np.set_printoptions(suppress=True,
formatter={'float_kind':'{:0.2f}'.format}) #float, 2 units
#precision right, 0 on left
a = np.array([1.01e-5, 22, 1.2345678e30]) #notice how index 2 is 30
#digits wide
print(a) #prints [0.00 22.00 1234567799999999979944197226496.00]
The drawback for force-suppressing all exponential notion in ndarrays is that if your ndarray gets a huge float value near infinity in it, and you print it, you're going to get blasted in the face with a page full of numbers.
from pprint import pprint
import numpy as np
#chaotic python list of lists with very different numeric magnitudes
my_list = [[3.74, 5162, 13683628846.64, 12783387559.86, 1.81],
[9.55, 116, 189688622.37, 260332262.0, 1.97],
[2.2, 768, 6004865.13, 5759960.98, 1.21],
[3.74, 4062, 3263822121.39, 3066869087.9, 1.93],
[1.91, 474, 44555062.72, 44555062.72, 0.41],
[5.8, 5006, 8254968918.1, 7446788272.74, 3.25],
[4.5, 7887, 30078971595.46, 27814989471.31, 2.18],
[7.03, 116, 66252511.46, 81109291.0, 1.56],
[6.52, 116, 47674230.76, 57686991.0, 1.43],
[1.85, 623, 3002631.96, 2899484.08, 0.64],
[13.76, 1227, 1737874137.5, 1446511574.32, 4.32],
[13.76, 1227, 1737874137.5, 1446511574.32, 4.32]]
#convert python list of lists to numpy ndarray called my_array
my_array = np.array(my_list)
#This is a little recursive helper function converts all nested
#ndarrays to python list of lists so that pretty printer knows what to do.
def arrayToList(arr):
if type(arr) == type(np.array):
#If the passed type is an ndarray then convert it to a list and
#recursively convert all nested types
return arrayToList(arr.tolist())
else:
#if item isn't an ndarray leave it as is.
return arr
#suppress exponential notation, define an appropriate float formatter
#specify stdout line width and let pretty print do the work
np.set_printoptions(suppress=True,
formatter={'float_kind':'{:16.3f}'.format}, linewidth=130)
pprint(arrayToList(my_array))
Prints:
array([[ 3.740, 5162.000, 13683628846.640, 12783387559.860, 1.810],
[ 9.550, 116.000, 189688622.370, 260332262.000, 1.970],
[ 2.200, 768.000, 6004865.130, 5759960.980, 1.210],
[ 3.740, 4062.000, 3263822121.390, 3066869087.900, 1.930],
[ 1.910, 474.000, 44555062.720, 44555062.720, 0.410],
[ 5.800, 5006.000, 8254968918.100, 7446788272.740, 3.250],
[ 4.500, 7887.000, 30078971595.460, 27814989471.310, 2.180],
[ 7.030, 116.000, 66252511.460, 81109291.000, 1.560],
[ 6.520, 116.000, 47674230.760, 57686991.000, 1.430],
[ 1.850, 623.000, 3002631.960, 2899484.080, 0.640],
[ 13.760, 1227.000, 1737874137.500, 1446511574.320, 4.320],
[ 13.760, 1227.000, 1737874137.500, 1446511574.320, 4.320]])
import numpy as np
#chaotic python list of lists with very different numeric magnitudes
# very tiny medium size large sized
# numbers numbers numbers
my_list = [[0.000000000074, 5162, 13683628846.64, 1.01e10, 1.81],
[1.000000000055, 116, 189688622.37, 260332262.0, 1.97],
[0.010000000022, 768, 6004865.13, -99e13, 1.21],
[1.000000000074, 4062, 3263822121.39, 3066869087.9, 1.93],
[2.91, 474, 44555062.72, 44555062.72, 0.41],
[5, 5006, 8254968918.1, 7446788272.74, 3.25],
[0.01, 7887, 30078971595.46, 27814989471.31, 2.18],
[7.03, 116, 66252511.46, 81109291.0, 1.56],
[6.52, 116, 47674230.76, 57686991.0, 1.43],
[1.85, 623, 3002631.96, 2899484.08, 0.64],
[13.76, 1227, 1737874137.5, 1446511574.32, 4.32],
[13.76, 1337, 1737874137.5, 1446511574.32, 4.32]]
import sys
#convert python list of lists to numpy ndarray called my_array
my_array = np.array(my_list)
#following two lines do the same thing, showing that np.savetxt can
#correctly handle python lists of lists and numpy 2D ndarrays.
np.savetxt(sys.stdout, my_list, '%19.2f')
np.savetxt(sys.stdout, my_array, '%19.2f')
Prints:
0.00 5162.00 13683628846.64 10100000000.00 1.81
1.00 116.00 189688622.37 260332262.00 1.97
0.01 768.00 6004865.13 -990000000000000.00 1.21
1.00 4062.00 3263822121.39 3066869087.90 1.93
2.91 474.00 44555062.72 44555062.72 0.41
5.00 5006.00 8254968918.10 7446788272.74 3.25
0.01 7887.00 30078971595.46 27814989471.31 2.18
7.03 116.00 66252511.46 81109291.00 1.56
6.52 116.00 47674230.76 57686991.00 1.43
1.85 623.00 3002631.96 2899484.08 0.64
13.76 1227.00 1737874137.50 1446511574.32 4.32
13.76 1337.00 1737874137.50 1446511574.32 4.32
0.00 5162.00 13683628846.64 10100000000.00 1.81
1.00 116.00 189688622.37 260332262.00 1.97
0.01 768.00 6004865.13 -990000000000000.00 1.21
1.00 4062.00 3263822121.39 3066869087.90 1.93
2.91 474.00 44555062.72 44555062.72 0.41
5.00 5006.00 8254968918.10 7446788272.74 3.25
0.01 7887.00 30078971595.46 27814989471.31 2.18
7.03 116.00 66252511.46 81109291.00 1.56
6.52 116.00 47674230.76 57686991.00 1.43
1.85 623.00 3002631.96 2899484.08 0.64
13.76 1227.00 1737874137.50 1446511574.32 4.32
13.76 1337.00 1737874137.50 1446511574.32 4.32
Notice that rounding is consistent at 2 units precision, and exponential notation is suppressed in both the very large e+x
and very small e-x
ranges.
This is a pretty vague question, I think; just because of the depth of the topic involved. A compiler can be decomposed into two separate parts, however; a top-half and a bottom-one. The top-half generally takes the source language and converts it into an intermediate representation, and the bottom half takes care of the platform specific code generation.
Nonetheless, one idea for an easy way to approach this topic (the one we used in my compilers class, at least) is to build the compiler in the two pieces described above. Specifically, you'll get a good idea of the entire process by just building the top-half.
Just doing the top half lets you get the experience of writing the lexical analyzer and the parser and go to generating some "code" (that intermediate representation I mentioned). So it will take your source program and convert it to another representation and do some optimization (if you want), which is the heart of a compiler. The bottom half will then take that intermediate representation and generate the bytes needed to run the program on a specific architecture. For example, the the bottom half will take your intermediate representation and generate a PE executable.
Some books on this topic that I found particularly helpful was Compilers Principles and Techniques (or the Dragon Book, due to the cute dragon on the cover). It's got some great theory and definitely covers Context-Free Grammars in a really accessible manner. Also, for building the lexical analyzer and parser, you'll probably use the *nix tools lex and yacc. And uninterestingly enough, the book called "lex and yacc" picked up where the Dragon Book left off for this part.
For some of you who uses Yii2 there is a method under the hood yii\helpers\StringHelper::truncate()
.
Example of usage:
$sting = "stringToTruncate";
$truncatedString = \yii\helpers\StringHelper::truncate($string, 6, '...');
echo $truncatedString; // result: "string..."
Here is the doc: https://www.yiiframework.com/doc/api/2.0/yii-helpers-basestringhelper#truncate()-detail
I'm using this in .NET 5, on Windows, with Windows Forms. It works even with other default browsers (such as Firefox):
Process.Start(new ProcessStartInfo { FileName = url, UseShellExecute = true });
Since I can only edit my own answer, I'm going to make a composite answer from the other answers to my question. Thanks to all of you who answered.
Using std::copy, this still iterates in the background, but you don't have to type out the code.
int foo(int* data, int size)
{
static std::vector<int> my_data; //normally a class variable
std::copy(data, data + size, std::back_inserter(my_data));
return 0;
}
Using regular memcpy. This is probably best used for basic data types (i.e. int) but not for more complex arrays of structs or classes.
vector<int> x(size);
memcpy(&x[0], source, size*sizeof(int));
Go to your build settings and switch the target's settings to ENABLE_BITCODE = YES
for now.
ALTER table dataset.tablename ADD column_current_ind integer DEFAULT 0
From next version of SQL Server you will be able to do
SELECT r.name,
STRING_AGG(a.name, ',')
FROM RESOURCES r
JOIN APPLICATIONSRESOURCES ar
ON ar.resource_id = r.id
JOIN APPLICATIONS a
ON a.id = ar.app_id
GROUP BY r.name
For previous versions of the product there are quite a wide variety of different approaches to this problem. An excellent review of them is in the article: Concatenating Row Values in Transact-SQL.
Concatenating values when the number of items are not known
Non-reliable approaches
You can define a struct and create its object in another struct like i have done below:
package main
import "fmt"
type Address struct {
streetNumber int
streetName string
zipCode int
}
type Person struct {
name string
age int
address Address
}
func main() {
var p Person
p.name = "Vipin"
p.age = 30
p.address = Address{
streetName: "Krishna Pura",
streetNumber: 14,
zipCode: 475110,
}
fmt.Println("Name: ", p.name)
fmt.Println("Age: ", p.age)
fmt.Println("StreetName: ", p.address.streetName)
fmt.Println("StreeNumber: ", p.address.streetNumber)
}
Hope it helped you :)
yes you can use MapView in v2... for further details you can get help from this
https://gist.github.com/joshdholtz/4522551
SomeFragment.java
public class SomeFragment extends Fragment implements OnMapReadyCallback{
MapView mapView;
GoogleMap map;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.some_layout, container, false);
// Gets the MapView from the XML layout and creates it
mapView = (MapView) v.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
return v;
}
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
/*
//in old Api Needs to call MapsInitializer before doing any CameraUpdateFactory call
try {
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
*/
// Updates the location and zoom of the MapView
/*CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
map.animateCamera(cameraUpdate);*/
map.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(43.1, -87.9)));
}
@Override
public void onResume() {
mapView.onResume();
super.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<permission
android:name="com.example.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.example.permission.MAPS_RECEIVE"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="your_key"/>
<activity
android:name=".HomeActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
some_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<com.google.android.gms.maps.MapView android:id="@+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
For template, you can use
{% firstof request.user.get_full_name request.user.username %}
firstof will return the first one if not null else the second one
Somewhat simplified (and what worked for me) way that worked for me (based on all the above)
Note that dependencies hierarchy can go deeper then one level
Get dependencies of your package
$ apt-cache depends mongodb | grep Depends:
Depends: mongodb-dev
Depends: mongodb-server
Get urls:
sudo apt-get --print-uris --yes -d --reinstall install mongodb-org mongodb-org-server mongodb-org-shell mongodb-org-tools | grep "http://" | awk '{print$1}' | xargs -I'{}' echo {} | tee files.list
wget --input-file files.list
Set the following two environment variables:
NVIDIA_VISIBLE_DEVICES=$gpu_id
CUDA_VISIBLE_DEVICES=0
where gpu_id
is the ID of your selected GPU, as seen in the host system's nvidia-smi
(a 0-based integer) that will be made available to the guest system (e.g. to the Docker container environment).
You can verify that a different card is selected for each value of gpu_id by inspecting Bus-Id
parameter in nvidia-smi
run in a terminal in the guest system).
This method based on NVIDIA_VISIBLE_DEVICES
exposes only a single card to the system (with local ID zero), hence we also hard-code the other variable, CUDA_VISIBLE_DEVICES
to 0 (mainly to prevent it from defaulting to an empty string that would indicate no GPU).
Note that the environmental variable should be set before the guest system is started (so no chances of doing it in your Jupyter Notebook's terminal), for instance using docker run -e NVIDIA_VISIBLE_DEVICES=0
or env
in Kubernetes or Openshift.
If you want GPU load-balancing, make gpu_id
random at each guest system start.
If setting this with python, make sure you are using strings for all environment variables, including numerical ones.
You can verify that a different card is selected for each value of gpu_id
by inspecting nvidia-smi
's Bus-Id parameter (in a terminal run in the guest system).
The accepted solution based on CUDA_VISIBLE_DEVICES
alone does not hide other cards (different from the pinned one), and thus causes access errors if you try to use them in your GPU-enabled python packages. With this solution, other cards are not visible to the guest system, but other users still can access them and share their computing power on an equal basis, just like with CPU's (verified).
This is also preferable to solutions using Kubernetes / Openshift controlers (resources.limits.nvidia.com/gpu
), that would impose a lock on the allocated card, removing it from the pool of available resources (so the number of containers with GPU access could not exceed the number of physical cards).
This has been tested under CUDA 8.0, 9.0 and 10.1 in docker containers running Ubuntu 18.04 orchestrated by Openshift 3.11.
Just read this post and according to the angular 2 docs:
export CUSTOM_ELEMENTS_SCHEMA
Defines a schema that will allow:
any non-Angular elements with a - in their name,
any properties on elements with a - in their name which is the common rule for custom elements.
So just in case anyone runs into this problem, once you have added CUSTOM_ELEMENTS_SCHEMA to your NgModule, make sure that whatever new custom element you use has a 'dash' in its name eg. or etc.
upgrading the google services in project-level build.gradle
solved my problem.
After upgrading:
dependencies {
...
classpath 'com.google.gms:google-services:4.3.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
I agree with Matthew Flaschen's answer and just wanted to show examples of the options for the case you cannot switch to List (because a library returns you a Collection):
List list = new ArrayList(theCollection);
list.get(5);
Or
Object[] list2 = theCollection.toArray();
doSomethingWith(list[2]);
If you know what generics is I can provide samples for that too.
Edit: It's another question what the intent and semantics of the original collection is.
And this:
FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken()
suppose to be solution of deprecated:
FirebaseInstanceId.getInstance().getToken()
EDIT
FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken()
can produce exception if the task is not yet completed, so the method witch Nilesh Rathod described (with .addOnSuccessListener
) is correct way to do it.
Kotlin:
FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener(this) { instanceIdResult ->
val newToken = instanceIdResult.token
Log.e("newToken", newToken)
}
You don't necessarily need the BouncyCastle library. The following code shows how to do so using the Integer.toHexString function
public static String sha256(String base) {
try{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(base.getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch(Exception ex){
throw new RuntimeException(ex);
}
}
Special thanks to user1452273 from this post: How to hash some string with sha256 in Java?
Keep up the good work !
The answer by Nick Mitchinson is for Bootstrap version 2.
If you are using Bootstrap version 3, then forms have changed a bit. For bootstrap 3, use the following instead:
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-6">
<textarea class="form-control" rows="3" placeholder="What's up?" required></textarea>
</div>
</div>
</div>
Where, col-md-6 will target medium sized devices. You can add col-xs-6 etc to target smaller devices.
If you want to display 24 hours format use:
SELECT FORMAT(GETDATE(),'HH:mm')
and to display 12 hours format use:
SELECT FORMAT(GETDATE(),'hh:mm')
Often times I think it is just good practice to keep larger databases inside a database (e.g. Postgres). I don't use anything too much larger than (nrow * ncol) ncell = 10M, which is pretty small; but I often find I want R to create and hold memory intensive graphs only while I query from multiple databases. In the future of 32 GB laptops, some of these types of memory problems will disappear. But the allure of using a database to hold the data and then using R's memory for the resulting query results and graphs still may be useful. Some advantages are:
(1) The data stays loaded in your database. You simply reconnect in pgadmin to the databases you want when you turn your laptop back on.
(2) It is true R can do many more nifty statistical and graphing operations than SQL. But I think SQL is better designed to query large amounts of data than R.
# Looking at Voter/Registrant Age by Decade
library(RPostgreSQL);library(lattice)
con <- dbConnect(PostgreSQL(), user= "postgres", password="password",
port="2345", host="localhost", dbname="WC2014_08_01_2014")
Decade_BD_1980_42 <- dbGetQuery(con,"Select PrecinctID,Count(PrecinctID),extract(DECADE from Birthdate) from voterdb where extract(DECADE from Birthdate)::numeric > 198 and PrecinctID in (Select * from LD42) Group By PrecinctID,date_part Order by Count DESC;")
Decade_RD_1980_42 <- dbGetQuery(con,"Select PrecinctID,Count(PrecinctID),extract(DECADE from RegistrationDate) from voterdb where extract(DECADE from RegistrationDate)::numeric > 198 and PrecinctID in (Select * from LD42) Group By PrecinctID,date_part Order by Count DESC;")
with(Decade_BD_1980_42,(barchart(~count | as.factor(precinctid))));
mtext("42LD Birthdays later than 1980 by Precinct",side=1,line=0)
with(Decade_RD_1980_42,(barchart(~count | as.factor(precinctid))));
mtext("42LD Registration Dates later than 1980 by Precinct",side=1,line=0)
Just use String.value of like below;
private static void h() {
String helloWorld = "helloWorld";
System.out.println(helloWorld);
char [] charArr = helloWorld.toCharArray();
System.out.println(String.valueOf(charArr));
}
In SQL Server 2008 and above just do this:
SELECT DATEADD(day, 1, Getdate()) AS DateAdd;
One way to workaround the lack of "?" operator using Java 8 without the overhead of try-catch (which could also hide a NullPointerException
originated elsewhere, as mentioned) is to create a class to "pipe" methods in a Java-8-Stream style.
public class Pipe<T> {
private T object;
private Pipe(T t) {
object = t;
}
public static<T> Pipe<T> of(T t) {
return new Pipe<>(t);
}
public <S> Pipe<S> after(Function<? super T, ? extends S> plumber) {
return new Pipe<>(object == null ? null : plumber.apply(object));
}
public T get() {
return object;
}
public T orElse(T other) {
return object == null ? other : object;
}
}
Then, the given example would become:
public String getFirstName(Person person) {
return Pipe.of(person).after(Person::getName).after(Name::getGivenName).get();
}
[EDIT]
Upon further thought, I figured out that it is actually possible to achieve the same only using standard Java 8 classes:
public String getFirstName(Person person) {
return Optional.ofNullable(person).map(Person::getName).map(Name::getGivenName).orElse(null);
}
In this case, it is even possible to choose a default value (like "<no first name>"
) instead of null
by passing it as parameter of orElse
.
Structural search and replace.
For example, search for something like:
System.out.println($string$ + $expr$);
Where $string$ is a literal, and $expr$ is an expression of type my.package.and.Class, and then replace with:
$expr$.inspect($string$);
Generally, the backtrace is used to get the stack of the current thread, but if there is a necessity to get the stack trace of all the threads, use the following command.
thread apply all bt
i wouldn't do it this way
I'd use name arrays in the form elements
so i'd get the layout
$_POST['field'][0]['name'] = 'value';
$_POST['field'][0]['price'] = 'value';
$_POST['field'][1]['name'] = 'value';
$_POST['field'][1]['price'] = 'value';
then you could do an array slice to get the amount you need
zlib
handles the deflate compression/decompression algorithm, but there is more than that in a ZIP file.
You can try libzip. It is free, portable and easy to use.
UPDATE: Here I attach quick'n'dirty example of libzip, with all the error controls ommited:
#include <zip.h>
int main()
{
//Open the ZIP archive
int err = 0;
zip *z = zip_open("foo.zip", 0, &err);
//Search for the file of given name
const char *name = "file.txt";
struct zip_stat st;
zip_stat_init(&st);
zip_stat(z, name, 0, &st);
//Alloc memory for its uncompressed contents
char *contents = new char[st.size];
//Read the compressed file
zip_file *f = zip_fopen(z, name, 0);
zip_fread(f, contents, st.size);
zip_fclose(f);
//And close the archive
zip_close(z);
//Do something with the contents
//delete allocated memory
delete[] contents;
}
To differentiate the routes, try adding a constraint that id must be numeric:
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
constraints: new { id = @"\d+" }, // Only matches if "id" is one or more digits.
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
MongoDB has some issues with licensing to businesses, I am not sure of the details but our legal department told us in no certain terms that we were not allowed to use MongoDB in any of our products.
To rename an image, you give it a new tag, and then remove the old tag using the ‘rmi’ command:
$ docker tag $ docker rmi
This second step is scary, as ‘rmi’ means “remove image”. However, docker won’t actually remove the image if it has any other tags. That is, if you were to immediately follow this with: docker rmi , then it would actually remove the image (assuming there are no other tags assigned to the image)
Theoretically, yes. Practice, not. Most kernels (incl. linux) doesn't allow you a second bind()
to an already allocated port. It weren't a really big patch to make this allowed.
Conceptionally, we should differentiate between socket and port. Sockets are bidirectional communication endpoints, i.e. "things" where we can send and receive bytes. It is a conceptional thing, there is no such field in a packet header named "socket".
Port is an identifier which is capable to identify a socket. In case of the TCP, a port is a 16 bit integer, but there are other protocols as well (for example, on unix sockets, a "port" is essentially a string).
The main problem is the following: if an incoming packet arrives, the kernel can identify its socket by its destination port number. It is a most common way, but it is not the only possibility:
Because you are working on an application server, it will be able to do that.
Make sure pom.xml is placed properly in Project folder. and not inside target folder or any where else.
Looks like pom.xml is not relatively aligned.
history.go(-1) this is a possible solution to the problem but it does not work in incognito mode as history is not maintained by the browser in this mode.
Both unix2dos and dos2unix is available in windows with gitbash. You can use the following command to perform UNIX(LF) -> DOS(CRLF) conversion. Hence, you will not get the warning.
unix2dos filename
or
dos2unix -D filename
But, don't run this command on any existing CRLF file, then you will get empty newlines every second line.
dos2unix -D filename
will not work with every operating system. Please check this link for compatibility.
If for some reason you need to force the command then use --force
. If it says invalid then use -f
.
Not really anything to do with jQuery, but if you want to trim a pattern from a string, then use a regular expression:
<textarea id="ta0"></textarea>
<button onclick="
var ta = document.getElementById('ta0');
var text = 'some<br>text<br />to<br/>replace';
var re = /<br *\/?>/gi;
ta.value = text.replace(re, '\n');
">Add stuff to text area</button>
This is similar to some of the other answers, but is compact and avoids the conversion to dictionary if you already have a list.
Given a ComboBox
"combobox" on a windows form and a class SomeClass
with the string
type property Name
,
List<SomeClass> list = new List<SomeClass>();
combobox.DisplayMember = "Name";
combobox.DataSource = list;
Which means that combobox.SelectedItem
is a SomeClass
object from list
, and each item in combobox
will be displayed using its property Name
.
You can read the selected item using
SomeClass someClass = (SomeClass)combobox.SelectedItem;
// We can apply `slice` from `Array.prototype`:
Array.prototype.slice.call([]); //-> []
// Since `slice` is available on an array's prototype chain,
'slice' in []; //-> true
[].slice === Array.prototype.slice; //-> true
// … we can just invoke it directly:
[].slice(); //-> []
// `arguments` has no `slice` method
'slice' in arguments; //-> false
// … but we can apply it the same way:
Array.prototype.slice.call(arguments); //-> […]
// In fact, though `slice` belongs to `Array.prototype`,
// it can operate on any array-like object:
Array.prototype.slice.call({0: 1, length: 1}); //-> [1]
NSArray *array = [NSArray arrayWithObjects:@"One",@"Two",@"Three", nil];
NSString *stringFromArray = [array componentsJoinedByString:@" "];
The first line initializes an array with objects. The second line joins all elements of that array by adding the string inside the "" and returns a string.
I almost always use curly-braces; however, in some cases where I'm writing tests, I do keyword packing/unpacking, and in these cases dict() is much more maintainable, as I don't need to change:
a=1,
b=2,
to:
'a': 1,
'b': 2,
It also helps in some circumstances where I think I might want to turn it into a namedtuple or class instance at a later time.
In the implementation itself, because of my obsession with optimisation, and when I don't see a particularly huge maintainability benefit, I'll always favour curly-braces.
In tests and the implementation, I would never use dict() if there is a chance that the keys added then, or in the future, would either:
dict(1foo=2)
raises a SyntaxError)Just use substring: "apple".substring(3);
will return le
My personal preference is to delete the branch name after I’m done with a topic branch.
Instead of trying to use the branch name to explain the meaning of the branch, I start the subject line of the commit message in the first commit on that branch with “Branch:” and include further explanations in the body of the message if the subject does not give me enough space.
The branch name in my use is purely a handle for referring to a topic branch while working on it. Once work on the topic branch has concluded, I get rid of the branch name, sometimes tagging the commit for later reference.
That makes the output of git branch
more useful as well: it only lists long-lived branches and active topic branches, not all branches ever.
For a perfectly dynamic solution, this is achievable by combining a cursor and a temp table. With this solution you do not need to know the starting position nor the length, and it is expandable without having to add any OR's to your SQL query.
For this example, let's say you want to select the ID, Details & creation date from a table where a certain list of text is inside 'Details'.
First create a table FilterTable with the search strings in a column called Search.
As the question starter requested:
insert into [DATABASE].dbo.FilterTable
select 'M510' union
select 'M615' union
select 'M515' union
select 'M612'
Then you can filter your data as following:
DECLARE @DATA NVARCHAR(MAX)
CREATE TABLE #Result (ID uniqueIdentifier, Details nvarchar(MAX), Created datetime)
DECLARE DataCursor CURSOR local forward_only FOR
SELECT '%' + Search + '%'
FROM [DATABASE].dbo.FilterTable
OPEN DataCursor
FETCH NEXT FROM DataCursor INTO @DATA
WHILE @@FETCH_STATUS = 0
BEGIN
insert into #Result
select ID, Details, Created
from [DATABASE].dbo.Table (nolock)
where Details like @DATA
FETCH NEXT FROM DataCursor INTO @DATA
END
CLOSE DataCursor
DEALLOCATE DataCursor
select * from #Result
drop table #Result
Hope this helped
While
constructs are terminated not with an End While
but with a Wend
.
While counter < 20
counter = counter + 1
Wend
Note that this information is readily available in the documentation; just press F1. The page you link to deals with Visual Basic .NET, not VBA. While (no pun intended) there is some degree of overlap in syntax between VBA and VB.NET, one can't just assume that the documentation for the one can be applied directly to the other.
Also in the VBA help file:
Tip The
Do...Loop
statement provides a more structured and flexible way to perform looping.
You can try 'onbeforeunload
' event.
Also take a look at this-
For me
Adding this line
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
Before this line.
<script id="microloader" type="text/javascript" src=".sencha/app/microloader/development.js"></script>
worked
You have two options:
Define a named class. Pass your parameter to the constructor of the named class.
Have your anonymous class close over your "parameter". Be sure to mark it as final
.
Ok, I'm probably late to the party, BUT...
THERE'S NO NEED TO RESIZE THE COLUMN IN YOUR CASE!
Postgres, unlike some other databases, is smart enough to only use just enough space to fit the string (even using compression for longer strings), so even if your column is declared as VARCHAR(255) - if you store 40-character strings in the column, the space usage will be 40 bytes + 1 byte of overhead.
The storage requirement for a short string (up to 126 bytes) is 1 byte plus the actual string, which includes the space padding in the case of character. Longer strings have 4 bytes of overhead instead of 1. Long strings are compressed by the system automatically, so the physical requirement on disk might be less. Very long values are also stored in background tables so that they do not interfere with rapid access to shorter column values.
(http://www.postgresql.org/docs/9.0/interactive/datatype-character.html)
The size specification in VARCHAR is only used to check the size of the values which are inserted, it does not affect the disk layout. In fact, VARCHAR and TEXT fields are stored in the same way in Postgres.
Now, if the repository is already existing on a remote machine, and you do not have anything locally, you do git clone instead.
The URL format is simple, it is PROTOCOL:/[user@]remoteMachineAddress/path/to/repository.git
For example, cloning a repository on a machine to which you have SSH access using the "dev" user, residing in /srv/repositories/awesomeproject.git and that machine has the ip 10.11.12.13 you do:
git clone ssh://[email protected]/srv/repositories/awesomeproject.git
Please take following steps:
As other friends mentioned, you should make a directory first for your database data to be stored. This folder could be something like:
C:\mongo-data
From command line navigate to where you have installed mongodb and where mongod.exe resides. In my case the full path is:
C:\Program Files\MongoDB\Server\3.4\bin
From here run mongod.exe and pass it the path to the folder you created in step one using the flag --dbpath as follows:
mongod.exe --dbpath "C:\mongo-data"
Please Note: If you are on windows it is necessary to use double-quotes ("") in the above to run properly.
In this way you will get something like the following:
2017-06-14T12:45:59.892+0430 I NETWORK [thread1] waiting for connections on port 27017
If you use single quotes (' ') on windows, you will get:
2017-06-14T01:13:45.965-0700 I CONTROL [initandlisten] shutting down with code:100
Hope it helps to resolve the issue.
Just use the --include
parameter, like this:
grep -inr --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP [email protected]
that should do what you want.
To take the explanation from HoldOffHunger's answer below:
grep
: command
-r
: recursively
-i
: ignore-case
-n
: each output line is preceded by its relative line number in the file
--include \*.cpp
: all *.cpp: C++ files (escape with \ just in case you have a directory with asterisks in the filenames)
./
: Start at current directory.
Use open(file, mode)
for files.
The mode is a variant of 'r' for read, 'w' for write, and possibly 'b' appended (e.g., 'rb') to open binary files. See the link below.
Use open
with readline()
or readlines()
. The former will return a line at a time, while the latter returns a list of the lines.
Use split(delimiter)
to split on the comma.
Lastly, you need to cast each item to an integer: int(foo)
. You'll probably want to surround your cast with a try block followed by except ValueError
as in the link below.
You can also use 'multiple assignment' to assign a and b at once:
>>>a, b = map(int, "2342342,2234234".split(","))
>>>print a
2342342
>>>type(a)
<type 'int'>
A "sort merge" join is performed by sorting the two data sets to be joined according to the join keys and then merging them together. The merge is very cheap, but the sort can be prohibitively expensive especially if the sort spills to disk. The cost of the sort can be lowered if one of the data sets can be accessed in sorted order via an index, although accessing a high proportion of blocks of a table via an index scan can also be very expensive in comparison to a full table scan.
A hash join is performed by hashing one data set into memory based on join columns and reading the other one and probing the hash table for matches. The hash join is very low cost when the hash table can be held entirely in memory, with the total cost amounting to very little more than the cost of reading the data sets. The cost rises if the hash table has to be spilled to disk in a one-pass sort, and rises considerably for a multipass sort.
(In pre-10g, outer joins from a large to a small table were problematic performance-wise, as the optimiser could not resolve the need to access the smaller table first for a hash join, but the larger table first for an outer join. Consequently hash joins were not available in this situation).
The cost of a hash join can be reduced by partitioning both tables on the join key(s). This allows the optimiser to infer that rows from a partition in one table will only find a match in a particular partition of the other table, and for tables having n partitions the hash join is executed as n independent hash joins. This has the following effects:
You should note that hash joins can only be used for equi-joins, but merge joins are more flexible.
In general, if you are joining large amounts of data in an equi-join then a hash join is going to be a better bet.
This topic is very well covered in the documentation.
http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/optimops.htm#i51523
12.1 docs: https://docs.oracle.com/database/121/TGSQL/tgsql_join.htm
Correct syntax looks like this. See MSDN.
SELECT *
FROM [FAEB].[dbo].[ExportaComisiones] AS f
JOIN [zCredifiel].[dbo].[optPerson] AS p
ON p.vTreasuryId COLLATE Latin1_General_CI_AS = f.RFC COLLATE Latin1_General_CI_AS
So you want to split on spaces, and on commas and periods that aren't surrounded by numbers. This should work:
r" |(?<![0-9])[.,](?![0-9])"
namespace: modules are namespaces...which don't exist in java ;)
I also switched from Java and python to Ruby, I remember had exactly this same question...
So the simplest answer is that module is a namespace, which doesn't exist in Java. In java the closest mindset to namespace is a package.
So a module in ruby is like what in java:
class? No
interface? No
abstract class? No
package? Yes (maybe)
static methods inside classes in java: same as methods inside modules in ruby
In java the minimum unit is a class, you can't have a function outside of a class. However in ruby this is possible (like python).
So what goes into a module?
classes, methods, constants. Module protects them under that namespace.
No instance: modules can't be used to create instances
Mixed ins: sometimes inheritance models are not good for classes, but in terms of functionality want to group a set of classes/ methods/ constants together
Rules about modules in ruby:
- Module names are UpperCamelCase
- constants within modules are ALL CAPS (this rule is the same for all ruby constants, not specific to modules)
- access methods: use . operator
- access constants: use :: symbol
simple example of a module:
module MySampleModule
CONST1 = "some constant"
def self.method_one(arg1)
arg1 + 2
end
end
how to use methods inside a module:
puts MySampleModule.method_one(1) # prints: 3
how to use constants of a module:
puts MySampleModule::CONST1 # prints: some constant
Some other conventions about modules:
Use one module in a file (like ruby classes, one class per ruby file)
I believe this has been answered in some sections already, just test with gmail for your "MAIL_HOST" instead and don't forget to clear cache. Setup like below: Firstly, you need to setup 2 step verification here google security. An App Password link will appear and you can get your App Password to insert into below "MAIL_PASSWORD". More info on getting App Password here
MAIL_DRIVER=smtp
[email protected]
MAIL_FROM_NAME=DomainName
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=YOUR_GMAIL_CREATED_APP_PASSWORD
MAIL_ENCRYPTION=tls
Clear cache with:
php artisan config:cache
If all you need to do is to turn file arguments.txt
with contents
arg1
arg2
argN
into my_command arg1 arg2 argN
then you can simply use xargs
:
xargs -a arguments.txt my_command
You can put additional static arguments in the xargs
call, like xargs -a arguments.txt my_command staticArg
which will call my_command staticArg arg1 arg2 argN
For new projects, I've started having every class I write extend the same base class where I can put all the utility methods that are annoyingly missing from Java like this one, the equivalent for collections (tired of writing list != null && ! list.isEmpty()), null-safe equals, etc. I still use Apache Commons for the implementation but this saves a small amount of typing and I haven't seen any negative effects.
sudo apt-get install curl-devel
sudo apt-get install libcurl-dev
(will install the default alternative)
OR
sudo apt-get install libcurl4-openssl-dev
(the OpenSSL variant)
OR
sudo apt-get install libcurl4-gnutls-dev
(the gnutls variant)
Put fragment name before the activity
Intent mIntent = new Intent(SigninFragment.this.getActivity(),MusicHome.class);
Explicit access to module level variables by accessing them explicity on the module
In short: The technique described here is the same as in steveha's answer, except, that no artificial helper object is created to explicitly scope variables. Instead the module object itself is given a variable pointer, and therefore provides explicit scoping upon access from everywhere. (like assignments in local function scope).
Think of it like self for the current module instead of the current instance !
# db.py
import sys
# this is a pointer to the module object instance itself.
this = sys.modules[__name__]
# we can explicitly make assignments on it
this.db_name = None
def initialize_db(name):
if (this.db_name is None):
# also in local function scope. no scope specifier like global is needed
this.db_name = name
# also the name remains free for local use
db_name = "Locally scoped db_name variable. Doesn't do anything here."
else:
msg = "Database is already initialized to {0}."
raise RuntimeError(msg.format(this.db_name))
As modules are cached and therefore import only once, you can import db.py
as often on as many clients as you want, manipulating the same, universal state:
# client_a.py
import db
db.initialize_db('mongo')
# client_b.py
import db
if (db.db_name == 'mongo'):
db.db_name = None # this is the preferred way of usage, as it updates the value for all clients, because they access the same reference from the same module object
# client_c.py
from db import db_name
# be careful when importing like this, as a new reference "db_name" will
# be created in the module namespace of client_c, which points to the value
# that "db.db_name" has at import time of "client_c".
if (db_name == 'mongo'): # checking is fine if "db.db_name" doesn't change
db_name = None # be careful, because this only assigns the reference client_c.db_name to a new value, but leaves db.db_name pointing to its current value.
As an additional bonus I find it quite pythonic overall as it nicely fits Pythons policy of Explicit is better than implicit.
Python is almost a functional language. It's "functional lite".
It has extra features, so it isn't pure enough for some.
It also lacks some features, so it isn't complete enough for some.
The missing features are relatively easy to write. Check out posts like this on FP in Python.
This is the code that worked for me:
jQuery('document').ready(function()
{
$(".navbar-header button").click(function(event) {
if ($(".navbar-collapse").hasClass('in'))
{ $(".navbar-collapse").slideUp(); }
});})
EDIT : this answer used to claim that it isn't possible to center an absolutely positioned element with margin: auto;
, but this simply isn't true. Because this is the most up-voted and accepted answer, I guessed I'd just change it to be correct.
When you apply the following CSS to an element
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
And then give the element a fixed width and height, such as 200px or 40%, the element will center itself.
Here's a Fiddle that demonstrates the effect.
The colorbar has to have its own axes. However, you can create an axes that overlaps with the previous one. Then use the cax
kwarg to tell fig.colorbar
to use the new axes.
For example:
import numpy as np
import matplotlib.pyplot as plt
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots()
cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])
im = ax.imshow(data, cmap='gist_earth')
fig.colorbar(im, cax=cax, orientation='horizontal')
plt.show()
If your script always requires an Administrator's privileges then:
runas /user:Administrator "python your_script.py"
If you have a small number of values to auto complete, you can simply add them in xaml. Typing will invoke auto-complete, plus you have dropdowns too.
<ComboBox Text="{Binding CheckSeconds, UpdateSourceTrigger=PropertyChanged}"
IsEditable="True">
<ComboBoxItem Content="60"/>
<ComboBoxItem Content="120"/>
<ComboBoxItem Content="180"/>
<ComboBoxItem Content="300"/>
<ComboBoxItem Content="900"/>
</ComboBox>
Similar to some of the solutions posted, but in my case I did the status bar transparent and fix the position of the action bar with some negative margin
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Color.TRANSPARENT);
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) toolbar.getLayoutParams();
lp.setMargins(0, -getStatusBarHeight(), 0, 0);
}
And I used in the toolbar and the root view
android:fitsSystemWindows="true"
Here's what I've been doing.
View:
<input type="checkbox" name="applyChanges" />
Controller:
var checkBox = Request.Form["applyChanges"];
if (checkBox == "on")
{
...
}
I found the Html.* helper methods not so useful in some cases, and that I was better off doing it in plain old HTML. This being one of them, the other one that comes to mind is radio buttons.
Edit: this is on Preview 5, obviously YMMV between versions.
The lack of a Linux-like backtick/backquote facility is a major annoyance of the pre-PowerShell world. Using backquotes via for-loops is not at all cosy. So we need kinda of setvar myvar cmd-line
command.
In my %path%
I have a dir with a number of bins and batches to cope with those Win shortcomings.
One batch I wrote is:
:: setvar varname cmd
:: Set VARNAME to the output of CMD
:: Triple escape pipes, eg:
:: setvar x dir c:\ ^^^| sort
:: -----------------------------
@echo off
SETLOCAL
:: Get command from argument
for /F "tokens=1,*" %%a in ("%*") do set cmd=%%b
:: Get output and set var
for /F "usebackq delims=" %%a in (`%cmd%`) do (
ENDLOCAL
set %1=%%a
)
:: Show results
SETLOCAL EnableDelayedExpansion
echo %1=!%1!
So in your case, you would type:
> setvar text echo Hello
text=Hello
The script informs you of the results, which means you can:
> echo text var is now %text%
text var is now Hello
You can use whatever command:
> setvar text FIND "Jones" names.txt
What if the command you want to pipe to some variable contains itself a pipe?
Triple escape it, ^^^|
:
> setvar text dir c:\ ^^^| find "Win"
I had the same error but I am using Perforce version control. Here's how I fixed it.
My original reply was factually incorrect and I'm glad it was removed. The code below will work under the following conditions a) you know that nobody else modified the sequence b) the sequence was modified by your session. In my case, I encountered a similar issue where I was calling a procedure which modified a value and I'm confident the assumption is true.
SELECT mysequence.CURRVAL INTO v_myvariable FROM DUAL;
Sadly, if you didn't modify the sequence in your session, I believe others are correct in stating that the NEXTVAL is the only way to go.