If you're using lodash and in the mood for a too-cute-for-its-own-good one-liner:
_.map(_.words('123, 124, 234,252'), _.add.bind(1, 1));
It's surprisingly robust thanks to lodash's powerful parsing capabilities.
If you want one that will also clean non-digit characters out of the string (and is easier to follow...and not quite so cutesy):
_.chain('123, 124, 234,252, n301')
.replace(/[^\d,]/g, '')
.words()
.map(_.partial(_.add, 1))
.value();
2017 edit:
I no longer recommend my previous solution. Besides being overkill and already easy to do without a third-party library, it makes use of _.chain, which has a variety of issues. Here's the solution I would now recommend:
const str = '123, 124, 234,252';
const arr = str.split(',').map(n => parseInt(n, 10) + 1);
My old answer is still correct, so I'll leave it for the record, but there's no need to use it nowadays.
Mutexes are useful in situations where you need to enforce exclusive access to a resource accross multiple processes, where a regular lock won't help since it only works accross threads.
You can loop through a hash map like this
<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);
%>
<c:forEach items="${itemList}" var="itemrow">
<input type="text" value="<c:out value='${itemrow.test}'/>"/>
</c:forEach>
For more JSTL functionality look here
This makes a difference on Windows, at least. See that link for details.
I took the liberty to expand the answer from nona-urbiz; just add this to your ~/.bashrc:
git-pullall () { for RMT in $(git remote); do git pull -v $RMT $1; done; }
alias git-pullall=git-pullall
git-pushall () { for RMT in $(git remote); do git push -v $RMT $1; done; }
alias git-pushall=git-pushall
Usage:
git-pullall master
git-pushall master ## or
git-pushall
If you do not provide any branch argument for git-pullall then the pull from non-default remotes will fail; left this behavior as it is, since it's analogous to git.
If you want to change the color of your toolbar all throughout your app, leverage the styles.xml. In general, I avoid altering ui components in my java code unless I am trying to do something programatically. If this is a one time set, then you should be doing it in xml to make your code cleaner. Here is what your styles.xml will look like:
<!-- Base application theme. -->
<style name="YourAppName.AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Color Primary will be your toolbar color -->
<item name="colorPrimary">@color/colorPrimary</item>
<!-- Color Primary Dark will be your default status bar color -->
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
</style>
Make sure you use the above style in your AndroidManifext.xml as such:
<application
android:theme="@style/YourAppName.AppTheme">
</application>
I wanted different toolbar colors for different activities. So I leveraged styles again like this:
<style name="YourAppName.AppTheme.Activity1">
<item name="colorPrimary">@color/activity1_primary</item>
<item name="colorPrimaryDark">@color/activity1_primaryDark</item>
</style>
<style name="YourAppName.AppTheme.Activity2">
<item name="colorPrimary">@color/activity2_primary</item>
<item name="colorPrimaryDark">@color/activity2_primaryDark</item>
</style>
again, apply the styles to each activity in your AndroidManifest.xml as such:
<activity
android:name=".Activity2"
android:theme="@style/YourAppName.AppTheme.Activity2"
</activity>
<activity
android:name=".Activity1"
android:theme="@style/YourAppName.AppTheme.Activity1"
</activity>
OK! never mind; I found the solution. with 403 Suspected that the HTTP is not going to the right URL.
Change the file which has the login credentials stored the ~/.docker/config.json
from the default generated of
{
"auths": {
"docker.io": {
"auth": "XXXXXXXXXXXXX",
"email": "[email protected]"
}
}
}
to - Note the change from docker.io -> index.docker.io/v1. That is the change.
{
"auths": {
"https://index.docker.io/v1/": {
"auth": "XXXXXXXXXXXXX",
"email": "[email protected]"
}
}
}
Hope that helps.
Note that the auth field should be 'username:password" base64 encoded. for example: "username:password" base64 encoded is "dXNlcm5hbWU6cGFzc3dvcmQ="
so your file would contain:
"auth": "dXNlcm5hbWU6cGFzc3dvcmQ="
double d = 1.234;
int i = Convert.ToInt32(d);
Handles rounding like so:
rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.
Use docstrings.
This is the built-in suggested convention in PyCharm for describing function using docstring comments:
def test_function(p1, p2, p3):
"""
test_function does blah blah blah.
:param p1: describe about parameter p1
:param p2: describe about parameter p2
:param p3: describe about parameter p3
:return: describe what it returns
"""
pass
To generate a shared library you need first to compile your C code with the -fPIC
(position independent code) flag.
gcc -c -fPIC hello.c -o hello.o
This will generate an object file (.o), now you take it and create the .so file:
gcc hello.o -shared -o libhello.so
EDIT: Suggestions from the comments:
You can use
gcc -shared -o libhello.so -fPIC hello.c
to do it in one step. – Jonathan Leffler
I also suggest to add -Wall
to get all warnings, and -g
to get debugging information, to your gcc
commands. – Basile Starynkevitch
Not the most beautiful way of doing it I guess:
git log --pretty=oneline | wc -l
This gives you a number then
git log HEAD~<The number minus one>
It's a placeholder for the first parameter, which in your case evaluates to "wordpad.exe".
If you had an additional parameter, you'd use {1}
, etc.
for the latest Chrome version, this works for me :
var win = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top="+(screen.height-400)+",left="+(screen.width-840));
win.document.body.innerHTML = 'iframe width="100%" height="100%" src="data:application/pdf;base64,"+base64+"></iframe>';
Thanks
TypeScript uses '<>' to surround casts, so the above becomes:
var script = <HTMLScriptElement>document.getElementsByName("script")[0];
However, unfortunately you cannot do:
var script = (<HTMLScriptElement[]>document.getElementsByName(id))[0];
You get the error
Cannot convert 'NodeList' to 'HTMLScriptElement[]'
But you can do :
(<HTMLScriptElement[]><any>document.getElementsByName(id))[0];
The function is max
. To obtain the first maximum value you should do
[val, idx] = max(a);
val
is the maximum value and idx
is its index.
MongoDB does not allow joins, but you can use plugins to handle that. Check the mongo-join plugin. It's the best and I have already used it. You can install it using npm directly like this npm install mongo-join
. You can check out the full documentation with examples.
(++) really helpful tool when we need to join (N) collections
(--) we can apply conditions just on the top level of the query
Example
var Join = require('mongo-join').Join, mongodb = require('mongodb'), Db = mongodb.Db, Server = mongodb.Server;
db.open(function (err, Database) {
Database.collection('Appoint', function (err, Appoints) {
/* we can put conditions just on the top level */
Appoints.find({_id_Doctor: id_doctor ,full_date :{ $gte: start_date },
full_date :{ $lte: end_date }}, function (err, cursor) {
var join = new Join(Database).on({
field: '_id_Doctor', // <- field in Appoints document
to: '_id', // <- field in User doc. treated as ObjectID automatically.
from: 'User' // <- collection name for User doc
}).on({
field: '_id_Patient', // <- field in Appoints doc
to: '_id', // <- field in User doc. treated as ObjectID automatically.
from: 'User' // <- collection name for User doc
})
join.toArray(cursor, function (err, joinedDocs) {
/* do what ever you want here */
/* you can fetch the table and apply your own conditions */
.....
.....
.....
resp.status(200);
resp.json({
"status": 200,
"message": "success",
"Appoints_Range": joinedDocs,
});
return resp;
});
});
# tar all files within and deeper in a given directory
# with no prefixes ( neither <directory>/ nor ./ )
# parameters: <source directory> <target archive file>
function tar_all_in_dir {
{ cd "$1" && find -type f -print0; } \
| cut --zero-terminated --characters=3- \
| tar --create --file="$2" --directory="$1" --null --files-from=-
}
Safely handles filenames with spaces or other unusual characters. You can optionally add a -name '*.sql'
or similar filter to the find command to limit the files included.
Probably shortest (based on OR operator and its precedence)
x-2||dosomething()
let x=1, y=2;_x000D_
let dosomething = s=>console.log(s); _x000D_
_x000D_
x-2||dosomething('x do something');_x000D_
y-2||dosomething('y do something');
_x000D_
You just do CSS changes for parent div
.parent-div {
text-align: center;
display: block;
}
You can use this tool to create appropriate c# classes:
http://jsonclassgenerator.codeplex.com/
and when you will have classes created you can simply convert string to object:
public static T ParseJsonObject<T>(string json) where T : class, new()
{
JObject jobject = JObject.Parse(json);
return JsonConvert.DeserializeObject<T>(jobject.ToString());
}
Here that classes: http://ge.tt/2KGtbPT/v/0?c
Just fix namespaces.
I'm going to leave this one here: https://stackoverflow.com/a/14509697/1356953
Please note that this works with java.lang.SuppressWarnings
so no need to use a separate annotation.
@SuppressWarnings on a field only suppresses findbugs warnings reported for that field declaration, not every warning associated with that field.
For example, this suppresses the "Field only ever set to null" warning:
@SuppressWarnings("UWF_NULL_FIELD") String s = null; I think the best you can do is isolate the code with the warning into the smallest method you can, then suppress the warning on the whole method.
You need to add the package containing the executable pg_config.
A prior answer should have details you need: pg_config executable not found
Just in case it may help somebody, you may also try this animator ViewPropertyAnimator as below
myView.animate().x(50f).y(100f);
myView.animate().translateX(pixelInScreen)
Note: This pixel is not relative to the view. This pixel is the pixel position in the screen.
credits to bpr10 answer
What i suggest is , its better to use post than get. here are some difference between post VS get
Some notes on GET requests:
Some notes on POST requests:
HTML Code
<html>
<head></head>
<body>
<form action="output.php" method="post">
Red<input type="checkbox" name="color[]" id="color" value="red">
Green<input type="checkbox" name="color[]" id="color" value="green">
Blue<input type="checkbox" name="color[]" id="color" value="blue">
Cyan<input type="checkbox" name="color[]" id="color" value="cyan">
Magenta<input type="checkbox" name="color[]" id="color" value="Magenta">
Yellow<input type="checkbox" name="color[]" id="color" value="yellow">
Black<input type="checkbox" name="color[]" id="color" value="black">
<input type="submit" value="submit">
</form>
<body>
</html>
PHP code
<?php
if(isset($_POST['color'])) {
$name = $_POST['color'];
echo "You chose the following color(s): <br>";
foreach ($name as $color){
echo $color."<br />";
}} // end brace for if(isset
else {
echo "You did not choose a color.";
}
?>
The thing you are missing is that T
and interface{}
which holds a value of T
have different representations in memory so can't be trivially converted.
A variable of type T
is just its value in memory. There is no associated type information (in Go every variable has a single type known at compile time not at run time). It is represented in memory like this:
An interface{}
holding a variable of type T
is represented in memory like this
T
So coming back to your original question: why go does't implicitly convert []T
to []interface{}
?
Converting []T
to []interface{}
would involve creating a new slice of interface {}
values which is a non-trivial operation since the in-memory layout is completely different.
You can try:
Open sql file by text editor find and replace all
utf8mb4 to utf8
Import again.
width="50%" and height="50%" sets the width and height attributes to half of the parent element's width and height if I'm not mistaken. Also setting just width or height should set the width or height to the percentage of the parent element, if you're using percents.
Installing modules usually requires you to run an sql script that is included with the database installation.
Assuming linux-like OS
find / -name dblink.sql
Verify the location and run it
System.setProperty is not working for applets. Because JVM already running before applet start. In this case we use applet parameters like this:
deployJava.runApplet({
id: 'MyApplet',
code: 'com.mkysoft.myapplet.SomeClass',
archive: 'com.mkysoft.myapplet.jar'
}, {
java_version: "1.6*", // Target version
cache_option: "no",
cache_archive: "",
codebase_lookup: true,
java_arguments: "-Djava.net.preferIPv4Stack=true"
},
"1.6" // Minimum version
);
You can find deployJava.js at https://www.java.com/js/deployJava.js
CharSequence is an interface and String is its one of the implementations other than StringBuilder, StringBuffer and many other.
So, just as you use InterfaceName i = new ItsImplementation()
, you can use CharSequence cs = new String("string")
or simply CharSequence cs = "string";
One reason lists work as they do (ordered) is to address the need for an ordered container that can contain any type at any node, which vectors do not do. Lists are re-used for a variety of purposes in R, including forming the base of a data.frame
, which is a list of vectors of arbitrary type (but the same length).
Why do these two expressions not return the same result?
x = list(1, 2, 3, 4); x2 = list(1:4)
To add to @Shane's answer, if you wanted to get the same result, try:
x3 = as.list(1:4)
Which coerces the vector 1:4
into a list.
In Swift 4.2 and Xcode 10.1
let myView = UIView()
myView.frame = CGRect(x: 200, y: 200, width: 200, height: 200)
myView.myViewCorners()
//myView.myViewCorners(width: myView.frame.width)//Pass View width
view.addSubview(myView)
extension UIView {
//If you want only round corners
func myViewCorners() {
layer.cornerRadius = 10
layer.borderWidth = 1.0
layer.borderColor = UIColor.red.cgColor
layer.masksToBounds = true
}
//If you want complete round shape, enable above comment line
func myViewCorners(width:CGFloat) {
layer.cornerRadius = width/2
layer.borderWidth = 1.0
layer.borderColor = UIColor.red.cgColor
layer.masksToBounds = true
}
}
I believe you are getting an empty array because PHP is expecting the posted data to be in a Querystring format (key=value&key1=value1).
Try changing your curl request to:
curl -i -X POST -d 'json={"screencast":{"subject":"tools"}}' \
http://localhost:3570/index.php/trainingServer/screencast.json
and see if that helps any.
Most IIS sections are locked by default but you can "unlock" them by setting the attribute overrideModeDefault
from "Deny" to "Allow" for the relevant section group by modifying the ApplicationHost.config file located in %windir%\system32\inetsrv\config
in Administrator mode
Check the column collation. This script might change the collation to the table default. Add the current collation to the script.
The StartsWith method will be faster, as there is no overhead of interpreting a regular expression, but here is how you do it:
if (Regex.IsMatch(theString, "^(mailto|ftp|joe):")) ...
The ^
mathes the start of the string. You can put any protocols between the parentheses separated by |
characters.
Another approach that is much faster, is to get the start of the string and use in a switch. The switch sets up a hash table with the strings, so it's faster than comparing all the strings:
int index = theString.IndexOf(':');
if (index != -1) {
switch (theString.Substring(0, index)) {
case "mailto":
case "ftp":
case "joe":
// do something
break;
}
}
Remove all widths set using CSS and set white-space to nowrap like so:
.content-loader tr td {
white-space: nowrap;
}
I would also remove the fixed width from the container (or add overflow-x: scroll
to the container) if you want the fields to display in their entirety without it looking odd...
See more here: http://www.w3schools.com/cssref/pr_text_white-space.asp
Before changing your react native package name! please make a backup of MainActivity.java and MainApplication.java file. Because this lib remove your MainActivity.java and MainApplication.java.
after doing this you can simply use react-native-rename npm package.
Install
npm install react-native-rename -g
Then from the root of your React Native project execute the following
react-native-rename "new_project_name" -b com.mycompany.newprojectname
finally you can check it out your new package name in your AndroidManifest.xml. Don't forgot to rename the package name in your MainActivity.java and MainApplication.java .
Thank you.
In addition to Dee Jee solution, After trying out his solution, My error never went.
I noticed(after two days of head scratch) that the browser has cached the files improperly.
Remove the cached files. By clearing the browser history in a span of 1 hour, so that all the cached files get deleted.
Aggregate is basically used to Group or Sum up data.
According to MSDN "Aggregate Function Applies an accumulator function over a sequence."
Example 1: Add all the numbers in a array.
int[] numbers = new int[] { 1,2,3,4,5 };
int aggregatedValue = numbers.Aggregate((total, nextValue) => total + nextValue);
*important: The initial aggregate value by default is the 1 element in the sequence of collection. i.e: the total variable initial value will be 1 by default.
variable explanation
total: it will hold the sum up value(aggregated value) returned by the func.
nextValue: it is the next value in the array sequence. This value is than added to the aggregated value i.e total.
Example 2: Add all items in an array. Also set the initial accumulator value to start adding with from 10.
int[] numbers = new int[] { 1,2,3,4,5 };
int aggregatedValue = numbers.Aggregate(10, (total, nextValue) => total + nextValue);
arguments explanation:
the first argument is the initial(starting value i.e seed value) which will be used to start addition with the next value in the array.
the second argument is a func which is a func that takes 2 int.
1.total: this will hold same as before the sum up value(aggregated value) returned by the func after the calculation.
2.nextValue: : it is the next value in the array sequence. This value is than added to the aggregated value i.e total.
Also debugging this code will give you a better understanding of how aggregate work.
If s
is your string than you could do it this way:
Mid(s, index, 1)
Edit based on comment below question.
It seems that you need a bit different approach which should be easier. Try in this way:
Dim character As String 'Integer if for numbers
's = ActiveDocument.Content.Text - we don't need it
character = Activedocument.Characters(index)
This would give you all valid numeric values in lines
. You can change the loop to validate, strip out invalid characters, etc - whichever you want.
var lines = [];
$('#my_textarea_selector').val().split("\n").each(function ()
{
if (parseInt($(this) != 'NaN')
lines[] = parseInt($(this));
}
$this->db->or_where('end_date IS', 'NULL', false);
The value of the certificate comes mostly from the trust of the internet users in the issuer of the certificate. To that end, Verisign is tough to beat. A certificate says to the client that you are who you say you are, and the issuer has verified that to be true.
You can get a free SSL certificate signed, for example, by StartSSL. This is an improvement on self-signed certificates, because your end-users would stop getting warning pop-ups informing them of a suspicious certificate on your end. However, the browser bar is not going to turn green when communicating with your site over https, so this solution is not ideal.
The cheapest SSL certificate that turns the bar green will cost you a few hundred dollars, and you would need to go through a process of proving the identity of your company to the issuer of the certificate by submitting relevant documents.
Like in other answers, start your span attributes with this:
display:inline-block;
Now you can use padding more than width:
padding-left:6%;
padding-right:6%;
When you use padding, your color expands to both side (right and left), not just right (like in widht).
Like "VB's On Error Resume Next?" That sounds kind of scary. First recommendation is don't do it. Second recommendation is don't do it and don't think about it. You need to isolate your faults better. As to how to approach this problem, it depends on how you're code is structured. If you are using a pattern like MVC or the like then this shouldn't be too difficult and would definitely not require a global exception swallower. Secondly, look for a good logging library like log4net or use tracing. We'd need to know more details like what kinds of exceptions you're talking about and what parts of your application may result in exceptions being thrown.
First of all, dynamically pivot using pivot xml
again needs to be parsed. We have another way of doing this by storing the column names in a variable and passing them in the dynamic sql as below.
Consider we have a table like below.
If we need to show the values in the column YR
as column names and the values in those columns from QTY
, then we can use the below code.
declare
sqlqry clob;
cols clob;
begin
select listagg('''' || YR || ''' as "' || YR || '"', ',') within group (order by YR)
into cols
from (select distinct YR from EMPLOYEE);
sqlqry :=
'
select * from
(
select *
from EMPLOYEE
)
pivot
(
MIN(QTY) for YR in (' || cols || ')
)';
execute immediate sqlqry;
end;
/
RESULT
You could use a pseudo element for this, and have your image on a hover:
.image {_x000D_
position: relative;_x000D_
height: 300px;_x000D_
width: 300px;_x000D_
background: url(http://lorempixel.com/300/300);_x000D_
}_x000D_
.image:before {_x000D_
content: "";_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
transition: all 0.8s;_x000D_
opacity: 0;_x000D_
background: url(http://lorempixel.com/300/200);_x000D_
background-size: 100% 100%;_x000D_
}_x000D_
.image:hover:before {_x000D_
opacity: 0.8;_x000D_
}
_x000D_
<div class="image"></div>
_x000D_
The pattern \d
might not be supported by your sed
. Try [0-9]
or [[:digit:]]
instead.
To only print the actual match (not the entire matching line), use a substitution.
sed -n 's/.*\([0-9][0-9]*G[0-9][0-9]*\).*/\1/p'
A variation on the 'digit' solutions offered here:
char separator = DecimalFormatSymbols.getInstance().getDecimalSeparator();
input.setKeyListener(DigitsKeyListener.getInstance("0123456789" + separator));
Taking into account the locale separator.
Fell into the same trouble with inlining functions into so libraries. It seems that inlined functions are not compiled into the library. as a result the linker puts out a "undefined reference" error, if a executable wants to use the inlined function of the library. (happened to me compiling Qt source with gcc 4.5.
Session in Java servlets is the same as session in other languages such as PHP. It is unique to the user. The server can keep track of it in different ways such as cookies, url rewriting etc. This Java doc article explains it in the context of Java servlets and indicates that exactly how session is maintained is an implementation detail left to the designers of the server. The specification only stipulates that it must be maintained as unique to a user across multiple connections to the server. Check out this article from Oracle for more information about both of your questions.
Edit There is an excellent tutorial here on how to work with session inside of servlets. And here is a chapter from Sun about Java Servlets, what they are and how to use them. Between those two articles, you should be able to answer all of your questions.
I couldn't find a direct GDrive/DropBox solution. I'm also surprised there's no lazy solution for a free ftp host. Windows azure offers a ftp server "FTP connector" that's fairly easy to turn on at: https://portal.azure.com
You can get a free 1 GB account by selecting "View All" machine types during your deployment.
To avoid this sort of trouble, you can use replace
(which takes a plain string) instead of replaceAll
(which takes a regular expression). You will still need to escape backslashes, but not in the wild ways required with regular expressions.
Use replace()
s = s.replace("'", "\\'");
output:
You\'ll be totally awesome, I\'m really terrible
Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.
Take this
<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
and place it in phpsqlajax_genxml.php
so your javascript can download the XML file. You are trying to do too many things in the same file.
The .import
command is a feature of the sqlite3 command-line tool. To do it in Python, you should simply load the data using whatever facilities Python has, such as the csv module, and inserting the data as per usual.
This way, you also have control over what types are inserted, rather than relying on sqlite3's seemingly undocumented behaviour.
As others said your Firewall needs to be configured to accept incoming calls on TCP Port 80.
in win 7+ (easy wizardry way)
Because outbound traffic(from server to outside world) is allowed by default .it means for example http responses that web server is sending back to outside users and requests
But inbound traffic (originating from outside world to the server) is blocked by default like the user web requests originating from their browser which cannot reach the web server by default and you must open it.
You can also take a closer look at inbound and outbound rules at this page
Complete Code for android Flashlight App
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.user.flashlight"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OFF"
android:id="@+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="turnFlashOnOrOff" />
</RelativeLayout>
MainActivity.java
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.security.Policy;
public class MainActivity extends AppCompatActivity {
Button button;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(!hasFlash) {
AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
return;
}
getCamera();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isFlashOn) {
turnOffFlash();
button.setText("ON");
} else {
turnOnFlash();
button.setText("OFF");
}
}
});
}
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
}catch (Exception e) {
}
}
}
private void turnOnFlash() {
if(!isFlashOn) {
if(camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
}
}
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onPause() {
super.onPause();
// on pause turn off the flash
turnOffFlash();
}
@Override
protected void onRestart() {
super.onRestart();
}
@Override
protected void onResume() {
super.onResume();
// on resume turn on the flash
if(hasFlash)
turnOnFlash();
}
@Override
protected void onStart() {
super.onStart();
// on starting the app get the camera params
getCamera();
}
@Override
protected void onStop() {
super.onStop();
// on stop release the camera
if (camera != null) {
camera.release();
camera = null;
}
}
}
I think what you want to do is this:
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="--Select One--" Value="" />
</asp:DropDownList>
Make sure the 'AppendDataBoundItems' is set to true or else you will clear the '--Select One--' list item when you bind your data.
If you have the 'AutoPostBack' property of the drop down list set to true you will have to also set the 'CausesValidation' property to true then use a 'RequiredFieldValidator' to make sure the '--Select One--' option doesn't cause a postback.
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="DropDownList1"></asp:RequiredFieldValidator>
If you go one level up in running the script in the command line of your bash shell, the issue will be resolved. To do this, use cd ..
command to change the working directory in which your script will be running. The result should look like this:
[username@localhost myProgram]$
rather than this:
[username@localhost app]$
Once you are there, instead of running the script in the following format:
python3 mymodule.py
Change it to this:
python3 app/mymodule.py
This process can be repeated once again one level up depending on the structure of your Tree diagram. Please also include the compilation command line that is giving you that mentioned error message.
The provided answers are the best solution in your case, and they are what I do as well, but if your text is printed by a function or class method you could do the same as in Javascript as well
function hello(){
echo 'HELLO';
}
$print = true;
$print && hello();
You are using wrong JSON. In this case you should use JSON that looks like this:
["orange", "apple"]
If you have to accept JSON in that form :
{"fruits":["apple","orange"]}
You'll have to create wrapper object:
public class FruitWrapper{
List<String> fruits;
//getter
//setter
}
and then your controller method should look like this:
@RequestMapping(value = "/saveFruits", method = RequestMethod.POST,
consumes = "application/json")
@ResponseBody
public ResultObject saveFruits(@RequestBody FruitWrapper fruits){
...
}
The "no frills" options are as follows:
ActiveSheet.Name = "New Name"
and
Sheets("Sheet2").Name = "New Name"
You can also check out recording macros and seeing what code it gives you, it's a great way to start learning some of the more vanilla functions.
alter user username superuser;
print(df.isnull().sum()) # check numbers of null value in each column
modifiedDf=df.fillna("NaN") # Replace empty/null values with "NaN"
# modifiedDf = fd.dropna() # Remove rows with empty values
print(modifiedDf.isnull().sum()) # check numbers of null value in each column
Cinn's answer is great, but there's one thing wrong with it.
The PreferredSize
widget will start immediately at the top of the screen, without accounting for the status bar, so some of its height will be shadowed by the status bar's height. This also accounts for the side notches.
The solution: Wrap the preferredSize
's child with a SafeArea
appBar: PreferredSize(
//Here is the preferred height.
preferredSize: Size.fromHeight(50.0),
child: SafeArea(
child: AppBar(
flexibleSpace: ...
),
),
),
If you don't wanna use the flexibleSpace property, then there's no need for all that, because the other properties of the AppBar
will account for the status bar automatically.
Handle the form’s Resize event. In this handler, you override the basic functionality of the Resize event to make the form minimize to the system tray and not to the taskbar. This can be done by doing the following in your form’s Resize event handler: Check whether the form’s WindowState property is set to FormWindowState.Minimized. If yes, hide your form, enable the NotifyIcon object, and show the balloon tip that shows some information. Once the WindowState becomes FormWindowState.Normal, disable the NotifyIcon object by setting its Visible property to false. Now, you want the window to reappear when you double click on the NotifyIcon object in the taskbar. For this, handle the NotifyIcon’s MouseDoubleClick event. Here, you show the form using the Show() method.
private void frmMain_Resize(object sender, EventArgs e)
{
if (FormWindowState.Minimized == this.WindowState)
{
mynotifyicon.Visible = true;
mynotifyicon.ShowBalloonTip(500);
this.Hide();
}
else if (FormWindowState.Normal == this.WindowState)
{
mynotifyicon.Visible = false;
}
}
Very late to the party but here is a generic solution that works with every index value.
You create and spread new array from the old array up to the index
you want to change.
Add the data you want.
Create and spread new array from the index
you wanted to change to the end of the array
let index=1;// probabbly action.payload.id
case 'SOME_ACTION':
return {
...state,
contents: [
...state.contents.slice(0,index),
{title: "some other title", text: "some other text"},
...state.contents.slice(index+1)
]
}
Update:
I have made a small module to simplify the code, so you just need to call a function:
case 'SOME_ACTION':
return {
...state,
contents: insertIntoArray(state.contents,index, {title: "some title", text: "some text"})
}
For more examples, take a look at the repository
function signature:
insertIntoArray(originalArray,insertionIndex,newData)
You can use Environment Replacement in your Dockerfile
as follows:
ENV PATH="/opt/gtk/bin:${PATH}"
In order to obtain the string in a Text
widget one can simply use get
method defined for Text
which accepts 1 to 2 arguments as start
and end
positions of characters, text_widget_object.get(start, end=None)
. If only start
is passed and end
isn't passed it returns only the single character positioned at start
, if end
is passed as well, it returns all characters in between positions start
and end
as string.
There are also special strings, that are variables to the underlying Tk. One of them would be "end"
or tk.END
which represents the variable position of the very last char in the Text
widget. An example would be to returning all text in the widget, with text_widget_object.get('1.0', 'end')
or text_widget_object.get('1.0', 'end-1c')
if you don't want the last newline character.
See below demonstration that selects the characters in between the given positions with sliders:
try:
import tkinter as tk
except:
import Tkinter as tk
class Demo(tk.LabelFrame):
"""
A LabeFrame that in order to demonstrate the string returned by the
get method of Text widget, selects the characters in between the
given arguments that are set with Scales.
"""
def __init__(self, master, *args, **kwargs):
tk.LabelFrame.__init__(self, master, *args, **kwargs)
self.start_arg = ''
self.end_arg = None
self.position_frames = dict()
self._create_widgets()
self._layout()
self.update()
def _create_widgets(self):
self._is_two_args = tk.Checkbutton(self,
text="Use 2 positional arguments...")
self.position_frames['start'] = PositionFrame(self,
text="start='{}.{}'.format(line, column)")
self.position_frames['end'] = PositionFrame( self,
text="end='{}.{}'.format(line, column)")
self.text = TextWithStats(self, wrap='none')
self._widget_configs()
def _widget_configs(self):
self.text.update_callback = self.update
self._is_two_args.var = tk.BooleanVar(self, value=False)
self._is_two_args.config(variable=self._is_two_args.var,
onvalue=True, offvalue=False)
self._is_two_args['command'] = self._is_two_args_handle
for _key in self.position_frames:
self.position_frames[_key].line.slider['command'] = self.update
self.position_frames[_key].column.slider['command'] = self.update
def _layout(self):
self._is_two_args.grid(sticky='nsw', row=0, column=1)
self.position_frames['start'].grid(sticky='nsew', row=1, column=0)
#self.position_frames['end'].grid(sticky='nsew', row=1, column=1)
self.text.grid(sticky='nsew', row=2, column=0,
rowspan=2, columnspan=2)
_grid_size = self.grid_size()
for _col in range(_grid_size[0]):
self.grid_columnconfigure(_col, weight=1)
for _row in range(_grid_size[1] - 1):
self.grid_rowconfigure(_row + 1, weight=1)
def _is_two_args_handle(self):
self.update_arguments()
if self._is_two_args.var.get():
self.position_frames['end'].grid(sticky='nsew', row=1, column=1)
else:
self.position_frames['end'].grid_remove()
def update(self, event=None):
"""
Updates slider limits, argument values, labels representing the
get method call.
"""
self.update_sliders()
self.update_arguments()
def update_sliders(self):
"""
Updates slider limits based on what's written in the text and
which line is selected.
"""
self._update_line_sliders()
self._update_column_sliders()
def _update_line_sliders(self):
if self.text.lines_length:
for _key in self.position_frames:
self.position_frames[_key].line.slider['state'] = 'normal'
self.position_frames[_key].line.slider['from_'] = 1
_no_of_lines = self.text.line_count
self.position_frames[_key].line.slider['to'] = _no_of_lines
else:
for _key in self.position_frames:
self.position_frames[_key].line.slider['state'] = 'disabled'
def _update_column_sliders(self):
if self.text.lines_length:
for _key in self.position_frames:
self.position_frames[_key].column.slider['state'] = 'normal'
self.position_frames[_key].column.slider['from_'] = 0
_line_no = int(self.position_frames[_key].line.slider.get())-1
_max_line_len = self.text.lines_length[_line_no]
self.position_frames[_key].column.slider['to'] = _max_line_len
else:
for _key in self.position_frames:
self.position_frames[_key].column.slider['state'] = 'disabled'
def update_arguments(self):
"""
Updates the values representing the arguments passed to the get
method, based on whether or not the 2nd positional argument is
active and the slider positions.
"""
_start_line_no = self.position_frames['start'].line.slider.get()
_start_col_no = self.position_frames['start'].column.slider.get()
self.start_arg = "{}.{}".format(_start_line_no, _start_col_no)
if self._is_two_args.var.get():
_end_line_no = self.position_frames['end'].line.slider.get()
_end_col_no = self.position_frames['end'].column.slider.get()
self.end_arg = "{}.{}".format(_end_line_no, _end_col_no)
else:
self.end_arg = None
self._update_method_labels()
self._select()
def _update_method_labels(self):
if self.end_arg:
for _key in self.position_frames:
_string = "text.get('{}', '{}')".format(
self.start_arg, self.end_arg)
self.position_frames[_key].label['text'] = _string
else:
_string = "text.get('{}')".format(self.start_arg)
self.position_frames['start'].label['text'] = _string
def _select(self):
self.text.focus_set()
self.text.tag_remove('sel', '1.0', 'end')
self.text.tag_add('sel', self.start_arg, self.end_arg)
if self.end_arg:
self.text.mark_set('insert', self.end_arg)
else:
self.text.mark_set('insert', self.start_arg)
class TextWithStats(tk.Text):
"""
Text widget that stores stats of its content:
self.line_count: the total number of lines
self.lines_length: the total number of characters per line
self.update_callback: can be set as the reference to the callback
to be called with each update
"""
def __init__(self, master, update_callback=None, *args, **kwargs):
tk.Text.__init__(self, master, *args, **kwargs)
self._events = ('<KeyPress>',
'<KeyRelease>',
'<ButtonRelease-1>',
'<ButtonRelease-2>',
'<ButtonRelease-3>',
'<Delete>',
'<<Cut>>',
'<<Paste>>',
'<<Undo>>',
'<<Redo>>')
self.line_count = None
self.lines_length = list()
self.update_callback = update_callback
self.update_stats()
self.bind_events_on_widget_to_callback( self._events,
self,
self.update_stats)
@staticmethod
def bind_events_on_widget_to_callback(events, widget, callback):
"""
Bind events on widget to callback.
"""
for _event in events:
widget.bind(_event, callback)
def update_stats(self, event=None):
"""
Update self.line_count, self.lines_length stats and call
self.update_callback.
"""
_string = self.get('1.0', 'end-1c')
_string_lines = _string.splitlines()
self.line_count = len(_string_lines)
del self.lines_length[:]
for _line in _string_lines:
self.lines_length.append(len(_line))
if self.update_callback:
self.update_callback()
class PositionFrame(tk.LabelFrame):
"""
A LabelFrame that has two LabelFrames which has Scales.
"""
def __init__(self, master, *args, **kwargs):
tk.LabelFrame.__init__(self, master, *args, **kwargs)
self._create_widgets()
self._layout()
def _create_widgets(self):
self.line = SliderFrame(self, orient='vertical', text="line=")
self.column = SliderFrame(self, orient='horizontal', text="column=")
self.label = tk.Label(self, text="Label")
def _layout(self):
self.line.grid(sticky='ns', row=0, column=0, rowspan=2)
self.column.grid(sticky='ew', row=0, column=1, columnspan=2)
self.label.grid(sticky='nsew', row=1, column=1)
self.grid_rowconfigure(1, weight=1)
self.grid_columnconfigure(1, weight=1)
class SliderFrame(tk.LabelFrame):
"""
A LabelFrame that encapsulates a Scale.
"""
def __init__(self, master, orient, *args, **kwargs):
tk.LabelFrame.__init__(self, master, *args, **kwargs)
self.slider = tk.Scale(self, orient=orient)
self.slider.pack(fill='both', expand=True)
if __name__ == '__main__':
root = tk.Tk()
demo = Demo(root, text="text.get(start, end=None)")
with open(__file__) as f:
demo.text.insert('1.0', f.read())
demo.text.update_stats()
demo.pack(fill='both', expand=True)
root.mainloop()
If you put <img src="iwojimaflag.jpg"/>
in html code then place iwojimaflag.jpg and html file in same folder.
If you put <img src="images/iwojimaflag.jpg"/>
then you must create "images" folder and put image iwojimaflag.jpg in that folder.
I advise you to run sftp with -v option. It becomes much easier to fathom what is happening.
The manual clearly states:
The final usage format allows for automated sessions using the -b option. In such cases, it is necessary to configure non-interactive authentication to obviate the need to enter a password at connection time (see sshd(8) and ssh-keygen(1) for details).
In other words you have to establish a publickey authentication. Then you'll be able to run a batch script.
P.S. It is wrong to put your password in your batch file.
An SMS Push is a message to tell the terminal to initiate the session. This happens because you can't initiate an IP session simply because you don't know the IP Adress of the mobile terminal. Mostly used to send a few lines of data to end recipient, to the effect of sending information, or reminding of events.
WAP Push is an SMS within the header of which is included a link to a WAP address. On receiving a WAP Push, the compatible mobile handset automatically gives the user the option to access the WAP content on his handset. The WAP Push directs the end-user to a WAP address where content is stored ready for viewing or downloading onto the handset. This wap address may be a page or a WAP site.
The user may “take action” by using a developer-defined soft-key to immediately activate an application to accomplish a specific task, such as downloading a picture, making a purchase, or responding to a marketing offer.
This is how I use the Fail method.
There are three states that your test case can end up in
intended (Unlike negative test cases that expect a exception to occur).
If you are using eclipse there three states are indicated by a Green, Blue and red marker respectively.
I use the fail operation for the the third scenario.
e.g. : public Integer add(integer a, Integer b) { return new Integer(a.intValue() + b.intValue())}
Lot of very detailed answers here but I don't think you are answering the right questions. As I understand the question, there are two concerns:
You can use most of the scoring functions in scikit-learn with both multiclass problem as with single class problems. Ex.:
from sklearn.metrics import precision_recall_fscore_support as score
predicted = [1,2,3,4,5,1,2,1,1,4,5]
y_test = [1,2,3,4,5,1,2,1,1,4,1]
precision, recall, fscore, support = score(y_test, predicted)
print('precision: {}'.format(precision))
print('recall: {}'.format(recall))
print('fscore: {}'.format(fscore))
print('support: {}'.format(support))
This way you end up with tangible and interpretable numbers for each of the classes.
| Label | Precision | Recall | FScore | Support |
|-------|-----------|--------|--------|---------|
| 1 | 94% | 83% | 0.88 | 204 |
| 2 | 71% | 50% | 0.54 | 127 |
| ... | ... | ... | ... | ... |
| 4 | 80% | 98% | 0.89 | 838 |
| 5 | 93% | 81% | 0.91 | 1190 |
Then...
... you can tell if the unbalanced data is even a problem. If the scoring for the less represented classes (class 1 and 2) are lower than for the classes with more training samples (class 4 and 5) then you know that the unbalanced data is in fact a problem, and you can act accordingly, as described in some of the other answers in this thread. However, if the same class distribution is present in the data you want to predict on, your unbalanced training data is a good representative of the data, and hence, the unbalance is a good thing.
Most of these answers either does not answer the question or is unnecessarily long in the explanation.
OK so JSON only uses double quotation marks, we get that!
I was trying to use JQuery AJAX to post JSON data to server and then later return that same information. The best solution to the posted question I found was to use:
var d = {
name: 'whatever',
address: 'whatever',
DOB: '01/01/2001'
}
$.ajax({
type: "POST",
url: 'some/url',
dataType: 'json',
data: JSON.stringify(d),
...
}
This will escape the characters for you.
This was also suggested by Mark Amery, Great answer BTW
Hope this helps someone.
select name, count(*) from table group by name;
i think should do it
Wait!
There is a way to retrieve the password by using Brute-Force attack, have a look at the following tool from codeproject Retrieve SQL Server Password
To Retrieve the password of SQL Server user,run the following query in SQL Query Analyzer
"Select Password from SysxLogins Where Name = 'XXXX'" Where XXXX is the user
name for which you want to retrieve password.Copy the password field (Hashed Code) and
paste here (in Hashed code Field) and click on start button to retrieve
I checked the tool on SQLServer 2000 and it's working fine.
Here is a generic solution that you can add to your Array library. All you need to do is supply the associated value and the target array!
PHP Manual: array_search() (similiar to .indexOf() in other languages)
public function getKey(string $value, array $target)
{
$key = array_search($value, $target);
if ($key === null) {
throw new InvalidArgumentException("Invalid arguments provided. Check inputs. Must be a (1) a string and (2) an array.");
}
if ($key === false) {
throw new DomainException("The search value does not exists in the target array.");
}
return $key;
}
Just like the others said before the way to do this is to press ctrl+w and then o. This will "maximize" the current window, while closing the others. If you'd like to be able to "unmaximize" it, there's a plugin called ZoomWin for that. Otherwise you'd have to recreate the window setup from scratch.
If you have multiple subplots, i.e.
fig, ax = plt.subplots(4, 2)
You can use the same y limits for all of them. It gets limits of y ax from first plot.
plt.setp(ax, ylim=ax[0,0].get_ylim())
if you want use with expression, the rigth way is :
<span class="ng-style: yourCondition && {color:'red'};">Sample Text</span>
but the best way is using ng-class
i was using
objectName.addEventListener('click', function() {
event.preventDefault();
}
but its show error "event is undefined" so in this case use event parameter like
objectName.addEventListener('click', function(event) {
event.preventDefault();
}
now its works fine
This is what you are looking for:
^((?!(abc|def)).)*$
the explanation is here: Regular expression to match a line that doesn't contain a word?
I have found that in some cases too much memory can slow the program down.
For example I had a hibernate based transform engine that started running slowly as the load increased. It turned out that each time we got an object from the db, hibernate was checking memory for objects that would never be used again.
The solution was to evict the old objects from the session.
Stuart
When you want to add a javascript object to the form data, you can use the following code
var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeArray();
for (var key in data) {
if (data.hasOwnProperty(key)) {
postData.push({name:key, value:data[key]});
}
}
$.post(url, postData, function(){});
Or if you add the method serializeObject(), you can do the following
var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeObject();
$.extend(postData, data);
$.post(url, postData, function(){});
This problem that the "../" means step up (parent folder) link "../images/img.png"
will not work because when you are using ajax like data passing to the web site from the server.
What you have to do is point the image location to root with "./" then the second folder (in this case the second folder is "images")
url("./images/img.png")
if you have folders like this
then you use url("./content/images/img.png")
, remember your image will not visible in the editor window but when it passed to the browser using ajax it will display.
Here ya go:
viewNoteDateMonth.text = [[displayDate objectAtIndex:2] uppercaseString];
Btw:
"april"
is lowercase
? [NSString lowercaseString]
"APRIL"
is UPPERCASE
? [NSString uppercaseString]
"April May"
is Capitalized/Word Caps
? [NSString capitalizedString]
"April may"
is Sentence caps
? (method missing; see workaround below)
Hence what you want is called "uppercase", not "capitalized". ;)
As for "Sentence Caps" one has to keep in mind that usually "Sentence" means "entire string". If you wish for real sentences use the second method, below, otherwise the first:
@interface NSString ()
- (NSString *)sentenceCapitalizedString; // sentence == entire string
- (NSString *)realSentenceCapitalizedString; // sentence == real sentences
@end
@implementation NSString
- (NSString *)sentenceCapitalizedString {
if (![self length]) {
return [NSString string];
}
NSString *uppercase = [[self substringToIndex:1] uppercaseString];
NSString *lowercase = [[self substringFromIndex:1] lowercaseString];
return [uppercase stringByAppendingString:lowercase];
}
- (NSString *)realSentenceCapitalizedString {
__block NSMutableString *mutableSelf = [NSMutableString stringWithString:self];
[self enumerateSubstringsInRange:NSMakeRange(0, [self length])
options:NSStringEnumerationBySentences
usingBlock:^(NSString *sentence, NSRange sentenceRange, NSRange enclosingRange, BOOL *stop) {
[mutableSelf replaceCharactersInRange:sentenceRange withString:[sentence sentenceCapitalizedString]];
}];
return [NSString stringWithString:mutableSelf]; // or just return mutableSelf.
}
@end
First you have to get the localVisible rectangle of the view
For eg:
Rect rectf = new Rect();
//For coordinates location relative to the parent
anyView.getLocalVisibleRect(rectf);
//For coordinates location relative to the screen/display
anyView.getGlobalVisibleRect(rectf);
Log.d("WIDTH :", String.valueOf(rectf.width()));
Log.d("HEIGHT :", String.valueOf(rectf.height()));
Log.d("left :", String.valueOf(rectf.left));
Log.d("right :", String.valueOf(rectf.right));
Log.d("top :", String.valueOf(rectf.top));
Log.d("bottom :", String.valueOf(rectf.bottom));
Hope this will help
For a different command I decided to change the network from public to work.
After trying to use the psexec command again it worked again.
So to get psexec to work try to change your network type from public to work or home.
where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS')
should work.
Calling async
code from synchronous code can be quite tricky.
I explain the full reasons for this deadlock on my blog. In short, there's a "context" that is saved by default at the beginning of each await
and used to resume the method.
So if this is called in an UI context, when the await
completes, the async
method tries to re-enter that context to continue executing. Unfortunately, code using Wait
(or Result
) will block a thread in that context, so the async
method cannot complete.
The guidelines to avoid this are:
ConfigureAwait(continueOnCapturedContext: false)
as much as possible. This enables your async
methods to continue executing without having to re-enter the context.async
all the way. Use await
instead of Result
or Wait
.If your method is naturally asynchronous, then you (probably) shouldn't expose a synchronous wrapper.
I had this issue while running MySQL on Minikube (Ubuntu box) and I solved it with:
sudo ln -s /etc/apparmor.d/usr.sbin.mysqld /etc/apparmor.d/disable/
sudo apparmor_parser -R /etc/apparmor.d/usr.sbin.mysqld
Don't worry about any performance differences, they're going to be minimal in this case normally.
Method 2 is preferable because
it doesn't require mutating a collection that exists outside the lambda expression,
it's more readable because the different steps that are performed in the collection pipeline are written sequentially: first a filter operation, then a map operation, then collecting the result (for more info on the benefits of collection pipelines, see Martin Fowler's excellent article),
you can easily change the way values are collected by replacing the Collector
that is used. In some cases you may need to write your own Collector
, but then the benefit is that you can easily reuse that.
The accepted answer doesn't create a name-only attribute anymore (as of September 2017).
You should use JQuery prop() method to create name-only attributes.
$(body).prop('data-body', true)
You will not able to test the app using the Google-Play-Service library
in emulator. In order to test that app in emulator you need to install some system framework in your emulator to make it work.
https://stackoverflow.com/a/11213598/1405008
Refer the above answer to install Google play service on your emulator.
AngularJS form elements look for the required
attribute to perform validation functions. ng-required
allows you to set the required
attribute depending on a boolean test (for instance, only require field B - say, a student number - if the field A has a certain value - if you selected "student" as a choice)
As an example, <input required>
and <input ng-required="true">
are essentially the same thing
If you are wondering why this is this way, (and not just make <input required="true">
or <input required="false">
), it is due to the limitations of HTML - the required
attribute has no associated value - its mere presence means (as per HTML standards) that the element is required - so angular needs a way to set/unset required value (required="false"
would be invalid HTML)
You can use the function ginv() (Moore-Penrose generalized inverse) in the MASS package
You can use window.postMessage to call a function between page and his iframe (cross domain or not).
page.html
<!DOCTYPE html>
<html>
<head>
<title>Page with an iframe</title>
<meta charset="UTF-8" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
var Page = {
id:'page',
variable:'This is the page.'
};
$(window).on('message', function(e) {
var event = e.originalEvent;
if(window.console) {
console.log(event);
}
alert(event.origin + '\n' + event.data);
});
function iframeReady(iframe) {
if(iframe.contentWindow.postMessage) {
iframe.contentWindow.postMessage('Hello ' + Page.id, '*');
}
}
</script>
</head>
<body>
<h1>Page with an iframe</h1>
<iframe src="iframe.html" onload="iframeReady(this);"></iframe>
</body>
</html>
iframe.html
<!DOCTYPE html>
<html>
<head>
<title>iframe</title>
<meta charset="UTF-8" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
var Page = {
id:'iframe',
variable:'The iframe.'
};
$(window).on('message', function(e) {
var event = e.originalEvent;
if(window.console) {
console.log(event);
}
alert(event.origin + '\n' + event.data);
});
$(window).on('load', function() {
if(window.parent.postMessage) {
window.parent.postMessage('Hello ' + Page.id, '*');
}
});
</script>
</head>
<body>
<h1>iframe</h1>
<p>It's the iframe.</p>
</body>
</html>
JDK9+ solution using java.time.Duration
Duration.ofNanos(1_000_000L).toSeconds()
https://docs.oracle.com/javase/9/docs/api/java/time/Duration.html#ofNanos-long-
https://docs.oracle.com/javase/9/docs/api/java/time/Duration.html#toSeconds--
Check out all the DateTime methods here: http://msdn.microsoft.com/en-us/library/system.datetime.aspx
Add
Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance.
AddDays
Returns a new DateTime that adds the specified number of days to the value of this instance.
AddHours
Returns a new DateTime that adds the specified number of hours to the value of this instance.
AddMilliseconds
Returns a new DateTime that adds the specified number of milliseconds to the value of this instance.
AddMinutes
Returns a new DateTime that adds the specified number of minutes to the value of this instance.
AddMonths
Returns a new DateTime that adds the specified number of months to the value of this instance.
AddSeconds
Returns a new DateTime that adds the specified number of seconds to the value of this instance.
AddTicks
Returns a new DateTime that adds the specified number of ticks to the value of this instance.
AddYears
Returns a new DateTime that adds the specified number of years to the value of this instance.
It seems that Scrapy
fails because installing Twisted
fails, which fails because incremental
fails. Running pip install --upgrade pip && pip install --upgrade incremental
fixed this for me.
Depending on your version (2012?) of SQL Server aside from the IF EXISTS you can also use MERGE like so:
ALTER PROCEDURE [dbo].[EmailsRecebidosInsert]
( @_DE nvarchar(50)
, @_ASSUNTO nvarchar(50)
, @_DATA nvarchar(30))
AS BEGIN
MERGE [dbo].[EmailsRecebidos] [Target]
USING (VALUES (@_DE, @_ASSUNTO, @_DATA)) [Source]([De], [Assunto], [Data])
ON [Target].[De] = [Source].[De] AND [Target].[Assunto] = [Source].[Assunto] AND [Target].[Data] = [Source].[Data]
WHEN NOT MATCHED THEN
INSERT ([De], [Assunto], [Data])
VALUES ([Source].[De], [Source].[Assunto], [Source].[Data]);
END
There are several helpful bits of code for this.
Place your cursor in a merged cell and ask these questions in the Immidiate Window:
Is the activecell a merged cell?
? Activecell.Mergecells
True
How many cells are merged?
? Activecell.MergeArea.Cells.Count
2
How many columns are merged?
? Activecell.MergeArea.Columns.Count
2
How many rows are merged?
? Activecell.MergeArea.Rows.Count
1
What's the merged range address?
? activecell.MergeArea.Address
$F$2:$F$3
Once I did it replacing the UIScrollView with a UITableView with only 1 cell, it worked fine.
Set the user name as data-username
attribute to the button and also a class:
HTML
<input type="button" name="theButton" value="Detail" class="btn" data-username="{{result['username']}}" />
JS
$(document).on('click', '.btn', function() {
var name = $(this).data('username');
if (name != undefined && name != null) {
window.location = '/player_detail?username=' + name;
}
});?
EDIT:
Also, you can simply check for undefined
&& null
using:
$(document).on('click', '.btn', function() {
var name = $(this).data('username');
if (name) {
window.location = '/player_detail?username=' + name;
}
});?
As, mentioned in this answer
if (name) {
}
will evaluate to true if value is not:
The above list represents all possible falsy values in ECMA/Javascript.
all of above answers would help you but you have to add three ports in the firewall of PC on which SQL Server is installed.
Add new TCP Local port in Windows firewall at port no. 1434
Add new program for SQL Server and select sql server.exe Path: C:\ProgramFiles\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Binn\sqlservr.exe
Add new program for SQL Browser and select sqlbrowser.exe Path: C:\ProgramFiles\Microsoft SQL Server\90\Shared\sqlbrowser.exe
In my case this was a syntax issue in the .yml file. I had:
@Value("${spring.kafka.bootstrap-servers}")
public List<String> BOOTSTRAP_SERVERS_LIST;
and the list in my .yml file:
bootstrap-servers:
- s1.company.com:9092
- s2.company.com:9092
- s3.company.com:9092
was not reading into the @Value-annotated field. When I changed the syntax in the .yml file to:
bootstrap-servers >
s1.company.com:9092
s2.company.com:9092
s3.company.com:9092
it worked fine.
Add a data-size property to the google recaptcha element and make it equal to "compact" in case of mobile.
Refer: google recaptcha docs
Don't update the styles in style.css, instead create a new stylesheet of your own and import in style.css
your-own-style.css
.body{
/*any updates*/
}
import your-own-style.css in style.css
@import url("your-own-style.css");
Kindly find below one liner bash script command to find all broken symbolic links recursively in any linux based OS
a=$(find / -type l); for i in $(echo $a); do file $i ; done |grep -i broken 2> /dev/null
further to what @JohnTESlade has answered. Google's python style guide has some pretty neat recommendations,
Names to Avoid
\__double_leading_and_trailing_underscore__ names
(reserved by Python)Naming Convention
CapWords
for class names, but lower_with_under.py
for module names. Although there are many existing modules named CapWords.py
, this is now discouraged because it's confusing when the module happens to be named after a class. ("wait -- did I write import StringIO
or from StringIO import StringIO
?")One way is to loop through the keys of the dictionary, which I recommend:
foreach(int key in sp.Keys)
dynamic value = sp[key];
Another way, is to loop through the dictionary as a sequence of pairs:
foreach(KeyValuePair<int, dynamic> pair in sp)
{
int key = pair.Key;
dynamic value = pair.Value;
}
I recommend the first approach, because you can have more control over the order of items retrieved if you decorate the Keys
property with proper LINQ statements, e.g., sp.Keys.OrderBy(x => x)
helps you retrieve the items in ascending order of the key. Note that Dictionary
uses a hash table data structure internally, therefore if you use the second method the order of items is not easily predictable.
Update (01 Dec 2016): replaced var
s with actual types to make the answer more clear.
Basically indexOf()
is a method belongs to string(array object also), But while calling the function you are passing a number, try to cast it to a string and pass it.
document.getElementById("oset").innerHTML = timeD2C(timeofday + "");
var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
function timeD2C(time) { // Converts 11.5 (decimal) to 11:30 (colon)_x000D_
var pos = time.indexOf('.');_x000D_
var hrs = time.substr(1, pos - 1);_x000D_
var min = (time.substr(pos, 2)) * 60;_x000D_
_x000D_
if (hrs > 11) {_x000D_
hrs = (hrs - 12) + ":" + min + " PM";_x000D_
} else {_x000D_
hrs += ":" + min + " AM";_x000D_
}_x000D_
return hrs;_x000D_
}_x000D_
alert(timeD2C(timeofday+""));
_x000D_
And it is good to do the string conversion inside your function definition,
function timeD2C(time) {
time = time + "";
var pos = time.indexOf('.');
So that the code flow won't break at times when devs forget to pass a string into this function.
Maybe you should try
^[#;].*$
^
matches the beggining, $
the end.
var seconds = 0;
setInterval(function () {
seconds++;
}, 1000);
There you go, now you have a variable counting seconds elapsed. Since I don't know the context, you'll have to decide whether you want to attach that variable to an object or make it global.
Set interval is simply a function that takes a function as it's first parameter and a number of milliseconds to repeat the function as it's second parameter.
You could also solve this by saving and comparing times.
EDIT: This answer will provide very inconsistent results due to things such as the event loop and the way browsers may choose to pause or delay processing when a page is in a background tab. I strongly recommend using the accepted answer.
You can use the controls PointToScreen
method to get the absolute position with respect to the screen.
You can do the Forms PointToScreen
method, and with basic math, get the control's position.
In my case DockerFile contained the image name in mixed case instead of lower case.
Earlier line in my DockerFile
FROM CentOs
and when I changed above to FROM centos
, it worked smoothly.
Use the event on handleChange
to figure out the element that has changed and then update it. For that you might need to change some property to identify it and update it.
See fiddle https://jsfiddle.net/69z2wepo/6164/
Applies to Bootstrap 3 only.
Ignoring the letters (xs, sm, md, lg) for now, I'll start with just the numbers...
col-*-6
spans 6 of 12 columns (half the width), col-*-12
spans 12 of 12 columns (the entire width), etcSo, if you want two equal columns to span a div, write
<div class="col-xs-6">Column 1</div>
<div class="col-xs-6">Column 2</div>
Or, if you want three unequal columns to span that same width, you could write:
<div class="col-xs-2">Column 1</div>
<div class="col-xs-6">Column 2</div>
<div class="col-xs-4">Column 3</div>
You'll notice the # of columns always add up to 12. It can be less than twelve, but beware if more than 12, as your offending divs will bump down to the next row (not .row
, which is another story altogether).
You can also nest columns within columns, (best with a .row
wrapper around them) such as:
<div class="col-xs-6">
<div class="row">
<div class="col-xs-4">Column 1-a</div>
<div class="col-xs-8">Column 1-b</div>
</div>
</div>
<div class="col-xs-6">
<div class="row">
<div class="col-xs-2">Column 2-a</div>
<div class="col-xs-10">Column 2-b</div>
</div>
</div>
Each set of nested divs also span up to 12 columns of their parent div. NOTE: Since each .col
class has 15px padding on either side, you should usually wrap nested columns in a .row
, which has -15px margins. This avoids duplicating the padding and keeps the content lined up between nested and non-nested col classes.
-- You didn't specifically ask about the xs, sm, md, lg
usage, but they go hand-in-hand so I can't help but touch on it...
In short, they are used to define at which screen size that class should apply:
Read the "Grid Options" chapter from the official Bootstrap documentation for more details.
You should usually classify a div using multiple column classes so it behaves differently depending on the screen size (this is the heart of what makes bootstrap responsive). eg: a div with classes col-xs-6
and col-sm-4
will span half the screen on the mobile phone (xs) and 1/3 of the screen on tablets(sm).
<div class="col-xs-6 col-sm-4">Column 1</div> <!-- 1/2 width on mobile, 1/3 screen on tablet) -->
<div class="col-xs-6 col-sm-8">Column 2</div> <!-- 1/2 width on mobile, 2/3 width on tablet -->
NOTE: as per comment below, grid classes for a given screen size apply to that screen size and larger unless another declaration overrides it (i.e. col-xs-6 col-md-4
spans 6 columns on xs
and sm
, and 4 columns on md
and lg
, even though sm
and lg
were never explicitly declared)
NOTE: if you don't define xs
, it will default to col-xs-12
(i.e. col-sm-6
is half the width on sm
, md
and lg
screens, but full-width on xs
screens).
NOTE: it's actually totally fine if your .row
includes more than 12 cols, as long as you are aware of how they will react. --This is a contentious issue, and not everyone agrees.
Yes they do.
You shouldn't really be overriding the constructor anyway. You should have a newInstance()
static method defined and pass any parameters via arguments (bundle)
For example:
public static final MyFragment newInstance(int title, String message) {
MyFragment f = new MyFragment();
Bundle bdl = new Bundle(2);
bdl.putInt(EXTRA_TITLE, title);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
return f;
}
And of course grabbing the args this way:
@Override
public void onCreate(Bundle savedInstanceState) {
title = getArguments().getInt(EXTRA_TITLE);
message = getArguments().getString(EXTRA_MESSAGE);
//...
//etc
//...
}
Then you would instantiate from your fragment manager like so:
@Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState == null){
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content, MyFragment.newInstance(
R.string.alert_title,
"Oh no, an error occurred!")
)
.commit();
}
}
This way if detached and re-attached the object state can be stored through the arguments. Much like bundles attached to Intents.
Reason - Extra reading
I thought I would explain why for people wondering why.
If you check: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/app/Fragment.java
You will see the instantiate(..)
method in the Fragment
class calls the newInstance
method:
public static Fragment instantiate(Context context, String fname, @Nullable Bundle args) {
try {
Class<?> clazz = sClassMap.get(fname);
if (clazz == null) {
// Class not found in the cache, see if it's real, and try to add it
clazz = context.getClassLoader().loadClass(fname);
if (!Fragment.class.isAssignableFrom(clazz)) {
throw new InstantiationException("Trying to instantiate a class " + fname
+ " that is not a Fragment", new ClassCastException());
}
sClassMap.put(fname, clazz);
}
Fragment f = (Fragment) clazz.getConstructor().newInstance();
if (args != null) {
args.setClassLoader(f.getClass().getClassLoader());
f.setArguments(args);
}
return f;
} catch (ClassNotFoundException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": make sure class name exists, is public, and has an"
+ " empty constructor that is public", e);
} catch (java.lang.InstantiationException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": make sure class name exists, is public, and has an"
+ " empty constructor that is public", e);
} catch (IllegalAccessException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": make sure class name exists, is public, and has an"
+ " empty constructor that is public", e);
} catch (NoSuchMethodException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": could not find Fragment constructor", e);
} catch (InvocationTargetException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": calling Fragment constructor caused an exception", e);
}
}
http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#newInstance() Explains why, upon instantiation it checks that the accessor is public
and that that class loader allows access to it.
It's a pretty nasty method all in all, but it allows the FragmentManger
to kill and recreate Fragments
with states. (The Android subsystem does similar things with Activities
).
Example Class
I get asked a lot about calling newInstance
. Do not confuse this with the class method. This whole class example should show the usage.
/**
* Created by chris on 21/11/2013
*/
public class StationInfoAccessibilityFragment extends BaseFragment implements JourneyProviderListener {
public static final StationInfoAccessibilityFragment newInstance(String crsCode) {
StationInfoAccessibilityFragment fragment = new StationInfoAccessibilityFragment();
final Bundle args = new Bundle(1);
args.putString(EXTRA_CRS_CODE, crsCode);
fragment.setArguments(args);
return fragment;
}
// Views
LinearLayout mLinearLayout;
/**
* Layout Inflater
*/
private LayoutInflater mInflater;
/**
* Station Crs Code
*/
private String mCrsCode;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCrsCode = getArguments().getString(EXTRA_CRS_CODE);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mInflater = inflater;
return inflater.inflate(R.layout.fragment_station_accessibility, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mLinearLayout = (LinearLayout)view.findViewBy(R.id.station_info_accessibility_linear);
//Do stuff
}
@Override
public void onResume() {
super.onResume();
getActivity().getSupportActionBar().setTitle(R.string.station_info_access_mobility_title);
}
// Other methods etc...
}
These steps worked for me:
Alternatively, I found these options which I had no need to try myself but looked easy to follow:
Finally, it may not be relevant but, if you are looking to create and setup a self-signed certificate (with mkcert) for your PWA app (website) hosted on a local IIS Web server, I followed this page:
Thanks and hope it helps!! :)
you can use simply write the code in a .bat
format extension ,the code of the batch file :
c:/ copy /b Image1.jpg + Archive.rar Image2.jpg
use this c# code :
Process.Start("file_name.bat")
A popup's parent can't itself be a popup. Both of their parents must be the same. So, if you create a popup inside a popup, you must save the parent's popup and make it a parent.
here's an example
If you wrap your Container
with rounded corners inside of a parent with the background color set to Colors.transparent
I think that does what you're looking for. If you're using a Scaffold
the default background color is white. Change that to Colors.transparent
if that achieves what you want.
new Container(
height: 300.0,
color: Colors.transparent,
child: new Container(
decoration: new BoxDecoration(
color: Colors.green,
borderRadius: new BorderRadius.only(
topLeft: const Radius.circular(40.0),
topRight: const Radius.circular(40.0),
)
),
child: new Center(
child: new Text("Hi modal sheet"),
)
),
),
If key is present table.put(key, val)
will just overwrite the value else it'll create a new entry. Poof! and you are done. :)
you can get the value from a map by using key is table.get(key);
That's about it
This should do the trick:
public int getNumberOfPdfPages(string fileName)
{
using (StreamReader sr = new StreamReader(File.OpenRead(fileName)))
{
Regex regex = new Regex(@"/Type\s*/Page[^s]");
MatchCollection matches = regex.Matches(sr.ReadToEnd());
return matches.Count;
}
}
From Rachael's answer and this one too.
You have to use the component's State to update component parameters such as Class Name if you want React to render your DOM correctly and efficiently.
UPDATE: I updated the example to toggle the Sidemenu on a button click. This is not necessary, but you can see how it would work. You might need to use "this.state" vs. "this.props" as I have shown. I'm used to working with Redux components.
constructor(props){
super(props);
}
getInitialState(){
return {"showHideSidenav":"hidden"};
}
render() {
return (
<div className="header">
<i className="border hide-on-small-and-down"></i>
<div className="container">
<a ref="btn" onClick={this.toggleSidenav.bind(this)} href="#" className="btn-menu show-on-small"><i></i></a>
<Menu className="menu hide-on-small-and-down"/>
<Sidenav className={this.props.showHideSidenav}/>
</div>
</div>
)
}
toggleSidenav() {
var css = (this.props.showHideSidenav === "hidden") ? "show" : "hidden";
this.setState({"showHideSidenav":css});
}
Now, when you toggle the state, the component will update and change the class name of the sidenav component. You can use CSS to show/hide the sidenav using the class names.
.hidden {
display:none;
}
.show{
display:block;
}
There are many ways to take input from the users. I personally like using the method gets. When you use gets, it gets the string that you typed, and that includes the ENTER key that you pressed to end your input.
name = gets
"mukesh\n"
You can see this in irb; type this and you will see the \n, which is the “newline” character that the ENTER key produces: Type
name = gets
you will see somethings like"mukesh\n"
You can get rid of pesky newline character using chomp method.
The chomp method gives you back the string, but without the terminating newline. Beautiful chomp method life saviour.
name = gets.chomp
"mukesh"
You can also use terminal to read the input. ARGV is a constant defined in the Object class. It is an instance of the Array class and has access to all the array methods. Since it’s an array, even though it’s a constant, its elements can be modified and cleared with no trouble. By default, Ruby captures all the command line arguments passed to a Ruby program (split by spaces) when the command-line binary is invoked and stores them as strings in the ARGV array.
When written inside your Ruby program, ARGV will take take a command line command that looks like this:
test.rb hi my name is mukesh
and create an array that looks like this:
["hi", "my", "name", "is", "mukesh"]
But, if I want to passed limited input then we can use something like this.
test.rb 12 23
and use those input like this in your program:
a = ARGV[0]
b = ARGV[1]
I had this exact error and I realized the my compileSdkVersion
was set at 25
and my buildToolsVersion
was set at "26.0.1"
.
So I just changed the compileSdkVersion
to 26
and synced the Gradle. it fixed the problem for me.
EDIT: my targetSDKVersion
was also set as 26
Very simple solution. Just rename your database and configure your new database name in your project.
The problem is the when you import your database, you got any errors and then the database will be corrupted. The log files will have the corrupted database name. You can rename your database easily using phpmyadmin for mysql.
phpmyadmin -> operations -> Rename database to
Single line code.. will return true or false
!!(arr.indexOf("val")+1)
Note you can use memcmp() on non static stuctures without worrying about padding, as long as you don't initialise all members (at once). This is defined by C90:
My big issue here was to build the Object structure required to match RestTemplate to a compatible Class. Luckily I found http://www.jsonschema2pojo.org/ (get the JSON response in a browser and use it as input) and I can't recommend this enough!
Using a single function with the possibility of custom unit of measure or formatted. Each time the function is called without parameters we restarted the initial time.
@ECHO OFF
ECHO.
ECHO DEMO timer function
ECHO --------------------
SET DELAY=4
:: First we call the function without any parameters to set the starting time
CALL:timer
:: We put some code we want to measure
ECHO.
ECHO Making some delay, please wait...
ECHO.
ping -n %DELAY% -w 1 127.0.0.1 >NUL
:: Now we call the function again with the desired parameters
CALL:timer elapsed_time
ECHO by Default : %elapsed_time%
CALL:timer elapsed_time "s"
ECHO in Seconds : %elapsed_time%
CALL:timer elapsed_time "anything"
ECHO Formatted : %elapsed_time% (HH:MM:SS.CS)
ECHO.
PAUSE
:: Elapsed Time Function
:: -----------------------------------------------------------------------
:: The returned value is in centiseconds, unless you enter the parameters
:: to be in another unit of measure or with formatted
::
:: Parameters:
:: <return> the returned value
:: [formatted] s (for seconds), m (for minutes), h (for hours)
:: anything else for formatted output
:: -----------------------------------------------------------------------
:timer <return> [formatted]
SetLocal EnableExtensions EnableDelayedExpansion
SET _t=%time%
SET _t=%_t::0=: %
SET _t=%_t:,0=, %
SET _t=%_t:.0=. %
SET _t=%_t:~0,2% * 360000 + %_t:~3,2% * 6000 + %_t:~6,2% * 100 + %_t:~9,2%
SET /A _t=%_t%
:: If we call the function without parameters is defined initial time
SET _r=%~1
IF NOT DEFINED _r (
EndLocal & SET TIMER_START_TIME=%_t% & GOTO :EOF
)
SET /A _t=%_t% - %TIMER_START_TIME%
:: In the case of wanting a formatted output
SET _f=%~2
IF DEFINED _f (
IF "%_f%" == "s" (
SET /A "_t=%_t% / 100"
) ELSE (
IF "%_f%" == "m" (
SET /A "_t=%_t% / 6000"
) ELSE (
IF "%_f%" == "h" (
SET /A "_t=%_t% / 360000"
) ELSE (
SET /A "_h=%_t% / 360000"
SET /A "_m=(%_t% - !_h! * 360000) / 6000"
SET /A "_s=(%_t% - !_h! * 360000 - !_m! * 6000) / 100"
SET /A "_cs=(%_t% - !_h! * 360000 - !_m! * 6000 - !_s! * 100)"
IF !_h! LSS 10 SET "_h=0!_h!"
IF !_m! LSS 10 SET "_m=0!_m!"
IF !_s! LSS 10 SET "_s=0!_s!"
IF !_cs! LSS 10 SET "_cs=0!_cs!"
SET "_t=!_h!:!_m!:!_s!.!_cs!"
SET "_t=!_t:00:=!"
)
)
)
)
EndLocal & SET %~1=%_t%
goto :EOF
A test with a delay of 94 sec
DEMO timer function
--------------------
Making some delay, please wait...
by Default : 9404
in Seconds : 94
Formatted : 01:34.05 (HH:MM:SS.CS)
Presione una tecla para continuar . . .
Mongo includes a mongoexport utility (see docs) which can dump a collection. This utility uses the native libmongoclient and is likely the fastest method.
mongoexport -d <database> -c <collection_name>
Also helpful:
-o
: write the output to file, otherwise standard output is used (docs)
--jsonArray
: generates a valid json document, instead of one json object per line (docs)
--pretty
: outputs formatted json (docs)
This is an ancient question, but why is everyone overlooking the simplest regexp-based solution? Normal regexp quantifiers are greedy, people! If you want to find the last instance of a pattern, just stick .*
in front of it. Here's how:
$text = "The quick brown fox, fox, fox, fox, jumps over etc.";
$fixed = preg_replace("((.*)fox)", "$1DUCK", $text);
print($fixed);
This will replace the last instance of "fox" to "DUCK", like it's supposed to, and print:
The quick brown fox, fox, fox, DUCK, jumps over etc.
It's not that different in bash
.
workdone=0
while : ; do
...
if [ "$workdone" -ne 0 ]; then
break
fi
done
:
is the no-op command; its exit status is always 0, so the loop runs until workdone
is given a non-zero value.
There are many ways you could set and test the value of workdone
in order to exit the loop; the one I show above should work in any POSIX-compatible shell.
Use dir
or type
on the 'string' to find out what it is. I suspect that it's one of BeautifulSoup's tag objects, that prints like a string, but really isn't one. Otherwise, its inside a list and you need to convert each string separately.
In any case, why are you objecting to using Unicode? Any specific reason?
Use git log --all <filename>
to view the commits influencing <filename>
in all branches.
There are multiple issues with the MMC however as on almost every PC in my business the ask scheduler API will not open and has somehow been corrupted. So you cannot edit, delete or otherwise modify tasks that were developed before the API decided not to run anymore. The only way we have found to fix that issue is to totally wipe away a persons profile under the C:\Users\ area and force the system to recreate the log in once the person logs back in. This seems to fix the API issue and it works again, however the tasks are often not visible anymore to that user since the tasks developed are specific to the user and not the machine in Windows 7. The other odd thing is that sometimes, although not with any frequency that can be analyzed, the tasks still run even though the API is corrupted and will not open. The cause of this issue is apparently not known but there are many "fixes" described on various websites, but the user profile deletion and adding anew seems to work every time for at least a little while. The tasks are saved as XML now in WIN 7, so if you do find them in the system32/tasks folder you can delete them, or copy them to a new drive and then import them back into task scheduler. We went with the system scheduler software from Splinterware though since we had the same corruption issue multiple times even with the fix that does not seem to be permanent.
You're declaring everything in the parent page. So the references to window
and document
are to the parent page's. If you want to do stuff to the iframe
's, use iframe || iframe.contentWindow
to access its window
, and iframe.contentDocument || iframe.contentWindow.document
to access its document
.
There's a word for what's happening, possibly "lexical scope": What is lexical scope?
The only context of a scope is this. And in your example, the owner of the method is doc
, which is the iframe
's document
. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.
This is how I would write it:
(function () {
var dom, win, doc, where, iframe;
iframe = document.createElement('iframe');
iframe.src = "javascript:false";
where = document.getElementsByTagName('script')[0];
where.parentNode.insertBefore(iframe, where);
win = iframe.contentWindow || iframe;
doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc._l = (function (w, d) {
return function () {
w.vanishing_global = new Date().getTime();
var js = d.createElement("script");
js.src = 'test-vanishing-global.js?' + w.vanishing_global;
w.name = "foobar";
d.foobar = "foobar:" + Math.random();
d.foobar = "barfoo:" + Math.random();
d.body.appendChild(js);
};
})(win, doc);
doc.write('<body onload="document._l();"></body>');
doc.close();
})();
The aliasing of win
and doc
as w
and d
aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe
's stuff. If you want to access the parent's, you still use window
and document
.
I'm not sure what the implications are of adding methods to a document
(doc
in this case), but it might make more sense to set the _l
method on win
. That way, things can be run without a prefix...such as <body onload="_l();"></body>
My solution: - XCode: 10.2.1 - Swift: 5
If unsure of compiled default for session.save_path
, look at the pertinent php.ini
.
Normally, this will show the commented out default value.
Ubuntu/Debian old/new php.ini
locations:
Older php5 with Apache: /etc/php5/apache2/php.ini
Older php5 with NGINX+FPM: /etc/php5/fpm/php.ini
Ubuntu 16+ with Apache: /etc/php/*/apache2/php.ini
*
Ubuntu 16+ with NGINX+FPM - /etc/php/*/fpm/php.ini
*
* /*/
= the current PHP version(s) installed on system.
To show the PHP version in use under Apache:
$ a2query -m | grep "php" | grep -Eo "[0-9]+\.[0-9]+"
7.3
Since PHP 7.3 is the version running for this example, you would use that for the php.ini
:
$ grep "session.save_path" /etc/php/7.3/apache2/php.ini
;session.save_path = "/var/lib/php/sessions"
Or, combined one-liner:
$ APACHEPHPVER=$(a2query -m | grep "php" | grep -Eo "[0-9]+\.[0-9]+") \ && grep ";session.save_path" /etc/php/${APACHEPHPVER}/apache2/php.ini
Result:
;session.save_path = "/var/lib/php/sessions"
Or, use PHP itself to grab the value using the "cli" environment (see NOTE below):
$ php -r 'echo session_save_path() . "\n";'
/var/lib/php/sessions
$
These will also work:
php -i | grep session.save_path
php -r 'echo phpinfo();' | grep session.save_path
NOTE:
The 'cli' (command line) version of php.ini
normally has the same default values as the Apache2/FPM versions (at least as far as the session.save_path
). You could also use a similar command to echo the web server's current PHP module settings to a webpage and use wget/curl to grab the info. There are many posts regarding phpinfo()
use in this regard. But, it is quicker to just use the PHP interface or grep
for it in the correct php.ini
to show it's default value.
EDIT: Per @aesede comment -> Added php -i
. Thanks
This error can be due to many many things.
The key here seems the hint about error reading
. I see you are working on a flash drive or something similar? Try to run the install on a local folder owned by your current user.
You could also try with sudo
, that might solve a permission problem if that's the case.
Another reason why it cannot read could be because it has not downloaded correctly, or saved correctly. A little problem in your network could have caused that, and the cache clean would remove the files and force a refetch but that does not solve your problem. That means it would be more on the save part, maybe it didn't save because of permissions, maybe it didn't not save correctly because it was lacking disk space...
For those looking for a command-line version, Microsoft released mssql-scripter
to do this:
$ pip install mssql-scripter
# Generate DDL scripts for all database objects and DML scripts (INSERT statements)
# for all tables in the Adventureworks database and save the script files in
# the current directory
$ mssql-scripter -S localhost -d AdventureWorks -U sa --schema-and-data \
-f './' --file-per-object
dbatools.io is a much more active project based on PowerShell, which provides the Get-DbaDbTable and Export-DbaDbTableData cmdlets to achieve this:
PS C:\> Get-DbaDbTable -SqlInstance sql2016 -Database MyDatabase \
-Table 'dbo.Table1', 'dbo.Table2' |
Export-DbaDbTableData -Path C:\temp\export.sql
This will give you the second row of each group (zero indexed, nth(0) is the same as first()):
df.groupby('id').nth(1)
Documentation: http://pandas.pydata.org/pandas-docs/stable/groupby.html#taking-the-nth-row-of-each-group
this seems to be working nicely for me
$(window).bind('resize', function() {
jQuery("#grid").setGridWidth($('#parentDiv').width()-30, true);
}).trigger('resize');
If you really want to cover the case that a script is called via execfile(...)
, you can use the inspect
module to deduce the filename (including the path). As far as I am aware, this will work for all cases you listed:
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
I met the same problem and for finding all validation errors and displaying them, I wrote next method:
getFormValidationErrors() {
Object.keys(this.productForm.controls).forEach(key => {
const controlErrors: ValidationErrors = this.productForm.get(key).errors;
if (controlErrors != null) {
Object.keys(controlErrors).forEach(keyError => {
console.log('Key control: ' + key + ', keyError: ' + keyError + ', err value: ', controlErrors[keyError]);
});
}
});
}
Form name productForm
should be changed to yours.
It works in next way: we get all our controls from form in format {[p: string]: AbstractControl}
and iterate by each error key, for get details of error. It skips null
error values.
It also can be changed for displaying validation errors on the template view, just replace console.log(..)
to what you need.
I just came across this as a really nice and elegant solution:
Math.random().toString(36).slice(2)
Notes on this implementation:
Math.random()
, the output may be predictable and therefore not necessarily unique.There is an operator just for this. For example, if I wanted to change a variable i by 3 then:
var someValue = 9;
var Increment = 3;
for(var i=0;i<someValue;i+=Increment){
//do whatever
}
_x000D_
var someValue = 3;
var Increment = 3;
for(var i=9;i>someValue;i+=Increment){
//do whatever
}
_x000D_
I'm using AS 3.2.1, and was about to try some of the plugins, but was hesitant realizing the plugins are able to monitor any data..
It's actually really simple doing it via the Terminal tab in AS:
adb tcpip 5555
adb connect 192.168.1.101
If you are using SQL Server try Linked Server
Instead of using this in your current class setClassRoomName("aClassName");
you have to use classroom.setClassRoomName("aClassName");
You have to add the class' and at a point like
yourClassNameWhereTheMethodIs.theMethodsName();
I know it's a really late answer but if someone starts learning Java and randomly sees this post he knows what to do.
urllib2.urlopen does an HTTP GET (or POST if you supply a data argument), not an HTTP HEAD (if it did the latter, you couldn't do readlines or other accesses to the page body, of course).
A micro library I wrote: https://github.com/pathikrit/better-files
file.appendLine("Hello", "World")
or
file << "Hello" << "\n" << "World"
One problem is that a ternary relational construct would introduce serious parser problems:
<expr> ::= <expr> <rel-op> <expr> |
... |
<expr> <rel-op> <expr> <rel-op> <expr>
When you try to express a grammar with those productions using a typical PGS, you'll find that there is a shift-reduce conflict at the point of the first <rel-op>
. The parse needs to lookahead an arbitrary number of symbols to see if there is a second <rel-op>
before it can decide whether the binary or ternary form has been used. In this case, you could not simply ignore the conflict because that would result in incorrect parses.
I'm not saying that this grammar is fatally ambiguous. But I think you'd need a backtracking parser to deal with it correctly. And that is a serious problem for a programming language where fast compilation is a major selling point.
Here is another approach, up to the OP to choose which one he prefers.
When including the code below in the __init__
.py file before any other code, messages printed with print
and any errors will no longer be logged to Ableton's Log.txt but to separate files on your disk:
import sys
path = "/Users/#username#"
errorLog = open(path + "/stderr.txt", "w", 1)
errorLog.write("---Starting Error Log---\n")
sys.stderr = errorLog
stdoutLog = open(path + "/stdout.txt", "w", 1)
stdoutLog.write("---Starting Standard Out Log---\n")
sys.stdout = stdoutLog
(for Mac, change #username#
to the name of your user folder. On Windows the path to your user folder will have a different format)
When you open the files in a text editor that refreshes its content when the file on disk is changed (example for Mac: TextEdit does not but TextWrangler does), you will see the logs being updated in real-time.
Credits: this code was copied mostly from the liveAPI control surface scripts by Nathan Ramella
Here is an example. (I am using CompareToBuilder
class from Apache for convenience, although this can be done without using it.)
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang.builder.CompareToBuilder;
public class Tester {
boolean ascending = true;
public static void main(String args[]) {
Tester tester = new Tester();
tester.printValues();
}
public void printValues() {
List<HashMap<String, Object>> list =
new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map =
new HashMap<String, Object>();
map.put( "actionId", new Integer(1234) );
map.put( "eventId", new Integer(21) );
map.put( "fromDate", getDate(1) );
map.put( "toDate", getDate(7) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(456) );
map.put( "eventId", new Integer(11) );
map.put( "fromDate", getDate(1) );
map.put( "toDate", getDate(1) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(1234) );
map.put( "eventId", new Integer(20) );
map.put( "fromDate", getDate(4) );
map.put( "toDate", getDate(16) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(1234) );
map.put( "eventId", new Integer(22) );
map.put( "fromDate", getDate(8) );
map.put( "toDate", getDate(11) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(1234) );
map.put( "eventId", new Integer(11) );
map.put( "fromDate", getDate(1) );
map.put( "toDate", getDate(10) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(1234) );
map.put( "eventId", new Integer(11) );
map.put( "fromDate", getDate(4) );
map.put( "toDate", getDate(15) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(567) );
map.put( "eventId", new Integer(12) );
map.put( "fromDate", getDate(-1) );
map.put( "toDate", getDate(1) );
list.add(map);
System.out.println("\n Before Sorting \n ");
for( int j = 0; j < list.size(); j++ )
System.out.println(list.get(j));
Collections.sort( list, new HashMapComparator2() );
System.out.println("\n After Sorting \n ");
for( int j = 0; j < list.size(); j++ )
System.out.println(list.get(j));
}
public static Date getDate(int days) {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DATE, days);
return cal.getTime();
}
public class HashMapComparator2 implements Comparator {
public int compare(Object object1, Object object2) {
if( ascending ) {
return new CompareToBuilder()
.append(
((HashMap)object1).get("actionId"),
((HashMap)object2).get("actionId")
)
.append(
((HashMap)object2).get("eventId"),
((HashMap)object1).get("eventId")
)
.toComparison();
} else {
return new CompareToBuilder()
.append(
((HashMap)object2).get("actionId"),
((HashMap)object1).get("actionId")
)
.append(
((HashMap)object2).get("eventId"),
((HashMap)object1).get("eventId")
)
.toComparison();
}
}
}
}
If you have a specific code that you are working on and are having issues, you can post your pseudo code and we can try to help you out!
If you happens to change the columns and stumbled on
'Doctrine\DBAL\Driver\PDOMySql\Driver' not found
then just install
composer require doctrine/dbal
You can also do this with hooks.
function MyComponent (props) {
const [isActive, setActive] = useState(false);
const toggleClass = () => {
setActive(!isActive);
};
return (
<div
className={isActive ? 'your_className': null}
onClick={toggleClass}
>
<p>{props.text}</p>
</div>
);
}
There are two ways of looking at github content, the "raw" way and the "Web page" way.
raw.githubusercontent.com
returns the raw content of files stored in github, so they can be downloaded simply to your computer. For example, if the page represents a ruby install script, then you will get a ruby install script that your ruby installation will understand.
If you instead download the file using the github.com link, you will actually be downloading a web page with buttons and comments and which displays your wanted script in the middle -- it's what you want to give to your web browser to get a nice page to look at, but for the computer, it is not a script that can be executed or code that can be compiled, but a web page to be displayed. That web page has a button called Raw that sends you to the corresponding content on raw.githubusercontent.com
.
To see the content of raw.githubusercontent.com/${repo}/${branch}/${path}
in the usual github interface:
raw.githubusercontent.com
with plain github.com
In this case, the branch name is "master" (which is a very common branch name), so you replace /master/
with /blob/master/
, and so
https://raw.githubusercontent.com/Homebrew/install/master/install
becomes
https://github.com/Homebrew/install/blob/master/install
This is the reverse of finding a file on Github and clicking the Raw link.
Ignoring the specific needs of this question, and while its never a good idea to cast a string to a bool, one way would be to use the ToBoolean() method on the Convert class:
bool val = Convert.ToBoolean("true");
or an extension method to do whatever weird mapping you're doing:
public static class StringExtensions
{
public static bool ToBoolean(this string value)
{
switch (value.ToLower())
{
case "true":
return true;
case "t":
return true;
case "1":
return true;
case "0":
return false;
case "false":
return false;
case "f":
return false;
default:
throw new InvalidCastException("You can't cast that value to a bool!");
}
}
}
I had a console application where I also had done a "Publish" to create an Install disk.
I was getting the same error at the OP:
The solution was right click
setup.exe
and clickRun as Administrator
This enabled the install process the necessary privilege's.
Using Linq to xml
Add a reference to System.Xml.Linq
and use
XDocument.Parse(string xmlString)
Edit: Sample follows, xml data (TestConfig.xml)..
<?xml version="1.0"?>
<Tests>
<Test TestId="0001" TestType="CMD">
<Name>Convert number to string</Name>
<CommandLine>Examp1.EXE</CommandLine>
<Input>1</Input>
<Output>One</Output>
</Test>
<Test TestId="0002" TestType="CMD">
<Name>Find succeeding characters</Name>
<CommandLine>Examp2.EXE</CommandLine>
<Input>abc</Input>
<Output>def</Output>
</Test>
<Test TestId="0003" TestType="GUI">
<Name>Convert multiple numbers to strings</Name>
<CommandLine>Examp2.EXE /Verbose</CommandLine>
<Input>123</Input>
<Output>One Two Three</Output>
</Test>
<Test TestId="0004" TestType="GUI">
<Name>Find correlated key</Name>
<CommandLine>Examp3.EXE</CommandLine>
<Input>a1</Input>
<Output>b1</Output>
</Test>
<Test TestId="0005" TestType="GUI">
<Name>Count characters</Name>
<CommandLine>FinalExamp.EXE</CommandLine>
<Input>This is a test</Input>
<Output>14</Output>
</Test>
<Test TestId="0006" TestType="GUI">
<Name>Another Test</Name>
<CommandLine>Examp2.EXE</CommandLine>
<Input>Test Input</Input>
<Output>10</Output>
</Test>
</Tests>
C# usage...
XElement root = XElement.Load("TestConfig.xml");
IEnumerable<XElement> tests =
from el in root.Elements("Test")
where (string)el.Element("CommandLine") == "Examp2.EXE"
select el;
foreach (XElement el in tests)
Console.WriteLine((string)el.Attribute("TestId"));
This code produces the following output: 0002 0006
if someone needs to view arrays so cool ;) use this method.. this will print to your browser console
function console($obj)
{
$js = json_encode($obj);
print_r('<script>console.log('.$js.')</script>');
}
you can use like this..
console($myObject);
Output will be like this.. so cool eh !!
Short answer: Both are needed.
I feel like the right answer was given but minimally. Yeah generally unset() is best for "speed", but if you want to reclaim memory immediately (at the cost of CPU) should want to use null.
Like others mentioned, setting to null doesn't mean everything is reclaimed, you can have shared memory (uncloned) objects that will prevent destruction of the object. Moreover, like others have said, you can't "destroy" the objects explicitly anyway so you shouldn't try to do it anyway.
You will need to figure out which is best for you. Also you can use __destruct() for an object which will be called on unset or null but it should be used carefully and like others said, never be called directly!
see:
http://www.stoimen.com/blog/2011/11/14/php-dont-call-the-destructor-explicitly/
var isProduction = (process.argv.indexOf("production")>-1);
CLI gulp production
calls my production task and sets a flag for any conditionals.
Include the port number with the IP address.
For example:
http://19.18.20.101:5566
where 5566 is the port number.
I have been using readlink -f works on linux
so
FULL_PATH=$(readlink -f filename)
DIR=$(dirname $FULL_PATH)
PWD=$(pwd)
cd $DIR
#<do more work>
cd $PWD
Prevent Default
Calling preventDefault() during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur. You can use Event.
return false
return false inside a callback prevents the default behaviour. For example, in a submit event, it doesn't submit the form. return false also stops bubbling, so the parents of the element won't know the event occurred. return false is equivalent to event.preventDefault() + event.stopPropagation()
On declaration you can do the following.
float[] values = {0.1f, 0.2f, 0.3f};
When the field is already defined, try this.
values = new float[] {0.1f, 0.2f, 0.3f};
Be aware that also the second version creates a new array.
If values
was the only reference to an already existing field, it becomes eligible for garbage collection.
Use the STL find function.
Keep in mind that there is also a find_if function, which you can use if your search is more complex, i.e. if you're not just looking for an element, but, for example, want see if there is an element that fulfills a certain condition, for example, a string that starts with "abc". (find_if
would give you an iterator that points to the first such element).
The decompiler of IntelliJ IDEA was not built with this kind of usage in mind. It is only meant to help programmers peek at the bytecode of the java classes that they are developing. For decompiling lots of class files of which you do not have source code, you will need some other java decompiler, which is specialized for this job, and most likely runs standalone. If you google you should find a bunch.
Try below code
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners
android:bottomLeftRadius="30dp"
android:bottomRightRadius="30dp"
android:topLeftRadius="30dp"
android:topRightRadius="30dp" />
<solid android:color="#1271BB" />
<stroke
android:width="5dp"
android:color="#1271BB" />
<padding
android:bottom="1dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" /></shape>
This will do it recursively for you:
find /path/to/base/dir/* -type d -ctime +10 -exec rm -rf {} \;
Explanation:
find
: the unix command for finding files / directories / links etc./path/to/base/dir
: the directory to start your search in.-type d
: only find directories-ctime +10
: only consider the ones with modification time older than 10 days-exec ... \;
: for each such result found, do the following command in ...
rm -rf {}
: recursively force remove the directory; the {}
part is where the find result gets substituted into from the previous part.Alternatively, use:
find /path/to/base/dir/* -type d -ctime +10 | xargs rm -rf
Which is a bit more efficient, because it amounts to:
rm -rf dir1 dir2 dir3 ...
as opposed to:
rm -rf dir1; rm -rf dir2; rm -rf dir3; ...
as in the -exec
method.
With modern versions of find
, you can replace the ;
with +
and it will do the equivalent of the xargs
call for you, passing as many files as will fit on each exec system call:
find . -type d -ctime +10 -exec rm -rf {} +
In my case, I forgot to set the value of the variable in the "CURRENT VALUE" field.
I thought I answer this question even though the answer is partly mentioned in both Adam Schmideg's and Alex Martelli's answers. In order for others like me that have the same question, to find the answer easily.
conn = sqlite3.connect(":memory:")
#This is the important part, here we are setting row_factory property of
#connection object to sqlite3.Row(sqlite3.Row is an implementation of
#row_factory)
conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute('select * from stocks')
result = c.fetchall()
#returns a list of dictionaries, each item in list(each dictionary)
#represents a row of the table
If you had your array like this: #!/bin/bash
Unix[0]='Debian'
Unix[1]="Red Hat"
Unix[2]='Ubuntu'
Unix[3]='Suse'
for i in $(echo ${Unix[@]});
do echo $i;
done
You would get:
Debian
Red
Hat
Ubuntu
Suse
I don't know why but the loop breaks down the spaces and puts them as an individual item, even you surround it with quotes.
To get around this, instead of calling the elements in the array, you call the indexes, which takes the full string thats wrapped in quotes. It must be wrapped in quotes!
#!/bin/bash
Unix[0]='Debian'
Unix[1]='Red Hat'
Unix[2]='Ubuntu'
Unix[3]='Suse'
for i in $(echo ${!Unix[@]});
do echo ${Unix[$i]};
done
Then you'll get:
Debian
Red Hat
Ubuntu
Suse
In support of unwind, remember that Objective-C is a superset of C, rather than a completely new language.
Anything you can do in regular old ANSI C can be done in Objective-C.
A more generic approach
To simplify this approach an "id" interface is used
public interface IGuidKey
{
Guid Id { get; set; }
}
The helper method
public static void Modify<T>(this DbSet<T> set, Guid id, Action<T> func)
where T : class, IGuidKey, new()
{
var target = new T
{
Id = id
};
var entry = set.Attach(target);
func(target);
foreach (var property in entry.Properties)
{
var original = property.OriginalValue;
var current = property.CurrentValue;
if (ReferenceEquals(original, current))
{
continue;
}
if (original == null)
{
property.IsModified = true;
continue;
}
var propertyIsModified = !original.Equals(current);
property.IsModified = propertyIsModified;
}
}
Usage
dbContext.Operations.Modify(id, x => { x.Title = "aaa"; });
Are you trying to find some work around getting xpath in IE?
There are many add-ons for other browsers like xpather for Chrome or xpather, xpath-checker and firebug for FireFox that will give you the xpath of an element in a second. But sadly there is no add-on or tool available that will do this for IE. For most cases you can get the xpath of the elements that fall in your script using the above tools in Firefox and tweak them a little (if required) to make them work in IE.
But if you are testing an application that will work only in IE or the specific scenario or page that has this element will open-up/play-out only in IE then you cannot use any of the above mention tools to find the XPATH. Well the only thing that works in this case is the Bookmarklets that were coded just for this purpose. Bookmarklets are JavaScript code that you will add in IE as bookmarks and later use to get the XPATH of the element you desire. Using these you can get the XPATH as easily as you get using xpather or any other firefox addon.
STEPS TO INSTALL BOOKMARKLETS
1)Open IE
2)Type about:blank in the address bar and hit enter
3)From Favorites main menu select ---> Add favorites
4) In the Add a favorite popup window enter name GetXPATH1.
5)Click add button in the add a favorite popup window.
6)Open the Favorites menu and right click the newly added favorite and select properties option.
7)GetXPATH1 Properties will open up. Select the web Document Tab.
8)Enter the following in the URL field.
javascript:function getNode(node){var nodeExpr=node.tagName;if(!nodeExpr)return null;if(node.id!=''){nodeExpr+="[@id='"+node.id+"']";return "/"+nodeExpr;}var rank=1;var ps=node.previousSibling;while(ps){if(ps.tagName==node.tagName){rank++;}ps=ps.previousSibling;}if(rank>1){nodeExpr+='['+rank+']';}else{var ns=node.nextSibling;while(ns){if(ns.tagName==node.tagName){nodeExpr+='[1]';break;}ns=ns.nextSibling;}}return nodeExpr;}
9)Click Ok. Click YES on the popup alert.
10)Add another favorite by following steps 3 to 5, Name this favorite GetXPATH2 (step4)
11)Repeat steps 6 and 7 for GetXPATH2 that you just created.
12)Enter the following in the URL field for GetXPATH2
javascript:function o__o(){var currentNode=document.selection.createRange().parentElement();var path=[];while(currentNode){var pe=getNode(currentNode);if(pe){path.push(pe);if(pe.indexOf('@id')!=-1)break;}currentNode=currentNode.parentNode;}var xpath="/"+path.reverse().join('/');clipboardData.setData("Text", xpath);}o__o();
13)Repeat Step 9.
You are all done!!
Now to get the XPATH of elements just select the element with your mouse. This would involve clicking the left mouse button just before the element (link, button, image, checkbox, text etc) begins and dragging it till the element ends. Once you do this first select the favorite GetXPATH1 from the favorites menu and then select the second favorite GetXPATH2. At this point you will get a confirmation, hit allow access button. Now open up a notepad file, right click and select paste option. This will give you the XPATH of the element you seek.
In your string I see: 15.5859949000000662452.23862099999999
which is not a double (it has two decimal points). Perhaps it's just a legitimate input error?
You may also want to figure out if your last String
will be empty, and account for that situation.
import urllib.request
bank_pdf_list = ["https://www.hdfcbank.com/content/bbp/repositories/723fb80a-2dde-42a3-9793-7ae1be57c87f/?path=/Personal/Home/content/rates.pdf",
"https://www.yesbank.in/pdf/forexcardratesenglish_pdf",
"https://www.sbi.co.in/documents/16012/1400784/FOREX_CARD_RATES.pdf"]
def get_pdf(url):
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
#url = "https://www.yesbank.in/pdf/forexcardratesenglish_pdf"
headers={'User-Agent':user_agent,}
request=urllib.request.Request(url,None,headers) #The assembled request
response = urllib.request.urlopen(request)
#print(response.text)
data = response.read()
# print(type(data))
name = url.split("www.")[-1].split("//")[-1].split(".")[0]+"_FOREX_CARD_RATES.pdf"
f = open(name, 'wb')
f.write(data)
f.close()
for bank_url in bank_pdf_list:
try:
get_pdf(bank_url)
except:
pass
Suppose you have a List Collection containing many items to show in a ListView, take the following example that iterates through the List Collection:
foreach (Inspection inspection in anInspector.getInspections())
{
ListViewItem item = new ListViewItem();
item.Text=anInspector.getInspectorName().ToString();
item.SubItems.Add(inspection.getInspectionDate().ToShortDateString());
item.SubItems.Add(inspection.getHouse().getAddress().ToString());
item.SubItems.Add(inspection.getHouse().getValue().ToString("C"));
listView1.Items.Add(item);
}
That code produces the following output in the ListView (of course depending how many items you have in the List Collection):
Basically the first column is a listviewitem containing many subitems (other columns). It may seem strange but listview is very flexible, you could even build a windows-like file explorer with it!
In my case I was using a custom extension for my PHP files and I had to edit /etc/apache2/conf-available/php7.2-fpm.conf
and add the following code:
<FilesMatch ".+\.YOUR_CUSTOM_EXTENSION$">
SetHandler "proxy:unix:/run/php/php7.2-fpm.sock|fcgi://localhost"
</FilesMatch>
you should try this
g++-4.4 -std=c++0x or g++-4.7 -std=c++0x
Here are a couple dplyr
options:
library(dplyr)
# all columns:
df %>%
mutate_all(~na_if(., ''))
# specific column types:
df %>%
mutate_if(is.factor, ~na_if(., ''))
# specific columns:
df %>%
mutate_at(vars(A, B), ~na_if(., ''))
# or:
df %>%
mutate(A = replace(A, A == '', NA))
# replace can be used if you want something other than NA:
df %>%
mutate(A = as.character(A)) %>%
mutate(A = replace(A, A == '', 'used to be empty'))
Your problem is basically that you never specified the right path to the file.
Try instead, from your main script:
from folder.file import Klasa
Or, with from folder import file
:
from folder import file
k = file.Klasa()
Or again:
import folder.file as myModule
k = myModule.Klasa()
For starters:
<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.
This would be the optimal solution:
<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Try this webconfg.. replace "NewsApi.dll" with your main dll!
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\NewsApi.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
</system.webServer>
</location>
</configuration>
The main purpose of a list comprehension is to create a new list based on another one without changing or destroying the original list.
Instead of writing
l = []
for n in range(1, 11):
l.append(n)
or
l = [n for n in range(1, 11)]
you should write only
l = range(1, 11)
In the two top code blocks you're creating a new list, iterating through it and just returning each element. It's just an expensive way of creating a list copy.
To get a new dictionary with all keys set to the same value based on another dict, do this:
old_dict = {'a': 1, 'c': 3, 'b': 2}
new_dict = { key:'your value here' for key in old_dict.keys()}
You're receiving a SyntaxError because when you write
d = {}
d[i for i in range(1, 11)] = True
you're basically saying: "Set my key 'i for i in range(1, 11)' to True" and "i for i in range(1, 11)" is not a valid key, it's just a syntax error. If dicts supported lists as keys, you would do something like
d[[i for i in range(1, 11)]] = True
and not
d[i for i in range(1, 11)] = True
but lists are not hashable, so you can't use them as dict keys.
String test = "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);
I also have the situation that I have a set of documents to be crawled. I start with an initial "seed" document which should be processed, that document contains links to other documents which should also be processed, and so on.
In my main program, I just want to write something like the following, where Crawler
controls a bunch of threads.
Crawler c = new Crawler();
c.schedule(seedDocument);
c.waitUntilCompletion()
The same situation would happen if I wanted to navigate a tree; i would pop in the root node, the processor for each node would add children to the queue as necessary, and a bunch of threads would process all the nodes in the tree, until there were no more.
I couldn't find anything in the JVM which I thought was a bit surprising. So I wrote a class ThreadPool
which one can either use directly or subclass to add methods suitable for the domain, e.g. schedule(Document)
. Hope it helps!