If you still don't know, you can get back the original object by:
alert($("#deviceTypeRoot")[0] == $("#deviceTypeRoot")[0]); //True
alert($("#deviceTypeRoot")[0] === $("#deviceTypeRoot")[0]);//True
because $("#deviceTypeRoot")
also returns an array of objects which the selector has selected.
This query will give you a list of email addresses and how many times they're used, with the most used addresses first.
SELECT email,
count(*) AS c
FROM TABLE
GROUP BY email
HAVING c > 1
ORDER BY c DESC
If you want the full rows:
select * from table where email in (
select email from table
group by email having count(*) > 1
)
You Can Wrap your widget with Flexible Widget and than you can set property of Text using overflow property of Text Widget. you have to set TextOverflow.clip for example:-
Flexible
(child: new Text("This is Dummy Long Text",
style: TextStyle(
fontFamily: "Roboto",
color: Colors.black,
fontSize: 10.0,
fontWeight: FontWeight.bold),
overflow: TextOverflow.clip,),)
hope this help someone :)
All previous answers are correct, here is one more and easy way to do it. For example, create a Dict data structure to serialize and deserialize an object
(Notice None is Null in python and I'm intentionally using this to demonstrate how you can store null and convert it to json null)
import json
print('serialization')
myDictObj = { "name":"John", "age":30, "car":None }
##convert object to json
serialized= json.dumps(myDictObj, sort_keys=True, indent=3)
print(serialized)
## now we are gonna convert json to object
deserialization=json.loads(serialized)
print(deserialization)
I am using MySQL 5.5.40. This version has the option --all-databases
mysqldump -u<username> -p<password> --all-databases --events > /tmp/all_databases__`date +%d_%b_%Y_%H_%M_%S`.sql
This command will create a complete backup of all databases in MySQL server to file named to current date-time.
Now that flexbox is supported in all modern browsers, something like this seems like an easier approach to me.
<style>
label {
display: flex;
align-items: center;
}
input[type=radio], input[type=checkbox]{
flex: none;
}
</style>
<form>
<div>
<label><input type="checkbox" /> Label text</label>
</div>
</form>
Here's the complete prefixed version demo:
label {_x000D_
display: -webkit-box;_x000D_
display: -webkit-flex;_x000D_
display: -ms-flexbox;_x000D_
display: flex;_x000D_
-webkit-box-align: center;_x000D_
-webkit-align-items: center;_x000D_
-ms-flex-align: center;_x000D_
align-items: center;_x000D_
}_x000D_
input[type=radio], _x000D_
input[type=checkbox] {_x000D_
-webkit-box-flex: 0;_x000D_
-webkit-flex: none;_x000D_
-ms-flex: none;_x000D_
flex: none;_x000D_
margin-right: 10px; _x000D_
}_x000D_
/* demo only (to show alignment) */_x000D_
form {_x000D_
max-width: 200px_x000D_
}
_x000D_
<form>_x000D_
<label>_x000D_
<input type="radio" checked>_x000D_
I am an aligned radio and label_x000D_
</label>_x000D_
<label>_x000D_
<input type="checkbox" checked>_x000D_
I am an aligned checkbox and label_x000D_
</label>_x000D_
</form>
_x000D_
On the documentation:
http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#mat
It says:
(...) if you know the matrix element type, e.g. it is float, then you can use at<>() method
That is, you can use:
Mat M(100, 100, CV_64F);
cout << M.at<double>(0,0);
Maybe it is easier to use the Mat_
class. It is a template wrapper for Mat
.
Mat_
has the operator()
overloaded in order to access the elements.
How about using "after" instead of "append".
$("#content ul li:last").after('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');
".after()" can insert content, specified by the parameter, after each element in the set of matched elements.
Another way using template reference variable and ViewChild, as proposed by Frelseren:
import { ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<div>
<input type="file" #fileInput/>
</div>
`
})
export class AppComponent {
@ViewChild("fileInput") fileInputVariable: any;
randomMethod() {
const files = this.fileInputVariable.nativeElement.files;
console.log(files);
}
}
This can be accomplished with a simple VBA function. Excel has support for a Worksheet Change Sub which can be programmed to put a date in a related column every time it fires.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 2 And Target.Offset(0, 3).Value = "" Then
Target.Offset(0, 3) = Format(Now(), "HH:MM:SS")
End If
End Sub
A quick explanation. The following "if" statement checks for two things: (1) if it is the second column that changed (Column B), and (2) if the cell 3 columns over (Column E) is currently empty.
If Target.Column = 2 And Target.Offset(0, 3).Value = "" Then
If both conditions are true, then it puts the date into the cell in Column E with the NOW()
function.
Target.Offset(0, 3) = Format(Now(), "HH:MM:SS")
var formData = new FormData;
var alphaArray = ['A', 'B', 'C','D','E'];
for (var i = 0; i < alphaArray.length; i++) {
formData.append('listOfAlphabet', alphaArray [i]);
}
And In your request you will get array of alphabets.
If you're dealing with a Java character array (such as password characters that you read from the console), you can convert it to a JRuby string with the following Ruby code:
# GIST: "pw_from_console.rb" under "https://gist.github.com/drhuffman12"
jconsole = Java::java.lang.System.console()
password = jconsole.readPassword()
ruby_string = ''
password.to_a.each {|c| ruby_string << c.chr}
# .. do something with 'password' variable ..
puts "password_chars: #{password_chars.inspect}"
puts "password_string: #{password_string}"
See also "https://stackoverflow.com/a/27628738/4390019" and "https://stackoverflow.com/a/27628756/4390019"
<html>
<head></head>
<body>
<script>
var a = document.createElement('a');
var linkText = document.createTextNode("my title text");
a.appendChild(linkText);
a.title = "my title text";
a.href = "http://example.com";
document.body.appendChild(a);
</script>
</body>
</html>
Here's a version that's much simpler - not sure how performant it is. Heavily based on some django snippet I found while building RGBA -> JPG + BG
support for sorl thumbnails.
from PIL import Image
png = Image.open(object.logo.path)
png.load() # required for png.split()
background = Image.new("RGB", png.size, (255, 255, 255))
background.paste(png, mask=png.split()[3]) # 3 is the alpha channel
background.save('foo.jpg', 'JPEG', quality=80)
Result @80%
Result @ 50%
I've modified your plunker to get it working via angular-xeditable:
http://plnkr.co/edit/xUDrOS?p=preview
It is common solution for inline editing - you creale hyperlinks with editable-text
directive
that toggles into <input type="text">
tag:
<a href="#" editable-text="bday.name" ng-click="myform.$show()" e-placeholder="Name">
{{bday.name || 'empty'}}
</a>
For date I used editable-date
directive that toggles into html5 <input type="date">
.
You may have 0 to many <img>
tags inside of your <div>
.
To find an element, use a .find()
.
To keep your code safe, use a .each()
.
Using .find()
and .each()
together prevents null reference errors in the case of 0 <img>
elements while also allowing for handling of multiple <img>
elements.
// Set the click handler on your div_x000D_
$("body").off("click", "#mydiv").on("click", "#mydiv", function() {_x000D_
_x000D_
// Find the image using.find() and .each()_x000D_
$(this).find("img").each(function() {_x000D_
_x000D_
var img = this; // "this" is, now, scoped to the image element_x000D_
_x000D_
// Do something with the image_x000D_
$(this).animate({_x000D_
width: ($(this).width() > 100 ? 100 : $(this).width() + 100) + "px"_x000D_
}, 500);_x000D_
_x000D_
});_x000D_
_x000D_
});
_x000D_
#mydiv {_x000D_
text-align: center;_x000D_
vertical-align: middle;_x000D_
background-color: #000000;_x000D_
cursor: pointer;_x000D_
padding: 50px;_x000D_
_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="mydiv">_x000D_
<img src="" width="100" height="100"/>_x000D_
</div>
_x000D_
Windoze-friendly Python script (because git-sweep
choked on Wesnoth repository):
#!/usr/bin/env python
# Remove merged git branches. Cross-platform way to execute:
#
# git branch --merged | grep -v master | xargs git branch -d
#
# Requires gitapi - https://bitbucket.org/haard/gitapi
# License: Public Domain
import gitapi
repo = gitapi.Repo('.')
output = repo.git_command('branch', '--merged').strip()
for branch in output.split('\n'):
branch = branch.strip()
if branch.strip(' *') != 'master':
print(repo.git_command('branch', '-d', branch).strip())
You are specifying .fixedbutton
in your CSS (a class) and specifying the id
on the element itself.
Change your CSS to the following, which will select the id
fixedbutton
#fixedbutton {
position: fixed;
bottom: 0px;
right: 0px;
}
Here is the way I did it. But I want to mentoin that I am not so shure about the regex. But It should work thou :)
$pattern = "#((http|https)://(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|”|\"|'|:|\<|$|\.\s)#i";
$text = preg_replace_callback($pattern,function($m){
return "<a href=\"$m[1]\" target=\"_blank\">$m[1]</a>$m[4]";
},
$text);
This way you won't need the eval marker on your pattern.
Hope it helps :)
Swift 3 version with the new Date
object instead NSDate
:
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd,yyyy"
let date: Date? = dateFormatterGet.date(from: "2017-02-14 17:24:26")
print(dateFormatter.string(from: date!))
EDIT: after mitul-nakum suggestion
jPlayer is a free and open source HTML5 Audio and Video library that you may find useful. It has support for playlists built in: http://jplayer.org/
Data view is good Feature of data table . We can filter the data table as per our requirements using data view . Below Functions is After binding data table to list box data source then filter by text box control . ( this condition you can change as per your needs .Contains(txtSearch.Text.Trim()) )
Private Sub BindClients()
okcl = 0
sql = "Select * from Client Order By cname"
Dim dacli As New SqlClient.SqlDataAdapter
Dim cmd As New SqlClient.SqlCommand()
cmd.CommandText = sql
cmd.CommandType = CommandType.Text
dacli.SelectCommand = cmd
dacli.SelectCommand.Connection = Me.sqlcn
Dim dtcli As New DataTable
dacli.Fill(dtcli)
dacli.Fill(dataTableClients)
lstboxc.DataSource = dataTableClients
lstboxc.DisplayMember = "cname"
lstboxc.ValueMember = "ccode"
okcl = 1
If dtcli.Rows.Count > 0 Then
ccode = dtcli.Rows(0)("ccode")
Call ClientDispData1()
End If
End Sub
Private Sub FilterClients()
Dim query As EnumerableRowCollection(Of DataRow) = From dataTableClients In
dataTableClients.AsEnumerable() Where dataTableClients.Field(Of String)
("cname").Contains(txtSearch.Text.Trim()) Order By dataTableClients.Field(Of
String)("cname") Select dataTableClients
Dim dataView As DataView = query.AsDataView()
lstboxc.DataSource = dataView
lstboxc.DisplayMember = "cname"
lstboxc.ValueMember = "ccode"
okcl = 1
If dataTableClients.Rows.Count > 0 Then
ccode = dataTableClients.Rows(0)("ccode")
Call ClientDispData1()
End If
End Sub
You can also add
<Resource
auth="Container"
driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
maxActive="20"
maxIdle="10"
maxWait="-1"
name="ds/flexeraDS"
type="javax.sql.DataSource"
url="jdbc:derby:flexeraDB;create=true"
/>
under META-INF/context.xml
file (This will be only at application level).
Using alpha 28, I accomplished programmatically subscribing to event emitters by way of the eventEmitter.toRx().subscribe(..)
method. As it is not intuitive, it may perhaps change in a future release.
In one situation involving a multi-domain application, app.request.getHttpHost
helped me out. It returns something like example.com
or subdomain.example.com
(or example.com:8000
when the port is not standard). This was in Symfony 3.4.
There's still no simple answer. It depends on your scenario. MSDN has documentation to help you decide.
There are other options covered here. Instead of storing in the file system directly or in a BLOB, you can use the FileStream or File Table in SQL Server 2012. The advantages to File Table seem like a no-brainier (but admittedly I have no personal first-hand experience with them.)
The article is definitely worth a read.
As @David Heffeman indicates the recommendation is to use .yaml
when possible, and the recommendation has been that way since September 2006.
That some projects use .yml
is mostly because of ignorance of the implementers/documenters: they wanted to use YAML because of readability, or some other feature not available in other formats, were not familiar with the recommendation and and just implemented what worked, maybe after looking at some other project/library (without questioning whether what was done is correct).
The best way to approach this is to be rigorous when creating new files (i.e. use .yaml
) and be permissive when accepting input (i.e. allow .yml
when you encounter it), possible automatically upgrading/correcting these errors when possible.
The other recommendation I have is to document the argument(s) why you have to use .yml
, when you think you have to. That way you don't look like an ignoramus, and give others the opportunity to understand your reasoning. Of course "everybody else is doing it" and "On Google .yml
has more pages than .yaml
" are not arguments, they are just statistics about the popularity of project(s) that have it wrong or right (with regards to the extension of YAML files). You can try to prove that some projects are popular, just because they use a .yml
extension instead of the correct .yaml
, but I think you will be hard pressed to do so.
Some projects realize (too late) that they use the incorrect extension (e.g. originally docker-compose
used .yml
, but in later versions started to use .yaml
, although they still support .yml
). Others still seem ignorant about the correct extension, like AppVeyor early 2019, but allow you to specify the configuration file for a project, including extension. This allows you to get the configuration file out of your face as well as giving it the proper extension: I use .appveyor.yaml
instead of appveyor.yml
for building the windows wheels of my YAML parser for Python).
On the other hand:
The Yaml (sic!) component of Symfony2 implements a selected subset of features defined in the YAML 1.2 version specification.
So it seems fitting that they also use a subset of the recommended extension.
UPDATE
The Google maps API v2 is now installed on the latest Google system images (api:19 ARM or x86).
So your application should just work with the new images. There is no need to install these files.
I've been trying to run an Android Google Maps V2 application under an emulator and once I finally got Google Play Services running, I updated my SDK to Google Play Services revision 4, and my emulator wouldn't run my application any more.
I have now worked out how to update my emulator from my transformer tablet. (You won't need a tablet as you can download the files below.)
I used Titanium Backup to backup my Asus Eee Pad Transformer (TF101) and then grabbed the com.android.vending and the com.google.android.gms APK files from the backup.
I installed these on an emulator configured with platform: 4.1.2, API Level: 16, CPU Intel/Atom x86) and my Google Maps V2 application works again.
That was all .. none of the other steps regarding /system/app were required.
My application only uses the Google Maps API, no doubt, more steps are required if you use other Google Play services.
New files for latest Google Play services:
Same instructions as before: Create a new emulator with any CPU/ABI, a non-Google API target (versions 10-19 work) and GPU emulation on or off, and then install the files:
adb install com.android.vending-20140218.apk
adb install com.google.android.gms-20140218.apk
If you are upgrading an existing emulator then you might need to uninstall previous versions by:
adb uninstall com.android.vending
adb uninstall com.google.android.gms
That's all.
I usually manually set the port that I am listening on in the app.js
file (assuming you are using express.js
var server = app.listen(8080, function() {
console.log('Ready on port %d', server.address().port);
});
This will log Ready on port 8080
to your console.
C99 N1256 draft
There are two different uses of character string literals:
Initialize char[]
:
char c[] = "abc";
This is "more magic", and described at 6.7.8/14 "Initialization":
An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.
So this is just a shortcut for:
char c[] = {'a', 'b', 'c', '\0'};
Like any other regular array, c
can be modified.
Everywhere else: it generates an:
So when you write:
char *c = "abc";
This is similar to:
/* __unnamed is magic because modifying it gives UB. */
static char __unnamed[] = "abc";
char *c = __unnamed;
Note the implicit cast from char[]
to char *
, which is always legal.
Then if you modify c[0]
, you also modify __unnamed
, which is UB.
This is documented at 6.4.5 "String literals":
5 In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence [...]
6 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
6.7.8/32 "Initialization" gives a direct example:
EXAMPLE 8: The declaration
char s[] = "abc", t[3] = "abc";
defines "plain" char array objects
s
andt
whose elements are initialized with character string literals.This declaration is identical to
char s[] = { 'a', 'b', 'c', '\0' }, t[] = { 'a', 'b', 'c' };
The contents of the arrays are modifiable. On the other hand, the declaration
char *p = "abc";
defines
p
with type "pointer to char" and initializes it to point to an object with type "array of char" with length 4 whose elements are initialized with a character string literal. If an attempt is made to usep
to modify the contents of the array, the behavior is undefined.
GCC 4.8 x86-64 ELF implementation
Program:
#include <stdio.h>
int main(void) {
char *s = "abc";
printf("%s\n", s);
return 0;
}
Compile and decompile:
gcc -ggdb -std=c99 -c main.c
objdump -Sr main.o
Output contains:
char *s = "abc";
8: 48 c7 45 f8 00 00 00 movq $0x0,-0x8(%rbp)
f: 00
c: R_X86_64_32S .rodata
Conclusion: GCC stores char*
it in .rodata
section, not in .text
.
Note however that the default linker script puts .rodata
and .text
in the same segment, which has execute but no write permission. This can be observed with:
readelf -l a.out
which contains:
Section to Segment mapping:
Segment Sections...
02 .text .rodata
If we do the same for char[]
:
char s[] = "abc";
we obtain:
17: c7 45 f0 61 62 63 00 movl $0x636261,-0x10(%rbp)
so it gets stored in the stack (relative to %rbp
).
Assuming that yourObject.toString() returns "true" or "false", you can try
boolean b = Boolean.valueOf(yourObject.toString())
The other possible solution is to use lastIndexOf
where it will look for character or String from backward.
In my scenario, I had following String
and I had to extract <<UserName>>
1QAJK-WKJSH_MyApplication_Extract_<<UserName>>.arc
So, indexOf
and StringUtils.substringBetween
was not helpful as they start looking for character from beginning.
So, I used lastIndexOf
String str = "1QAJK-WKJSH_MyApplication_Extract_<<UserName>>.arc";
String userName = str.substring(str.lastIndexOf("_") + 1, str.lastIndexOf("."));
And, it gives me
<<UserName>>
just make sure how you are using image through css background use backgroud image position like background: url(your image path) no-repeat center center; automatically it wil align center to the screen.
I ran into this error message whilst trying to commit some files.
Simply running git fetch
then trying my commit again worked for me.
This worked for me:
position: absolute;
left: 50%;
transform: translateX(-50%);
Besides the already stated answers about using Vector, Vector also has a bunch of methods around enumeration and element retrieval which are different than the List interface, and developers (especially those who learned Java before 1.2) can tend to use them if they are in the code. Although Enumerations are faster, they don't check if the collection was modified during iteration, which can cause issues, and given that Vector might be chosen for its syncronization - with the attendant access from multiple threads, this makes it a particularly pernicious problem. Usage of these methods also couples a lot of code to Vector, such that it won't be easy to replace it with a different List implementation.
For change button style
1st: define resource styles
<Window.Resources>
<Style x:Key="OvergroundIn" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid Background="#FF16832F">
<ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid Background="#FF06731F">
<ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
<Style x:Key="OvergroundOut" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid Background="#FFF35E5E">
<ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid Background="#FFE34E4E">
<ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
2nd define button code
<Border Grid.Column="2" BorderBrush="LightGray" BorderThickness="2" CornerRadius="3" Margin="2,2,2,2" >
<Button Name="btnFichar" BorderThickness="0" Click="BtnFichar_Click">
<Button.Content>
<Grid>
<TextBlock Margin="0,7,0,7" TextAlignment="Center">Fichar</TextBlock>
</Grid>
</Button.Content>
</Button>
</Border>
3th code behind
public void ShowStatus()
{
switch (((MainDto)this.DataContext).State)
{
case State.IN:
this.btnFichar.BorderBrush = new SolidColorBrush(Color.FromRgb(243, 94, 94));
this.btnFichar.Style = Resources["OvergroundIn"] as Style;
this.btnFichar.Content = "Fichar Salida";
break;
case State.OUT:
this.btnFichar.BorderBrush = new SolidColorBrush(Color.FromRgb(76, 106, 83));
this.btnFichar.Style = Resources["OvergroundOut"] as Style;
this.btnFichar.Content = "Fichar Entrada";
break;
}
}
If using 3rd Pary Libaries is ok cyclops-react defines Lazy extended collections with this functionality built in. For example we could simply write
ListX myListToParse;
ListX myFinalList = myListToParse.filter(elt -> elt != null) .map(elt -> doSomething(elt));
myFinalList is not evaluated until first access (and there after the materialized list is cached and reused).
[Disclosure I am the lead developer of cyclops-react]
Michael,
Two things:
When Jenkins connects to a computer, it goes to the sh
shell, and not the bash
shell (at least this is what I have noticed - I may be wrong). So any changes you make to $PATH in your bashrc file are not considered.
Also, any changes you make to $PATH in your local shell (one that you personally ssh into) will not show up in Jenkins.
To change the path that Jenkins uses, you have two options (AFAIK):
1) Edit your /etc/profile
file and add the paths that you want there
2) Go to the configuration page of your slave, and add environment variable PATH
, with value: $PATH:/followed-by/paths/you/want/to/add
If you use the second option, your System Information will still not show it, but your builds will see the added paths.
No. Go to database tools (for 2007) and click checkmark on the Message Bar. Then, after the message bar apears, click on Options, and then Enable. Hope this helps.
Dimitri
Here a CSS animation fork of jezzipin's Solution, to seperate code from styling.
JS:
$(window).on("scroll touchmove", function () {
$('#header_nav').toggleClass('tiny', $(document).scrollTop() > 0);
});
CSS:
.header {
width:100%;
height:100px;
background: #26b;
color: #fff;
position:fixed;
top:0;
left:0;
transition: height 500ms, background 500ms;
}
.header.tiny {
height:40px;
background: #aaa;
}
http://jsfiddle.net/sinky/S8Fnq/
On scroll/touchmove the css class "tiny" is set to "#header_nav" if "$(document).scrollTop()" is greater than 0.
CSS transition attribute animates the "height" and "background" attribute nicely.
This is a late post, but can still be effective for people in future.
Spring provides a utility BeanUtils.copyProperties(srcObj, tarObj)
which copies values from source object to target object when the names of the member variables of both classes are the same.
If there is a date conversion, (eg, String to Date) 'null' would be copied to the target object. We can then, explicitly set the values of the date as required.
The BeanUtils from Apache Common
throws an error when there is a mismatch of data-types (esp. conversion to and from Date)
Hope this helps!
In my case, I had a sequence with the same name.
A lot of the answers are providing custom examples because of the accepted answer's dependency on System.Web. From the Microsoft.AspNet.WebApi.Client NuGet package there is a UriExtensions.ParseQueryString, method that can also be used:
var uri = new Uri("https://stackoverflow.com/a/22167748?p1=6&p2=7&p3=8");
NameValueCollection query = uri.ParseQueryString();
So if you want to avoid the System.Web dependency and don't want to roll your own, this is a good option.
You should consider that a "true value" is everything except 0 and not only 1. So instead of 1=1 you should write 1<>0.
Because when you will use parameter (@param <> 0) you could have some conversion issue.
The most know is Access which translate True value on control as -1 instead of 1.
Just for the sake of fun Ill add a few that, although they are over complicated and useless, they were not mentioned :
head -c 2 <( echo 'USCAGoleta9311734.5021-120.1287855805')
echo 'USCAGoleta9311734.5021-120.1287855805' | dd bs=2 count=1 status=none
sed -e 's/^\(.\{2\}\).*/\1/;' <( echo 'USCAGoleta9311734.5021-120.1287855805')
cut -c 1-2 <( echo 'USCAGoleta9311734.5021-120.1287855805')
python -c "print(r'USCAGoleta9311734.5021-120.1287855805'[0:2])"
ruby -e 'puts "USCAGoleta9311734.5021-120.1287855805"[0..1]'
Since your pull
was unsuccessful then HEAD
(not HEAD^
) is the last "valid" commit on your branch:
git reset --hard HEAD
The other piece you want is to let their changes over-ride your changes.
Older versions of git allowed you to use the "theirs" merge strategy:
git pull --strategy=theirs remote_branch
But this has since been removed, as explained in this message by Junio Hamano (the Git maintainer). As noted in the link, instead you would do this:
git fetch origin
git reset --hard origin
You can tie it to button or on load of the page.
window.print();
No, it will not be evaluated. And this is very useful. For example, if you need to test whether a String is not null or empty, you can write:
if (str != null && !str.isEmpty()) {
doSomethingWith(str.charAt(0));
}
or, the other way around
if (str == null || str.isEmpty()) {
complainAboutUnusableString();
} else {
doSomethingWith(str.charAt(0));
}
If we didn't have 'short-circuits' in Java, we'd receive a lot of NullPointerExceptions in the above lines of code.
It's easy. If you have two or more running container, complete next steps:
docker network create myNetwork
docker network connect myNetwork web1
docker network connect myNetwork web2
Now you connect from web1 to web2 container or the other way round.
Use the internal network IP addresses which you can find by running:
docker network inspect myNetwork
Note that only internal IP addresses and ports are accessible to the containers connected by the network bridge.
So for example assuming that web1 container was started with: docker run -p 80:8888 web1
(meaning that its server is running on port 8888 internally), and inspecting myNetwork
shows that web1's IP is 172.0.0.2, you can connect from web2 to web1 using curl 172.0.0.2:8888
).
This could also some extra reasons instead of the mentioned reasons :
<form id="myform" class="form-wizard">
<h2 class="form-wizard-heading">BootStap Wizard Form</h2>
<input type="text" value=""/>
<input type="submit" id="submitButton"/>
</form>
<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary">Save changes</button>
</div>
</div>
You can launch the modal with the code below this.
$(document).ready(function(){
$("#submitButton").click(function(){
$("#myModal").modal();
});
});
I'm on a roll, just found an even simpler way to do it using the by keyword in the hist method:
df['N'].hist(by=df['Letter'])
That's a very handy little shortcut for quickly scanning your grouped data!
For future visitors, the product of this call is the following chart:
executes a command and never returns.
It's like a return
statement in a function.
If the command is not found exec
returns false.
It never returns true, because if the command is found it never returns at all.
There is also no point in returning STDOUT
, STDERR
or exit status of the command.
You can find documentation about it in perlfunc
,
because it is a function.
executes a command and your Perl script is continued after the command has finished.
The return value is the exit status of the command.
You can find documentation about it in perlfunc
.
like system
executes a command and your perl script is continued after the command has finished.
In contrary to system
the return value is STDOUT
of the command.
qx//
is equivalent to backticks.
You can find documentation about it in perlop
, because unlike system
and exec
it is an operator.
What is missing from the above is a way to execute a command asynchronously.
That means your perl script and your command run simultaneously.
This can be accomplished with open
.
It allows you to read STDOUT
/STDERR
and write to STDIN
of your command.
It is platform dependent though.
There are also several modules which can ease this tasks.
There is IPC::Open2
and IPC::Open3
and IPC::Run
, as well as
Win32::Process::Create
if you are on windows.
According to official documentation, you can set or remove the "executable" flag on any tracked file using update-index
sub-command.
To set the flag, use following command:
git update-index --chmod=+x path/to/file
To remove it, use:
git update-index --chmod=-x path/to/file
Under the hood
While this looks like the regular unix files permission system, actually it is not. Git maintains a special "mode" for each file in its internal storage:
100644
for regular files100755
for executable onesYou can visualize it using ls-file
subcommand, with --stage
option:
$ git ls-files --stage
100644 aee89ef43dc3b0ec6a7c6228f742377692b50484 0 .gitignore
100755 0ac339497485f7cc80d988561807906b2fd56172 0 my_executable_script.sh
By default, when you add a file to a repository, Git will try to honor its filesystem attributes and set the correct filemode accordingly. You can disable this by setting core.fileMode
option to false:
git config core.fileMode false
Troubleshooting
If at some point the Git filemode is not set but the file has correct filesystem flag, try to remove mode and set it again:
git update-index --chmod=-x path/to/file
git update-index --chmod=+x path/to/file
Bonus
Starting with Git 2.9, you can stage a file AND set the flag in one command:
git add --chmod=+x path/to/file
As you know the string is coming in as Encoding.Default
you could simply use:
byte[] bytes = Encoding.Default.GetBytes(myString);
myString = Encoding.UTF8.GetString(bytes);
Another thing you may have to remember: If you are using Console.WriteLine to output some strings, then you should also write Console.OutputEncoding = System.Text.Encoding.UTF8;
!!! Or all utf8 strings will be outputed as gbk...
i know this is late , but you should try redirecting to a path and not to a file ha ha
You can find a nice list of corresponding URL encoded characters on W3Schools.
+
becomes %2B
%20
You are mixing pointers and arrays. If what you want is an array, then use an array:
struct test {
static int data[10]; // array, not pointer!
};
int test::data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
If on the other hand you want a pointer, the simplest solution is to write a helper function in the translation unit that defines the member:
struct test {
static int *data;
};
// cpp
static int* generate_data() { // static here is "internal linkage"
int * p = new int[10];
for ( int i = 0; i < 10; ++i ) p[i] = 10*i;
return p;
}
int *test::data = generate_data();
The traditional way is to have a Makefile
in each of the subdirectories (part1
, part2
, etc.) allowing you to build them independently. Further, have a Makefile
in the root directory of the project which builds everything. The "root" Makefile
would look something like the following:
all:
+$(MAKE) -C part1
+$(MAKE) -C part2
+$(MAKE) -C part3
Since each line in a make target is run in its own shell, there is no need to worry about traversing back up the directory tree or to other directories.
I suggest taking a look at the GNU make manual section 5.7; it is very helpful.
foo.bars.one.counter=1
foo.bars.one.active=false
foo.bars[two].id=IdOfBarWithKeyTwo
public class Foo {
private Map<String, Bar> bars = new HashMap<>();
public Map<String, Bar> getBars() { .... }
}
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-Configuration-Binding
When you build your assembly, you can call AssemblyBuilder.SetEntryPoint
, and then get it back from the Assembly.EntryPoint
property to invoke it.
Keep in mind you'll want to use this signature, and note that it doesn't have to be named Main
:
static void Run(string[] args)
A relative URL without a scheme (http: or https:) is valid, per RFC 3986: "Uniform Resource Identifier (URI): Generic Syntax", Section 4.2. If a client chokes on it, then it's the client's fault because they're not complying with the URI syntax specified in the RFC.
Your example is valid and should work. I've used that relative URL method myself on heavily trafficked sites and have had zero complaints. Also, we test our sites in Firefox, Safari, IE6, IE7 and Opera. These browsers all understand that URL format.
Another option is using reduce()
and new Map()
to group the array. Use Spread syntax
to convert set object into an array.
var myArray = [{"group":"one","color":"red"},{"group":"two","color":"blue"},{"group":"one","color":"green"},{"group":"one","color":"black"}]_x000D_
_x000D_
var result = [...myArray.reduce((c, {group,color}) => {_x000D_
if (!c.has(group)) c.set(group, {group,color: []});_x000D_
c.get(group).color.push(color);_x000D_
return c;_x000D_
}, new Map()).values()];_x000D_
_x000D_
console.log(result);
_x000D_
Try these (reference):
clear linenum
clear filename:linenum
Pretty sure pk_OrderID is the PK of AC_Shipping_Addresses
And you are trying to insert a duplicate via the _Order.OrderNumber
Do a
select * from AC_Shipping_Addresses where pk_OrderID = 165863;
or select count(*) ....
Pretty sure you will get a row returned.
What it is telling you is you are already using pk_OrderID = 165863 and cannot have another row with that value.
if you want to not insert if there is a row
insert into table (pk, value)
select 11 as pk, 'val' as value
where not exists (select 1 from table where pk = 11)
post.capabilities.items
will still be defined because it's an empty array, if you check post.capabilities.items.length
it should work fine because 0
is falsy.
This is a base service class (ServiceBase subclass) that can be subclassed to build a windows service that can be easily installed from the command line, without installutil.exe. This solution is derived from How to make a .NET Windows Service start right after the installation?, adding some code to get the service Type using the calling StackFrame
public abstract class InstallableServiceBase:ServiceBase
{
/// <summary>
/// returns Type of the calling service (subclass of InstallableServiceBase)
/// </summary>
/// <returns></returns>
protected static Type getMyType()
{
Type t = typeof(InstallableServiceBase);
MethodBase ret = MethodBase.GetCurrentMethod();
Type retType = null;
try
{
StackFrame[] frames = new StackTrace().GetFrames();
foreach (StackFrame x in frames)
{
ret = x.GetMethod();
Type t1 = ret.DeclaringType;
if (t1 != null && !t1.Equals(t) && !t1.IsSubclassOf(t))
{
break;
}
retType = t1;
}
}
catch
{
}
return retType;
}
/// <summary>
/// returns AssemblyInstaller for the calling service (subclass of InstallableServiceBase)
/// </summary>
/// <returns></returns>
protected static AssemblyInstaller GetInstaller()
{
Type t = getMyType();
AssemblyInstaller installer = new AssemblyInstaller(
t.Assembly, null);
installer.UseNewContext = true;
return installer;
}
private bool IsInstalled()
{
using (ServiceController controller =
new ServiceController(this.ServiceName))
{
try
{
ServiceControllerStatus status = controller.Status;
}
catch
{
return false;
}
return true;
}
}
private bool IsRunning()
{
using (ServiceController controller =
new ServiceController(this.ServiceName))
{
if (!this.IsInstalled()) return false;
return (controller.Status == ServiceControllerStatus.Running);
}
}
/// <summary>
/// protected method to be called by a public method within the real service
/// ie: in the real service
/// new internal void InstallService()
/// {
/// base.InstallService();
/// }
/// </summary>
protected void InstallService()
{
if (this.IsInstalled()) return;
try
{
using (AssemblyInstaller installer = GetInstaller())
{
IDictionary state = new Hashtable();
try
{
installer.Install(state);
installer.Commit(state);
}
catch
{
try
{
installer.Rollback(state);
}
catch { }
throw;
}
}
}
catch
{
throw;
}
}
/// <summary>
/// protected method to be called by a public method within the real service
/// ie: in the real service
/// new internal void UninstallService()
/// {
/// base.UninstallService();
/// }
/// </summary>
protected void UninstallService()
{
if (!this.IsInstalled()) return;
if (this.IsRunning()) {
this.StopService();
}
try
{
using (AssemblyInstaller installer = GetInstaller())
{
IDictionary state = new Hashtable();
try
{
installer.Uninstall(state);
}
catch
{
throw;
}
}
}
catch
{
throw;
}
}
private void StartService()
{
if (!this.IsInstalled()) return;
using (ServiceController controller =
new ServiceController(this.ServiceName))
{
try
{
if (controller.Status != ServiceControllerStatus.Running)
{
controller.Start();
controller.WaitForStatus(ServiceControllerStatus.Running,
TimeSpan.FromSeconds(10));
}
}
catch
{
throw;
}
}
}
private void StopService()
{
if (!this.IsInstalled()) return;
using (ServiceController controller =
new ServiceController(this.ServiceName))
{
try
{
if (controller.Status != ServiceControllerStatus.Stopped)
{
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped,
TimeSpan.FromSeconds(10));
}
}
catch
{
throw;
}
}
}
}
All you have to do is to implement two public/internal methods in your real service:
new internal void InstallService()
{
base.InstallService();
}
new internal void UninstallService()
{
base.UninstallService();
}
and then call them when you want to install the service:
static void Main(string[] args)
{
if (Environment.UserInteractive)
{
MyService s1 = new MyService();
if (args.Length == 1)
{
switch (args[0])
{
case "-install":
s1.InstallService();
break;
case "-uninstall":
s1.UninstallService();
break;
default:
throw new NotImplementedException();
}
}
}
else {
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyService()
};
ServiceBase.Run(MyService);
}
}
The solution that worked for me in both Visual Studio 2013 and Microsoft Test Manager (MTM) was to ensure that both devenv.exe.config and mtm.exe.config included this configurations section:
<system.net>
<settings>
<ipv6 enabled="true"/>
<servicePointManager expect100Continue="false"/>
</settings>
<defaultProxy useDefaultCredentials="true" enabled="true">
<proxy usesystemdefault="True" />
</defaultProxy>
</system.net>
MTM did not have a system.net setting and the whole section was added immediately following the closing xml tag </appSettings>
.
format
is definitely the most elegant way, but afaik you can't use that with python's logging
module, so here's how you can do it using the %
formatting:
formatter = logging.Formatter(
fmt='%(asctime)s | %(name)-20s | %(levelname)-10s | %(message)s',
)
Here, the -
indicates left-alignment, and the number before s
indicates the fixed width.
Some sample output:
2017-03-14 14:43:42,581 | this-app | INFO | running main
2017-03-14 14:43:42,581 | this-app.aux | DEBUG | 5 is an int!
2017-03-14 14:43:42,581 | this-app.aux | INFO | hello
2017-03-14 14:43:42,581 | this-app | ERROR | failed running main
More info at the docs here: https://docs.python.org/2/library/stdtypes.html#string-formatting-operations
As alluded to by Eric, you can use environ with ComputerName argument like so:
MsgBox Environ("USERNAME")
Some additional information that might be helpful for you to know:
Sub EnumSEVars()
Dim strVar As String
Dim i As Long
For i = 1 To 255
strVar = Environ$(i)
If LenB(strVar) = 0& Then Exit For
Debug.Print strVar
Next
End Sub
I've done this with PowerShell:
function DownloadFromFtp($destination, $ftp_uri, $user, $pass){
$dirs = GetDirecoryTree $ftp_uri $user $pass
foreach($dir in $dirs){
$path = [io.path]::Combine($destination,$dir)
if ((Test-Path $path) -eq $false) {
"Creating $path ..."
New-Item -Path $path -ItemType Directory | Out-Null
}else{
"Exists $path ..."
}
}
$files = GetFilesTree $ftp_uri $user $pass
foreach($file in $files){
$source = [io.path]::Combine($ftp_uri,$file)
$dest = [io.path]::Combine($destination,$file)
"Downloading $source ..."
Get-FTPFile $source $dest $user $pass
}
}
function UploadToFtp($artifacts, $ftp_uri, $user, $pass){
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
foreach($item in Get-ChildItem -recurse $artifacts){
$relpath = [system.io.path]::GetFullPath($item.FullName).SubString([system.io.path]::GetFullPath($artifacts).Length + 1)
if ($item.Attributes -eq "Directory"){
try{
Write-Host Creating $item.Name
$makeDirectory = [System.Net.WebRequest]::Create($ftp_uri+$relpath);
$makeDirectory.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
$makeDirectory.Method = [System.Net.WebRequestMethods+FTP]::MakeDirectory;
$makeDirectory.GetResponse();
}catch [Net.WebException] {
Write-Host $item.Name probably exists ...
}
continue;
}
"Uploading $item..."
$uri = New-Object System.Uri($ftp_uri+$relpath)
$webclient.UploadFile($uri, $item.FullName)
}
}
function Get-FTPFile ($Source,$Target,$UserName,$Password)
{
$ftprequest = [System.Net.FtpWebRequest]::create($Source)
$ftprequest.Credentials = New-Object System.Net.NetworkCredential($username,$password)
$ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
$ftprequest.UseBinary = $true
$ftprequest.KeepAlive = $false
$ftpresponse = $ftprequest.GetResponse()
$responsestream = $ftpresponse.GetResponseStream()
$targetfile = New-Object IO.FileStream ($Target,[IO.FileMode]::Create)
[byte[]]$readbuffer = New-Object byte[] 1024
do{
$readlength = $responsestream.Read($readbuffer,0,1024)
$targetfile.Write($readbuffer,0,$readlength)
}
while ($readlength -ne 0)
$targetfile.close()
}
#task ListFiles {
#
# $files = GetFilesTree 'ftp://127.0.0.1/' "web" "web"
# $files | ForEach-Object {Write-Host $_ -foregroundcolor cyan}
#}
function GetDirecoryTree($ftp, $user, $pass){
$creds = New-Object System.Net.NetworkCredential($user,$pass)
$files = New-Object "system.collections.generic.list[string]"
$folders = New-Object "system.collections.generic.queue[string]"
$folders.Enqueue($ftp)
while($folders.Count -gt 0){
$fld = $folders.Dequeue()
$newFiles = GetAllFiles $creds $fld
$dirs = GetDirectories $creds $fld
foreach ($line in $dirs){
$dir = @($newFiles | Where { $line.EndsWith($_) })[0]
[void]$newFiles.Remove($dir)
$folders.Enqueue($fld + $dir + "/")
[void]$files.Add($fld.Replace($ftp, "") + $dir + "/")
}
}
return ,$files
}
function GetFilesTree($ftp, $user, $pass){
$creds = New-Object System.Net.NetworkCredential($user,$pass)
$files = New-Object "system.collections.generic.list[string]"
$folders = New-Object "system.collections.generic.queue[string]"
$folders.Enqueue($ftp)
while($folders.Count -gt 0){
$fld = $folders.Dequeue()
$newFiles = GetAllFiles $creds $fld
$dirs = GetDirectories $creds $fld
foreach ($line in $dirs){
$dir = @($newFiles | Where { $line.EndsWith($_) })[0]
[void]$newFiles.Remove($dir)
$folders.Enqueue($fld + $dir + "/")
}
$newFiles | ForEach-Object {
$files.Add($fld.Replace($ftp, "") + $_)
}
}
return ,$files
}
function GetDirectories($creds, $fld){
$dirs = New-Object "system.collections.generic.list[string]"
$operation = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
$reader = GetStream $creds $fld $operation
while (($line = $reader.ReadLine()) -ne $null) {
if ($line.Trim().ToLower().StartsWith("d") -or $line.Contains(" <DIR> ")) {
[void]$dirs.Add($line)
}
}
$reader.Dispose();
return ,$dirs
}
function GetAllFiles($creds, $fld){
$newFiles = New-Object "system.collections.generic.list[string]"
$operation = [System.Net.WebRequestMethods+Ftp]::ListDirectory
$reader = GetStream $creds $fld $operation
while (($line = $reader.ReadLine()) -ne $null) {
[void]$newFiles.Add($line.Trim())
}
$reader.Dispose();
return ,$newFiles
}
function GetStream($creds, $url, $meth){
$ftp = [System.Net.WebRequest]::Create($url)
$ftp.Credentials = $creds
$ftp.Method = $meth
$response = $ftp.GetResponse()
return New-Object IO.StreamReader $response.GetResponseStream()
}
Export-ModuleMember UploadToFtp, DownLoadFromFtp
I got the unexpected token export error also when I was trying to import a local javascript module in my project. I solved it by declaring a type as a module when adding a script tag in my index.html file.
<script src = "./path/to/the/module/" type = "module"></script>
When a float
is passed to printf
, it is automatically converted to a double
. This is part of the default argument promotions, which apply to functions that have a variable parameter list (containing ...
), largely for historical reasons. Therefore, the “natural” specifier for a float
, %f
, must work with a double
argument. So the %f
and %lf
specifiers for printf
are the same; they both take a double
value.
When scanf
is called, pointers are passed, not direct values. A pointer to float
is not converted to a pointer to double
(this could not work since the pointed-to object cannot change when you change the pointer type). So, for scanf
, the argument for %f
must be a pointer to float
, and the argument for %lf
must be a pointer to double
.
This does not work:
string s = (string)malloc(sizeof string);
string
refers to a pointer, you need the size of the structure itself:
string s = malloc(sizeof (*string));
Note the lack of cast as well (conversion from void*
(malloc
's return type) is implicitly performed).
Also, in your main
, you have a globally delcared patient
, but that is uninitialized. Try:
patient.number = 3;
patient.name = "John";
patient.address = "Baker street";
patient.birthdate = "4/15/2012";
patient.gender = 'M';
before you read-access any of its members
Also, strcpy
is inherently unsafe as it does not have boundary checking (will copy until the first '\0'
is encountered, writing past allocated memory if the source is too long). Use strncpy
instead, where you can at least specify the maximum number of characters copied -- read the documentation to ensure you pass the correct value, it is easy to make an off-by-one error.
How about this one.
ArrayList<String> names = new ArrayList<String>();
Collections.addAll(names, "Ryan", "Julie", "Bob");
I know this is stupidly hacky,
but if you want to support under v21, here are my achievements.
rectangle_with_10dp_radius_white_bg_and_shadow.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Shadow layers -->
<item
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape>
<corners android:radius="10dp" />
<padding
android:bottom="1.8dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="@color/shadow_hack_level_1" />
</shape>
</item>
<item
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape>
<corners android:radius="10dp" />
<padding
android:bottom="1.8dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="@color/shadow_hack_level_2" />
</shape>
</item>
<item
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape>
<corners android:radius="10dp" />
<padding
android:bottom="1.8dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="@color/shadow_hack_level_3" />
</shape>
</item>
<item
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape>
<corners android:radius="10dp" />
<padding
android:bottom="1.8dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="@color/shadow_hack_level_4" />
</shape>
</item>
<item
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape>
<corners android:radius="10dp" />
<padding
android:bottom="1.8dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="@color/shadow_hack_level_5" />
</shape>
</item>
<item
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape>
<corners android:radius="10dp" />
<padding
android:bottom="1.8dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="@color/shadow_hack_level_6" />
</shape>
</item>
<item
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape>
<corners android:radius="10dp" />
<padding
android:bottom="1.8dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="@color/shadow_hack_level_7" />
</shape>
</item>
<item
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape>
<corners android:radius="10dp" />
<padding
android:bottom="1.8dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="@color/shadow_hack_level_8" />
</shape>
</item>
<item
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape>
<corners android:radius="10dp" />
<padding
android:bottom="1.8dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="@color/shadow_hack_level_9" />
</shape>
</item>
<item
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape>
<corners android:radius="10dp" />
<padding
android:bottom="1.8dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="@color/shadow_hack_level_10" />
</shape>
</item>
<!-- Background layer -->
<item>
<shape>
<solid android:color="@android:color/white" />
<corners android:radius="10dp" />
</shape>
</item>
</layer-list>
rectangle_with_10dp_radius_white_bg_and_shadow.xml (v21)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@android:color/white" />
<corners android:radius="10dp" />
</shape>
view_incoming.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/rectangle_with_10dp_radius_white_bg_and_shadow"
android:elevation="7dp"
android:gravity="center"
android:minWidth="240dp"
android:minHeight="240dp"
android:orientation="horizontal"
android:padding="16dp"
tools:targetApi="lollipop">
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="Hello World !" />
</LinearLayout>
Here is result:
Under v21 (this is which you made with xml)
Above v21 (real elevation rendering)
I've used this with Jackson 2.x and Spring 3.1.2+
servlet-context.xml:
Note that the root element is <beans:beans>
, so you may need to remove beans
and add mvc
to some of these elements depending on your setup.
<annotation-driven>
<message-converters>
<beans:bean
class="org.springframework.http.converter.StringHttpMessageConverter" />
<beans:bean
class="org.springframework.http.converter.ResourceHttpMessageConverter" />
<beans:bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<beans:property name="objectMapper" ref="jacksonObjectMapper" />
</beans:bean>
</message-converters>
</annotation-driven>
<beans:bean id="jacksonObjectMapper"
class="au.edu.unimelb.atcom.transfer.json.mappers.JSONMapper" />
au.edu.unimelb.atcom.transfer.json.mappers.JSONMapper.java:
public class JSONMapper extends ObjectMapper {
public JSONMapper() {
SimpleModule module = new SimpleModule("JSONModule", new Version(2, 0, 0, null, null, null));
module.addSerializer(Date.class, new DateSerializer());
module.addDeserializer(Date.class, new DateDeserializer());
// Add more here ...
registerModule(module);
}
}
DateSerializer.java:
public class DateSerializer extends StdSerializer<Date> {
public DateSerializer() {
super(Date.class);
}
@Override
public void serialize(Date date, JsonGenerator json,
SerializerProvider provider) throws IOException,
JsonGenerationException {
// The client side will handle presentation, we just want it accurate
DateFormat df = StdDateFormat.getBlueprintISO8601Format();
String out = df.format(date);
json.writeString(out);
}
}
DateDeserializer.java:
public class DateDeserializer extends StdDeserializer<Date> {
public DateDeserializer() {
super(Date.class);
}
@Override
public Date deserialize(JsonParser json, DeserializationContext context)
throws IOException, JsonProcessingException {
try {
DateFormat df = StdDateFormat.getBlueprintISO8601Format();
return df.parse(json.getText());
} catch (ParseException e) {
return null;
}
}
}
Sure Google has a limit of downloads so that you don't abuse the system. These are the limits if you are using Gmail:
The following limits apply for Google Apps for Business or Education editions. Limits for domains during trial are lower. These limits may change without notice in order to protect Google’s infrastructure.
Bandwidth limits
Limit Per hour Per day
Download via web client 750 MB 1250 MB
Upload via web client 300 MB 500 MB
POP and IMAP bandwidth limits
Limit Per day
Download via IMAP 2500 MB
Download via POP 1250 MB
Upload via IMAP 500 MB
You can set the caret position using TextBox.CaretIndex. If the only thing you need is to set the cursor at the end, you can simply pass the string's length, eg:
txtBox.CaretIndex=txtBox.Text.Length;
You need to set the caret index at the length, not length-1, because this would put the caret before the last character.
You can do that using Requestify, a very simple and cool HTTP client I wrote for nodeJS, it support easy use of cookies and it also supports caching.
To perform a request with a cookie attached just do the following:
var requestify = require('requestify');
requestify.post('http://google.com', {}, {
cookies: {
sessionCookie: 'session-cookie-data'
}
});
Using new api fetch:
const dataToSend = JSON.stringify({"email": "[email protected]", "password": "101010"});
let dataReceived = "";
fetch("", {
credentials: "same-origin",
mode: "same-origin",
method: "post",
headers: { "Content-Type": "application/json" },
body: dataToSend
})
.then(resp => {
if (resp.status === 200) {
return resp.json()
} else {
console.log("Status: " + resp.status)
return Promise.reject("server")
}
})
.then(dataJson => {
dataReceived = JSON.parse(dataJson)
})
.catch(err => {
if (err === "server") return
console.log(err)
})
console.log(`Received: ${dataReceived}`)
_x000D_
Try using the @
symbol before the url string. Import your css in the following manner:
import Vue from 'vue'
require('@/assets/styles/main.css')
In your App.vue file you can do this to import a css file in the style tag
<template>
<div>
</div>
</template>
<style scoped src="@/assets/styles/mystyles.css">
</style>
Use the slicing operator:
list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
list[:10]
You can always check if the thread's id is different than std::thread::id() default constructed. A Running thread has always a genuine associated id. Try to avoid too much fancy stuff :)
Per the jQuery documentation, try this:
$('input[inputName\\[\\]=someValue]')
[EDIT] However, I'm not sure that's the right syntax for your selector. You probably want:
$('input[name="inputName[]"][value="someValue"]')
<script>
alert("i am ajith fan");
<?php die(); ?>
alert("i love boxing");
alert("i love MMA");
</script>
You can use div to achieve this. without img tag :) hope this helps.
.img{_x000D_
width:100px;_x000D_
height:100px;_x000D_
background-image:url('http://www.mandalas.com/mandala/htdocs/images/Lrg_image_Pages/Flowers/Large_Orange_Lotus_8.jpg');_x000D_
background-repeat:no-repeat;_x000D_
background-position:center center;_x000D_
border:1px solid red;_x000D_
background-size:cover;_x000D_
}_x000D_
.img1{_x000D_
width:100px;_x000D_
height:100px;_x000D_
background-image:url('https://images.freeimages.com/images/large-previews/9a4/large-pumpkin-1387927.jpg');_x000D_
background-repeat:no-repeat;_x000D_
background-position:center center;_x000D_
border:1px solid red;_x000D_
background-size:cover;_x000D_
}
_x000D_
<div class="img"> _x000D_
</div>_x000D_
<div class="img1"> _x000D_
</div>
_x000D_
As described in Cast Functions and Operators:
The type for the result can be one of the following values:
BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]
Therefore, you should use:
SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT
YES - solution is to save workbook in to XML file (eg. 'XML Spreadsheet 2003') and edit this file as text in notepad! use "SEARCH" function of notepad to find query text and change your data to "?".
save and open in excel, try refresh data and excel will be monit about parameters.
maybe this will help you out:
or this page:
www.scala-lang.org/node/6372
According to this article, != performs faster
please try following to generate
function addRow()
{
var e1 = document.createElement("input");
e1.type = "text";
e1.name = "name1";
var cont = document.getElementById("content")
cont.appendChild(e1);
}
Add #pragma comment(lib, "Your library name here")
to your source.
You want a proc object:
gaussian = Proc.new do |dist, *args|
sigma = args.first || 10.0
...
end
def weightedknn(data, vec1, k = 5, weightf = gaussian)
...
weight = weightf.call(dist)
...
end
Just note that you can't set a default argument in a block declaration like that. So you need to use a splat and setup the default in the proc code itself.
Or, depending on your scope of all this, it may be easier to pass in a method name instead.
def weightedknn(data, vec1, k = 5, weightf = :gaussian)
...
weight = self.send(weightf)
...
end
In this case you are just calling a method that is defined on an object rather than passing in a complete chunk of code. Depending on how you structure this you may need replace self.send
with object_that_has_the_these_math_methods.send
Last but not least, you can hang a block off the method.
def weightedknn(data, vec1, k = 5)
...
weight =
if block_given?
yield(dist)
else
gaussian.call(dist)
end
end
...
end
weightedknn(foo, bar) do |dist|
# square the dist
dist * dist
end
But it sounds like you would like more reusable chunks of code here.
If you are using API level 21, you can use editText.setShowSoftInputOnFocus(false);
or you can
SELECT
String_to_array(CASE
WHEN <condition 1> THEN a1||','||b1
WHEN <condition 2> THEN a2||','||b2
ELSE a3||','||b3
END, ',') K
FROM <table>
According to sdk src code from ...\android-22\android\content\pm\PackageManager.java
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* the new package has an older version code than the currently installed package.
* @hide
*/
public static final int INSTALL_FAILED_VERSION_DOWNGRADE = -25;
if the new package has an older version code than the currently installed package.
Setup twig
$twig = new Twig_Environment(...);
$twig->addGlobal('session', $_SESSION);
Then within your template access session values for example
$_SESSION['username'] in php file Will be equivalent to {{ session.username }} in your twig template
As soon as signed and unsigned ints are mixed in an expression things start to get messy and you probably will lose information. Restricting Java to signed ints only really clears things up. I’m glad I don’t have to worry about the whole signed/unsigned business, though I sometimes do miss the 8th bit in a byte.
Since the release of iOS 8, UIAlertView
is now deprecated; UIAlertController is the replacement.
Here is a sample of how it looks in Swift:
let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
let alertAction = UIAlertAction(title: "OK!", style: UIAlertActionStyle.default)
{
(UIAlertAction) -> Void in
}
alert.addAction(alertAction)
present(alert, animated: true)
{
() -> Void in
}
As you can see, the API allows us to implement callbacks for both the action and when we are presenting the alert, which is quite handy!
Updated for Swift 4.2
let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK!", style: .default)
{
(UIAlertAction) -> Void in
}
alert.addAction(alertAction)
present(alert, animated: true)
{
() -> Void in
}
If you didn't commit it to the master branch yet, its easy:
git checkout -b oops/fluke/dang
)git add -u; git commit;
)git checkout master
)Your changes will be saved in branch oops/fluke/dang; master will be as it was.
The map() function is a best choice for this case
tl;dr - Do this:
const newArr = [
{name: 'eve'},
{name: 'john'},
{name: 'jane'}
].map(v => ({...v, isActive: true}))
The map() function won't modify the initial array, but creates a new one. This is also a good practice to keep initial array unmodified.
Alternatives:
const initialArr = [
{name: 'eve'},
{name: 'john'},
{name: 'jane'}
]
const newArr1 = initialArr.map(v => ({...v, isActive: true}))
const newArr2 = initialArr.map(v => Object.assign(v, {isActive: true}))
// Results of newArr1 and newArr2 are the same
Add a key value pair conditionally
const arr = [{value: 1}, {value: 1}, {value: 2}]
const newArr1 = arr.map(v => ({...v, isActive: v.value > 1}))
What if I don't want to add new field at all if the condition is false?
const arr = [{value: 1}, {value: 1}, {value: 2}]
const newArr = arr.map(v => {
return v.value > 1 ? {...v, isActive: true} : v
})
Adding WITH modification of the initial array
const initialArr = [{a: 1}, {b: 2}]
initialArr.forEach(v => {v.isActive = true;});
This is probably not a best idea, but in a real life sometimes it's the only way.
Questions
...
), or Object.assign
and what's the difference?Personally I prefer to use spread operator, because I think it uses much wider in modern web community (especially react's developers love it). But you can check the difference yourself: link(a bit opinionated and old, but still)
function
keyword instead of =>
?Sure you can. The fat arrow (=>
) functions play a bit different with this
, but it's not so important for this particular case. But fat arrows function shorter and sometimes plays better as a callbacks. Therefore the usage of fat arrow functions is more modern approach.
.map(v => ({...v, isActive: true})
?Map function iterates by array's elements and apply callback function for each of them. That callback function should return something that will become an element of a new array.
We tell to the .map()
function following: take current value(v
which is an object), take all key-value pairs away from v
andput it inside a new object({...v}
), but also add property isActive
and set it to true ({...v, isActive: true}
) and then return the result. Btw, if original object contains isActive
filed it will be overwritten. Object.assign
works in a similar way.
Yes.
[{value: 1}, {value: 1}, {value: 2}].map(v => ({...v, isActive: true, howAreYou: 'good'}))
.map()
methodYou shouldn't do any side effects[link 1, link 2], but apparently you can.
Also be noticed that map()
iterates over each element of the array and apply function for each of them. So if you do some heavy stuff inside, you might be slow. This (a bit hacky) solution might be more productive in some cases (but I don't think you should apply it more then once in a lifetime).
Sure you can.
const arr = [{value: 1}, {value: 1}, {value: 2}]
const newArr = arr.map(addIsActive)
function addIsActive(v) {
return {...v, isActive: true}
}
Nothing is wrong with for
, you can still use it, it's just an old-school approach which is more verbose, less safe and mutate the initial array. But you can try:
const arr = [{a: 1}, {b: 2}]
for (let i = 0; i < arr.length; i++) {
arr[i].isActive = true
}
It would be smart to learn well following methods map(), filter(), reduce(), forEach(), and find(). These methods can solve 80% of what you usually want to do with arrays.
Try this,
this.props.router.push('/foo')
warning works for versions prior to v4
and
this.props.history.push('/foo')
for v4 and above
array_change_value_case
by continue
function array_change_value_case($array, $case = CASE_LOWER){
if ( ! is_array($array)) return false;
foreach ($array as $key => &$value){
if (is_array($value))
call_user_func_array(__function__, array (&$value, $case ) ) ;
else
$array[$key] = ($case == CASE_UPPER )
? strtoupper($array[$key])
: strtolower($array[$key]);
}
return $array;
}
$arrays = array ( 1 => 'ONE', 2=> 'TWO', 3 => 'THREE',
'FOUR' => array ('a' => 'Ahmed', 'b' => 'basem',
'c' => 'Continue'),
5=> 'FIVE',
array('AbCdeF'));
$change_case = array_change_value_case($arrays, CASE_UPPER);
echo "<pre>";
print_r($change_case);
Array ( [1] => one [2] => two [3] => three [FOUR] => Array ( [a] => ahmed [b] => basem [c] => continue ) [5] => five [6] => Array ( [0] => abcdef ) )
An activity populates the ActionBar in its onCreateOptionsMenu()
method.
Instead of using setcustomview()
, just override onCreateOptionsMenu
like this:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
If an actions in the ActionBar is selected, the onOptionsItemSelected()
method is called. It receives the selected action as parameter. Based on this information you code can decide what to do for example:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuitem1:
Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show();
break;
case R.id.menuitem2:
Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
The issue with the conversion (the reason it's giving you a ffffff at the end) is because your hex integer (that you are using the & binary operator with) is interpreted as being signed. Cast it to an unsigned integer, and you'll be fine.
import java.math.BigInteger;
import java.util.*;
class A
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.print("Enter The First Number= ");
String a=in.next();
System.out.print("Enter The Second Number= ");
String b=in.next();
BigInteger obj=new BigInteger(a);
BigInteger obj1=new BigInteger(b);
System.out.println("Sum="+obj.add(obj1));
}
}
Detect:
Debug CRT
Avoid:
Smart pointers, boehm GC
Let me add a little to Sebastian Roth's answer.
Your project can be compiled by using ndk-build
in the command line after adding the code Sebastian had posted. But as for me, there were syntax errors in Eclipse, and I didn't have code completion.
Note that your project must be converted to a C/C++ project.
How to convert a C/C++ project
To fix this issue right-click on your project, click Properties
Choose C/C++ General -> Paths and Symbols and include the ${ANDROID_NDK}/sources/cxx-stl/stlport/stlport
to Include directories
Click Yes when a dialog shows up.
Before
After
Update #1
GNU C. Add directories, rebuild. There won't be any errors in C source files
GNU C++. Add directories, rebuild. There won't be any errors in CPP source files.
I would sugest using array native reverse method is always better choice over creating filter or using $index
.
<div ng-repeat="friend in friends.reverse()">{{friend.name}}</div>
You can easily check for the Imagick class in PHP.
if( class_exists("Imagick") )
{
//Imagick is installed
}
If you have problems using the location: http://dl-ssl.google.com/android/eclipse/, try editing the location by replacing "http" with "https" or the other way round.
\w
matches a word character. \b
is a zero-width match that matches a position character that has a word character on one side, and something that's not a word character on the other. (Examples of things that aren't word characters include whitespace, beginning and end of the string, etc.)
\w
matches a
, b
, c
, d
, e
, and f
in "abc def"
\b
matches the (zero-width) position before a
, after c
, before d
, and after f
in "abc def"
You can use atoi
, which is part of the standard library.
The easiest method is to use sys.path.append().
However, you may be also interested in the imp module. It provides access to internal import functions.
# mod_name is the filename without the .py/.pyc extention
py_mod = imp.load_source(mod_name,filename_path) # Loads .py file
py_mod = imp.load_compiled(mod_name,filename_path) # Loads .pyc file
This can be used to load modules dynamically when you don't know a module's name.
I've used this in the past to create a plugin type interface to an application, where the user would write a script with application specific functions, and just drop thier script in a specific directory.
Also, these functions may be useful:
imp.find_module(name[, path])
imp.load_module(name, file, pathname, description)
Integer.parseInt(hex,16);
System.out.print(Integer.toBinaryString(hex));
Parse hex(String) to integer with base 16 then convert it to Binary String using toBinaryString(int) method
example
int num = (Integer.parseInt("A2B", 16));
System.out.print(Integer.toBinaryString(num));
Will Print
101000101011
Max Hex vakue Handled by int is FFFFFFF
i.e. if FFFFFFF0 is passed ti will give error
let dateString = "1970-01-01T13:30:00.000Z"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let date = formatter.date(from: String(dateString.dropLast(5)))!
formatter.dateFormat = "hh.mma"
print(formatter.string(from: date))
if You notice I have set .dateFormat = "hh.mma"
by this you will get time only.
Result:01.30PM
$(document).ready(function() {
var referrer = document.referrer;
if(referrer.equals("Setting.jsp")){
function goBack() {
window.history.go();
}
}
if(referrer.equals("http://localhost:8080/Ads/Terms.jsp")){
window.history.forward();
function noBack() {
window.history.forward();
}
}
});
using this you can avoid load previous page load
You can use
Arrays.copyOfRange(Object[] src, int from, int to)
System.arraycopy(Object[] src, int srcStartIndex, Object[] dest, int dstStartIndex, int lengthOfCopiedIndices);
The mysql
command by default uses UNIX sockets to connect to MySQL.
If you're using MariaDB, you need to load the Unix Socket Authentication Plugin on the server side.
You can do it by editing the [mysqld]
configuration like this:
[mysqld]
plugin-load-add = auth_socket.so
Depending on distribution, the config file is usually located at /etc/mysql/
or /usr/local/etc/mysql/
Use the predefined PHP_EOL
constant:
echo $clientid, ' ', $lastname, PHP_EOL;
The constant value will be set according to the line endings of the operating system where PHP is executing. On Linux, it will be "\n"
; on Windows, it will be "\r\n"
.
According to Martin Fowler a POJO is an object which encapsulates Business Logic while a Bean (except for the definition already stated in other answers) is little more than a container for holding data and the operations available on the object merely set and get data.
The term was coined while Rebecca Parsons, Josh MacKenzie and I were preparing for a talk at a conference in September 2000. In the talk we were pointing out the many benefits of encoding business logic into regular java objects rather than using Entity Beans. We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it's caught on very nicely.
Strictly speaking, the difference between Database and Schema is inexisting in MySql.
However, this is not the case in other database engines such as SQL Server. In SQL server:,
Every table belongs to a grouping of objects in the database called database schema. It's a container or namespace (Querying Microsoft SQL Server 2012)
By default, all the tables in SQL Server belong to a default schema called dbo. When you query a table that hasn't been allocated to any particular schema, you can do something like:
SELECT *
FROM your_table
which is equivalent to:
SELECT *
FROM dbo.your_table
Now, SQL server allows the creation of different schema, which gives you the possibility of grouping tables that share a similar purpose. That helps to organize the database.
For example, you can create an schema called sales, with tables such as invoices, creditorders (and any other related with sales), and another schema called lookup, with tables such as countries, currencies, subscriptiontypes (and any other table used as look up table).
The tables that are allocated to a specific domain are displayed in SQL Server Studio Manager with the schema name prepended to the table name (exactly the same as the tables that belong to the default dbo schema).
There are special schemas in SQL Server. To quote the same book:
There are several built-in database schemas, and they can't be dropped or altered:
1) dbo, the default schema.
2) guest contains objects available to a guest user ("guest user" is a special role in SQL Server lingo, with some default and highly restricted permissions). Rarely used.
3) INFORMATION_SCHEMA, used by the Information Schema Views
4) sys, reserved for SQL Server internal use exclusively
Schemas are not only for grouping. It is actually possible to give different permissions for each schema to different users, as described MSDN.
Doing this way, the schema lookup mentioned above could be made available to any standard user in the database (e.g. SELECT
permissions only), whereas a table called supplierbankaccountdetails may be allocated in a different schema called financial, and to give only access to the users in the group accounts
(just an example, you get the idea).
Finally, and quoting the same book again:
It isn't the same Database Schema and Table Schema. The former is the namespace of a table, whereas the latter refers to the table definition
$user_list
is an array of data which when looped through can be split into it's name and value.
In this case it's name is $user
and it's value is $pass
.
Things have changed since this question was originally asked and answered. There's been a large amount of work done on getting cross-browser font embedding for body text to work using @font-face embedding.
Paul Irish put together Bulletproof @font-face syntax combining attempts from multiple other people. If you actually go through the entire article (not just the top) it allows a single @font-face statement to cover IE, Firefox, Safari, Opera, Chrome and possibly others. Basically this can feed out OTF, EOT, SVG and WOFF in ways that don't break anything.
Snipped from his article:
@font-face {
font-family: 'Graublau Web';
src: url('GraublauWeb.eot');
src: local('Graublau Web Regular'), local('Graublau Web'),
url("GraublauWeb.woff") format("woff"),
url("GraublauWeb.otf") format("opentype"),
url("GraublauWeb.svg#grablau") format("svg");
}
Working from that base, Font Squirrel put together a variety of useful tools including the @font-face Generator which allows you to upload a TTF or OTF file and get auto-converted font files for the other types, along with pre-built CSS and a demo HTML page. Font Squirrel also has Hundreds of @font-face kits.
Soma Design also put together the FontFriend Bookmarklet, which redefines fonts on a page on the fly so you can try things out. It includes drag-and-drop @font-face support in FireFox 3.6+.
More recently, Google has started to provide the Google Web Fonts, an assortment of fonts available under an Open Source license and served from Google's servers.
License Restrictions
Finally, WebFonts.info has put together a nice wiki'd list of Fonts available for @font-face embedding based on licenses. It doesn't claim to be an exhaustive list, but fonts on it should be available (possibly with conditions such as an attribution in the CSS file) for embedding/linking. It's important to read the licenses, because there are some limitations that aren't pushed forward obviously on the font downloads.
You probably are looking for style="display:none;"
which will totally hide your element, whereas the visibility hides it but keeps the screen place it would take...
UPDATE: visible
is not a valid property in HTML, that's why it didn't work... See my suggestion above to correctly hide your html element
Try the following code to display scroll bar always on your page,
::-webkit-scrollbar {
-webkit-appearance: none;
width: 10px;
}
::-webkit-scrollbar-thumb {
border-radius: 5px;
background-color: rgba(0,0,0,.5);
-webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
}
this will always show the vertical and horizontal scroll bar on your page. If you need only a vertical scroll bar then put overflow-x: hidden
Have you changed the permissions on the individual files as well as just the directory?
chmod -R 777 /home/user/xxx
This is the JSON String we want to decode :
{
"stats": {
"sdr": "aa:bb:cc:dd:ee:ff",
"rcv": "aa:bb:cc:dd:ee:ff",
"time": "UTC in millis",
"type": 1,
"subt": 1,
"argv": [
{"1": 2},
{"2": 3}
]}
}
I store this string under the variable name "sJSON" Now, this is how to decode it :)
// Creating a JSONObject from a String
JSONObject nodeRoot = new JSONObject(sJSON);
// Creating a sub-JSONObject from another JSONObject
JSONObject nodeStats = nodeRoot.getJSONObject("stats");
// Getting the value of a attribute in a JSONObject
String sSDR = nodeStats.getString("sdr");
You could check for the count of the Object keys:
if (Object.keys(a).length > 0) {
// not empty
}
You cannot use the datetime function using the Java wrapper "ContentValues". Either you can use :
SQLiteDatabase.execSQL so you can enter a raw SQL query.
mDb.execSQL("INSERT INTO "+DATABASE_TABLE+" VALUES (null, datetime()) ");
Or the java date time capabilities :
// set the format to sql date time
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
ContentValues initialValues = new ContentValues();
initialValues.put("date_created", dateFormat.format(date));
long rowId = mDb.insert(DATABASE_TABLE, null, initialValues);
Try the following code:
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings.Add("YourKey", "YourValue");
config.Save(ConfigurationSaveMode.Minimal);
It worked for me :-)
var List = @Html.Raw(Json.Encode(Model));
$.ajax({
type: 'post',
url: '/Controller/action',
data:JSON.stringify({ 'item': List}),
contentType: 'application/json; charset=utf-8',
success: function (response) {
//do your actions
},
error: function (response) {
alert("error occured");
}
});
It worked for me.
Your public key is saved to the id_rsa.pub;file and is the key you upload to your account. You can save this key to the clipboard by running this:
pbcopy < ~/.ssh/id_rsa.pub
Here are a couple possible solutions...
I have not tried all of these myself yet, but I will be trying them all soon.
Note: I do not have any personal or financial connection to any of these tools.
1) VB Script to EXE Converter (NOT Compiler): (Free)
vbs2exe.com.
The exe produced appears to be a true EXE.
From their website:
VBS to EXE is a free online converter that doesn't only convert your vbs files into exe but it also:
1- Encrypt your vbs file source code using 128 bit key.
2- Allows you to call win32 API
3- If you have troubles with windows vista especially when UAC is enabled then you may give VBS to EXE a try.
4- No need for wscript.exe to run your vbs anymore.
5- Your script is never saved to the hard disk like some others converters. it is a TRUE exe not an extractor.
This solution should work even if wscript/cscript is not installed on the computer.
Basically, this creates a true .EXE file. Inside the created .EXE is an "engine" that replaces wscript/cscript, and an encrypted copy of your VB Script code. This replacement engine executes your code IN MEMORY without calling wscript/cscript to do it.
2) Compile and Convert VBS to EXE...:
ExeScript
The current version is 3.5.
This is NOT a Free solution. They have a 15 day trial. After that, you need to buy a license for a hefty $44.96 (Home License/noncommercial), or $89.95 (Business License/commercial usage).
It seems to work in a similar way to the previous solution.
According to a forum post there:
Post: "A Exe file still need Windows Scripting Host (WSH) ??"
WSH is not required if "Compile" option was used, since ExeScript
implements it's own scripting host. ...
3) Encrypt the script with Microsoft's ".vbs to .vbe" encryption tool.
Apparently, this does not work for Windows 7/8, and it is possible there are ways to "decrypt" the .vbe file. At the time of writing this, I could not find a working link to download this. If I find one, I will add it to this answer.
You can recursively revert like this:
svn revert --recursive .
There is no way (without writing a creative script) to remove things that aren't under source control. I think the closest you could do is to iterate over all of the files, use then grep the result of svn list
, and if the grep fails, then delete it.
EDIT: The solution for the creative script is here: Automatically remove Subversion unversioned files
So you could create a script that combines a revert
with whichever answer in the linked question suits you best.
The correct way to implement your code is
y="HELLO"
val=$(echo "$y" | tr '[:upper:]' '[:lower:]')
string="$val world"
This uses $(...)
notation to capture the output of the command in a variable. Note also the quotation marks around the string
variable -- you need them there to indicate that $val
and world
are a single thing to be assigned to string
.
If you have bash
4.0 or higher, a more efficient & elegant way to do it is to use bash
builtin string manipulation:
y="HELLO"
string="${y,,} world"
How about the more readable:
Node *pop (Node **root)
{
Node *popped = *root;
if (*root) {
*root = (*root)->next;
}
return (popped);
}
void push (Node **root, Node *new_node)
{
new_node->next = *root;
*root = new_node;
}
Node *reverse (Node *root)
{
Node *new_root = NULL;
Node *next;
while ((next = pop(&root))) {
push (&new_root, next);
}
return (new_root);
}
this may help
string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../../")) + "Orders.xml";
if (File.Exists(parentOfStartupPath))
{
// file found
}
function isFunction( o ) { return null !== o && "function" === typeof o && !!o.apply; }
Go to command prompt and enter the command,
net user <username>
Will show your local group memberships.
If you're on a domain, use localgroup instead:
net localgroup Administrators or net localgroup [Admin group name]
Check the list of local groups with localgroup on its own.
net localgroup
How about custom module based .htaccess script (like its used in CodeIgniter)? I tried and it worked good in CodeIgniter apps. Any ideas to use it on other apps?
<IfModule authz_core_module>
Require all denied
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>
Following works out for me.
#!/usr/bin/env python
a = [{ 'main_color': 'red', 'second_color':'blue'},
{ 'main_color': 'yellow', 'second_color':'green'},
{ 'main_color': 'yellow', 'second_color':'blue'}]
found_event = next(
filter(
lambda x: x['main_color'] == 'red',
a
),
#return this dict when not found
dict(
name='red',
value='{}'
)
)
if found_event:
print(found_event)
$python /tmp/x
{'main_color': 'red', 'second_color': 'blue'}
Thank you for this example, SPRBRN. It helped me. And I can suggest the mixin, which I've used based on the code given above:
//multi-column-list( fixed columns width)
@mixin multi-column-list($column-width, $column-rule-style) {
-webkit-column-width: $column-width;
-moz-column-width: $column-width;
-o-column-width: $column-width;
-ms-column-width: $column-width;
column-width: $column-width;
-webkit-column-rule-style: $column-rule-style;
-moz-column-rule-style: $column-rule-style;
-o-column-rule-style: $column-rule-style;
-ms-column-rule-style: $column-rule-style;
column-rule-style: $column-rule-style;
}
Using:
@include multi-column-list(250px, solid);
Simple Solution:
import pandas as pd
df = pd.read_csv('file_name.csv', engine='python')
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
The chosen answer looks like does not apply to modern browsers, at least on Firefox 52. What I observed is that the requests of loading resources like css, javascript are issued before HTML parser reaches the element, for example
<html>
<head>
<!-- prints the date before parsing and blocks HTMP parsering -->
<script>
console.log("start: " + (new Date()).toISOString());
for(var i=0; i<1000000000; i++) {};
</script>
<script src="jquery.js" type="text/javascript"></script>
<script src="abc.js" type="text/javascript"></script>
<link rel="stylesheets" type="text/css" href="abc.css"></link>
<style>h2{font-wight:bold;}</style>
<script>
$(document).ready(function(){
$("#img").attr("src", "kkk.png");
});
</script>
</head>
<body>
<img id="img" src="abc.jpg" style="width:400px;height:300px;"/>
<script src="kkk.js" type="text/javascript"></script>
</body>
</html>
What I found that the start time of requests to load css and javascript resources were not being blocked. Looks like Firefox has a HTML scan, and identify key resources(img resource is not included) before starting to parse the HTML.
google.maps.event.addListener(infowindow, 'domready', function() {
// Reference to the DIV that wraps the bottom of infowindow
var iwOuter = $('.gm-style-iw');
/* Since this div is in a position prior to .gm-div style-iw.
* We use jQuery and create a iwBackground variable,
* and took advantage of the existing reference .gm-style-iw for the previous div with .prev().
*/
var iwBackground = iwOuter.prev();
// Removes background shadow DIV
iwBackground.children(':nth-child(2)').css({'display' : 'none'});
// Removes white background DIV
iwBackground.children(':nth-child(4)').css({'display' : 'none'});
// Moves the infowindow 115px to the right.
iwOuter.parent().parent().css({left: '115px'});
// Moves the shadow of the arrow 76px to the left margin.
iwBackground.children(':nth-child(1)').attr('style', function(i,s){ return s + 'left: 76px !important;'});
// Moves the arrow 76px to the left margin.
iwBackground.children(':nth-child(3)').attr('style', function(i,s){ return s + 'left: 76px !important;'});
// Changes the desired tail shadow color.
iwBackground.children(':nth-child(3)').find('div').children().css({'box-shadow': 'rgba(72, 181, 233, 0.6) 0px 1px 6px', 'z-index' : '1'});
// Reference to the div that groups the close button elements.
var iwCloseBtn = iwOuter.next();
// Apply the desired effect to the close button
iwCloseBtn.css({opacity: '1', right: '38px', top: '3px', border: '7px solid #48b5e9', 'border-radius': '13px', 'box-shadow': '0 0 5px #3990B9'});
// If the content of infowindow not exceed the set maximum height, then the gradient is removed.
if($('.iw-content').height() < 140){
$('.iw-bottom-gradient').css({display: 'none'});
}
// The API automatically applies 0.7 opacity to the button after the mouseout event. This function reverses this event to the desired value.
iwCloseBtn.mouseout(function(){
$(this).css({opacity: '1'});
});
});
//CSS put in stylesheet
.gm-style-iw {
background-color: rgb(237, 28, 36);
border: 1px solid rgba(72, 181, 233, 0.6);
border-radius: 10px;
box-shadow: 0 1px 6px rgba(178, 178, 178, 0.6);
color: rgb(255, 255, 255) !important;
font-family: gothambook;
text-align: center;
top: 15px !important;
width: 150px !important;
}
This is a simple MaxHeap
implementation based on heapq
. Though it only works with numeric values.
import heapq
from typing import List
class MaxHeap:
def __init__(self):
self.data = []
def top(self):
return -self.data[0]
def push(self, val):
heapq.heappush(self.data, -val)
def pop(self):
return -heapq.heappop(self.data)
Usage:
max_heap = MaxHeap()
max_heap.push(3)
max_heap.push(5)
max_heap.push(1)
print(max_heap.top()) # 5
In similar case I used: white-space: nowrap;
You might take advantage of ruby's "splat" or flattening syntax.
This makes overgrown when
clauses — you have about 10 values to test per branch if I understand correctly — a little more readable in my opinion. Additionally, you can modify the values to test at runtime. For example:
honda = ['honda', 'acura', 'civic', 'element', 'fit', ...]
toyota = ['toyota', 'lexus', 'tercel', 'rx', 'yaris', ...]
...
if include_concept_cars
honda += ['ev-ster', 'concept c', 'concept s', ...]
...
end
case car
when *toyota
# Do something for Toyota cars
when *honda
# Do something for Honda cars
...
end
Another common approach would be to use a hash as a dispatch table, with keys for each value of car
and values that are some callable object encapsulating the code you wish to execute.
Try these utility methods of mine:
using System.ComponentModel;
using System.Globalization;
using System.Linq;
public static T GetAttribute<T>(this MemberInfo member, bool isRequired)
where T : Attribute
{
var attribute = member.GetCustomAttributes(typeof(T), false).SingleOrDefault();
if (attribute == null && isRequired)
{
throw new ArgumentException(
string.Format(
CultureInfo.InvariantCulture,
"The {0} attribute must be defined on member {1}",
typeof(T).Name,
member.Name));
}
return (T)attribute;
}
public static string GetPropertyDisplayName<T>(Expression<Func<T, object>> propertyExpression)
{
var memberInfo = GetPropertyInformation(propertyExpression.Body);
if (memberInfo == null)
{
throw new ArgumentException(
"No property reference expression was found.",
"propertyExpression");
}
var attr = memberInfo.GetAttribute<DisplayNameAttribute>(false);
if (attr == null)
{
return memberInfo.Name;
}
return attr.DisplayName;
}
public static MemberInfo GetPropertyInformation(Expression propertyExpression)
{
Debug.Assert(propertyExpression != null, "propertyExpression != null");
MemberExpression memberExpr = propertyExpression as MemberExpression;
if (memberExpr == null)
{
UnaryExpression unaryExpr = propertyExpression as UnaryExpression;
if (unaryExpr != null && unaryExpr.NodeType == ExpressionType.Convert)
{
memberExpr = unaryExpr.Operand as MemberExpression;
}
}
if (memberExpr != null && memberExpr.Member.MemberType == MemberTypes.Property)
{
return memberExpr.Member;
}
return null;
}
Usage would be:
string displayName = ReflectionExtensions.GetPropertyDisplayName<SomeClass>(i => i.SomeProperty);
tr:not(:contains(.... work for me
function busca(busca){
$("#listagem tr:not(:contains('"+busca+"'))").css("display", "none");
$("#listagem tr:contains('"+busca+"')").css("display", "");
}
There are two ways:
ax.set_xticks
and ax.set_xticklabels
) orplt.sca
to set the current axes for the pyplot state machine (i.e. the plt
interface).As an example (this also illustrates using setp
to change the properties of all of the subplots):
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=3, ncols=4)
# Set the ticks and ticklabels for all axes
plt.setp(axes, xticks=[0.1, 0.5, 0.9], xticklabels=['a', 'b', 'c'],
yticks=[1, 2, 3])
# Use the pyplot interface to change just one subplot...
plt.sca(axes[1, 1])
plt.xticks(range(3), ['A', 'Big', 'Cat'], color='red')
fig.tight_layout()
plt.show()
This will give DISTINCT values across all the columns:
SELECT DISTINCT value
FROM (
SELECT DISTINCT a AS value FROM my_table
UNION SELECT DISTINCT b AS value FROM my_table
UNION SELECT DISTINCT c AS value FROM my_table
) AS derived
If you only want to commit all the changes in one commit as if you typed yourself, --squash will do too
$ git merge --squash v1.0
$ git commit
Another way to look at it is to consider git rebase master
as:
Rebase the current branch on top of
master
Here , 'master
' is the upstream branch, and that explain why, during a rebase, ours
and theirs
are reversed.
Here is a DLL that shows:
* Hard drive ID (unique hardware serial number written in drive's IDE electronic chip)
* Partition ID (volume serial number)
* CPU ID (unique hardware ID)
* CPU vendor
* CPU running speed
* CPU theoretic speed
* Memory Load ( Total memory used in percentage (%) )
* Total Physical ( Total physical memory in bytes )
* Avail Physical ( Physical memory left in bytes )
* Total PageFile ( Total page file in bytes )
* Available PageFile( Page file left in bytes )
* Total Virtual( Total virtual memory in bytes )
* Available Virtual ( Virtual memory left in bytes )
* Bios unique identification numberBiosDate
* Bios unique identification numberBiosVersion
* Bios unique identification numberBiosProductID
* Bios unique identification numberBiosVideo
(text grabbed from original web site)
It works with C#.
Instead of editing the bringup service, add a post-start delay to the service which it depends on. Edit cassandra.service
like so:
ExecStartPost=/bin/sleep 30
This way the added sleep shouldn't slow down restarts of starting services that depend on it (though does slow down its own start, maybe that's desirable?).
Another simple example:
public static void listFilesInDirectory(String pathString) {
// A local class (a class defined inside a block, here a method).
class MyFilter implements FileFilter {
@Override
public boolean accept(File file) {
return !file.isHidden() && file.getName().endsWith(".txt");
}
}
File directory = new File(pathString);
File[] files = directory.listFiles(new MyFilter());
for (File fileLoop : files) {
System.out.println(fileLoop.getName());
}
}
// Call it
listFilesInDirectory("C:\\Users\\John\\Documents\\zTemp");
// Output
Cool.txt
RedditKinsey.txt
...
You could use a variable to make the calculation and use toFixed
when you set the #diskamountUnit
element value:
var amount = $("#disk").slider("value") * 1.60;
$("#diskamountUnit").val('$' + amount.toFixed(2));
You can also do that in one step, in the val
method call but IMO the first way is more readable:
$("#diskamountUnit").val('$' + ($("#disk").slider("value") * 1.60).toFixed(2));
Use whatever navigation key you want to get inside the parentheses, then you can use either yi(
or yi)
to copy everything within the matching parens. This also works with square brackets (e.g. yi]
) and curly braces. In addition to y
, you can also delete or change text (e.g. ci)
, di]
).
I tried this with double and single-quotes and it appears to work there as well. For your data, I do:
write (*, '(a)') 'Computed solution coefficients:'
Move cursor to the C
, then type yi'
. Move the cursor to a blank line, hit p
, and get
Computed solution coefficients:
As CMS noted, this works for visual mode selection as well - just use vi)
, vi}
, vi'
, etc.
Well, certainly
frames / sec = 1 / (sec / frame)
But, as you point out, there's a lot of variation in the time it takes to render a single frame, and from a UI perspective updating the fps value at the frame rate is not usable at all (unless the number is very stable).
What you want is probably a moving average or some sort of binning / resetting counter.
For example, you could maintain a queue data structure which held the rendering times for each of the last 30, 60, 100, or what-have-you frames (you could even design it so the limit was adjustable at run-time). To determine a decent fps approximation you can determine the average fps from all the rendering times in the queue:
fps = # of rendering times in queue / total rendering time
When you finish rendering a new frame you enqueue a new rendering time and dequeue an old rendering time. Alternately, you could dequeue only when the total of the rendering times exceeded some preset value (e.g. 1 sec). You can maintain the "last fps value" and a last updated timestamp so you can trigger when to update the fps figure, if you so desire. Though with a moving average if you have consistent formatting, printing the "instantaneous average" fps on each frame would probably be ok.
Another method would be to have a resetting counter. Maintain a precise (millisecond) timestamp, a frame counter, and an fps value. When you finish rendering a frame, increment the counter. When the counter hits a pre-set limit (e.g. 100 frames) or when the time since the timestamp has passed some pre-set value (e.g. 1 sec), calculate the fps:
fps = # frames / (current time - start time)
Then reset the counter to 0 and set the timestamp to the current time.
Another solution without using any height but still fills 100% available height. Checkout this e.g on the codepen. http://codepen.io/gauravshankar/pen/PqoLLZ
For this html and body should have 100% height. This height is equal to the viewport height.
Make inner div position absolute and give top and bottom 0. This fills the div to available height. (height equal to body.)
html code:
<head></head>
<body>
<div></div>
</body>
</html>
css code:
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
position: relative;
}
html {
background-color: red;
}
body {
background-color: green;
}
body> div {
position: absolute;
background-color: teal;
width: 300px;
top: 0;
bottom: 0;
}
This works for me:
In link, to attribute has value:
to="/filter/arr?fruits=apple&fruits=banana"
Route can handle this:
path="/filter/:arr"
For Multiple arrays:
to="filter/arr?fruits=apple&fruits=banana&vegetables=potato&vegetables=onion"
Route stays same.
SCREENSHOT
You can do this:
def deleteContent(pfile):
fn=pfile.name
pfile.close()
return open(fn,'w')
EMS's SQL Manager is much easier to use and has many more features than either phpPgAdmin or PG Admin III. However, it's windows only and you have to pay for it.
Your b + a
is equal "someonedamage"
, since your d
doesn't contain that string, your if
statement returns false
and doesn't run following parts.
Console.WriteLine(" " + d);
Console.ReadLine();
You can control this more efficient as;
bool b = d.Contains(a) && d.Contains(b);
Here is a DEMO
.
TL&DR: Using the for in
loop in arrays is not evil, in fact quite the opposite.
I think the for in
loop is a gem of JS if used correctly in arrays. You are expected to have full control over your software and know what you are doing. Let's see the mentioned drawbacks and disprove them one by one.
Array.prototype
should have been done by using Object.defineProperty()
and their enumerable
descriptor should be set to false
. Any library not doing so should not be used at all.Object.setPrototypeOf
or by Class extend
. You should again use Object.defineProperty()
which by default sets the writable
, enumerable
and configurable
property descriptors to false
. Lets see an array sub-classing example here...function Stack(...a){_x000D_
var stack = new Array(...a);_x000D_
Object.setPrototypeOf(stack, Stack.prototype);_x000D_
return stack;_x000D_
}_x000D_
Stack.prototype = Object.create(Array.prototype); // now stack has full access to array methods._x000D_
Object.defineProperty(Stack.prototype,"constructor",{value:Stack}); // now Stack is a proper constructor_x000D_
Object.defineProperty(Stack.prototype,"peak",{value: function(){ // add Stack "only" methods to the Stack.prototype._x000D_
return this[this.length-1];_x000D_
}_x000D_
});_x000D_
var s = new Stack(1,2,3,4,1);_x000D_
console.log(s.peak());_x000D_
s[s.length] = 7;_x000D_
console.log("length:",s.length);_x000D_
s.push(42);_x000D_
console.log(JSON.stringify(s));_x000D_
console.log("length:",s.length);_x000D_
_x000D_
for(var i in s) console.log(s[i]);
_x000D_
So you see.. for in
loop is now safe since you cared about your code.
for in
loop is slow: Hell no. It's by far the fastest method of iteration if you are looping over sparse arrays which are needed time to time. This is one of the most important performance tricks that one should know. Let's see an example. We will loop over a sparse array.var a = [];_x000D_
a[0] = "zero";_x000D_
a[10000000] = "ten million";_x000D_
console.time("for loop on array a:");_x000D_
for(var i=0; i < a.length; i++) a[i] && console.log(a[i]);_x000D_
console.timeEnd("for loop on array a:");_x000D_
console.time("for in loop on array a:");_x000D_
for(var i in a) a[i] && console.log(a[i]);_x000D_
console.timeEnd("for in loop on array a:");
_x000D_
You can use destructuring to only focus on the part of your interest.
So you can do:
let str = "My cow always gives milk";
let [, result] = str.match(/\bcow\s+(.*?)\s+milk\b/) || [];
console.log(result);
_x000D_
In this way you ignore the first part (the complete match) and only get the capture group's match. The addition of || []
may be interesting if you are not sure there will be a match at all. In that case match
would return null
which cannot be destructured, and so we return []
instead in that case, and then result
will be null
.
The additional \b
ensures the surrounding words "cow" and "milk" are really separate words (e.g. not "milky"). Also \s+
is needed to avoid that the match includes some outer spacing.
Change your code to:
System.out.println("AM or PM?");
Scanner TimeOfDayQ = new Scanner(System.in);
TimeOfDayStringQ = TimeOfDayQ.next();
if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) { // <--
System.out.println("Sorry, incorrect input.");
System.exit(1);
}
...
if(Hours == 13){
if (TimeOfDayStringQ.equals("AM")) {
TimeOfDayStringQ = "PM"; // <--
} else {
TimeOfDayStringQ = "AM"; // <--
}
Hours = 1;
}
}
Quote your args in Testscript 1:
echo "TestScript1 Arguments:"
echo "$1"
echo "$2"
echo "$#"
./testscript2 "$1" "$2"
For Android 2.2
Use this code:
//activity is an instance of a class which extends android.app.Activity
Dialog dialog = new Dialog(activity);
instead of this code:
// this code produces an ERROR:
//android.view.WindowManager$BadTokenException:
//Unable to add window -- token null is not for an application
Context mContext = activity.getApplicationContext();
Dialog dialog = new Dialog(mContext);
Remark: My custom dialog is created outside activity.onCreateDialog(int dialogId)
method.
public class Factorial {
public static void main(String[] args) {
System.out.println(factorial(4));
}
private static long factorial(int i) {
if(i<0) throw new IllegalArgumentException("x must be >= 0");
return i==0||i==1? 1:i*factorial(i-1);
}
}
The data would probably have been posted originally from a web form looking a bit like this (but probably much more complicated):
<form action="http://example.com" method="post">
User login <input name="user[login]" /><br />
User password <input name="user[password]" /><br />
<input type="submit" />
</form>
If the method were "get" instead of "post", clicking the submit button would take you to a URL looking a bit like this:
http://example.com/?user%5Blogin%5D=username&user%5Bpassword%5D=123456
or:
http://example.com/?user[login]=username&user[password]=123456
The web server on the other end will likely take the user[login]
and user[password]
parameters, and make them into a user
object with login
and password
fields containing those values.
Below line helped me to fix the issue of scroll bar for a table; the issue was awkward 2 scroll bars in a page. Below style when applied to table worked fine for me.
<table Style="position: absolute; height: 100%; width: 100%";/>
The .gitignore
file in the root directory does apply to all subdirectories. Mine looks like this:
.classpath
.project
.settings/
target/
This is in a multi-module maven project. All the submodules are imported as individual eclipse projects using m2eclipse. I have no further .gitignore
files. Indeed, if you look in the gitignore man page:
Patterns read from a
.gitignore
file in the same directory as the path, or in any parent directory…
So this should work for you.
Please not that sometimes this will not work:
git checkout --ours path/to/file
or
git checkout --theirs path/to/file
I did this instead, assuming HEAD is ours and MERGE_HEAD is theirs
git checkout HEAD -- path/to/file
or:
git checkout MERGE_HEAD -- path/to/file
After we do this and we are good:
git add .
If you want to understand more, see wonderful post of torek here : git checkout --ours does not remove files from unmerged files list
Just do something like this,<input type="radio" ng-disabled="loading" name="dateRange" ng-model="filter.DateRange" value="1" ng-checked="(filter.DateRange == 1)"/>
Use this code to setup your mongodb connection:
var mongoose = require('mongoose');
var mongoURI = "mongodb://localhost:27017/test";
var MongoDB = mongoose.connect(mongoURI).connection;
MongoDB.on('error', function(err) { console.log(err.message); });
MongoDB.once('open', function() {
console.log("mongodb connection open");
});
Make sure mongod is running while you start the server. Are you using Express or just a simple node.js server? What is the error message you get with the above code?
Add a class:
.com_box:after {
content: '';
position: absolute;
left: 18px;
top: 50px;
width: 0;
height: 0;
border-left: 20px solid transparent;
border-right: 20px solid transparent;
border-top: 20px solid #000;
clear: both;
}
Updated your jsfiddle: http://jsfiddle.net/wrm4y8k6/8/
You can do this without JavaScript. You can set the style on both divs to position: fixed
and overflow-y: auto
. You may need to make one of them higher than the other by setting its z-index
(if they overlap).
Here's a basic example on CodePen.
I recommend a clean shutdown with the exit(0) builtin rather than using sys.exit()
I'm not sure if this is good advice.
The very documentation mentioned reads:
The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace. They are useful for the interactive interpreter shell and should not be used in programs.
Then:
exit(code=None)
Objects that when printed, print a message like “Use quit() or Ctrl-D (i.e. EOF) to exit”, and when called, raise SystemExit with the specified exit code.
If we compare it to sys.exit() documentation, it's using the same mechanism which is raising a SystemExit
exception.
Date.now() returns a unix timestamp in milliseconds.
const now = Date.now(); // Unix timestamp in milliseconds_x000D_
console.log( now );
_x000D_
Prior to ECMAScript5 (I.E. Internet Explorer 8 and older) you needed to construct a Date object, from which there are several ways to get a unix timestamp in milliseconds:
console.log( +new Date );_x000D_
console.log( (new Date).getTime() );_x000D_
console.log( (new Date).valueOf() );
_x000D_
You have the same result when calling .size() method or .length property but the .length property is preferred because it doesn't have the overhead of a function call. So the best way:
$("#mylist li").length
file_get_contents(php://input) - gets the raw POST data and you need to use this when you write APIs and need XML/JSON/... input that cannot be decoded to $_POST by PHP some example :
send by post JSON string
<input type="button" value= "click" onclick="fn()">
<script>
function fn(){
var js_obj = {plugin: 'jquery-json', version: 2.3};
var encoded = JSON.stringify( js_obj );
var data= encoded
$.ajax({
type: "POST",
url: '1.php',
data: data,
success: function(data){
console.log(data);
}
});
}
</script>
1.php
//print_r($_POST); //empty!!! don't work ...
var_dump( file_get_contents('php://input'));
From the Javadoc:
The EAGER strategy is a requirement on the persistence provider runtime that data must be eagerly fetched. The LAZY strategy is a hint to the persistence provider runtime that data should be fetched lazily when it is first accessed.
E.g., eager is more proactive than lazy. Lazy only happens on first use (if the provider takes the hint), whereas with eager things (may) get pre-fetched.
It is because you use a relative path.
The easy way to fix this is by using the __DIR__
magic constant, like:
require_once(__DIR__."/initcontrols/config.php");
From the PHP doc:
The directory of the file. If used inside an include, the directory of the included file is returned
Make use of Relative layout it will adjust the view so that you can see that view while typing the text
For apache Ubuntu 2.4.7 , I finally found you need to white list your virtual host in apache2.conf
# access here, or in any related virtual host.
<Directory /home/gav/public_html/>
Options FollowSymLinks
AllowOverride None
Require all granted
</Directory>
I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path
But the main issue was not here. The problem was with these 2 lines of code
strFile = Dir(strPath & "*.csv")
Which should have written as
strFile = Dir(strPath & "\*.csv")
and
With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _
Which should have written as
With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _