try this:
sedSelectNumbers='s".* \(+[0-9]*[.][0-9]*\) .*"\1,"'
sedClearLastComma='s"\(.*\),$"\1"'
cat file.txt |sed "$sedSelectNumbers" |tr -d "\n" |sed "$sedClearLastComma"
the good thing is the easy part of deleting newline "\n" characters!
EDIT: another great way to join lines into a single line with sed is this: |sed ':a;N;$!ba;s/\n/ /g'
got from here.
There are a lot of answer above which will definitely help you but (after 2 days of afford and research on adb memory tools) I think i can help with my opinion too.
As Hackbod says : Thus if you were to take all of the physical RAM actually mapped in to each process, and add up all of the processes, you would probably end up with a number much greater than the actual total RAM. so there is no way you can get exact amount of memory per process.
But you can get close to it by some logic..and I will tell how..
There are some API like
android.os.Debug.MemoryInfo
andActivityManager.getMemoryInfo()
mentioned above which you already might have being read about and used but I will talk about other way
So firstly you need to be a root user to get it work. Get into console with root privilege by executing su
in process and get its output and input stream
. Then pass id\n
(enter) in ouputstream and write it to process output, If will get an inputstream containing uid=0
, you are root user.
Now here is the logic which you will use in above process
When you get ouputstream of process pass you command (procrank, dumpsys meminfo etc...) with \n
instead of id and get its inputstream
and read, store the stream in bytes[ ] ,char[ ] etc.. use raw data..and you are done!!!!!
permission :
<uses-permission android:name="android.permission.FACTORY_TEST"/>
Check if you are root user :
// su command to get root access
Process process = Runtime.getRuntime().exec("su");
DataOutputStream dataOutputStream =
new DataOutputStream(process.getOutputStream());
DataInputStream dataInputStream =
new DataInputStream(process.getInputStream());
if (dataInputStream != null && dataOutputStream != null) {
// write id to console with enter
dataOutputStream.writeBytes("id\n");
dataOutputStream.flush();
String Uid = dataInputStream.readLine();
// read output and check if uid is there
if (Uid.contains("uid=0")) {
// you are root user
}
}
Execute your command with su
Process process = Runtime.getRuntime().exec("su");
DataOutputStream dataOutputStream =
new DataOutputStream(process.getOutputStream());
if (dataOutputStream != null) {
// adb command
dataOutputStream.writeBytes("procrank\n");
dataOutputStream.flush();
BufferedInputStream bufferedInputStream =
new BufferedInputStream(process.getInputStream());
// this is important as it takes times to return to next line so wait
// else you with get empty bytes in buffered stream
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// read buffered stream into byte,char etc.
byte[] bff = new byte[bufferedInputStream.available()];
bufferedInputStream.read(bff);
bufferedInputStream.close();
}
}
You get a raw data in a single string from console instead of in some instance from any API,which is complex to store as you will need to separate it manually.
This is just a try, please suggest me if I missed something
Another way is to use box-shadow
:
#mybox {
box-shadow:
0 0 0 1px #CCC,
0 0 0 2px #888,
0 0 0 3px #444,
0 0 0 4px #000;
-moz-box-shadow:
0 0 0 1px #CCC,
0 0 0 2px #888,
0 0 0 3px #444,
0 0 0 4px #000;
-webkit-shadow:
0 0 0 1px #CCC,
0 0 0 2px #888,
0 0 0 3px #444,
0 0 0 4px #000;
}
<div id="mybox">ABC</div>
See example here.
get()
raises aDoesNotExist
exception if an object is not found for the given parameters. This exception is also an attribute of the model class. TheDoesNotExist
exception inherits fromdjango.core.exceptions.ObjectDoesNotExist
You can catch the exception and assign None
to go.
from django.core.exceptions import ObjectDoesNotExist
try:
go = Content.objects.get(name="baby")
except ObjectDoesNotExist:
go = None
The code below differs from all other code because at the end it prints the response string in the console that the request returns. I learned in previous posts that the user doesn't get the response Stream and displays it.
//Visual Basic Implementation Request and Response String
Dim params = "key1=value1&key2=value2"
Dim byteArray = UTF8.GetBytes(params)
Dim url = "https://okay.com"
Dim client = WebRequest.Create(url)
client.Method = "POST"
client.ContentType = "application/x-www-form-urlencoded"
client.ContentLength = byteArray.Length
Dim stream = client.GetRequestStream()
//sending the data
stream.Write(byteArray, 0, byteArray.Length)
stream.Close()
//getting the full response in a stream
Dim response = client.GetResponse().GetResponseStream()
//reading the response
Dim result = New StreamReader(response)
//Writes response string to Console
Console.WriteLine(result.ReadToEnd())
Console.ReadKey()
Put webpack -v
into your package.json:
{
"name": "js",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack -v",
"dev": "webpack --watch"
}
}
Then enter in the console:
npm run build
Expected output should look like:
> npm run build
> [email protected] build /home/user/repositories/myproject/js
> webpack -v
4.42.0
Since beta Bootstrap 4 doesn't depend on Tether but Popper.js. All scripts (must be in this order):
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
See the current documentation for the newest script versions.
Bootstrap 4 alpha needs Tether, so you need to include tether.min.js
before you include bootstrap.min.js
, eg.
<script src="https://npmcdn.com/[email protected]/dist/js/tether.min.js"></script>
<script src="https://npmcdn.com/[email protected]/dist/js/bootstrap.min.js"></script>
Fill
is command always return how many records inserted into dataset.
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlString, sqlConn);
var count = da.Fill(ds);
if(count > 0)
{
Console.Write("It is not Empty");
}
The arguments can never be null
. They just wont exist.
In other words, what you need to do is check the length of your arguments.
public static void main(String[] args)
{
// Check how many arguments were passed in
if(args.length == 0)
{
System.out.println("Proper Usage is: java program filename");
System.exit(0);
}
}
you have to change the -> sourceCompatibility = '1.7' in build.Gradle
module.exports = { ClientIDUnsplash : 'SuperSecretKey' };
var { ClientIDUnsplash } = require('./FileOne');
This example works best for React.
My preference would actually be to have a dist target in your Makefile (or other build system) that exports a distributable archive of your code (.tar.bz2, .zip, .jar, or whatever is appropriate). If you happen to be using GNU autotools or Perl's MakeMaker systems, I think this exists for you automatically. If not, I highly recommend adding it.
ETA (2012-09-06): Wow, harsh downvotes. I still believe it is better to build your distributions with your build tools rather than your source code control tool. I believe in building artifacts with build tools. In my current job, our main product is built with an ant target. We are in the midst of switching source code control systems, and the presence of this ant target means one less hassle in migration.
I faced with the same issue. I just added credentials config:
aws_access_key_id = your_aws_access_key_id
aws_secret_access_key = your_aws_secret_access_key
into "~/.aws/credentials" + restart terminal for default profile.
In the case of multi profiles --profile arg needs to be added:
aws s3 sync ./localDir s3://bucketName --profile=${PROFILE_NAME}
where PROFILE_NAME:
.bash_profile ( or .bashrc) -> export PROFILE_NAME="yourProfileName"
More info about how to config credentials and multi profiles can be found here
IsValidDate: function(date) {
var regex = /\d{1,2}\/\d{1,2}\/\d{4}/;
if (!regex.test(date)) return false;
var day = Number(date.split("/")[1]);
date = new Date(date);
if (date && date.getDate() != day) return false;
return true;
}
I ended up doing this
typeof ($('#mySelector').data('events').click) == "object"
If you look in the source code for $.fn.bind
you will find that it's just an rewrite function for on
:
function (types, data, fn) {
return this.on(types, null, data, fn);
}
Try this: jdbc:oracle:thin:@oracle.hostserver2.mydomain.ca:1522/ABCD
Edit: per comment below this is actualy correct: jdbc:oracle:thin:@//oracle.hostserver2.mydomain.ca:1522/ABCD
(note the //
)
Here is a link to a helpful article
If you are using jQuery:
$('#sel').val('bike');
Check out UI Bootstrap's pagination directive. I ended up using it rather than what is posted here as it has enough features for my current use and has a thorough test spec to accompany it.
<!-- table here -->
<pagination
ng-model="currentPage"
total-items="todos.length"
max-size="maxSize"
boundary-links="true">
</pagination>
<!-- items/page select here if you like -->
todos.controller("TodoController", function($scope) {
$scope.filteredTodos = []
,$scope.currentPage = 1
,$scope.numPerPage = 10
,$scope.maxSize = 5;
$scope.makeTodos = function() {
$scope.todos = [];
for (i=1;i<=1000;i++) {
$scope.todos.push({ text:"todo "+i, done:false});
}
};
$scope.makeTodos();
$scope.$watch("currentPage + numPerPage", function() {
var begin = (($scope.currentPage - 1) * $scope.numPerPage)
, end = begin + $scope.numPerPage;
$scope.filteredTodos = $scope.todos.slice(begin, end);
});
});
I have made a working plunker for reference.
<!-- table here -->
<div data-pagination="" data-num-pages="numPages()"
data-current-page="currentPage" data-max-size="maxSize"
data-boundary-links="true"></div>
<!-- items/page select here if you like -->
todos.controller("TodoController", function($scope) {
$scope.filteredTodos = []
,$scope.currentPage = 1
,$scope.numPerPage = 10
,$scope.maxSize = 5;
$scope.makeTodos = function() {
$scope.todos = [];
for (i=1;i<=1000;i++) {
$scope.todos.push({ text:"todo "+i, done:false});
}
};
$scope.makeTodos();
$scope.numPages = function () {
return Math.ceil($scope.todos.length / $scope.numPerPage);
};
$scope.$watch("currentPage + numPerPage", function() {
var begin = (($scope.currentPage - 1) * $scope.numPerPage)
, end = begin + $scope.numPerPage;
$scope.filteredTodos = $scope.todos.slice(begin, end);
});
});
I have made a working plunker for reference.
To print the name of the fields in a struct:
fmt.Printf("%+v\n", yourProject)
From the fmt
package:
when printing structs, the plus flag (
%+v
) adds field names
That supposes you have an instance of Project (in 'yourProject
')
The article JSON and Go will give more details on how to retrieve the values from a JSON struct.
This Go by example page provides another technique:
type Response2 struct {
Page int `json:"page"`
Fruits []string `json:"fruits"`
}
res2D := &Response2{
Page: 1,
Fruits: []string{"apple", "peach", "pear"}}
res2B, _ := json.Marshal(res2D)
fmt.Println(string(res2B))
That would print:
{"page":1,"fruits":["apple","peach","pear"]}
If you don't have any instance, then you need to use reflection to display the name of the field of a given struct, as in this example.
type T struct {
A int
B string
}
t := T{23, "skidoo"}
s := reflect.ValueOf(&t).Elem()
typeOfT := s.Type()
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
fmt.Printf("%d: %s %s = %v\n", i,
typeOfT.Field(i).Name, f.Type(), f.Interface())
}
This is what finally worked for me.
Configure your Android emulator's proxy to use your IP address as host name and the port your backend is running on as port (in my case: 192.168.1.86:8080
Have your Android app send requests to the same URL (192.168.1.86:8080) (sending requests to localhost, and http://10.0.2.2 did not work for me)
Use a for
loop instead of .forEach()
var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false
for(var call of myObj) {
console.log(call)
var a = call['a'], b = call['b']
if(a == null || b == null) {
result = false
break
}
}
Use a regular for loop and format the index to be used in the selector.
var array = [];
for (var i = 0; i < 4; i++) {
var selector = '' + i;
if (selector.length == 1)
selector = '0' + selector;
selector = '#event' + selector;
array.push($(selector, response).html());
}
The following worked for me.
This would create the required meta data and other internal eclipse project file system which will display your project's files.
You can also import the project directly as a file system. Follow the above steps if you are unable to import it directly.
sudo chown -R $(whoami) /usr/local
would do just fine as mentioned in the brew site troubleshooting
use this:
$(document).on('show.bs.modal','#myModal', function () {
alert('hi');
})
It points to the docker host! I followed these steps:
$ boot2docker start
Waiting for VM and Docker daemon to start...
..............................
Started.
To connect the Docker client to the Docker daemon, please set:
export DOCKER_HOST=tcp://192.168.59.103:2375
$ export DOCKER_HOST=tcp://192.168.59.103:2375
$ docker run ubuntu:14.04 /bin/echo 'Hello world'
Unable to find image 'ubuntu:14.04' locally
Pulling repository ubuntu
9cbaf023786c: Download complete
511136ea3c5a: Download complete
97fd97495e49: Download complete
2dcbbf65536c: Download complete
6a459d727ebb: Download complete
8f321fc43180: Download complete
03db2b23cf03: Download complete
Hello world
You can get top and left without traversing DOM like this:
function getCoords(elem) { // crossbrowser version
var box = elem.getBoundingClientRect();
var body = document.body;
var docEl = document.documentElement;
var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft;
var clientTop = docEl.clientTop || body.clientTop || 0;
var clientLeft = docEl.clientLeft || body.clientLeft || 0;
var top = box.top + scrollTop - clientTop;
var left = box.left + scrollLeft - clientLeft;
return { top: Math.round(top), left: Math.round(left) };
}
SELECT ..., CONCAT( 'category_id=', tableOne.category_id) as query2 FROM tableOne
LEFT JOIN tableTwo
ON tableTwo.query = query2
To answer the question. stringstream
basically allows you to treat a string
object like a stream
, and use all stream
functions and operators on it.
I saw it used mainly for the formatted output/input goodness.
One good example would be c++
implementation of converting number to stream object.
Possible example:
template <class T>
string num2str(const T& num, unsigned int prec = 12) {
string ret;
stringstream ss;
ios_base::fmtflags ff = ss.flags();
ff |= ios_base::floatfield;
ff |= ios_base::fixed;
ss.flags(ff);
ss.precision(prec);
ss << num;
ret = ss.str();
return ret;
};
Maybe it's a bit complicated but it is quite complex. You create stringstream
object ss
, modify its flags, put a number into it with operator<<
, and extract it via str()
. I guess that operator>>
could be used.
Also in this example the string
buffer is hidden and not used explicitly. But it would be too long of a post to write about every possible aspect and use-case.
Note: I probably stole it from someone on SO and refined, but I don't have original author noted.
To check for all int chars, you can simply use a double negative. if (!searchString.matches("[^0-9]+$")) ...
[^0-9]+$ checks to see if there are any characters that are not integer, so the test fails if it's true. Just NOT that and you get true on success.
If you change from using a lambda with one argument to a function with one argument, you will get this error.
For example:
You had:
foobar = lambda do |baz|
puts baz
end
and you changed the definition to
def foobar(baz)
puts baz
end
And you left your invocation as:
foobar.call(baz)
And then you got the message
ArgumentError: wrong number of arguments (0 for 1)
when you really meant:
foobar(baz)
This answer has two main sections:
If you're only interested in the solutions, skip the first section.
To fully understand how centering works in a grid container, it's important to first understand the structure and scope of grid layout.
The HTML structure of a grid container has three levels:
Each of these levels is independent from the others, in terms of applying grid properties.
The scope of a grid container is limited to a parent-child relationship.
This means that a grid container is always the parent and a grid item is always the child. Grid properties work only within this relationship.
Descendants of a grid container beyond the children are not part of grid layout and will not accept grid properties. (At least not until the subgrid
feature has been implemented, which will allow descendants of grid items to respect the lines of the primary container.)
Here's an example of the structure and scope concepts described above.
Imagine a tic-tac-toe-like grid.
article {
display: inline-grid;
grid-template-rows: 100px 100px 100px;
grid-template-columns: 100px 100px 100px;
grid-gap: 3px;
}
You want the X's and O's centered in each cell.
So you apply the centering at the container level:
article {
display: inline-grid;
grid-template-rows: 100px 100px 100px;
grid-template-columns: 100px 100px 100px;
grid-gap: 3px;
justify-items: center;
}
But because of the structure and scope of grid layout, justify-items
on the container centers the grid items, not the content (at least not directly).
article {_x000D_
display: inline-grid;_x000D_
grid-template-rows: 100px 100px 100px;_x000D_
grid-template-columns: 100px 100px 100px;_x000D_
grid-gap: 3px;_x000D_
justify-items: center;_x000D_
}_x000D_
_x000D_
section {_x000D_
border: 2px solid black;_x000D_
font-size: 3em;_x000D_
}
_x000D_
<article>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
</article>
_x000D_
Same problem with align-items
: The content may be centered as a by-product, but you've lost the layout design.
article {
display: inline-grid;
grid-template-rows: 100px 100px 100px;
grid-template-columns: 100px 100px 100px;
grid-gap: 3px;
justify-items: center;
align-items: center;
}
article {_x000D_
display: inline-grid;_x000D_
grid-template-rows: 100px 100px 100px;_x000D_
grid-template-columns: 100px 100px 100px;_x000D_
grid-gap: 3px;_x000D_
justify-items: center;_x000D_
align-items: center;_x000D_
}_x000D_
_x000D_
section {_x000D_
border: 2px solid black;_x000D_
font-size: 3em;_x000D_
}
_x000D_
<article>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
</article>
_x000D_
To center the content you need to take a different approach. Referring again to the structure and scope of grid layout, you need to treat the grid item as the parent and the content as the child.
article {
display: inline-grid;
grid-template-rows: 100px 100px 100px;
grid-template-columns: 100px 100px 100px;
grid-gap: 3px;
}
section {
display: flex;
justify-content: center;
align-items: center;
border: 2px solid black;
font-size: 3em;
}
article {_x000D_
display: inline-grid;_x000D_
grid-template-rows: 100px 100px 100px;_x000D_
grid-template-columns: 100px 100px 100px;_x000D_
grid-gap: 3px;_x000D_
}_x000D_
_x000D_
section {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
border: 2px solid black;_x000D_
font-size: 3em;_x000D_
}
_x000D_
<article>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
</article>
_x000D_
There are multiple methods for centering grid items and their content.
Here's a basic 2x2 grid:
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
}_x000D_
_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
For a simple and easy way to center the content of grid items use flexbox.
More specifically, make the grid item into a flex container.
There is no conflict, spec violation or other problem with this method. It's clean and valid.
grid-item {
display: flex;
align-items: center;
justify-content: center;
}
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
display: flex; /* new */_x000D_
align-items: center; /* new */_x000D_
justify-content: center; /* new */_x000D_
}_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
See this post for a complete explanation:
In the same way that a flex item can also be a flex container, a grid item can also be a grid container. This solution is similar to the flexbox solution above, except centering is done with grid, not flex, properties.
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
display: grid; /* new */_x000D_
align-items: center; /* new */_x000D_
justify-items: center; /* new */_x000D_
}_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
auto
marginsUse margin: auto
to vertically and horizontally center grid items.
grid-item {
margin: auto;
}
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
margin: auto;_x000D_
}_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
To center the content of grid items you need to make the item into a grid (or flex) container, wrap anonymous items in their own elements (since they cannot be directly targeted by CSS), and apply the margins to the new elements.
grid-item {
display: flex;
}
span, img {
margin: auto;
}
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
span, img {_x000D_
margin: auto;_x000D_
}_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item><span>this text should be centered</span></grid-item>_x000D_
<grid-item><span>this text should be centered</span></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
When considering using the following properties to align grid items, read the section on auto
margins above.
align-items
justify-items
align-self
justify-self
https://www.w3.org/TR/css-align-3/#property-index
text-align: center
To center content horizontally in a grid item, you can use the text-align
property.
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
text-align: center; /* new */_x000D_
}_x000D_
_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
Note that for vertical centering, vertical-align: middle
will not work.
This is because the vertical-align
property applies only to inline and table-cell containers.
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
text-align: center; /* <--- works */_x000D_
vertical-align: middle; /* <--- fails */_x000D_
}_x000D_
_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
One might say that display: inline-grid
establishes an inline-level container, and that would be true. So why doesn't vertical-align
work in grid items?
The reason is that in a grid formatting context, items are treated as block-level elements.
The
display
value of a grid item is blockified: if the specifieddisplay
of an in-flow child of an element generating a grid container is an inline-level value, it computes to its block-level equivalent.
In a block formatting context, something the vertical-align
property was originally designed for, the browser doesn't expect to find a block-level element in an inline-level container. That's invalid HTML.
Lastly, there's a general CSS centering solution that also works in Grid: absolute positioning
This is a good method for centering objects that need to be removed from the document flow. For example, if you want to:
Simply set position: absolute
on the element to be centered, and position: relative
on the ancestor that will serve as the containing block (it's usually the parent). Something like this:
grid-item {
position: relative;
text-align: center;
}
span {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
position: relative;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
span, img {_x000D_
position: absolute;_x000D_
left: 50%;_x000D_
top: 50%;_x000D_
transform: translate(-50%, -50%);_x000D_
}_x000D_
_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item><span>this text should be centered</span></grid-item>_x000D_
<grid-item><span>this text should be centered</span></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
Here's a complete explanation for how this method works:
Here's the section on absolute positioning in the Grid spec:
Open Android SDK manager,"intelhaxm-86 emulator" install that
The answer from Tanoh could use some clarification. VersionCode is the equivalent of a build number. So typically an app will go through many iterations before release. Some of these iterations may make it to the Google Play store in the form of alpha, beta, and actual releases. Each successive iteration must have an incremented versionCode. However, typically you only increase the versionName when between public releases. Both numbers are significant. Your users need to know if the version they have on their phone is the latest or not (versionName) and the Play Store and CI systems such as bitrise rely on and/or update the build number (versionCode)
The R packages dplyr and sf import the operator %>% from the R package magrittr.
Help is available by using the following command:
?'%>%'
Of course the package must be loaded before by using e.g.
library(sf)
The documentation of the magrittr forward-pipe operator gives a good example: When functions require only one argument, x %>% f is equivalent to f(x)
I use mostly 978px width for my designs. Adv. of 978px : can be divided by 2,3.
In my case this error was caused by the existence of the _MigrationsHistory table in the database. Deleting that table fixed the problem. Not sure how that table got into our test environment database.
To select properties a
AND b
of a X
element:
X[a][b]
To select properties a
OR b
of a X
element:
X[a],X[b]
Change this:
<li><a href="#one">One</a></li>
to this:
<li><a data-toggle="collapse" data-target=".navbar-collapse" href="#one">One</a></li>
This simple change worked for me.
As I felt similarly confused with .transform
operation vs. .apply
I found a few answers shedding some light on the issue. This answer for example was very helpful.
My takeout so far is that .transform
will work (or deal) with Series
(columns) in isolation from each other. What this means is that in your last two calls:
df.groupby('A').transform(lambda x: (x['C'] - x['D']))
df.groupby('A').transform(lambda x: (x['C'] - x['D']).mean())
You asked .transform
to take values from two columns and 'it' actually does not 'see' both of them at the same time (so to speak). transform
will look at the dataframe columns one by one and return back a series (or group of series) 'made' of scalars which are repeated len(input_column)
times.
So this scalar, that should be used by .transform
to make the Series
is a result of some reduction function applied on an input Series
(and only on ONE series/column at a time).
Consider this example (on your dataframe):
zscore = lambda x: (x - x.mean()) / x.std() # Note that it does not reference anything outside of 'x' and for transform 'x' is one column.
df.groupby('A').transform(zscore)
will yield:
C D
0 0.989 0.128
1 -0.478 0.489
2 0.889 -0.589
3 -0.671 -1.150
4 0.034 -0.285
5 1.149 0.662
6 -1.404 -0.907
7 -0.509 1.653
Which is exactly the same as if you would use it on only on one column at a time:
df.groupby('A')['C'].transform(zscore)
yielding:
0 0.989
1 -0.478
2 0.889
3 -0.671
4 0.034
5 1.149
6 -1.404
7 -0.509
Note that .apply
in the last example (df.groupby('A')['C'].apply(zscore)
) would work in exactly the same way, but it would fail if you tried using it on a dataframe:
df.groupby('A').apply(zscore)
gives error:
ValueError: operands could not be broadcast together with shapes (6,) (2,)
So where else is .transform
useful? The simplest case is trying to assign results of reduction function back to original dataframe.
df['sum_C'] = df.groupby('A')['C'].transform(sum)
df.sort('A') # to clearly see the scalar ('sum') applies to the whole column of the group
yielding:
A B C D sum_C
1 bar one 1.998 0.593 3.973
3 bar three 1.287 -0.639 3.973
5 bar two 0.687 -1.027 3.973
4 foo two 0.205 1.274 4.373
2 foo two 0.128 0.924 4.373
6 foo one 2.113 -0.516 4.373
7 foo three 0.657 -1.179 4.373
0 foo one 1.270 0.201 4.373
Trying the same with .apply
would give NaNs
in sum_C
.
Because .apply
would return a reduced Series
, which it does not know how to broadcast back:
df.groupby('A')['C'].apply(sum)
giving:
A
bar 3.973
foo 4.373
There are also cases when .transform
is used to filter the data:
df[df.groupby(['B'])['D'].transform(sum) < -1]
A B C D
3 bar three 1.287 -0.639
7 foo three 0.657 -1.179
I hope this adds a bit more clarity.
Readin file with file inputstream and append file content to string.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class CopyOffileInputStream {
public static void main(String[] args) {
//File file = new File("./store/robots.txt");
File file = new File("swingloggingsscce.log");
FileInputStream fis = null;
String str = "";
try {
fis = new FileInputStream(file);
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
str += (char) content;
}
System.out.println("After reading file");
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
This will show original dimensions of Image on Hover using jQuery custom code
HTML
<ul class="thumb">
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/1.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/2.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/3.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/4.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/5.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/6.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/7.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/8.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/9.jpg)"></div>
</a>
</li>
</ul>
CSS
ul.thumb {
float: left;
list-style: none;
padding: 10px;
width: 360px;
margin: 80px;
}
ul.thumb li {
margin: 0;
padding: 5px;
float: left;
position: relative;
/* Set the absolute positioning base coordinate */
width: 110px;
height: 110px;
}
ul.thumb li .thumbnail-wrap {
width: 100px;
height: 100px;
/* Set the small thumbnail size */
-ms-interpolation-mode: bicubic;
/* IE Fix for Bicubic Scaling */
border: 1px solid #ddd;
padding: 5px;
position: absolute;
left: 0;
top: 0;
background-size: cover;
background-repeat: no-repeat;
-webkit-box-shadow: inset -3px 0px 40px -15px rgba(0, 0, 0, 1);
-moz-box-shadow: inset -3px 0px 40px -15px rgba(0, 0, 0, 1);
box-shadow: inset -3px 0px 40px -15px rgba(0, 0, 0, 1);
}
ul.thumb li .thumbnail-wrap.hover {
-webkit-box-shadow: -2px 1px 22px -1px rgba(0, 0, 0, 0.75);
-moz-box-shadow: -2px 1px 22px -1px rgba(0, 0, 0, 0.75);
box-shadow: -2px 1px 22px -1px rgba(0, 0, 0, 0.75);
}
.thumnail-zoomed-wrapper {
display: none;
position: fixed;
top: 0px;
left: 0px;
height: 100vh;
width: 100%;
background: rgba(0, 0, 0, 0.2);
z-index: 99;
}
.thumbnail-zoomed-image {
margin: auto;
display: block;
text-align: center;
margin-top: 12%;
}
.thumbnail-zoomed-image img {
max-width: 100%;
}
.close-image-zoom {
z-index: 10;
float: right;
margin: 10px;
cursor: pointer;
}
jQuery
var perc = 40;
$("ul.thumb li").hover(function () {
$("ul.thumb li").find(".thumbnail-wrap").css({
"z-index": "0"
});
$(this).find(".thumbnail-wrap").css({
"z-index": "10"
});
var imageval = $(this).find(".thumbnail-wrap").css("background-image").slice(5);
var img;
var thisImage = this;
img = new Image();
img.src = imageval.substring(0, imageval.length - 2);
img.onload = function () {
var imgh = this.height * (perc / 100);
var imgw = this.width * (perc / 100);
$(thisImage).find(".thumbnail-wrap").addClass("hover").stop()
.animate({
marginTop: "-" + (imgh / 4) + "px",
marginLeft: "-" + (imgw / 4) + "px",
width: imgw + "px",
height: imgh + "px"
}, 200);
}
}, function () {
var thisImage = this;
$(this).find(".thumbnail-wrap").removeClass("hover").stop()
.animate({
marginTop: "0",
marginLeft: "0",
top: "0",
left: "0",
width: "100px",
height: "100px",
padding: "5px"
}, 400, function () {});
});
//Show thumbnail in fullscreen
$("ul.thumb li .thumbnail-wrap").click(function () {
var imageval = $(this).css("background-image").slice(5);
imageval = imageval.substring(0, imageval.length - 2);
$(".thumbnail-zoomed-image img").attr({
src: imageval
});
$(".thumnail-zoomed-wrapper").fadeIn();
return false;
});
//Close fullscreen preview
$(".thumnail-zoomed-wrapper .close-image-zoom").click(function () {
$(".thumnail-zoomed-wrapper").hide();
return false;
});
This can be easily done by using rd
command with two parameters:
rd <folder> /Q /S
/Q - Quiet mode, do not ask if ok to remove a directory tree with /S
/S - Removes all directories and files in the specified directory in addition to the directory itself. Used to remove a directory tree.
For multicolumn listbox extract data from any column of selected row by
listboxControl.List(listboxControl.ListIndex,col_num)
where col_num is required column ( 0 for first column)
Let me introduce you to my friend "dotglob". It turns on and off whether or not "*" includes hidden files.
$ mkdir test
$ cd test
$ touch a b c .hidden .hi .den
$ ls -a
. .. .den .hi .hidden a b c
$ shopt -u dotglob
$ ls *
a b c
$ for i in * ; do echo I found: $i ; done
I found: a
I found: b
I found: c
$ shopt -s dotglob
$ ls *
.den .hi .hidden a b c
$ for i in * ; do echo I found: $i ; done
I found: .den
I found: .hi
I found: .hidden
I found: a
I found: b
I found: c
It defaults to "off".
$ shopt dotglob
dotglob off
It is best to turn it back on when you are done otherwise you will confuse things that assume it will be off.
Read XLSX (Excel 97-2003)
https://github.com/shuchkin/simplexls
if ( $xls = SimpleXLS::parse('book.xls') ) {
print_r( $xls->rows() );
} else {
echo SimpleXLS::parseError();
}
Read XLSX (Excel 2003+)
https://github.com/shuchkin/simplexlsx
if ( $xlsx = SimpleXLSX::parse('book.xlsx') ) {
print_r( $xlsx->rows() );
} else {
echo SimpleXLSX::parseError();
}
Output
Array ( [0] => Array ( [0] => ISBN [1] => title [2] => author [3] => publisher [4] => ctry ) [1] => Array ( [0] => 618260307 [1] => The Hobbit [2] => J. R. R. Tolkien [3] => Houghton Mifflin [4] => USA ) )
CSV php reader
https://github.com/shuchkin/simplecsv
You have already have container-selinux installed for version 3.7 check if the following docker-ce version works for you , it did for me.
sudo yum -y install docker-ce-cli.x86_64 1:19.03.5-3.el7
>>> thing = 'foo'
>>> type(thing).__name__ == 'str' or type(thing).__name__ == 'unicode'
True
If you don't want to use pickle, you can store the list as text and then evaluate it:
data = [0,1,2,3,4,5]
with open("test.txt", "w") as file:
file.write(str(data))
with open("test.txt", "r") as file:
data2 = eval(file.readline())
# Let's see if data and types are same.
print(data, type(data), type(data[0]))
print(data2, type(data2), type(data2[0]))
[0, 1, 2, 3, 4, 5] class 'list' class 'int'
[0, 1, 2, 3, 4, 5] class 'list' class 'int'
Google, Yahoo, Bing, and other search engines crawl the web in traditional ways using traditional crawlers. They run robots that crawl the HTML on web pages, collecting information along the way. They keep interesting words and look for other links to other pages (these links, the amount of them and the number of them come into play with SEO).
The answer has to do with the fact that the search engine robots work through headless browsers and they most often do not have a javascript rendering engine to render the javascript of a page. This works for most pages as most static pages don't care about JavaScript rendering their page, as their content is already available.
Luckily, crawlers of the larger sites have started to implement a mechanism that allows us to make our JavaScript sites crawlable, but it requires us to implement a change to our site.
If we change our hashPrefix
to be #!
instead of simply #
, then modern search engines will change the request to use _escaped_fragment_
instead of #!
. (With HTML5 mode, i.e. where we have links without the hash prefix, we can implement this same feature by looking at the User Agent
header in our backend).
That is to say, instead of a request from a normal browser that looks like:
http://www.ng-newsletter.com/#!/signup/page
A search engine will search the page with:
http://www.ng-newsletter.com/?_escaped_fragment_=/signup/page
We can set the hash prefix of our Angular apps using a built-in method from ngRoute
:
angular.module('myApp', [])
.config(['$location', function($location) {
$location.hashPrefix('!');
}]);
And, if we're using html5Mode
, we will need to implement this using the meta tag:
<meta name="fragment" content="!">
Reminder, we can set the html5Mode()
with the $location
service:
angular.module('myApp', [])
.config(['$location',
function($location) {
$location.html5Mode(true);
}]);
We have a lot of opportunities to determine how we'll deal with actually delivering content to search engines as static HTML. We can host a backend ourselves, we can use a service to host a back-end for us, we can use a proxy to deliver the content, etc. Let's look at a few options:
We can write a service to handle dealing with crawling our own site using a headless browser, like phantomjs or zombiejs, taking a snapshot of the page with rendered data and storing it as HTML. Whenever we see the query string ?_escaped_fragment_
in a search request, we can deliver the static HTML snapshot we took of the page instead of the pre-rendered page through only JS. This requires us to have a backend that delivers our pages with conditional logic in the middle. We can use something like prerender.io's backend as a starting point to run this ourselves. Of course, we still need to handle the proxying and the snippet handling, but it's a good start.
The easiest and the fastest way to get content into search engine is to use a service Brombone, seo.js, seo4ajax, and prerender.io are good examples of these that will host the above content rendering for you. This is a good option for the times when we don't want to deal with running a server/proxy. Also, it's usually super quick.
For more information about Angular and SEO, we wrote an extensive tutorial on it at http://www.ng-newsletter.com/posts/serious-angular-seo.html and we detailed it even more in our book ng-book: The Complete Book on AngularJS. Check it out at ng-book.com.
For all those who enjoying CONNECTIVITY_CHANGE broadcast, please note this is no more fired when app is in background in Android O.
https://developer.android.com/about/versions/o/background.html
Why do you want to use strange hard commands, when you can use:
if(a < 0)
a -= 2a;
The if statement obviously only applies when you aren't sure if the number will be positive or negative.
Otherwise you'll have to use this code:
a = abs(a) // a is an integer
a = fabs(a) // a is declared as a double
a = fabsf(a) // a is declared as a float (C++ 11 is able to use fabs(a) for floats instead of fabs)
To activate C++ 11 (if you are using Code::Blocks, you have to:
After following these steps, you should be able to use fabs(a) for floats instead of fabsf(a), which was used only for C99 or less! (Even C++ 98 could allow you to use fabs instead of fabsf :P)
Python lists
translate to JSON arrays
. What it is giving you is a perfectly valid JSON string that could be used in a Javascript application. To get what you expected, you would need to use a dict
:
>>> json.dumps({'apple': 'cat', 'banana':'dog', 'pear':'fish'})
'{"pear": "fish", "apple": "cat", "banana": "dog"}'
Some dude has come up with a smart preprocessor idea in this post
This is untested, but I believe the syntax should work for a lambda query. As you join more tables with this syntax you have to drill further down into the new objects to reach the values you want to manipulate.
var fullEntries = dbContext.tbl_EntryPoint
.Join(
dbContext.tbl_Entry,
entryPoint => entryPoint.EID,
entry => entry.EID,
(entryPoint, entry) => new { entryPoint, entry }
)
.Join(
dbContext.tbl_Title,
combinedEntry => combinedEntry.entry.TID,
title => title.TID,
(combinedEntry, title) => new
{
UID = combinedEntry.entry.OwnerUID,
TID = combinedEntry.entry.TID,
EID = combinedEntry.entryPoint.EID,
Title = title.Title
}
)
.Where(fullEntry => fullEntry.UID == user.UID)
.Take(10);
It seems that Facebook Page Plugin doesn't change at all in past 5-7 years :) It wasn't responsive from the begining and still not now, even new param Adapt to plugin container width
doesn't work or I don't understand how it works.
I'm searching for the most posible simple way to do PLUGIN SIZE 100% WIDTH
, and it seems it is not posible. Nonsense at it's best. How designers solve this problem?
I found the best decision for this time 2017 Oct:
.fb-page, .fb-page iframe[style], .fb-page span {
width: 100% !important;
}
.fb-comments, .fb-comments iframe[style], .fb-comments span {
width: 100% !important;
}
This lets do not broke screen size width for responsive screens, but still looks ugly, because cuted in some time and doesn't stretch... Facebook doesn't care about plugins design at all. That's the truth.
Old question but I usually use this solution:
import org.apache.commons.io.FilenameUtils;
String fileName = "/abc/defg/file.txt";
String basename = FilenameUtils.getBaseName(fileName);
String extension = FilenameUtils.getExtension(fileName);
System.out.println(basename); // file
System.out.println(extension); // txt (NOT ".txt" !)
edgesForExtendedLayout
does the trick for iOS 7. However, if you build the app across iOS 7 SDK and deploy it in iOS 6, the navigation bar appears translucent and the views go beneath it. So, to fix it for both iOS 7 as well as for iOS 6 do this:
self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
self.edgesForExtendedLayout = UIRectEdgeNone; // iOS 7 specific
I needed to apply a translation to the Ok and Cancel buttons. I modified the code to except dynamic text (calls my translation function)
$.extend({_x000D_
confirm: function(message, title, okAction) {_x000D_
$("<div></div>").dialog({_x000D_
// Remove the closing 'X' from the dialog_x000D_
open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); },_x000D_
width: 500,_x000D_
buttons: [{_x000D_
text: localizationInstance.translate("Ok"),_x000D_
click: function () {_x000D_
$(this).dialog("close");_x000D_
okAction();_x000D_
}_x000D_
},_x000D_
{_x000D_
text: localizationInstance.translate("Cancel"),_x000D_
click: function() {_x000D_
$(this).dialog("close");_x000D_
}_x000D_
}],_x000D_
close: function(event, ui) { $(this).remove(); },_x000D_
resizable: false,_x000D_
title: title,_x000D_
modal: true_x000D_
}).text(message);_x000D_
}_x000D_
});
_x000D_
I had the very same issue, not being able to instantiate the type of a class which I was absolutely sure was not abstract. Turns out I was implementing an abstract class from Java.util
instead of implementing my own class.
So if the previous answers did not help you, please check that you import
the class you actually wanted to import, and not something else with the same name that you IDE might have hinted you.
For example, if you were trying to instantiate the class Queue from the package myCollections which you coded yourself :
import java.util.*; // replace this line
import myCollections.Queue; // by this line
Queue<Edge> theQueue = new Queue<Edge>();
No. If you don't have access to the php.ini, you can't guarantee that changes would have any effect.
I doubt you need to extend your sessions time though.
It has pretty sensible timeout at the moment and there are no reasons to extend it.
This simple solution worked for me.
import 'rxjs/add/operator/pairwise';
import { Router } from '@angular/router';
export class TempComponent {
constructor(private router: Router) {
this.router.events.pairwise().subscribe((event) => {
console.log(event); // NavigationEnd will have last and current visit url
});
};
}
The "lsb_release" command provides certain Linux Standard Base and distribution-specific information. So using the below command we can get Operating system name and operating system version.
"lsb_release -a"
/System/Library
and /usr/bin
, as this may break your whole operating system.NOTE: The steps listed below do not affect the Apple-supplied system Python 2.7; they only remove a third-party Python framework, like those installed by python.org installers.
The complete list is documented here. Basically, all you need to do is the following:
Remove the third-party Python 2.7 framework
sudo rm -rf /Library/Frameworks/Python.framework/Versions/2.7
Remove the Python 2.7 applications directory
sudo rm -rf "/Applications/Python 2.7"
Remove the symbolic links, in /usr/local/bin
, that point to this Python version. See them using
ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7'
and then run the following command to remove all the links:
cd /usr/local/bin/
ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' | awk '{print $9}' | tr -d @ | xargs rm
If necessary, edit your shell profile file(s) to remove adding /Library/Frameworks/Python.framework/Versions/2.7
to your PATH
environment file. Depending on which shell you use, any of the following files may have been modified:
~/.bash_login
, ~/.bash_profile
, ~/.cshrc
, ~/.profile
, ~/.tcshrc
, and/or ~/.zprofile
.
It's called String#start_with?
, not String#startswith
: In Ruby, the names of boolean-ish methods end with ?
and the words in method names are separated with an _
. Not sure where the s
went, personally, I'd prefer String#starts_with?
over the actual String#start_with?
Update! You can access the Android filesystem via Android Device Monitor. In Android Studio go to Tools >> Android >> Android Device Monitor.
Note that you can run your app in the simulator while using the Android Device Monitor. But you cannot debug you app while using the Android Device Monitor.
This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):
SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC
This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.
$var = mysqli_real_escape_string($conn, $_POST['varfield']);
You didn't tell us what particular problem do you have with the WinSCP, so I can really only repeat what's in WinSCP documentation.
Download WinSCP .NET assembly.
The latest package as of now is WinSCP-5.17.10-Automation.zip
;
Extract the .zip
archive along your script;
Use a code like this (based on the official PowerShell upload example):
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "example.com"
UserName = "user"
Password = "mypassword"
SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
}
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Upload
$session.PutFiles("C:\FileDump\export.txt", "/Outbox/").Check()
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
You can have WinSCP generate the PowerShell script for the upload for you:
You will get a code like above with all session and transfer settings filled in.
(I'm the author of WinSCP)
To run org.apache.http.legacy perfectely in Android 9.0 Pie create an xml file res/xml/network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>
And add 2 tags tag in your AndroidManifest.xml
android:networkSecurityConfig="@xml/network_security_config" android:name="org.apache.http.legacy"
<?xml version="1.0" encoding="utf-8"?>
<manifest......>
<application android:networkSecurityConfig="@xml/network_security_config">
<activity..../>
......
......
<uses-library
android:name="org.apache.http.legacy"
android:required="false"/>
</application>
Also add useLibrary 'org.apache.http.legacy'
in your app build gradle
android {
compileSdkVersion 28
defaultConfig {
applicationId "your application id"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
useLibrary 'org.apache.http.legacy'
}
Store scroll length in a global variable and restore it when needed!
var sctollTop_length = 0;
function scroll_pause(){
sctollTop_length = $(window).scrollTop();
$("body").css("overflow", "hidden");
}
function scroll_resume(){
$("body").css("overflow", "auto");
$(window).scrollTop(sctollTop_length);
}
slight variation of Charles Bailey's answer that gives more information:
git diff --name-only --diff-filter=U | xargs git status
I am also a Windows user. And I have installed Python 3.7 and when I try to install any package it throws the same error that you are getting.
Try this out. This worked for me.
python -m pip install numpy
And whenever you install new package just write python -m pip install <package_name>
Hope this is helpful.
In gcc, you can label the parameter with the unused
attribute.
This attribute, attached to a variable, means that the variable is meant to be possibly unused. GCC will not produce a warning for this variable.
In practice this is accomplished by putting __attribute__ ((unused))
just before the parameter. For example:
void foo(workerid_t workerId) { }
becomes
void foo(__attribute__((unused)) workerid_t workerId) { }
If you are serializing your data object, it will not be a proper json object. Take what you have, and just wrap the data object in a JSON.stringify()
.
$http({
url: '/user_to_itsr',
method: "POST",
data: JSON.stringify({application:app, from:d1, to:d2}),
headers: {'Content-Type': 'application/json'}
}).success(function (data, status, headers, config) {
$scope.users = data.users; // assign $scope.persons here as promise is resolved here
}).error(function (data, status, headers, config) {
$scope.status = status + ' ' + headers;
});
You can iterate through arraylist to identify the index and eventually the object which you need to modify. You can use for-each for the same as below:
for(Customer customer : myList) {
if(customer!=null && "Doe".equals(customer.getName())) {
customer.setEmail("[email protected]");
break;
}
}
Here customer is a reference to the object present in Arraylist, If you change any property of this customer reference, these changes will reflect in your object stored in Arraylist.
Probably the easiest way to do it is to have a php file return JSON. So let's say you have a file query.php
,
$result = mysql_query("SELECT field_name, field_value
FROM the_table");
$to_encode = array();
while($row = mysql_fetch_assoc($result)) {
$to_encode[] = $row;
}
echo json_encode($to_encode);
If you're constrained to using document.write (as you note in the comments below) then give your fields an id attribute like so: <input type="text" id="field1" />
. You can reference that field with this jQuery: $("#field1").val()
.
Here's a complete example with the HTML. If we're assuming your fields are called field1
and field2
, then
<!DOCTYPE html>
<html>
<head>
<title>That's about it</title>
</head>
<body>
<form>
<input type="text" id="field1" />
<input type="text" id="field2" />
</form>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$.getJSON('data.php', function(data) {
$.each(data, function(fieldName, fieldValue) {
$("#" + fieldName).val(fieldValue);
});
});
</script>
</html>
That's insertion after the HTML has been constructed, which might be easiest. If you mean to populate data while you're dynamically constructing the HTML, then you'd still want the PHP file to return JSON, you would just add it directly into the value
attribute.
This is my sample code for load static variable
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class OnelinkConfig {
public static int MODULE_CODE;
public static int DEFAULT_PAGE;
public static int DEFAULT_SIZE;
@Autowired
public void loadOnelinkConfig(@Value("${onelink.config.exception.module.code}") int code,
@Value("${onelink.config.default.page}") int page, @Value("${onelink.config.default.size}") int size) {
MODULE_CODE = code;
DEFAULT_PAGE = page;
DEFAULT_SIZE = size;
}
}
Be aware that if your string number contains more than 15 significant digits float(s)
will round it.In those cases it is better to use Decimal
Here is an explanation and some code samples: https://docs.python.org/3/library/sys.html#sys.float_info
This is a "feature" of the M2E plugin that had been introduced a while ago. It's not directly related to the JBoss EAR plugin but also happens with most other Maven plugins.
If you have a plugin execution defined in your pom
(like the execution of maven-ear-plugin:generate-application-xml
), you also need to add additional config information for M2E that tells M2E what to do when the build is run in Eclipse, e.g. should the plugin execution be ignored or executed by M2E, should it be also done for incremental builds, ... If that information is missing, M2E complains about it by showing this error message:
"Plugin execution not covered by lifecycle configuration"
See here for a more detailed explanation and some sample config that needs to be added to the pom to make that error go away:
https://www.eclipse.org/m2e/documentation/m2e-execution-not-covered.html
As it turns out, Git is smart enough not to drop a stash if it doesn't apply cleanly. I was able to get to the desired state with the following steps:
git reset HEAD .
(note the trailing dot)git stash
git checkout master
git fetch upstream; git merge upstream/master
git checkout new-branch; git rebase master
git stash apply stash@{1}
An Object if passed as a value type then changes made to the members of the object inside the method are impacted outside the method also. But if the object itself is set to another object or reinitialized then it will not be reflected outside the method. So i would say object as a whole is passed as Valuetype only but object members are still reference type.
private void button1_Click(object sender, EventArgs e)
{
Class1 objc ;
objc = new Class1();
objc.empName = "name1";
checkobj( objc);
MessageBox.Show(objc.empName); //propert value changed; but object itself did not change
}
private void checkobj ( Class1 objc)
{
objc.empName = "name 2";
Class1 objD = new Class1();
objD.empName ="name 3";
objc = objD ;
MessageBox.Show(objc.empName); //name 3
}
std::cout.precision(2);
std::cout<<std::fixed;
when you are using operator overloading try this.
I like this one, because it is suited to be passed as an XElement, which is suitable for SqlCommand
(Sorry it is VB.NET but you get the idea)
<Extension()>
Public Function ToXml(Of T)(array As IEnumerable(Of T)) As XElement
Return XElement.Parse(
String.Format("<doc>{0}</doc>", String.Join("", array.Select(Function(s) String.Concat("<d>", s.ToString(), "</d>")))), LoadOptions.None)
End Function
This is the sql Stored proc, shortened, not complete!
CREATE PROCEDURE [dbo].[myproc]
(@blah xml)
AS
... WHERE SomeID IN (SELECT doc.t.value('.','int') from @netwerkids.nodes(N'/doc/d') as doc(t))
[root@host]# mysqladmin -u root -p drop [DB]
Enter password:******
There may be situations when df.reset_index()
cannot be used (e.g., when you need the index, too). In this case, use index.get_level_values()
to access index values directly:
df['Trial'] = df.index.get_level_values(0)
df['measurement'] = df.index.get_level_values(1)
This will assign index values to individual columns and keep the index.
See the docs for further info.
To increment versionCode only in release version do it:
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
def versionPropsFile = file('version.properties')
def code = 1;
if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
List<String> runTasks = gradle.startParameter.getTaskNames();
def value = 0
for (String item : runTasks)
if ( item.contains("assembleRelease")) {
value = 1;
}
code = Integer.parseInt(versionProps['VERSION_CODE']).intValue() + value
versionProps['VERSION_CODE']=code.toString()
versionProps.store(versionPropsFile.newWriter(), null)
}
else {
throw new GradleException("Could not read version.properties!")
}
defaultConfig {
applicationId "com.pack"
minSdkVersion 14
targetSdkVersion 21
versionName "1.0."+ code
versionCode code
}
expects an existing c://YourProject/app/version.properties
file, which you would create by hand before the first build to have VERSION_CODE=8
File
version.properties
:
VERSION_CODE=8
Try this :
$('#resetBtn').on('click', function(e){
e.preventDefault();
$("#myform")[0].reset.click();
}
This works for me in irb:
irb> (1..4).to_a
=> [1, 2, 3, 4]
I notice that:
irb> 1..4.to_a
(irb):1: warning: default `to_a' will be obsolete
ArgumentError: bad value for range
from (irb):1
So perhaps you are missing the parentheses?
(I am running Ruby 1.8.6 patchlevel 114)
The performance should be the same; it's much more important to have the correct indexes and clustering applied on your tables (there exist some good resources on that topic).
(Edited to reflect the updated question)
Determine the type of an object with type
>>> obj = object()
>>> type(obj)
<class 'object'>
Although it works, avoid double underscore attributes like __class__
- they're not semantically public, and, while perhaps not in this case, the builtin functions usually have better behavior.
>>> obj.__class__ # avoid this!
<class 'object'>
Is there a simple way to determine if a variable is a list, dictionary, or something else? I am getting an object back that may be either type and I need to be able to tell the difference.
Well that's a different question, don't use type - use isinstance
:
def foo(obj):
"""given a string with items separated by spaces,
or a list or tuple,
do something sensible
"""
if isinstance(obj, str):
obj = str.split()
return _foo_handles_only_lists_or_tuples(obj)
This covers the case where your user might be doing something clever or sensible by subclassing str
- according to the principle of Liskov Substitution, you want to be able to use subclass instances without breaking your code - and isinstance
supports this.
Even better, you might look for a specific Abstract Base Class from collections
or numbers
:
from collections import Iterable
from numbers import Number
def bar(obj):
"""does something sensible with an iterable of numbers,
or just one number
"""
if isinstance(obj, Number): # make it a 1-tuple
obj = (obj,)
if not isinstance(obj, Iterable):
raise TypeError('obj must be either a number or iterable of numbers')
return _bar_sensible_with_iterable(obj)
Or, perhaps best of all, use duck-typing, and don't explicitly type-check your code. Duck-typing supports Liskov Substitution with more elegance and less verbosity.
def baz(obj):
"""given an obj, a dict (or anything with an .items method)
do something sensible with each key-value pair
"""
for key, value in obj.items():
_baz_something_sensible(key, value)
type
to actually get an instance's class. isinstance
to explicitly check for actual subclasses or registered abstractions. this function will set the prompt location to script path, dealing with the differents way to get scriptpath between vscode, psise and pwd :
function Set-CurrentLocation
{
$currentPath = $PSScriptRoot # AzureDevOps, Powershell
if (!$currentPath) { $currentPath = Split-Path $pseditor.GetEditorContext().CurrentFile.Path -ErrorAction SilentlyContinue } # VSCode
if (!$currentPath) { $currentPath = Split-Path $psISE.CurrentFile.FullPath -ErrorAction SilentlyContinue } # PsISE
if ($currentPath) { Set-Location $currentPath }
}
If you're working on the CLI and only have one flask app/process running (or rather, you just want want to kill any flask process running on your system), you can kill it with:
kill $(pgrep -f flask)
If I remember correctly, Bluetooth defines certain roles that devices can take. Most cell phones only support a certain number of roles. For instance, I can have a Bluetooth stereo headset that connects to my phone to receive audio, but just because my cell phone has Bluetooth does mean that it supports BEING a speaker for a different device - it doesn't advertise its capabilities of having a speaker for use by other Bluetooth devices.
I assume you want to transfer files between two iPhones? Transferring files via Bluetooth does seem like functionality that I would put in the iPhone, but I'm not Apple so I don't know for sure. In fact, yes, it seems that file transfer is not supported except in jailbroken phones:
http://gizmodo.com/5138797/iphone-bluetooth-file-transfer-coming-soon-yes
You'll probably get similar answers for Bluetooth Dial-Up Networking. I'd imagine they kept the Bluetooth commands out of the SDK for various reasons and you'll have to jailbreak your phone to get the functionality back.
The mPDF docs state that the first argument of Output()
is the file path, second is the saving mode - you need to set it to 'F'
.
$mpdf->Output('filename.pdf','F');
To sum up all of the options for VS 2017, WebHelpers was installed by installing MVC in previous versions of Visual Studio. If you're getting this error, you probably don't have the older versions of VS installed anymore.
So, installing the Microsoft.AspNet.MVC
NuGet package will require Microsoft.AspNet.WebPages
and Microsoft.AspNet.Razor
, and the Microsoft.AspNet.WebPages
includes System.Web.Helpers.dll
.
If you've got direct references to System.Web.Mvc.dll and you don't want to use NuGet for MVC, you can get the Microsoft.AspNet.WebPages
NuGet, or there are some other NuGet packages that only contain System.Web.Helpers.dll
, like the microsoft-web-helpers
or System-Web-Helpers.dll
packages.
There appear to be 2 versions of System.Web.Helpers.dll
, one for .Net 4.0 and one for 4.5. Choosing the correct version of MVC or AspNet.WebPages will ensure you get the right one.
Try the following to convert it to hex
public static string ToHex(this int value) {
return String.Format("0x{0:X}", value);
}
And back again
public static int FromHex(string value) {
// strip the leading 0x
if ( value.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) {
value = value.Substring(2);
}
return Int32.Parse(value, NumberStyles.HexNumber);
}
Gimp can be used to convert SVGs with primitives (e.g. rects, circles, etc.) into a single path which can be used within HTML5.
.svg
file with any tool of choice e.g. Illustrator. Don't worry if the SVG output is messy for now, Gimp will clean it upCheck both the Import Paths and Merge imported paths options
<path d="copy this text here" />
Laravel collections has method last
Model::all() -> last(); // last element
Model::all() -> last() -> pluck('name'); // extract value from name field.
This is the best way to do it.
Reference types do not store the object directly into the variable to which it is assigned, so the object variable in the example below, doesn’t actually contain the object instance. Instead, it holds a pointer (or reference) to the location in memory, where the object exists.
var object = new Object();
if you assign one reference typed variable to another, each variable gets a copy of the pointer, and both still reference to the same object in memory.
var object1 = new Object();
var object2 = object1;
JavaScript is a garbage-collected language, so you don’t really need to worry about memory allocations when you use reference types. However, it’s best to dereference objects that you no longer need so that the garbage collector can free up that memory. The best way to do this is to set the object variable to null.
var object1 = new Object();
// do something
object1 = null; // dereference
Dereferencing objects is especially important in very large applications that use millions of objects.
from The Principles of Object-Oriented JavaScript - NICHOLAS C. ZAKAS
For me I had to put the whole interval in single quotes not just the value of the interval.
select id,
title,
created_at + interval '1 day' * claim_window as deadline from projects
Instead of
select id,
title,
created_at + interval '1' day * claim_window as deadline from projects
The problem is that your class contains a managed RAW pointer but does not implement the rule of three (five in C++11). As a result you are getting (expectedly) a double delete because of copying.
If you are learning you should learn how to implement the rule of three (five). But that is not the correct solution to this problem. You should be using standard container objects rather than try to manage your own internal container. The exact container will depend on what you are trying to do but std::vector is a good default (and you can change afterwords if it is not opimal).
#include <queue>
#include <vector>
class Test{
std::vector<int> myArray;
public:
Test(): myArray(10){
}
};
int main(){
queue<Test> q
Test t;
q.push(t);
}
The reason you should use a standard container is the separation of concerns
. Your class should be concerned with either business logic or resource management (not both). Assuming Test
is some class you are using to maintain some state about your program then it is business logic and it should not be doing resource management. If on the other hand Test
is supposed to manage an array then you probably need to learn more about what is available inside the standard library.
I was having a similar issue with formatting CardViews in a recylerView.
I got this simple solution working, not sure if it's the best solution, but it worked for me.
mv_cardView.getBackground().setTint(Color.BLUE)
It gets the background Drawable of the cardView and tints it.
On 2013-12-03 Google launched Chrome DevTools for Mobile, which lets developers remote debug mobile web applications via emulation and screen-casting with Zero Configuration.
For all features, checkout Paul Irish's talk on YouTube.
The length function will do it. See http://www.techonthenet.com/oracle/functions/length.php
For normal DateTimes, if you don't initialize them at all then they will match DateTime.MinValue
, because it is a value type rather than a reference type.
You can also use a nullable DateTime, like this:
DateTime? MyNullableDate;
Or the longer form:
Nullable<DateTime> MyNullableDate;
And, finally, there's a built in way to reference the default of any type. This returns null
for reference types, but for our DateTime example it will return the same as DateTime.MinValue
:
default(DateTime)
or, in more recent versions of C#,
default
In JSF 2.2 it's possible to use passthrough elements:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:jsf="http://xmlns.jcp.org/jsf">
...
<div jsf:id="id1" />
...
</html>
The requirement is to have at least one attribute in the element using jsf namespace.
There exist special libraries to do just that. (Plus wrappers for python)
netCDF4 Python interface: http://www.unidata.ucar.edu/software/netcdf/software.html#Python
hope this helps
open your browser,check whether Tomcat homepage is visible by below command.
http://ipaddress:portnumber
also check this
I got this working by installing the various plugins below.
Most of the time things just import by themselves as soon as I type the class name. Alternatively, a lightbulb appears that you can click on. Or you can push F1, and type "import..." and there are various options there too. I kinda use all of them. Also F1 Implement for implementing an interface is helpful, but doesn't always work.
Screenshot of Extensions
With ES6 syntax
import mongoose from "mongoose";
// Generate a new new ObjectId
const newId2 = new mongoose.Types.ObjectId();
// Convert string to ObjectId
const newId = new mongoose.Types.ObjectId('56cb91bdc3464f14678934ca');
plt.cla() means clear current axis
plt.clf() means clear current figure
also, there's plt.gca() (get current axis) and plt.gcf() (get current figure)
Read more here: Matplotlib, Pyplot, Pylab etc: What's the difference between these and when to use each?
We had the exact same issue that you mentioned. We're using nunit to run tests through CI, and we have nunit running a file called tests.nunit, which describe a list of test dll fixtures to run.
Each test fixture had their own config file, but when run through the "tests.nunit" file the binding redirects seem to be ignored. The solution was to add the binding redirects to a new config file, "tests.config" that was beside the "tests.nunit" file.
Looks like you have a typo -- "trustStrore" should be "trustStore", i.e.
System.setProperty("javax.net.ssl.trustStrore", "cacerts.jks");
should be:
System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");
Can I tell the interface to default the properties I don't supply to null? What would let me do this
No. You cannot provide default values for interfaces or type aliases as they are compile time only and default values need runtime support
But values that are not specified default to undefined
in JavaScript runtimes. So you can mark them as optional:
interface IX {
a: string,
b?: any,
c?: AnotherType
}
And now when you create it you only need to provide a
:
let x: IX = {
a: 'abc'
};
You can provide the values as needed:
x.a = 'xyz'
x.b = 123
x.c = new AnotherType()
Check out pyftpdlib from Giampaolo Rodola. It is one of the very best ftp servers out there for python. It's used in google's chromium (their browser) and bazaar (a version control system). It is the most complete implementation on Python for RFC-959 (aka: FTP server implementation spec).
To install:
pip3 install pyftpdlib
From the commandline:
python3 -m pyftpdlib
Alternatively 'my_server.py':
#!/usr/bin/env python3
from pyftpdlib import servers
from pyftpdlib.handlers import FTPHandler
address = ("0.0.0.0", 21) # listen on every IP on my machine on port 21
server = servers.FTPServer(address, FTPHandler)
server.serve_forever()
There's more examples on the website if you want something more complicated.
To get a list of command line options:
python3 -m pyftpdlib --help
Note, if you want to override or use a standard ftp port, you'll need admin privileges (e.g. sudo).
Use this i liked it so much since creates link with blue color to particular text only not on whole label text: FRHyperLabel
To do:
Download from above link and copy FRHyperLabel.h
, FRHyperLabel.m
to your project.
Drag drop UILabel
in your Storyboard
and define custom class name to FRHyperLabel
in identify inspector as shown in image.
@property (weak, nonatomic) IBOutlet FRHyperLabel *label;
`NSString *string = @"By uploading I agree to the Terms of Use"; NSDictionary *attributes = @{NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]};
_label.attributedText = [[NSAttributedString alloc]initWithString:string attributes:attributes];
[_label setFont:[_label.font fontWithSize:13.0]];
[_label setLinkForSubstring:@"Terms of Use" withLinkHandler:^(FRHyperLabel *label, NSString *substring){
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.google.com"]];
}];`
The Content hugging priority
is like a Rubber band that is placed around a view.
The higher the priority value, the stronger the rubber band and the more it wants to hug to its content size.
The priority value can be imagined like the "strength" of the rubber band
And the Content Compression Resistance
is, how much a view "resists" getting smaller
The View with higher resistance priority value is the one that will resist compression.
If your current line wraps around the visible screen onto the next line, you can use g$ to get to the end of the screen line.
return;
is used in a method of void return type to return the control of execution to its parent method.The CSS code would be:
box-shadow: 0 0 10px 5px white;
That will shadow the entire DIV no matter its shape!
Just to be clear, you are wanting to launch a program from a batch file and then have the batch file press keys (in your example, the arrow keys) within that launched program?
If that is the case, you aren't going to be able to do that with simply a ".bat" file as the launched would stop the batch file from continuing until it terminated--
My first recommendation would be to use something like AutoHotkey or AutoIt if possible, simply because they both have active forums where you'd find countless examples of people launching applications and sending key presses not to mention tools to simply "record" what you want to do. However you said this is a work computer and you may not be able to load a 3rd party program.. but you aren't without options.
You can use Windows Scripting Host from something like a .vbs file to launch a program and send keys to that process. If you're running a version of Windows that includes PowerShell 2.0 (Windows XP with Service Pack 3, Windows Vista with Service Pack 1, Windows 7, etc.) you can use Windows Scripting Host as a COM object from your PS script or use VB's Intereact class.
The specifics of how to do it are outside the scope of this answer but you can find numerous examples using the methods I just described by searching on SO or Google.
edit: Just to help you get started you can look here:
If you are reading from that file using FileStream and then wanting to delete it, make sure you close the FileStream before you call the File.Delete(path). I had this issue.
var filestream = new System.IO.FileStream(@"C:\Test\PutInv.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
filestream.Close();
File.Delete(@"C:\Test\PutInv.txt");
HTML:
First, we will need to add a class to your text container so that we can access and style it accordingly.
<div class="col-xs-5 textContainer">
<h3 class="text-left">Link up with other gamers all over the world who share the same tastes in games.</h3>
</div>
CSS:
Next, we will apply the following styles to align it vertically, according to the size of the image div next to it.
.textContainer {
height: 345px;
line-height: 340px;
}
.textContainer h3 {
vertical-align: middle;
display: inline-block;
}
All Done! Adjust the line-height and height on the styles above if you believe that it is still slightly out of align.
Use time.sleep()
:
import time
time.sleep(50 / 1000)
See the Python documentation: https://docs.python.org/library/time.html#time.sleep
var option_user_selection = document.getElementById("maincourse").options[document.getElementById("maincourse").selectedIndex ].text
You can use:
cat f.csv | sed 's/,/ /g' | awk '{print $1 " / " $4}'
or
echo "Hello,World,Questions,Answers,bash shell,script" | sed 's/,/ /g' | awk '{print $1 " / " $4}'
This is the part that replace comma with space
sed 's/,/ /g'
SQL Server doesn't have a boolean data type. As @Mikael has indicated, the closest approximation is the bit. But that is a numeric type, not a boolean type. In addition, it only supports 2 values - 0
or 1
(and one non-value, NULL
).
SQL (standard SQL, as well as T-SQL dialect) describes a Three valued logic. The boolean type for SQL should support 3 values - TRUE
, FALSE
and UNKNOWN
(and also, the non-value NULL
). So bit
isn't actually a good match here.
Given that SQL Server has no support for the data type, we should not expect to be able to write literals of that "type".
Try this. It always works for me
wget --mirror -p --convert-links -P ./LOCAL-DIR WEBSITE-URL
If you are using the Android Support Library you can use ConfigurationCompat
instead of @Makalele's method to get rid of deprecation warnings:
Locale current = ConfigurationCompat.getLocales(getResources().getConfiguration()).get(0);
or in Kotlin:
val currentLocale = ConfigurationCompat.getLocales(resources.configuration)[0]
Very weird, but. You have to declare the class for your application instance as myApplication: UIApplication instead of myApplication: NSObject . It seems that the UIApplicationDelegate protocol doesn't implement the +registerForSystemEvents message. Crazy Apple APIs, again.
Things have changed a little in the way Charles provides HTTPS proxying.
First the certificates installation options have been moved to the help menu.
Help -> SSL Proxying -> Install Charles Root Certificate
Help -> SSL Proxying -> Install Charles Root Certificate in iOS Simulators
Second, starting in iOS 9 you must provide a NSAppTransportSecurity
option in your Info.plist
and if you want Charles to work properly as a man in the middle, you must add:
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
as part of the your domains see full example:
<key>NSExceptionDomains</key>
<dict>
<key>yourdomain.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
The reason being (I guess) that Charles at some point communicates in clear http after acting as the man in the middle https server.
Last step is to activate SSL Proxying for this domain in Charles (right click on domain and select Enable SSL Proxying)
It depends on the configuration of the application as well as on IIS as this gentleman in the below link has rightfully explained. Please see his article below
http://richhewlett.com/2011/02/15/getting-a-users-username-in-asp-net/
It's not possible with CSS3. There is a proposed CSS4 selector, $
, to do just that, which could look like this (Selecting the li
element):
ul $li ul.sub { ... }
See the list of CSS4 Selectors here.
As an alternative, with jQuery, a one-liner you could make use of would be this:
$('ul li:has(ul.sub)').addClass('has_sub');
You could then go ahead and style the li.has_sub
in your CSS.
Use the -S switch
g++ -S main.cpp
or also with gcc
gcc -S main.c
Also see this
This Gist by Eldon McGuinness is by far the most complete implementation of a JavaScript query string parser that I've seen so far.
Unfortunately, it's written as a jQuery plugin.
I rewrote it to vanilla JS and made a few improvements :
function parseQuery(str) {_x000D_
var qso = {};_x000D_
var qs = (str || document.location.search);_x000D_
// Check for an empty querystring_x000D_
if (qs == "") {_x000D_
return qso;_x000D_
}_x000D_
// Normalize the querystring_x000D_
qs = qs.replace(/(^\?)/, '').replace(/;/g, '&');_x000D_
while (qs.indexOf("&&") != -1) {_x000D_
qs = qs.replace(/&&/g, '&');_x000D_
}_x000D_
qs = qs.replace(/([\&]+$)/, '');_x000D_
// Break the querystring into parts_x000D_
qs = qs.split("&");_x000D_
// Build the querystring object_x000D_
for (var i = 0; i < qs.length; i++) {_x000D_
var qi = qs[i].split("=");_x000D_
qi = qi.map(function(n) {_x000D_
return decodeURIComponent(n)_x000D_
});_x000D_
if (typeof qi[1] === "undefined") {_x000D_
qi[1] = null;_x000D_
}_x000D_
if (typeof qso[qi[0]] !== "undefined") {_x000D_
_x000D_
// If a key already exists then make this an object_x000D_
if (typeof (qso[qi[0]]) == "string") {_x000D_
var temp = qso[qi[0]];_x000D_
if (qi[1] == "") {_x000D_
qi[1] = null;_x000D_
}_x000D_
qso[qi[0]] = [];_x000D_
qso[qi[0]].push(temp);_x000D_
qso[qi[0]].push(qi[1]);_x000D_
_x000D_
} else if (typeof (qso[qi[0]]) == "object") {_x000D_
if (qi[1] == "") {_x000D_
qi[1] = null;_x000D_
}_x000D_
qso[qi[0]].push(qi[1]);_x000D_
}_x000D_
} else {_x000D_
// If no key exists just set it as a string_x000D_
if (qi[1] == "") {_x000D_
qi[1] = null;_x000D_
}_x000D_
qso[qi[0]] = qi[1];_x000D_
}_x000D_
}_x000D_
return qso;_x000D_
}_x000D_
_x000D_
// DEMO_x000D_
console.log(parseQuery("?foo=bar&foo=boo&roo=bar;bee=bop;=ghost;=ghost2;&;checkbox%5B%5D=b1;checkbox%5B%5D=b2;dd=;http=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab&http=http%3A%2F%2Fw3schools2.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab"));
_x000D_
See also this Fiddle.
If you need stricter replacement matching, PostgreSQL's regexp_replace
function can match using POSIX regular expression patterns. It has the syntax regexp_replace(source, pattern, replacement [, flags ]).
I will use flags i
and g
for case-insensitive and global matching, respectively. I will also use \m
and \M
to match the beginning and the end of a word, respectively.
There are usually quite a few gotchas when performing regex replacment. Let's see how easy it is to replace a cat with a dog.
SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog');
--> Cat bobdog cat cats catfish
SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog', 'i');
--> dog bobcat cat cats catfish
SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog', 'g');
--> Cat bobdog dog dogs dogfish
SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog', 'gi');
--> dog bobdog dog dogs dogfish
SELECT regexp_replace('Cat bobcat cat cats catfish', '\mcat', 'dog', 'gi');
--> dog bobcat dog dogs dogfish
SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat\M', 'dog', 'gi');
--> dog bobdog dog cats catfish
SELECT regexp_replace('Cat bobcat cat cats catfish', '\mcat\M', 'dog', 'gi');
--> dog bobcat dog cats catfish
SELECT regexp_replace('Cat bobcat cat cats catfish', '\mcat(s?)\M', 'dog\1', 'gi');
--> dog bobcat dog dogs catfish
Even after all of that, there is at least one unresolved condition. For example, sentences that begin with "Cat" will be replaced with lower-case "dog" which break sentence capitalization.
Check out the current PostgreSQL pattern matching docs for all the details.
Given my examples, maybe the safest option would be:
UPDATE table SET field = regexp_replace(field, '\mcat\M', 'dog', 'gi');
An easy way to write cron is to use the online cron generator It will generate the line for you. One thing to note is that if you wish to run it each day (not just weekdays) you need to highlight all the days.
Going off of what Surreal Dreams said, it's probably best to style the anchor tag in my experience, but it really does depend on what you are doing. Here's an example:
Html:
<div class="parent-div">
<a href="#">Test</a>
<a href="#">Test</a>
<a href="#">Test</a>
</div>
Then the CSS:
.parent-div {
width: 200px;
}
a {
display:block;
background-color: #ccc;
color: #000;
text-decoration:none;
padding:10px;
margin-bottom:1px;
}
a:hover {
background-color: #ddd;
}
Jerryf's answer is fine, except for one flaw.
The onload event should be set before the src. Sometimes the src can be loaded instantly and never fire the onload event.
(Like Totty.js pointed out.)
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
var image = new Image();
image.onload = function() {
ctx.drawImage(image, 0, 0);
};
image.src = "data:image/ png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
There are several reasons this can happen. Some of these I found here, others I discovered on my own.
Id
, you need to add the [Key]
attribute to it.public
uint
, ulong
etc. are not allowed.I thought this looked pretty bad - because I was working on a Joomla template recently and I kept getting the template failing W3C because it was using the <i>
tag and that had deprecated, as it's original use was to italicize something, which is now done through CSS not HTML any more.
It does make really bad practice because when I saw it I went through the template and changed all the <i>
tags to <span style="font-style:italic">
instead and then wondered why the entire template looked strange.
This is the main reason it is a bad idea to use the <i>
tag in this way - you never know who is going to look at your work afterwards and "assume" that what you were really trying to do is italicize the text rather than display an icon. I've just put some icons in a website and I did it with the following code
<img class="icon" src="electricity.jpg" alt="Electricity" title="Electricity">
that way I've got all my icons in one class so any changes I make affects all the icons (say I wanted them larger or smaller, or rounded borders, etc), the alt text gives screen readers the chance to tell the person what the icon is rather than possibly getting just "text in italics, end of italics" (I don't exactly know how screen readers read screens but I guess it's something like that), and the title also gives the user a chance to mouse over the image and get a tooltip telling them what the icon is in case they can't figure it out. Much better than using <i>
- and also it passes W3C standard.
window.location
adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.
window.location.replace
replaces the current history item so you can't go back to it.
See window.location
:
assign(url)
: Load the document at the provided URL.
replace(url)
:Replace the current document with the one at the provided URL. The difference from theassign()
method is that after usingreplace()
the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.
Oh and generally speaking:
window.location.href = url;
is favoured over:
window.location = url;
Just for those who want to get $setPristine
without having to upgrade to v1.1.x, here is the function I used to simulate the $setPristine
function. I was reluctant to use the v1.1.5 because one of the AngularUI components I used is no compatible.
var setPristine = function(form) {
if (form.$setPristine) {//only supported from v1.1.x
form.$setPristine();
} else {
/*
*Underscore looping form properties, you can use for loop too like:
*for(var i in form){
* var input = form[i]; ...
*/
_.each(form, function (input) {
if (input.$dirty) {
input.$dirty = false;
}
});
}
};
Note that it ONLY makes $dirty
fields clean and help changing the 'show error' condition like $scope.myForm.myField.$dirty && $scope.myForm.myField.$invalid
.
Other parts of the form object (like the css classes) still need to consider, but this solve my problem: hide error messages.
count of the contained lists in the outmost list
int count = data.size();
lambda to get the count of the contained inner lists
int count = data.stream().collect( summingInt(l -> l.size()) );
UPDATE 15.3.2017:
I have opened a Django-issue on this and it seems to be preliminary accepted here: https://code.djangoproject.com/ticket/27825
My experience is that when using the Constructor
(ORM
) class by references with Django 1.10.5
there might be some inconsistencies in the data (i.e. the attributes of the created object may get the type of the input data instead of the casted type of the ORM object property)
example:
models
class Payment(models.Model):
amount_cash = models.DecimalField()
some_test.py
- object.create
Class SomeTestCase:
def generate_orm_obj(self, _constructor, base_data=None, modifiers=None):
objs = []
if not base_data:
base_data = {'amount_case': 123.00}
for modifier in modifiers:
actual_data = deepcopy(base_data)
actual_data.update(modifier)
# Hacky fix,
_obj = _constructor.objects.create(**actual_data)
print(type(_obj.amount_cash)) # Decimal
assert created
objs.append(_obj)
return objs
some_test.py
- Constructor()
Class SomeTestCase:
def generate_orm_obj(self, _constructor, base_data=None, modifiers=None):
objs = []
if not base_data:
base_data = {'amount_case': 123.00}
for modifier in modifiers:
actual_data = deepcopy(base_data)
actual_data.update(modifier)
# Hacky fix,
_obj = _constructor(**actual_data)
print(type(_obj.amount_cash)) # Float
assert created
objs.append(_obj)
return objs
I have been faced with a similar problem with SDK 24.0.2, and ADT 23.0, on windows 7 and Eclipse Luna (4.4.0). The android SDK Manager comes with default Proxy IP of 127.0.0.1 (localhost) and port 8081. So as you try to run the SDK Managers as advised by earlier solutions, it will try to connect through the default proxy settings, which keep on failing(...at least on my system). Therefore, if you do not need proxy settings, simply clear default proxy settings (i.e. remove proxy server IP and Port, leaving the fields empty). Otherwise set them as necessary. To access these settings in eclipse, go Window-> Android SDK Manager->Tools->Options.
Hope this helps someone.
From here Routing in Asp.net Mvc 4 and Web Api
Darin Dimitrov has posted a very good answer which is working for me.
It says...
You could have a couple of routes:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "ApiById",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = @"^[0-9]+$" }
);
config.Routes.MapHttpRoute(
name: "ApiByName",
routeTemplate: "api/{controller}/{action}/{name}",
defaults: null,
constraints: new { name = @"^[a-z]+$" }
);
config.Routes.MapHttpRoute(
name: "ApiByAction",
routeTemplate: "api/{controller}/{action}",
defaults: new { action = "Get" }
);
}
}
This Code worked for me
List<Object> collection = new List<Object>((IEnumerable<Object>)myObject);
Delete:
C:\Documents and Settings\%Your Username%\Application Data\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat"
I suggest Validator.nu's parser, based on the HTML5 parsing algorithm. It is the parser used in Mozilla from 2010-05-03
Normally, that is not an error per se; it is a warning that the first file it found that matches the -lPI-Http
argument to the compiler/linker is not valid. The error occurs when no other library can be found with the right content.
So, you need to look to see whether /dvlpmnt/libPI-Http.a
is a library of 32-bit object files or of 64-bit object files - it will likely be 64-bit if you are compiling with the -m32
option. Then you need to establish whether there is an alternative libPI-Http.a
or libPI-Http.so
file somewhere else that is 32-bit. If so, ensure that the directory that contains it is listed in a -L/some/where
argument to the linker. If not, then you will need to obtain or build a 32-bit version of the library from somewhere.
To establish what is in that library, you may need to do:
mkdir junk
cd junk
ar x /dvlpmnt/libPI-Http.a
file *.o
cd ..
rm -fr junk
The 'file
' step tells you what type of object files are in the archive. The rest just makes sure you don't make a mess that can't be easily cleaned up.
A non-jQuery solution that more closely mimics IsNullOrWhiteSpace
, but to detect null, empty or all-spaces only:
function isEmptyOrSpaces(str){
return str === null || str.match(/^ *$/) !== null;
}
...then:
var addr = ' ';
if(isEmptyOrSpaces(addr)){
// error
}
* EDIT * Please note that op specifically states:
I need to check to see if a var is null or has any empty spaces or for that matter just blank.
So while yes, "white space" encompasses more than null, spaces or blank my answer is intended to answer op's specific question. This is important because op may NOT want to catch things like tabs, for example.
Yes. You need to prefix the table name with "#" (hash) to create temporary tables.
If you do NOT need the table later, go ahead & create it. Temporary Tables are very much like normal tables. However, it gets created in tempdb. Also, it is only accessible via the current session i.e. For EG: if another user tries to access the temp table created by you, he'll not be able to do so.
"##" (double-hash creates "Global" temp table that can be accessed by other sessions as well.
Refer the below link for the Basics of Temporary Tables: http://www.codeproject.com/Articles/42553/Quick-Overview-Temporary-Tables-in-SQL-Server-2005
If the content of your table is less than 5000 rows & does NOT contain data types such as nvarchar(MAX), varbinary(MAX), consider using Table Variables.
They are the fastest as they are just like any other variables which are stored in the RAM. They are stored in tempdb as well, not in RAM.
DECLARE @ItemBack1 TABLE
(
column1 int,
column2 int,
someInt int,
someVarChar nvarchar(50)
);
INSERT INTO @ItemBack1
SELECT column1,
column2,
someInt,
someVarChar
FROM table2
WHERE table2.ID = 7;
More Info on Table Variables: http://odetocode.com/articles/365.aspx
One thing that wasn't mentioned completely (although @BlooB kinda mentioned it) is that map returns a map object NOT a list. This is a big difference when it comes to time performance on initialization and iteration. Consider these two tests.
import time
def test1(iterable):
a = time.clock()
map(str, iterable)
a = time.clock() - a
b = time.clock()
[ str(x) for x in iterable ]
b = time.clock() - b
print(a,b)
def test2(iterable):
a = time.clock()
[ x for x in map(str, iterable)]
a = time.clock() - a
b = time.clock()
[ str(x) for x in iterable ]
b = time.clock() - b
print(a,b)
test1(range(2000000)) # Prints ~1.7e-5s ~8s
test2(range(2000000)) # Prints ~9s ~8s
As you can see initializing the map function takes almost no time at all. However iterating through the map object takes longer than simply iterating through the iterable. This means that the function passed to map() is not applied to each element until the element is reached in the iteration. If you want a list use list comprehension. If you plan to iterate through in a for loop and will break at some point, then use map.
One-to-many and Many-to-one relationship is talking about the same logical relationship, eg an Owner may have many Homes, but a Home can only have one Owner.
So in this example Owner is the One, and Homes are the Many. Each Home always has an owner_id (eg the Foreign Key) as an extra column.
The difference in implementation between these two, is which table defines the relationship. In One-to-Many, the Owner is where the relationship is defined. Eg, owner1.homes lists all the homes with owner1's owner_id In Many-to-One, the Home is where the relationship is defined. Eg, home1.owner lists owner1's owner_id.
I dont actually know in what instance you would implement the many-to-one arrangement, because it seems a bit redundant as you already know the owner_id. Perhaps its related to cleanness of deletions and changes.
a = ('x', 'y')
b = a + ('z',)
print(b)
a = ('x', 'y')
b = a + tuple('b')
print(b)
This was the best solution I found after more time than I care to admit. Basically, add target="_self" to each link that you need to insure a page reload.
http://blog.panjiesw.com/posts/2013/09/angularjs-normal-links-with-html5mode/
$(this).find('td')
will give you an array of td's in the tr.
1) Download Ruby 1.9.3
2) cmd check command: ruby -v
'return result ruby 1.9.3 then success full install ruby
3) Download DevKit file from http://rubyinstaller.org/downloads (DevKit-tdm-32-4.5.2-20110712-1620-sfx.exe)
4) Extract DevKit to path C:\Ruby193\DevKit
5) cd C:\Ruby193\DevKit
6) ruby dk.rb init
7) ruby dk.rb review
8) ruby dk.rb install
9) cmd : gem install rails -v3.1.1
'few time installing full process'
10) cmd : rails -v
'return result rails 3.1.1 then its success fully install'
enjoy Ruby on Rails...
$filename = pathinfo( parse_url( $url, PHP_URL_PATH ), PATHINFO_FILENAME );
Use parse_url to extract the path from the URL, then pathinfo returns the filename from the path
private static bool CompareDictionaries(IDictionary<string, IEnumerable<string>> dict1, IDictionary<string, IEnumerable<string>> dict2)
{
if (dict1.Count != dict2.Count)
{
return false;
}
var keyDiff = dict1.Keys.Except(dict2.Keys);
if (keyDiff.Any())
{
return false;
}
return (from key in dict1.Keys
let value1 = dict1[key]
let value2 = dict2[key]
select value1.Except(value2)).All(diffInValues => !diffInValues.Any());
}
IN GALAXY Devices :
You need to make sure that you havn't turned it off in the device using the Settings > Developer Options:
SELECT l.*
FROM (
SELECT DISTINCT usr_id
FROM lives
) lo, lives l
WHERE l.ctid = (
SELECT ctid
FROM lives li
WHERE li.usr_id = lo.usr_id
ORDER BY
time_stamp DESC, trans_id DESC
LIMIT 1
)
Creating an index on (usr_id, time_stamp, trans_id)
will greatly improve this query.
You should always, always have some kind of PRIMARY KEY
in your tables.
You can use HAVING clause for filter calculated in SELECT fields and aliases
Installing Windows 10 I had this problem: apache(ipv4) and spooler service(ipv6) listening the same 80 port.
I resolved editing apache httpd.conf file changing the line
Listen 80
to
Listen 127.0.0.1:80
If you want to reset the selected options
$('select option:selected').removeAttr('selected');
If you actually want to remove the options (although I don't think you mean this).
$('select').empty();
Substitute select
for the most appropriate selector in your case (this may be by id or by CSS class). Using as is will reset all <select>
elements on the page
You can use Ctrl+U to clear up to the beginning.
You can use Ctrl+W to delete just a word.
You can also use Ctrl+C to cancel.
If you want to keep the history, you can use Alt+Shift+# to make it a comment.
You could use php to echo the browser name as a body
class, e.g.
<body class="mozilla">
Then, your conditional CSS would look like
.ie #container { top: 5px;}
.mozilla #container { top: 5px;}
.chrome #container { top: 5px;}
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'
}
});
this workes for me:
private int GetaRandom()
{
Thread.Sleep(1);
return new Random(DateTime.Now.Millisecond).Next();
}
run the following command will fix this issue.
npm install @types/node --save-dev
I used below code and it's working fine for me. :
let jsonText = "{\"userName\":\"Bhavsang\"}"
var dictonary:NSDictionary?
if let data = jsonText.dataUsingEncoding(NSUTF8StringEncoding) {
do {
dictonary = try NSJSONSerialization.JSONObjectWithData(data, options: [.allowFragments]) as? [String:AnyObject]
if let myDictionary = dictonary
{
print(" User name is: \(myDictionary["userName"]!)")
}
} catch let error as NSError {
print(error)
}
}
SOLUTION
<style>
.container {
margin: 10px;
width: 115px;
height: 115px;
line-height: 115px;
text-align: center;
border: 1px solid red;
background-image: url("http://i.imgur.com/H9lpVkZ.jpg");
background-repeat: no-repeat;
background-position: center;
background-size: contain;
}
</style>
<div class='container'>
</div>
<div class='container' style='width:50px;height:100px;line-height:100px'>
</div>
<div class='container' style='width:140px;height:70px;line-height:70px'>
</div>
If your using a background resource and wish to change the resource out you can use setBackgroundResource() function.
ui_item.setBackgroundResource(R.drawable.myResource)
A background resource in XML would look like:
<LinearLayout
android:id="@+id/ui_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/background_01"
android:orientation="vertical">
If you are editing HTML in Notepad you should use "Save As" and alter the default "Encoding:" selection at the botom of the dialog to UTF-8. you should also include-
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
_x000D_
This un-ambiguously sets the correct character set and informs the browser.
This code gets the maximum value from the maxlength
attribute of the textarea
and decreases the value as the user types.
<DEMO>
var el_t = document.getElementById('textarea');_x000D_
var length = el_t.getAttribute("maxlength");_x000D_
var el_c = document.getElementById('count');_x000D_
el_c.innerHTML = length;_x000D_
el_t.onkeyup = function () {_x000D_
document.getElementById('count').innerHTML = (length - this.value.length);_x000D_
};
_x000D_
<textarea id="textarea" name="text"_x000D_
maxlength="500"></textarea>_x000D_
<span id="count"></span>
_x000D_
If you want to scroll down to bottom of infinite page (like linkedin.com), you can use this code:
SCROLL_PAUSE_TIME = 0.5
# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
# Scroll down to bottom
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# Wait to load page
time.sleep(SCROLL_PAUSE_TIME)
# Calculate new scroll height and compare with last scroll height
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
Reference: https://stackoverflow.com/a/28928684/1316860
I'd say the default value is always new DateTime()
. So we can write
DateTime datetime;
if (datetime == new DateTime())
{
//unassigned
}
Just in case someone checked this thread and had the same issue as mine...
Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)
I'm using NHibernate, I receive same error, during creating an object...
I was passing the key manually, and also specified a GUID generator in mapping, so hibernate generate same exact error for me, so once I removed the GUID, and left the field empty, everything went just fine.
this answer may not help you, but will help someone like me, who just your thread becasue of same error
in_array() is fine if you're only checking but if you need to check that a value exists and return the associated key, array_search is a better option.
$data = [
'hello',
'world'
];
$key = array_search('world', $data);
if ($key) {
echo 'Key is ' . $key;
} else {
echo 'Key not found';
}
This will print "Key is 1"
id="hiddenBtn"
and type="submit"
that do the submittype="button"
set onclick
of the current button call a function
look like below:
function foo() {
// do something before submit
...
// trigger click event of the hidden button
$('#hinddenBtn').trigger("click");
}
ERROR in The Angular Compiler requires TypeScript >=3.4.0 and <3.6.0 but 3.6.3 was found instead.
For this error you can also define a version range:
yarn add typescript@">=3.4.0 <3.6.0" --save-dev --save-exact
or for npm
npm install typescript@">=3.4.0 <3.6.0" --save-dev --save-exact
After installing the correct typescript version:
node_modules
folderyarn install
or npm install
A pointer is a "reference" to a value.. much like a library call number is a reference to a book. "Dereferencing" the call number is physically going through and retrieving that book.
int a=4 ;
int *pA = &a ;
printf( "The REFERENCE/call number for the variable `a` is %p\n", pA ) ;
// The * causes pA to DEREFERENCE... `a` via "callnumber" `pA`.
printf( "%d\n", *pA ) ; // prints 4..
If the book isn't there, the librarian starts shouting, shuts the library down, and a couple of people are set to investigate the cause of a person going to find a book that isn't there.
It wont break if you wrap each item in a div. Check out my fiddle with the link below. I made the width of the fieldset 125px and made each item 50px wide. You'll see the label and checkbox remain side by side on a new line and don't break.
<fieldset>
<div class="item">
<input type="checkbox" id="a">
<label for="a">a</label>
</div>
<div class="item">
<input type="checkbox" id="b">
<!-- depending on width, a linebreak can occur here. -->
<label for="b">bgf bh fhg fdg hg dg gfh dfgh</label>
</div>
<div class="item">
<input type="checkbox" id="c">
<label for="c">c</label>
</div>
</fieldset>
In VSCode if "editor.fontFamily": ""
is blank, the font size will NOT work. Set a font family to change the size.
"editor.fontFamily": "Verdana",
or
"editor.fontFamily": "Monaco",
Really, use whatever font family you like.
Then "editor.fontSize": 16,
should work.
To get all attributes of a property in a dictionary use this:
typeof(Book)
.GetProperty("Name")
.GetCustomAttributes(false)
.ToDictionary(a => a.GetType().Name, a => a);
remember to change from false
to true
if you want to include inheritted attributes as well.
Here's a rewrite of the accepted answer that ideally clarifies the advantages/risks of possible approaches:
You're trying to cherry pick fd9f578, which was a merge with two parents.
Instead of cherry-picking a merge, the simplest thing is to cherry pick the commit(s) you actually want from each branch in the merge.
Since you've already merged, it's likely all your desired commits are in your list. Cherry-pick them directly and you don't need to mess with the merge commit.
The way a cherry-pick works is by taking the diff that a changeset represents (the difference between the working tree at that point and the working tree of its parent), and applying the changeset to your current branch.
If a commit has two or more parents, as is the case with a merge, that commit also represents two or more diffs. The error occurs because of the uncertainty over which diff should apply.
If you determine you need to include the merge vs cherry-picking the related commits, you have two options:
(More complicated and obscure; also discards history) you can indicate which parent should apply.
Use the -m
option to do so. For example, git cherry-pick -m 1 fd9f578
will use the first parent listed in the merge as the base.
Also consider that when you cherry-pick a merge commit, it collapses all the changes made in the parent you didn't specify to -m
into that one commit. You lose all their history, and glom together all their diffs. Your call.
(Simpler and more familiar; preserves history) you can use git merge
instead of git cherry-pick
.
git merge
, it will attempt to apply all commits that exist on the branch you are merging, and list them individually in your git log.You probably want to start investigating the os module for forking different threads (by opening an interactive session and issuing help(os)). The relevant functions are fork and any of the exec ones. To give you an idea on how to start, put something like this in a function that performs the fork (the function needs to take a list or tuple 'args' as an argument that contains the program's name and its parameters; you may also want to define stdin, out and err for the new thread):
try:
pid = os.fork()
except OSError, e:
## some debug output
sys.exit(1)
if pid == 0:
## eventually use os.putenv(..) to set environment variables
## os.execv strips of args[0] for the arguments
os.execv(args[0], args)
this work with me
File file = ..... // Save file
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
The answers involving sending 'signal 0' to the process will work only if the process in question is owned by the user running the test. Otherwise you will get an OSError
due to permissions, even if the pid exists in the system.
In order to bypass this limitation you can check if /proc/<pid>
exists:
import os
def is_running(pid):
if os.path.isdir('/proc/{}'.format(pid)):
return True
return False
This applies to linux based systems only, obviously.
The current HTML5 draft also allows ommitting the href attribute completely.
If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant.
To answer your question: Yes it's valid.
This question was posted quite a while ago and most of the answers are quite old too. So when I spent hours trying to figure this out, nothing worked, and I tried all suggestions in this post.
I was still getting the standard JPEG errors when trying to upload a JPG in my Django avatar form:
raise IOError("decoder %s not available" % decoder_name)
OSError: decoder jpeg not available
Then I checked the repository for Ubuntu 12.04 and noticed some extra packages for libjpeg
. I installed these and my problem was solved:
sudo apt-get install libjpeg62 libjpeg62-dev
Installing these removed libjpeg-dev
, libjpeg-turbo8-dev
, and libjpeg8-dev
.
Hope this helps someone in the year 2015 and beyond!
Cheers
Use your bean class like this, if your JSON data starts with an an array object. it helps you.
Users[] bean = gson.fromJson(response,Users[].class);
Users is my bean class.
Response is my JSON data.