In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198
For truncate:
var intvalue = Math.floor(value);
For round:
var intvalue = Math.round(value);
textView.setTypeface(null, Typeface.BOLD_ITALIC);
textView.setTypeface(null, Typeface.BOLD);
textView.setTypeface(null, Typeface.ITALIC);
textView.setTypeface(null, Typeface.NORMAL);
To keep the previous typeface
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC)
To Start Tomcat7 Service :
Open cmd, go to bin directory within "Apache Tomcat 7" folder. You will see some this like C:\..\bin>
Enter above command to start the service: C:\..\bin>service.bat install
. The service will get started now.
Enter above command to start tomcat7w monitory service. If you have issue with starting the tomcat7 service then remove the service with command : C:\..\bin>tomcat7 //DS//Tomcat7
Now the service will no longer exist. Try the install command again, now the service will get installed and started: C:\..\bin>tomcat7w \\MS\tomcat7w
You will see the tomcat 7 icon in the system tray. Now, the tomcat7 service and tomcat7w will start automatically when the windows get start.
Try this to get type parameters for generic types:
public static string CSharpName(this Type type)
{
var sb = new StringBuilder();
var name = type.Name;
if (!type.IsGenericType) return name;
sb.Append(name.Substring(0, name.IndexOf('`')));
sb.Append("<");
sb.Append(string.Join(", ", type.GetGenericArguments()
.Select(t => t.CSharpName())));
sb.Append(">");
return sb.ToString();
}
Maybe not the best solution (due to the recursion), but it works. Outputs look like:
Dictionary<String, Object>
If you wish to go to the login page of phpmyadmin, click the "exit" button (the second one from left to right under the main logo "phpmyadmin").
The question didn't clarify what type of session store was being used. Both answers seem to be correct.
For cookie based sessions:
From http://expressjs.com/api.html#cookieSession
req.session = null // Deletes the cookie.
For Redis, etc based sessions:
req.session.destroy // Deletes the session in the database.
If you can change the format of your placeholder, you could use String.format()
. If not, you could also replace it as pre-processing.
String.format("hello %s!", "world");
More information in this other thread.
I hit this error. After some frustration I tried Xcode clean and everything started working again. Just leaving this here for future reference.
Select the text you want capitalized
Open View->Command Palette (or Shift+Command+P)
Start typing "Transform to uppercase" and select that option
Voila!
MongoDB needs data directory to store data.
Default path is /data/db
When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx
permission to user.
If you want to change the path of your data directory then you should specify it while starting mongod server like,
mongod --dbpath /data/<path> --port <port no>
This should help you start your mongod server with custom path and port.
Try this one:
jQuery(".usercontent").hover(function() {
jQuery(this).animate({backgroundColor:"pink"}, "slow");
},function(){
jQuery(this).animate({backgroundColor:"white"}, "slow");
});
Revised way with effects:
jQuery(".usercontent").hover(function() {
jQuery(this).fadeout("slow",function(){
jQuery(this).animate({"color","yellow"}, "slow");
});
});
The foreign keys are there to ensure data integrity, so you can't drop a column as long as it's part of a foreign key. You need to drop the key first.
I would think the following query would do it:
ALTER TABLE assignmentStuff DROP FOREIGN KEY assignmentIDX;
I would personally recommend that you use os.path.isdir()
to test instead of os.path.exists()
.
>>> os.path.exists('/tmp/dirname')
True
>>> os.path.exists('/tmp/dirname/filename.etc')
True
>>> os.path.isdir('/tmp/dirname/filename.etc')
False
>>> os.path.isdir('/tmp/fakedirname')
False
If you have:
>>> dir = raw_input(":: ")
And a foolish user input:
:: /tmp/dirname/filename.etc
... You're going to end up with a directory named filename.etc
when you pass that argument to os.makedirs()
if you test with os.path.exists()
.
Hashing algorithms such as sha1 and md5 are not suitable for password storing. They are designed to be very efficient. This means that brute forcing is very fast. Even if a hacker obtains a copy of your hashed passwords, it is pretty fast to brute force it. If you use a salt, it makes rainbow tables less effective, but does nothing against brute force. Using a slower algorithm makes brute force ineffective. For instance, the bcrypt algorithm can be made as slow as you wish (just change the work factor), and it uses salts internally to protect against rainbow tables. I would go with such an approach or similar (e.g. scrypt or PBKDF2) if I were you.
Make the value a list, e.g.
a["abc"] = [1, 2, "bob"]
UPDATE:
There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.
key = "somekey"
a.setdefault(key, [])
a[key].append(1)
Results:
>>> a
{'somekey': [1]}
Next, try:
key = "somekey"
a.setdefault(key, [])
a[key].append(2)
Results:
>>> a
{'somekey': [1, 2]}
The magic of setdefault
is that it initializes the value for that key if that key is not defined, otherwise it does nothing. Now, noting that setdefault
returns the key you can combine these into a single line:
a.setdefault("somekey",[]).append("bob")
Results:
>>> a
{'somekey': [1, 2, 'bob']}
You should look at the dict
methods, in particular the get()
method, and do some experiments to get comfortable with this.
After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:
10
but you want it to return a String and not a Fixnum, write '10'
or "10"
.:
, {
, }
, [
, ]
, ,
, &
, *
, #
, ?
, |
, -
, <
, >
, =
, !
, %
, @
, \
).'\n'
would be returned as the string \n
."\n"
would be returned as a line feed character.!ruby/sym
to return a Ruby symbol.Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.
Update
"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:
en:
yesno:
'yes': 'Yes'
'no': 'No'
I would like to add that there is a Parallel class with ForEach function built in that can be used for this purpose.
[[ There are some good answers here but I find that they still are lacking a bit of information. ]]
return (new StringBuilder("select id1, " + " id2 " + " from " + " table"))
.toString();
So as you point out, the example you give is a simplistic but let's analyze it anyway. What happens here is the compiler actually does the +
work here because "select id1, " + " id2 " + " from " + " table"
are all constants. So this turns into:
return new StringBuilder("select id1, id2 from table").toString();
In this case, obviously, there is no point in using StringBuilder
. You might as well do:
// the compiler combines these constant strings
return "select id1, " + " id2 " + " from " + " table";
However, even if you were appending any fields or other non-constants then the compiler would use an internal StringBuilder
-- there's no need for you to define one:
// an internal StringBuilder is used here
return "select id1, " + fieldName + " from " + tableName;
Under the covers, this turns into code that is approximately equivalent to:
StringBuilder sb = new StringBuilder("select id1, ");
sb.append(fieldName).append(" from ").append(tableName);
return sb.toString();
Really the only time you need to use StringBuilder
directly is when you have conditional code. For example, code that looks like the following is desperate for a StringBuilder
:
// 1 StringBuilder used in this line
String query = "select id1, " + fieldName + " from " + tableName;
if (where != null) {
// another StringBuilder used here
query += ' ' + where;
}
The +
in the first line uses one StringBuilder
instance. Then the +=
uses another StringBuilder
instance. It is more efficient to do:
// choose a good starting size to lower chances of reallocation
StringBuilder sb = new StringBuilder(64);
sb.append("select id1, ").append(fieldName).append(" from ").append(tableName);
// conditional code
if (where != null) {
sb.append(' ').append(where);
}
return sb.toString();
Another time that I use a StringBuilder
is when I'm building a string from a number of method calls. Then I can create methods that take a StringBuilder
argument:
private void addWhere(StringBuilder sb) {
if (where != null) {
sb.append(' ').append(where);
}
}
When you are using a StringBuilder
, you should watch for any usage of +
at the same time:
sb.append("select " + fieldName);
That +
will cause another internal StringBuilder
to be created. This should of course be:
sb.append("select ").append(fieldName);
Lastly, as @T.J.rowder points out, you should always make a guess at the size of the StringBuilder
. This will save on the number of char[]
objects created when growing the size of the internal buffer.
This also works....sometimes you may want to construct the definition of the parameters outside of the actual EXEC call.
DECLARE @Parmdef nvarchar (500)
DECLARE @SQL nvarchar (max)
DECLARE @xTxt1 nvarchar (100) = 'test1'
DECLARE @xTxt2 nvarchar (500) = 'test2'
SET @parmdef = '@text1 nvarchar (100), @text2 nvarchar (500)'
SET @SQL = 'PRINT @text1 + '' '' + @text2'
EXEC sp_executeSQL @SQL, @Parmdef, @xTxt1, @xTxt2
The first attempt was pretty close. This variation should work:
echo "hello world" | { test=$(< /dev/stdin); echo "test=$test"; };
and the output is:
test=hello world
You need braces after the pipe to enclose the assignment to test and the echo.
Without the braces, the assignment to test (after the pipe) is in one shell, and the echo "test=$test" is in a separate shell which doesn't know about that assignment. That's why you were getting "test=" in the output instead of "test=hello world".
It looks like you want:
public static string GetRandomBits()
Without static
, you would need an object before you can call the GetRandomBits()
method. However, since the implementation of GetRandomBits()
does not depend on the state of any Program
object, it's best to declare it static
.
If you are already using ExtJS in your project you could use Ext.Date:
var date = new Date();
Ext.Date.format(date, "d-M-Y");
returns:
"11-Nov-2015"
I saw in at least one other place that people don't realize Date-Time
takes in times as well, so I figured I'd share it here since it's really short to do so:
Get-Date # Following the OP's example, let's say it's Friday, March 12, 2010 9:00:00 AM
(Get-Date '22:00').AddDays(-1) # Thursday, March 11, 2010 10:00:00 PM
It's also the shortest way to strip time information and still use other parameters of Get-Date
. For instance you can get seconds since 1970 this way (Unix timestamp):
Get-Date '0:00' -u '%s' # 1268352000
Or you can get an ISO 8601 timestamp:
Get-Date '0:00' -f 's' # 2010-03-12T00:00:00
Then again if you reverse the operands, it gives you a little more freedom with formatting with any date object:
'The sortable timestamp: {0:s}Z{1}Vs measly human format: {0:D}' -f (Get-Date '0:00'), "`r`n"
# The sortable timestamp: 2010-03-12T00:00:00Z
# Vs measly human format: Friday, March 12, 2010
However if you wanted to both format a Unix timestamp (via -u
aka -UFormat
), you'll need to do it separately. Here's an example of that:
'ISO 8601: {0:s}Z{1}Unix: {2}' -f (Get-Date '0:00'), "`r`n", (Get-Date '0:00' -u '%s')
# ISO 8601: 2010-03-12T00:00:00Z
# Unix: 1268352000
Hope this helps!
You don't need to escape the '
character in a String (wrapped in "
), and you don't have to escape a "
character in a char (wrapped in '
).
User.hasMany(Post, {foreignKey: 'user_id'})
Post.belongsTo(User, {foreignKey: 'user_id'})
Post.find({ where: { ...}, include: [User]})
Which will give you
SELECT
`posts`.*,
`users`.`username` AS `users.username`, `users`.`email` AS `users.email`,
`users`.`password` AS `users.password`, `users`.`sex` AS `users.sex`,
`users`.`day_birth` AS `users.day_birth`,
`users`.`month_birth` AS `users.month_birth`,
`users`.`year_birth` AS `users.year_birth`, `users`.`id` AS `users.id`,
`users`.`createdAt` AS `users.createdAt`,
`users`.`updatedAt` AS `users.updatedAt`
FROM `posts`
LEFT OUTER JOIN `users` AS `users` ON `users`.`id` = `posts`.`user_id`;
The query above might look a bit complicated compared to what you posted, but what it does is basically just aliasing all columns of the users table to make sure they are placed into the correct model when returned and not mixed up with the posts model
Other than that you'll notice that it does a JOIN instead of selecting from two tables, but the result should be the same
Further reading:
Your alternatives are to override the toString()
method of your object to output its contents in a way that you like, or to use reflection to inspect the object (in a way similar to what debuggers do).
The advantage of using reflection is that you won't need to modify your individual objects to be "analysable", but there is added complexity and if you need nested object support you'll have to write that.
This code will list the fields and their values for an Object
"o"
Field[] fields = o.getClass().getDeclaredFields();
for (int i=0; i<fields.length; i++)
{
System.out.println(fields[i].getName() + " - " + fields[i].get(o));
}
Thanks to @user2630576 and @Ed.S.
the following worked a treat:
BACKUP LOG [database] TO DISK = 'D:\database.bak'
GO
ALTER DATABASE [database] SET RECOVERY SIMPLE
use [database]
declare @log_File_Name varchar(200)
select @log_File_Name = name from sysfiles where filename like '%LDF'
declare @i int = FILE_IDEX ( @log_File_Name)
dbcc shrinkfile ( @i , 50)
ALTER DATABASE [database] SET RECOVERY FULL
The "IN" clause is built into linq via the .Contains() method.
For example, to get all People whose .States's are "NY" or "FL":
using (DataContext dc = new DataContext("connectionstring"))
{
List<string> states = new List<string>(){"NY", "FL"};
List<Person> list = (from p in dc.GetTable<Person>() where states.Contains(p.State) select p).ToList();
}
Set width and height of the outer container
div. Then use below styling on img:
.container img{
width:100%;
height:auto;
max-height:100%;
}
This will help you to keep an aspect ratio of your img
The &
means that the function accepts the address (or reference) to a variable, instead of the value of the variable.
For example, note the difference between this:
void af(int& g)
{
g++;
cout<<g;
}
int main()
{
int g = 123;
cout << g;
af(g);
cout << g;
return 0;
}
And this (without the &
):
void af(int g)
{
g++;
cout<<g;
}
int main()
{
int g = 123;
cout << g;
af(g);
cout << g;
return 0;
}
find /PATH/TO/YOUR/FILES -name NAME.EXT -exec cp -rfp {} /DST_DIR \;
I guess the easiest and most basic way is this
import math
number = int (input ('Enter number: '))
if number % 2 == 0 and number != 0:
print ('Even number')
elif number == 0:
print ('Zero is neither even, nor odd.')
else:
print ('Odd number')
Just basic conditions and math. It also minds zero, which is neither even, nor odd and you give any number you want by input so it's very variable.
If I get you right, you need ..\..\src
Change:
CONVERT(varchar(3), DATEPART(MONTH, S0.OrderDateTime) AS OrderMonth
To:
CONVERT(varchar(3), DATENAME(MONTH, S0.OrderDateTime)) AS OrderMonth
android developers documentation says : "Updated the AppCompatActivity as the base class for activities that use the support library action bar features. This class replaces the deprecated ActionBarActivity."
checkout changes for Android Support Library, revision 22.1.0 (April 2015)
Use utf8_encode()
Man page can be found here http://php.net/manual/en/function.utf8-encode.php
Also read this article from Joel on Software. It provides an excellent explanation if what Unicode is and how it works. http://www.joelonsoftware.com/articles/Unicode.html
As an alternative, there's a nice 3rd party library designed just for this use case. Whereby you need to generate headers based on the data being stored in the adapter. They are called Rolodex adapters and are used with ExpandableListViews
. They can easily be customized to behave like a normal list with headers.
Using the OP's Event
objects and knowing the headers are based on the Date
associated with it...the code would look something like this:
The Activity
//There's no need to pre-compute what the headers are. Just pass in your List of objects.
EventDateAdapter adapter = new EventDateAdapter(this, mEvents);
mExpandableListView.setAdapter(adapter);
The Adapter
private class EventDateAdapter extends NFRolodexArrayAdapter<Date, Event> {
public EventDateAdapter(Context activity, Collection<Event> items) {
super(activity, items);
}
@Override
public Date createGroupFor(Event childItem) {
//This is how the adapter determines what the headers are and what child items belong to it
return (Date) childItem.getDate().clone();
}
@Override
public View getChildView(LayoutInflater inflater, int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
//Inflate your view
//Gets the Event data for this view
Event event = getChild(groupPosition, childPosition);
//Fill view with event data
}
@Override
public View getGroupView(LayoutInflater inflater, int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
//Inflate your header view
//Gets the Date for this view
Date date = getGroup(groupPosition);
//Fill view with date data
}
@Override
public boolean hasAutoExpandingGroups() {
//This forces our group views (headers) to always render expanded.
//Even attempting to programmatically collapse a group will not work.
return true;
}
@Override
public boolean isGroupSelectable(int groupPosition) {
//This prevents a user from seeing any touch feedback when a group (header) is clicked.
return false;
}
}
There are basically 4 techniques for this task, all of them standard SQL.
NOT EXISTS
Often fastest in Postgres.
SELECT ip
FROM login_log l
WHERE NOT EXISTS (
SELECT -- SELECT list mostly irrelevant; can just be empty in Postgres
FROM ip_location
WHERE ip = l.ip
);
Also consider:
LEFT JOIN / IS NULL
Sometimes this is fastest. Often shortest. Often results in the same query plan as NOT EXISTS
.
SELECT l.ip
FROM login_log l
LEFT JOIN ip_location i USING (ip) -- short for: ON i.ip = l.ip
WHERE i.ip IS NULL;
EXCEPT
Short. Not as easily integrated in more complex queries.
SELECT ip
FROM login_log
EXCEPT ALL -- "ALL" keeps duplicates and makes it faster
SELECT ip
FROM ip_location;
Note that (per documentation):
duplicates are eliminated unless
EXCEPT ALL
is used.
Typically, you'll want the ALL
keyword. If you don't care, still use it because it makes the query faster.
NOT IN
Only good without NULL
values or if you know to handle NULL
properly. I would not use it for this purpose. Also, performance can deteriorate with bigger tables.
SELECT ip
FROM login_log
WHERE ip NOT IN (
SELECT DISTINCT ip -- DISTINCT is optional
FROM ip_location
);
NOT IN
carries a "trap" for NULL
values on either side:
Similar question on dba.SE targeted at MySQL:
Yes you can change it. if you call VBscript function within Javascript.
Here is simple example
<script>
function alert_confirm(){
customMsgBox("This is my title","how are you?",64,0,0,0);
}
</script>
<script language="VBScript">
Function customMsgBox(tit,mess,icon,buts,defs,mode)
butVal = icon + buts + defs + mode
customMsgBox= MsgBox(mess,butVal,tit)
End Function
</script>
<html>
<body>
<a href="javascript:alert_confirm()">Alert</a>
</body>
</html>
Richard Schneider is right. use code below to fetch data from site which is not utf8 charset will get wrong string.
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
}
" i can't vote.so wrote this.
.so
files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.
.a
files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar
command -- a predecessor of tar
that's now just used for making libraries) of the original .o object files.
.la
files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?
Static and dynamic libraries each have pros and cons.
Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.
Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.
Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.
Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.
Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.
Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.
Dynamic libraries are especially useful for system libraries, like libc
. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.
There is no such font as “Calibri (Body)”. You probably saw this string in Microsoft Word font selection menu, but it’s not a font name (see e.g. the explanation Font: +body (in W07)).
So use just font-family: Calibri
or, better, font-family: Calibri, sans-serif
. (There is no adequate backup font for Calibri, but the odds are that when Calibri is not available, the browser’s default sans-serif font suits your design better than the browser’s default font, which is most often a serif font.)
Just use this for the closing tag:
@:</tr>
And leave your if/else as is.
Seems like the if statement doesn't wanna' work.
It works fine. You're working in 2 language-spaces here, it seems only proper not to split open/close sandwiches over the border.
bool
is just a macro that expands to _Bool
. You can use _Bool
with no #include
very much like you can use int
or double
; it is a C99 keyword.
The macro is defined in <stdbool.h>
along with 3 other macros.
The macros defined are
bool
: macro expands to _Bool
false
: macro expands to 0
true
: macro expands to 1
__bool_true_false_are_defined
: macro expands to 1
Short answers:
Q1: Yes.
Q2: Doesn't matter which you use.
Long answer:
A select ... for update
will (as it implies) select certain rows but also lock them as if they have already been updated by the current transaction (or as if the identity update had been performed). This allows you to update them again in the current transaction and then commit, without another transaction being able to modify these rows in any way.
Another way of looking at it, it is as if the following two statements are executed atomically:
select * from my_table where my_condition;
update my_table set my_column = my_column where my_condition;
Since the rows affected by my_condition
are locked, no other transaction can modify them in any way, and hence, transaction isolation level makes no difference here.
Note also that transaction isolation level is independent of locking: setting a different isolation level doesn't allow you to get around locking and update rows in a different transaction that are locked by your transaction.
What transaction isolation levels do guarantee (at different levels) is the consistency of data while transactions are in progress.
Start with this:
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(path)) Then
msg = path & " exists."
Else
msg = path & " doesn't exist."
End If
Taken from the documentation.
Following Peter Hauge's comment, upon running docker network ls
I saw (among other lines) the following:
NETWORK ID NAME DRIVER SCOPE
dc6a83d13f44 bridge bridge local
ea98225c7754 docker_gwbridge bridge local
107dcd8aa889 host host local
The line with NAME
and DRIVER
as both host
seems to be what he is referring to with "networks already created on your host". So, following https://gist.github.com/bastman/5b57ddb3c11942094f8d0a97d461b430, I ran the command
docker network rm $(docker network ls | grep "bridge" | awk '/ / { print $1 }')
Now docker-compose up
works (although newnym.py
produces an error).
No need to use any strings
.Its over burden.
int i = 124;
int last= i%10;
System.out.println(last); //prints 4
Just my two cents to this very old question. I would highly recommend taking a look at ElasticSearch.
Elasticsearch is a search server based on Lucene. It provides a distributed, multitenant-capable full-text search engine with a RESTful web interface and schema-free JSON documents. Elasticsearch is developed in Java and is released as open source under the terms of the Apache License.
The advantages over other FTS (full text search) Engines are:
We are using this search engine at our project and very happy with it.
mydict = dict(zip(df.id, df.value))
With SQL Developer 4.x, the language option is to be added to ..\sqldeveloper\bin\sqldeveloper.conf
, rather than ..\sqldeveloper\bin\ide.conf
:
# ----- MODIFICATION BEGIN -----
AddVMOption -Duser.language=en
# ----- MODIFICATION END -----
Try obuildfactory.
There is need to modify these scripts (contains error and don't exactly do the "thing" required), i will upload mine scripts forked from obuildfactory in next few days. and so i will also update my answer accordingly.
Until then enjoy, sir :)
I have had this issue also, and while -UseBasicParsing will work for some, if you actually need to interact with the dom it wont work. Try using a a group policy to stop the initial configuration window from ever appearing and powershell won't stop you anymore. See here https://wahlnetwork.com/2015/11/17/solving-the-first-launch-configuration-error-with-powershells-invoke-webrequest-cmdlet/
Took me just a few minutes once I found this page, once the GP is set, powershell will allow you through.
The return
exits the current function, but the iterations keeps on, so you get the "next" item that skips the if
and alerts the 4...
If you need to stop the looping, you should just use a plain for
loop like so:
$('button').click(function () {
var arr = [1, 2, 3, 4, 5];
for(var i = 0; i < arr.length; i++) {
var n = arr[i];
if (n == 3) {
break;
}
alert(n);
})
})
You can read more about js break & continue here: http://www.w3schools.com/js/js_break.asp
LinkedHashMap
is precisely what you're looking for.
It is exactly like HashMap
, except that when you iterate over it, it presents the items in the insertion order.
You can use Control.Parent to get the parent of the control or Control.FindForm to get the first parent Form
the control is on. There is a difference between the two in terms of finding forms, so one may be more suitable to use than the other.:
The control's Parent property value might not be the same as the Form returned by FindForm method. For example, if a RadioButton control is contained within a GroupBox control, and the GroupBox is on a Form, the RadioButton control's Parent is the GroupBox and the GroupBox control's Parent is the Form.
curl -iv https://your.domain.io
That will give you cert and header output if you do not wish to use openssl command.
UPDATE
"QuestionTrackings"
SET
"QuestionID" = (SELECT "QuestionID" FROM "Answers" WHERE "AnswerID"="QuestionTrackings"."AnswerID")
WHERE
"QuestionID" is NULL
AND ...
I was compiling my application targeting any CPU and main problem turned out that adobe reader was installed older v10.x needs to upgrade v11.x, this is the way how I get to resolve this issue.
It seems that Facebook Page Plugin doesn't change at all in past 5-7 years :) It wasn't responsive from the begining and still not now, even new param Adapt to plugin container width
doesn't work or I don't understand how it works.
I'm searching for the most posible simple way to do PLUGIN SIZE 100% WIDTH
, and it seems it is not posible. Nonsense at it's best. How designers solve this problem?
I found the best decision for this time 2017 Oct:
.fb-page, .fb-page iframe[style], .fb-page span {
width: 100% !important;
}
.fb-comments, .fb-comments iframe[style], .fb-comments span {
width: 100% !important;
}
This lets do not broke screen size width for responsive screens, but still looks ugly, because cuted in some time and doesn't stretch... Facebook doesn't care about plugins design at all. That's the truth.
The selector ".nr:first"
is specifically looking for the first, and only the first, element having class "nr"
within the selected table element. If you instead call .find(".nr")
you will get all of the elements within the table having class "nr"
. Once you have all of those elements, you could use the .each method to iterate over them. For example:
$(".use-address").click(function() {
$("#choose-address-table").find(".nr").each(function(i, nrElt) {
var id = nrElt.text();
$("#resultas").append("<p>" + id + "</p>"); // Testing: append the contents of the td to a div
});
});
However, that would get you all of the td.nr
elements in the table, not just the one in the row that was clicked. To further limit your selection to the row containing the clicked button, use the .closest method, like so:
$(".use-address").click(function() {
$(this).closest("tr").find(".nr").each(function(i, nrElt) {
var id = nrElt.text();
$("#resultas").append("<p>" + id + "</p>"); // Testing: append the contents of the td to a div
});
});
I'm fairly certain that the ls
command is for Linux, not Windows (I'm assuming you're using Windows as you referred to cmd
, which is the command line for the Windows OS).
You should use dir
instead, which is the Windows equivalent of ls
.
Edit (since this post seems to be getting so many views :) ):
You can't use ls
on cmd
as it's not shipped with Windows
, but you can use it on other terminal programs (such as GitBash). Note, ls
might work on some FTP
servers if the servers are linux
based and the FTP
is being used from cmd
.
dir
on Windows
is similar to ls
. To find out the various options available, just do dir/?
.
If you really want to use ls
, you could install 3rd party tools to allow you to run unix
commands on Windows
. Such a program is Microsoft Windows Subsystem for Linux
(link to docs).
Here is a SUMMARY of all the major answers above (or maybe below later :)
For modern browsers, put css wherever you like it. They would analyze your html file (which they call speculative parsing) and start downloading css in parallel with html parsing.
For old browsers keep putting css on top (if you don't want to show a naked but interactive page first).
For all browsers, put javascript as farther down on the page as possible, since it will halt parsing of your html. Preferably, download it asynchronously (i.e., ajax call)
There are also, some experimental results for a particular case which claims putting javascript first (as opposed to traditional wisdom of putting CSS first) gives better performance but there is no logical reasoning given for it, and lacks validation regarding widespread applicability, so you can ignore it for now.
So, to answer the question: Yes. The recommendation to include the CSS before JS is invalid for the modern browsers. Put CSS wherever you like, and put JS towards the end, as possible.
from item in db.vw_Dropship_OrderItems
where (listStatus != null ? listStatus.Contains(item.StatusCode) : true) &&
(listMerchants != null ? listMerchants.Contains(item.MerchantId) : true)
select item;
Might give strange behavior if both listMerchants and listStatus are both null.
import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.json.JSONObject;
import java.util.ArrayList;
public class OurteamAdapter extends BaseAdapter {
Context cont;
ArrayList<OurteamModel> llist;
OurteamAdapter madap;
LayoutInflater inflater;
JsonHelper Jobj;
String Id;
JSONObject obj = null;
int position = 0;
public OurteamAdapter(Context c,ArrayList<OurteamModel> Mi)
{
this.cont = c;
this.llist = Mi;
}
@Override
public int getCount()
{
// TODO Auto-generated method stub
return llist.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return llist.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
if(convertView == null)
{
LayoutInflater in = (LayoutInflater) cont.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = in.inflate(R.layout.doctorlist, null);
}
TextView category = (TextView) convertView.findViewById(R.id.button1);
TextView title = (TextView) convertView.findViewById(R.id.button2);
ImageView i1=(ImageView) convertView.findViewById(R.id.imageView1);
category.setText(Html.fromHtml(llist.get(position).getGalleryName()));
title.setText(Html.fromHtml(llist.get(position).getGalleryDetail()));
if(llist.get(position).getImagesrc()!=null)
{
i1.setImageBitmap(llist.get(position).getImagesrc());
}
else
{
i1.setImageResource(R.drawable.anandlogo);
}
return convertView;
}
}
Figure sizes are specified in inches and can be included as a global option of the document output format. For example:
---
title: "My Document"
output:
html_document:
fig_width: 6
fig_height: 4
---
And the plot's size in the graphic device can be increased at the chunk level:
```{r, fig.width=14, fig.height=12} #Expand the plot width to 14 inches
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
You can also use the out.width
and out.height
arguments to directly define the size of the plot in the output file:
```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
If you modify your list, then use listIterator()
and iterate from last index (that is size()-1
respectively).
If you fail again, check your list structure.
No, not all browsers support the sizes
attribute:
Note that some platforms define specific sizes:
manifest.json
if it is present. Plus, Chrome uses the Apple Touch icon for bookmarks.This is a simpler mechanism. It simply involves the addition of a Windows Batch command task build step before the MSBuild step and the use of a simple find and replace program (FART).
The Batch Step
fart --svn -r AssemblyInfo.cs "[assembly: AssemblyVersion(\"1.0.0.0\")]" "[assembly: AssemblyVersion(\"1.0.%BUILD_NUMBER%.%SVN_REVISION%\")]"
if %ERRORLEVEL%==0 exit /b 1
fart --svn -r AssemblyInfo.cs "[assembly: AssemblyFileVersion(\"1.0.0.0\")]" "[assembly: AssemblyFileVersion(\"1.0.%BUILD_NUMBER%.%SVN_REVISION%\")]"
if %ERRORLEVEL%==0 exit /b 1
exit /b 0
If you are using source control other than svn change the --svn option for the appropriate one for your scm environment.
I know this is an old post but I recently ran into a very similar problem. Unfortunately I wasn't able to use any of the alter database commands because an exclusive lock couldn't be placed. But I was never able to find an open connection to the db. I eventually had to forcefully delete the health state of the database to force it into a restoring state instead of in recovery.
I had two incompatible dependencies.
The below dependencies caused the error.
compile 'com.google.android.gms:play-services-fitness:8.3.0'
compile 'com.google.android.gms:play-services-wearable:8.4.0'
By changing the fitness dependency to version 8.4.0 I was able to run the app.
compile 'com.google.android.gms:play-services-fitness:8.4.0'
compile 'com.google.android.gms:play-services-wearable:8.4.0'
If you are using LoaderManager try with this statement:
getLoaderManager().restartLoader(0, null, this);
It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.
Edit: This is what the forums say:
By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.
To disable:
/system/bin/bugmailer.sh must be deleted/renamed.
There should be a folder on your SD card called "bug reports".
Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948
And this one: http://forum.xda-developers.com/showthread.php?t=1405639
If you want to have your own nice looking wpf MessageBox: Create new Wpf Windows
here is xaml :
<Window x:Class="popup.MessageboxNew"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:popup"
mc:Ignorable="d"
Title="" SizeToContent="WidthAndHeight" WindowStartupLocation="CenterScreen" WindowStyle="None" ResizeMode="NoResize" AllowsTransparency="True" Background="Transparent" Opacity="1"
>
<Window.Resources>
</Window.Resources>
<Border x:Name="MainBorder" Margin="10" CornerRadius="8" BorderThickness="0" BorderBrush="Black" Padding="0" >
<Border.Effect>
<DropShadowEffect x:Name="DSE" Color="Black" Direction="270" BlurRadius="20" ShadowDepth="3" Opacity="0.6" />
</Border.Effect>
<Border.Triggers>
<EventTrigger RoutedEvent="Window.Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="DSE" Storyboard.TargetProperty="ShadowDepth" From="0" To="3" Duration="0:0:1" AutoReverse="False" />
<DoubleAnimation Storyboard.TargetName="DSE" Storyboard.TargetProperty="BlurRadius" From="0" To="20" Duration="0:0:1" AutoReverse="False" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Border.Triggers>
<Grid Loaded="FrameworkElement_OnLoaded">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Border Name="Mask" CornerRadius="8" Background="White" />
<Grid x:Name="Grid" Background="White">
<Grid.OpacityMask>
<VisualBrush Visual="{Binding ElementName=Mask}"/>
</Grid.OpacityMask>
<StackPanel Name="StackPanel" >
<TextBox Style="{DynamicResource MaterialDesignTextBox}" Name="TitleBar" IsReadOnly="True" IsHitTestVisible="False" Padding="10" FontFamily="Segui" FontSize="14"
Foreground="Black" FontWeight="Normal"
Background="Yellow" HorizontalAlignment="Stretch" VerticalAlignment="Center" Width="Auto" HorizontalContentAlignment="Center" BorderThickness="0"/>
<DockPanel Name="ContentHost" Margin="0,10,0,10" >
<TextBlock Margin="10" Name="Textbar"></TextBlock>
</DockPanel>
<DockPanel Name="ButtonHost" LastChildFill="False" HorizontalAlignment="Center" >
<Button Margin="10" Click="ButtonBase_OnClick" Width="70">Yes</Button>
<Button Name="noBtn" Margin="10" Click="cancel_Click" Width="70">No</Button>
</DockPanel>
</StackPanel>
</Grid>
</Grid>
</Border>
</Window>
for cs of this file :
public partial class MessageboxNew : Window
{
public MessageboxNew()
{
InitializeComponent();
//second time show error solved
if (Application.Current == null) new Application();
Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
DialogResult = true;
}
private void cancel_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
private void FrameworkElement_OnLoaded(object sender, RoutedEventArgs e)
{
this.MouseDown += delegate { DragMove(); };
}
}
then create a class to use this :
public class Mk_MessageBox
{
public static bool? Show(string title, string text)
{
MessageboxNew msg = new MessageboxNew
{
TitleBar = {Text = title},
Textbar = {Text = text}
};
msg.noBtn.Focus();
return msg.ShowDialog();
}
}
now you can create your message box like this:
var result = Mk_MessageBox.Show("Remove Alert", "This is gonna remove directory from host! Are you sure?");
if (result == true)
{
// whatever
}
copy this to App.xaml inside
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!-- MahApps.Metro resource dictionaries. Make sure that all file names are Case Sensitive! -->
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />
<!-- Accent and AppTheme setting -->
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
<!--two new guys-->
<ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.LightBlue.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Green.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
-------------------------------
My Refrence : https://www.red-gate.com/simple-talk/dotnet/net-development/using-c-to-create-powershell-cmdlets-the-basics/
Not sure what you are really after but if you want to print exactly what you have you can do:
Option 1
print(df['Item'].to_csv(index=False))
Sweet
Candy
Chocolate
Option 2
for v in df['Item']:
print(v)
Sweet
Candy
Chocolate
In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):
select myintfield + 0.0 as myfloatfield from mytable
While @Heximal's answer works, I don't personally recommend it.
This is because it uses implicit casting. Although you didn't type CAST
, either the SUM()
or the 0.0
need to be cast to be the same data-types, before the +
can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +
. But SUM(aFloatField) + 0
does not yield an INT, because the 0
is being implicitly cast to a FLOAT.
I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.
If you want to be explicit, I would use the following.
CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT requires 8.0
You can try the following to see what happens...
CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))
With > 4.0 of select2 I am using
$("select").select2({
dropdownAutoWidth: true
});
These others did not work:
no array
no extra for loop
for (var i = 0; i < 3; i++) {
createfunc(i)();
}
function createfunc(i) {
return function(){console.log("My value: " + i);};
}
I had similar problem and only one solution worked out for me. I tried everything suggested, and I knew that I set my bridging header fine, because I had some other lib working.
When I copied library (drag and drop) into the project, without Cocoapods, only after that I could import headers without errors.
I used facebook/Shimmer library.
There were a number of suggestions from an earlier similar question "Best way to test for existing string against a large list of comparables".
Regex might be sufficient for your requirement. The expression would be a concatenation of all the candidate substrings, with an OR "|
" operator between them. Of course, you'll have to watch out for unescaped characters when building the expression, or a failure to compile it because of complexity or size limitations.
Another way to do this would be to construct a trie data structure to represent all the candidate substrings (this may somewhat duplicate what the regex matcher is doing). As you step through each character in the test string, you would create a new pointer to the root of the trie, and advance existing pointers to the appropriate child (if any). You get a match when any pointer reaches a leaf.
The correct answer is already given, nevertheless here is the better way (than switch):
private Dictionary<Operator, Func<int, int, double>> operators =
new Dictionary<Operator, Func<int, int, double>>
{
{ Operator.PLUS, ( a, b ) => a + b },
{ Operator.MINUS, ( a, b ) => a - b },
{ Operator.MULTIPLY, ( a, b ) => a * b },
{ Operator.DIVIDE ( a, b ) => (double)a / b },
};
public double Calculate( int left, int right, Operator op )
{
return operators.ContainsKey( op ) ? operators[ op ]( left, right ) : 0.0;
}
On Apple platforms (iOS/macOS/tvOS/watchOS), the limit may be a 2 GB long URL scheme, as seen by this comment in the source code of Swift:
// Make sure the URL string isn't too long. // We're limiting it to 2GB for backwards compatibility with 32-bit executables using NS/CFURL if ( (urlStringLength > 0) && (urlStringLength <= INT_MAX) ) { ...
On iOS, I've tested and confirmed that even a 300+ MB long URL is accepted. You can try such a long URL like this in Objective-C:
NSString *path = [@"a:" stringByPaddingToLength:314572800 withString:@"a" startingAtIndex:0];
NSString *js = [NSString stringWithFormat:@"window.location.href = \"%@\";", path];
[self.webView stringByEvaluatingJavaScriptFromString:js];
And catch if it succeed with:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(@"length: %@", @(request.URL.absoluteString.length));
return YES;
}
It is very simple
public void onClick(View v) {
imgButton.setImageResource(R.drawable.ic_launcher);
}
Using set Background image resource will chanage the background of the button
To get cell column name as well as cell value :
List<JObject> dataList = new List<JObject>();
for (int i = 0; i < dataTable.Rows.Count; i++)
{
JObject eachRowObj = new JObject();
for (int j = 0; j < dataTable.Columns.Count; j++)
{
string key = Convert.ToString(dataTable.Columns[j]);
string value = Convert.ToString(dataTable.Rows[i].ItemArray[j]);
eachRowObj.Add(key, value);
}
dataList.Add(eachRowObj);
}
Export the .ipa by checking the "with manifest plist checkbox" and provide the links requested.
Upload the .ipa file and .plist file to the same location of the server (which you provided when exporting .ipa/ which mentioned in the .plist file).
Create the Download Link as given below. url should link to your .plist file location.
itms-services://?action=download-manifest&url=https://yourdomainname.com/app.plist
Copy this link and paste it in safari browser in your iphone. It will ask to install :D
Create a html button using this full url
As a good practice you can use an Ant Script (Eclipse comes with it) to generate your JAR file. Inside this JAR you can have all dependent libs.
You can even set the MANIFEST's Class-path header to point to files in your filesystem, it's not a good practice though.
Ant build.xml script example:
<project name="jar with libs" default="compile and build" basedir=".">
<!-- this is used at compile time -->
<path id="example-classpath">
<pathelement location="${root-dir}" />
<fileset dir="D:/LIC/xalan-j_2_7_1" includes="*.jar" />
</path>
<target name="compile and build">
<!-- deletes previously created jar -->
<delete file="test.jar" />
<!-- compile your code and drop .class into "bin" directory -->
<javac srcdir="${basedir}" destdir="bin" debug="true" deprecation="on">
<!-- this is telling the compiler where are the dependencies -->
<classpath refid="example-classpath" />
</javac>
<!-- copy the JARs that you need to "bin" directory -->
<copy todir="bin">
<fileset dir="D:/LIC/xalan-j_2_7_1" includes="*.jar" />
</copy>
<!-- creates your jar with the contents inside "bin" (now with your .class and .jar dependencies) -->
<jar destfile="test.jar" basedir="bin" duplicate="preserve">
<manifest>
<!-- Who is building this jar? -->
<attribute name="Built-By" value="${user.name}" />
<!-- Information about the program itself -->
<attribute name="Implementation-Vendor" value="ACME inc." />
<attribute name="Implementation-Title" value="GreatProduct" />
<attribute name="Implementation-Version" value="1.0.0beta2" />
<!-- this tells which class should run when executing your jar -->
<attribute name="Main-class" value="ApplyXPath" />
</manifest>
</jar>
</target>
You can use valueOf("a1")
if you want to look up by String
First of all, login to your database and check whether the database table which you want to import is not available on your database.
If it is available, delete the table using the command. Else it will throw an error while importing the table.
DROP TABLE Table_Name;
Then, move to the folder in which you have the .sql
file to import and run the following command from your terminal
mysql -u username -p databasename < yourtable.sql
The terminal will ask you to enter the password. Enter it and check the database.
Here is an extension to the Answer to the question "difference between run-time and compile-time?" -- Differences in overheads associated with run-time and compile-time?
The run-time performance of the product contributes to its quality by delivering results faster. The compile-time performance of the product contributes to its timeliness by shortening the edit-compile-debug cycle. However, both run-time performance and compile-time performance are secondary factors in achieving timely quality. Therefore, one should consider run-time and compile-time performance improvements only when justified by improvements in overall product quality and timeliness.
A great source for further reading here:
thought I would add this for any future peeps. It will always make sure that its monday if needed, can also be used to always ensure sunday. For me I always need monday, but local is dependant on the machine being used, and this is an easy fix:
var begin = moment().isoWeekday(1).startOf('week');
var begin2 = moment().startOf('week');
// could check to see if day 1 = Sunday then add 1 day
// my mac on bst still treats day 1 as sunday
var firstDay = moment().startOf('week').format('dddd') === 'Sunday' ?
moment().startOf('week').add('d',1).format('dddd DD-MM-YYYY') :
moment().startOf('week').format('dddd DD-MM-YYYY');
document.body.innerHTML = '<b>could be monday or sunday depending on client: </b><br />' +
begin.format('dddd DD-MM-YYYY') +
'<br /><br /> <b>should be monday:</b> <br>' + firstDay +
'<br><br> <b>could also be sunday or monday </b><br> ' +
begin2.format('dddd DD-MM-YYYY');
Or you can make your own function that passes the array by reference.
function array_unset($unsets, &$array) {
foreach ($array as $key => $value) {
foreach ($unsets as $unset) {
if ($value == $unset) {
unset($array[$key]);
break;
}
}
}
$array = array_values($array);
}
So then all you have to do is...
$unsets = array(1,2);
array_unset($unsets, $array);
... and now your $array
is without the values you placed in $unsets
and the keys are reset
Finally, I got a solution!
My Context is:- I want disconnect socket connection when activity destroyed, I tried to finish() activity but it didn't work me, its keep connection live somewhere.
so I use android.os.Process.killProcess(android.os.Process.myPid());
its kill my activity and i used android:excludeFromRecents="true"
for remove from recent activity .
As per discussion over here, ENOSPC
means Error No more hard-disk space available
. Reason why this much memory required by nodemon
or gulp-nodemon
(in my case) is that it was watching contents of a folder which it shouldn't. To fix that nodemon has ignore
setting that can be used to tell nodemon what not to watch. Have a look at nodemon sample config here.
Depends on your RDBMS
MS SQL Server
SELECT TOP 10 ...
MySQL
SELECT ... LIMIT 10
Sybase
SET ROWCOUNT 10
SELECT ...
Etc.
In one of my projects I use a "mixture" between vw and vh to adjust the font size to my needs, for example:
font-size: calc(3vw + 3vh);
I know this doesn't answer the OP's question, but maybe it can be a solution to anyone else.
thanks for this post. I want to add something that can be useful.
For IE, it is good to use
object["property"] = value;
syntax because some special words in IE can give you an error.
An example:
object.class = 'value';
this fails in IE, because "class" is a special word. I spent several hours with this.
Here are some examples:
> z$mean <- rowMeans(subset(z, select = c(x, y)), na.rm = TRUE)
> z
w x y mean
1 5 1 1 1
2 6 2 2 2
3 7 3 3 3
4 8 4 NA 4
weighted mean
> z$y <- rev(z$y)
> z
w x y mean
1 5 1 NA 1
2 6 2 3 2
3 7 3 2 3
4 8 4 1 4
>
> weight <- c(1, 2) # x * 1/3 + y * 2/3
> z$wmean <- apply(subset(z, select = c(x, y)), 1, function(d) weighted.mean(d, weight, na.rm = TRUE))
> z
w x y mean wmean
1 5 1 NA 1 1.000000
2 6 2 3 2 2.666667
3 7 3 2 3 2.333333
4 8 4 1 4 2.000000
in my case using angular
in my HTTP interceptor , i set
with Credentials: true.
in the header of the request
Using ES6 syntax in React does not bind this
to user-defined functions however it will bind this
to the component lifecycle methods.
So the function that you declared will not have the same context as the class and trying to access this
will not give you what you are expecting.
For getting the context of class you have to bind the context of class to the function or use arrow functions.
Method 1 to bind the context:
class MyContainer extends Component {
constructor(props) {
super(props);
this.onMove = this.onMove.bind(this);
this.testVarible= "this is a test";
}
onMove() {
console.log(this.testVarible);
}
}
Method 2 to bind the context:
class MyContainer extends Component {
constructor(props) {
super(props);
this.testVarible= "this is a test";
}
onMove = () => {
console.log(this.testVarible);
}
}
Method 2 is my preferred way but you are free to choose your own.
Update: You can also create the properties on class without constructor:
class MyContainer extends Component {
testVarible= "this is a test";
onMove = () => {
console.log(this.testVarible);
}
}
Note If you want to update the view as well, you should use state
and setState
method when you set or change the value.
Example:
class MyContainer extends Component {
state = { testVarible: "this is a test" };
onMove = () => {
console.log(this.state.testVarible);
this.setState({ testVarible: "new value" });
}
}
you can use "dynamicObject.PropertyName.Value
" to get value of dynamic property directly.
Example :
d.property11.Value
Another option with Filter
Filter(function(x) !all(is.na(x)), df)
NOTE: Data from @Simon O'Hanlon's post.
original answer moved to this topic .
Most likely, the item is being selected, you just can't tell because a different control has the focus. There are a couple of different ways that you can solve this, depending on the design of your application.
The simple solution is to set the focus to the ListView
first whenever your form is displayed. The user typically sets focus to controls by clicking on them. However, you can also specify which controls gets the focus programmatically. One way of doing this is by setting the tab index of the control to 0 (the lowest value indicates the control that will have the initial focus). A second possibility is to use the following line of code in your form's Load
event, or immediately after you set the Selected
property:
myListView.Select();
The problem with this solution is that the selected item will no longer appear highlighted when the user sets focus to a different control on your form (such as a textbox or a button).
To fix that, you will need to set the HideSelection
property of the ListView
control to False. That will cause the selected item to remain highlighted, even when the control loses the focus.
When the control has the focus, the selected item's background will be painted with the system highlight color. When the control does not have the focus, the selected item's background will be painted in the system color used for grayed (or disabled) text.
You can set this property either at design time, or through code:
myListView.HideSelection = false;
You can specify the shell to be used by the remote host locally.
echo 'echo "Bash version: ${BASH_VERSION}"' | ssh -q localhost bash
And be careful to (single-)quote the variables you wish to be expanded by the remote host; otherwise variable expansion will be done by your local shell!
# example for local / remote variable expansion
{
echo "[[ $- == *i* ]] && echo 'Interactive' || echo 'Not interactive'" |
ssh -q localhost bash
echo '[[ $- == *i* ]] && echo "Interactive" || echo "Not interactive"' |
ssh -q localhost bash
}
So, to check if a certain file exists on the remote host you can do the following:
host='localhost' # localhost as test case
file='~/.bash_history'
if `echo 'test -f '"${file}"' && exit 0 || exit 1' | ssh -q "${host}" sh`; then
#if `echo '[[ -f '"${file}"' ]] && exit 0 || exit 1' | ssh -q "${host}" bash`; then
echo exists
else
echo does not exist
fi
The way it's often done is as follows:
I find that this pattern comes up pretty frequently.
What's interesting about this method is that it allows one to insert N
elements into an empty array one-by-one in amortized O(N)
time without knowing N
in advance.
is there some other clause in the language specification that this exploits?
Yes, see 12.8 §34 and §35:
When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object [...] This elision of copy/move operations, called copy elision, is permitted [...] in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object with the same cv-unqualified type as the function return type [...]
When the criteria for elision of a copy operation are met and the object to be copied is designated by an lvalue, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue.
Just wanted to add one more point that returning by value should be the default choice here because a named value in the return statement in the worst case, i.e. without elisions in C++11, C++14 and C++17 is treated as an rvalue. So for example the following function compiles with the -fno-elide-constructors
flag
std::unique_ptr<int> get_unique() {
auto ptr = std::unique_ptr<int>{new int{2}}; // <- 1
return ptr; // <- 2, moved into the to be returned unique_ptr
}
...
auto int_uptr = get_unique(); // <- 3
With the flag set on compilation there are two moves (1 and 2) happening in this function and then one move later on (3).
Also, you can try use CustomScrollView
CustomScrollView(
controller: _scrollController,
slivers: <Widget>[
SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
final OrderModel order = _orders[index];
return Container(
margin: const EdgeInsets.symmetric(
vertical: 8,
),
child: _buildOrderCard(order, size, context),
);
},
childCount: _orders.length,
),
),
SliverToBoxAdapter(
child: _buildPreloader(context),
),
],
);
Tip: _buildPreloader
return CircularProgressIndicator
or Text
In my case i want to show under ListView some widgets. Use Column
does't work me, because widgets around ListView inside Column showing always "up" on the screen, like "position absolute"
Sorry for my bad english
In some browsers
(MSIE "as usually" ;-))
replacing space in string ignores the non-breaking space (the 160 char code).
One should always replace like this:
myString.replace(/[ \u00A0]/, myReplaceString)
Very nice detailed explanation:
http://www.adamkoch.com/2009/07/25/white-space-and-character-160/
Since you already have yarn installed and only want to upgrade/update. you can simply use
yarn self-update
Find ref here https://yarnpkg.com/en/docs/cli/self-update
As far as the http verb is concerned the WebRequest
might be easier. You could go for something like:
WebRequest r = WebRequest.Create("http://some.url");
r.Method = "POST";
using (var s = r.GetResponse().GetResponseStream())
{
using (var reader = new StreamReader(r, FileMode.Open))
{
var content = reader.ReadToEnd();
}
}
Obviously this lacks exception handling and writing the request body (for which you can use r.GetRequestStream()
and write it like a regular stream, but I hope it may be of some help.
You've missed the id out before the NOT; it needs to be specified.
SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'
I think troelskn is close. I would do this instead:
class ClassToTest
{
protected function testThisMethod()
{
// Implement stuff here
}
}
Then, implement something like this:
class TestClassToTest extends ClassToTest
{
public function testThisMethod()
{
return parent::testThisMethod();
}
}
You then run your tests against TestClassToTest.
It should be possible to automatically generate such extension classes by parsing the code. I wouldn't be surprised if PHPUnit already offers such a mechanism (though I haven't checked).
Yes! In your settings.py define the following
LOGIN_REDIRECT_URL = '/your-path'
And have '/your-path' be a simple View that looks up self.request.user
and does whatever logic it needs to return a HttpResponseRedirect
object.
A better way might be to define a simple URL like '/simple'
that does the lookup logic there. The URL looks more beautiful, saves you some work, etc.
I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:
multiDexEnabled true
And it worked!
Example
android {
compileSdkVersion 27
buildToolsVersion '27.0.1'
defaultConfig {
applicationId "com.xx.xxx"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
multiDexEnabled true //Add this
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
And clean the project.
None is used to indicate "not set", whereas any other value is used to indicate a "default" value.
Hence, if your class copes with empty strings and you like it as a default value, use "". If your class needs to check if the variable was set at all, use None.
Notice that it doesn't matter if your variable is a string initially. You can change it to any other type/value at any other moment.
From Java8 and above, you may use below command:
jcmd JAVA_PROCESS_ID
GC.heap_info
You may refer to sum of, total and used memory from the output.
Sample Command And Output: jcmd 9758 GC.heap_info
PSYoungGen total 1579520K, used 487543K [0x0000000751d80000, 0x00000007c0000000, 0x00000007c0000000)
eden space 1354240K, 36% used [0x0000000751d80000,0x000000076f99dc40,0x00000007a4800000)
from space 225280K, 0% used [0x00000007b2400000,0x00000007b2400000,0x00000007c0000000)
to space 225280K, 0% used [0x00000007a4800000,0x00000007a4800000,0x00000007b2400000)
ParOldGen total 3610112K, used 0K [0x0000000675800000, 0x0000000751d80000, 0x0000000751d80000)
object space 3610112K, 0% used [0x0000000675800000,0x0000000675800000,0x0000000751d80000)
Metaspace used 16292K, capacity 16582K, committed 16896K, reserved 1064960K
class space used 1823K, capacity 1936K, committed 2048K, reserved 1048576K
For more details on jcmd command, visit link here
A data.frame
is a list
, so ...
For vectorized functions do.call
is usually a good bet. But the names of arguments come into play. Here your testFunc
is called with args x and y in place of a and b. The ...
allows irrelevant args to be passed without causing an error:
do.call( function(x,z,...) testFunc(x,z), df )
For non-vectorized functions, mapply
will work, but you need to match the ordering of the args or explicitly name them:
mapply(testFunc, df$x, df$z)
Sometimes apply
will work - as when all args are of the same type so coercing the data.frame
to a matrix does not cause problems by changing data types. Your example was of this sort.
If your function is to be called within another function into which the arguments are all passed, there is a much slicker method than these. Study the first lines of the body of lm()
if you want to go that route.
Set your SMTP auth to true if using the PHPmailer class:
$mail->SMTPAuth = true;
Kenny is right, just want to clear some things out.
border.xml
and put it in the folder res/drawable/
add the code
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="4dp" android:color="#FF00FF00" />
<solid android:color="#ffffff" />
<padding android:left="7dp" android:top="7dp"
android:right="7dp" android:bottom="0dp" />
<corners android:radius="4dp" />
</shape>
set back ground like android:background="@drawable/border"
wherever you want the border
Mine first didn't work cause i put the border.xml
in the wrong folder!
My /var/log/apache2 folder was 35g and some logs in /var/log totaled to be the other 5g of my 40g hard drive. I cleared out all the *.gz logs and after making sure the other logs werent going to do bad things if I messed with them, i just cleared them too.
echo "clear" > access.log
etc.
Try this:
div{
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
background: red;
}
Here div is html tag. You wrote a html tag followed by a dot that is wrong.Only a class is written followed by dot.
You could use prop
as well. Check the following code below.
$(document).ready(function(){
$('.staff_on_site').click(function(){
var rBtnVal = $(this).val();
if(rBtnVal == "yes"){
$("#no_of_staff").prop("readonly", false);
}
else{
$("#no_of_staff").prop("readonly", true);
}
});
});
git remote update && git status
Found this on the answer to Check if pull needed in Git
git remote update
to bring your remote refs up to date. Then you can do one of several things, such as:
git status -uno
will tell you whether the branch you are tracking is ahead, behind or has diverged. If it says nothing, the local and remote are the same.
git show-branch *master
will show you the commits in all of the branches whose names end in master (eg master and origin/master).If you use
-v
withgit remote update
you can see which branches got updated, so you don't really need any further commands.
It is purely a string:
startInfo.Arguments = "-sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer"
Of course, when arguments contain whitespaces you'll have to escape them using \" \", like:
"... -ss \"My MyAdHocTestCert.cer\""
See MSDN for this.
FWIW with Ansible 2.2 one can use include_role:
playbook test.yml
:
- name: test
hosts:
- 127.0.0.1
connection: local
tasks:
- include_role:
name: test
tasks_from: other
then in roles/test/tasks/other.yml
:
- name: say something else
shell: echo "I'm the other guy"
And invoke the playbook with: ansible-playbook test.yml
to get:
TASK [test : say something else] *************
changed: [127.0.0.1]
Yep.
// FakeChart.cs
// ------------------------------------------------------------------
//
// A Winforms app that produces a contrived chart using
// DataVisualization (MSChart). Requires .net 4.0.
//
// Author: Dino
//
// ------------------------------------------------------------------
//
// compile: \net4.0\csc.exe /t:winexe /debug+ /R:\net4.0\System.Windows.Forms.DataVisualization.dll FakeChart.cs
//
using System;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace Dino.Tools.WebMonitor
{
public class FakeChartForm1 : Form
{
private System.ComponentModel.IContainer components = null;
System.Windows.Forms.DataVisualization.Charting.Chart chart1;
public FakeChartForm1 ()
{
InitializeComponent();
}
private double f(int i)
{
var f1 = 59894 - (8128 * i) + (262 * i * i) - (1.6 * i * i * i);
return f1;
}
private void Form1_Load(object sender, EventArgs e)
{
chart1.Series.Clear();
var series1 = new System.Windows.Forms.DataVisualization.Charting.Series
{
Name = "Series1",
Color = System.Drawing.Color.Green,
IsVisibleInLegend = false,
IsXValueIndexed = true,
ChartType = SeriesChartType.Line
};
this.chart1.Series.Add(series1);
for (int i=0; i < 100; i++)
{
series1.Points.AddXY(i, f(i));
}
chart1.Invalidate();
}
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
this.chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart();
((System.ComponentModel.ISupportInitialize)(this.chart1)).BeginInit();
this.SuspendLayout();
//
// chart1
//
chartArea1.Name = "ChartArea1";
this.chart1.ChartAreas.Add(chartArea1);
this.chart1.Dock = System.Windows.Forms.DockStyle.Fill;
legend1.Name = "Legend1";
this.chart1.Legends.Add(legend1);
this.chart1.Location = new System.Drawing.Point(0, 50);
this.chart1.Name = "chart1";
// this.chart1.Size = new System.Drawing.Size(284, 212);
this.chart1.TabIndex = 0;
this.chart1.Text = "chart1";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.chart1);
this.Name = "Form1";
this.Text = "FakeChart";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.chart1)).EndInit();
this.ResumeLayout(false);
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FakeChartForm1());
}
}
}
UI:
$('input[id^="rad"]').dblclick(function(){
var nombre = $(this).attr('id');
var checked = $(this).is(":checked") ;
if(checked){
$("input[id="+nombre+"]:radio").prop( "checked", false );
}
});
Every time you have a double click in a checked radio the checked changes to false
My radios begin with id=radxxxxxxxx
because I use this id selector.
Alert alert = driver.switchTo().alert(); alert.accept();
You can also decline the alert box:
Alert alert = driver.switchTo().alert(); alert().dismiss();
Yes, you can program Android apps in C++ (for the most part), using the Native Development Kit (NDK), although Java is the primary/preferred language for programming Android, and your C++ code will likely have to interface with Java components, and you'll likely need to read and understand the documentation for Java components, as well. Therefore, I'd advise you to use Java unless you have some existing C++ code base that you need to port and that isn't practical to rewrite in Java.
Java is very similar to C++, I don't think you will have any problems picking it up... going from C++ to Java is incredibly easy; going from Java to C++ is a little more difficult, though not terrible. Java for C++ Programmers does a pretty good job at explaining the differences. Writing your Android code in Java will be more idiomatic and will also make the development process easier for you (as the tooling for the Java Android SDK is significantly better than the corresponding NDK tooling)
In terms of setup, Google provides the Android Studio IDE for both Java and C++ Android development (with Gradle as the build system), but you are free to use whatever IDE or build system you want so long as, under the hood, you are using the Android SDK / NDK to produce the final outputs.
To expand on the answer given by @jsp, you can even evaluate variables in your help text with the $(eval)
function.
The proposed version below has these enhanced properties:
# TARGETDOC:
)So to document, use this form:
RANDOM_VARIABLE := this will be expanded in help text
.PHONY: target1 # Target 1 help with $(RANDOM_VARIABLE)
target1: deps
[... target 1 build commands]
# TARGETDOC: $(BUILDDIR)/real-file.txt # real-file.txt help text
$(BUILDDIR)/real-file.txt:
[... $(BUILDDIR)/real-file.txt build commands]
Then, somewhere in your makefile:
.PHONY: help # Generate list of targets with descriptions
help:
@# find all help in targets and .PHONY and evaluate the embedded variables
$(eval doc_expanded := $(shell grep -E -h '^(.PHONY:|# TARGETDOC:) .* #' $(MAKEFILE_LIST) | sed -E -n 's/(\.PHONY|# TARGETDOC): (.*) # (.*)/\2 \3\\n/'p | expand -t40))
@echo
@echo ' TARGET HELP' | expand -t40
@echo ' ------ ----' | expand -t40
@echo -e ' $(doc_expanded)'
Personally, I found that by opening cmd
as admin then run
python -m pip install mitproxy
seems to fix my problem.
Note:- I installed python through chocolatey
Okay, I realized the answer myself, after I had to think about other people's answers. :P
var htmlContent = ... // a response via AJAX containing HTML
var e = document.createElement('div');
e.setAttribute('style', 'display: none;');
e.innerHTML = htmlContent;
document.body.appendChild(e);
var htmlConvertedIntoDom = e.lastChild.childNodes; // the HTML converted into a DOM element :), now let's remove the
document.body.removeChild(e);
AFAIK the json module was added in version 2.6, see here. I'm guessing you can update your python installation to the latest stable 2.6 from this page.
Please use the below mentioned URL to encrypt string using AES excryption with
key and IV values.
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$email = $_POST["email"];
$pass = $_POST["password"];
$check_email = mysqli_query($conn, "SELECT Email FROM crud where Email = '$email' ");
if(mysqli_num_rows($check_email) > 0){
echo('Email Already exists');
}
else{
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$result = mysqli_query($conn, "INSERT INTO crud (Firstname, Lastname, Email, Password) VALUES ('$firstname', '$lastname', '$email', '$pass')");
}
echo('Record Entered Successfully');
}
None of these seemed to work for me:
@ECHO OFF
REM 1. Initialize our counter
SET /A "c=0"
REM Iterate through a dummy list.
REM Notice how the counter is used: "CALL ECHO %%c%%"
FOR /L %%i in (10,1,20) DO (
REM 2. Increment counter
SET /A "c+=1"
REM 3. Print our counter "%c%" and some dummy data "%%i"
CALL ECHO Line %%c%%: - Data: %%i
)
The answer was extracted from: https://www.tutorialspoint.com/batch_script/batch_script_arrays.htm (Section: Length of an Array)
Result:
Line 1: - Data: 10
Line 2: - Data: 11
Line 3: - Data: 12
Line 4: - Data: 13
Line 5: - Data: 14
Line 6: - Data: 15
Line 7: - Data: 16
Line 8: - Data: 17
Line 9: - Data: 18
Line 10: - Data: 19
Line 11: - Data: 20
While map
is a proper solution to select 'columns' from a list of objects, it has a downside. If not explicitly checked whether or not the columns exists, it'll throw an error and (at best) provide you with undefined
.
I'd opt for a reduce
solution, which can simply ignore the property or even set you up with a default value.
function getFields(list, field) {
// reduce the provided list to an array only containing the requested field
return list.reduce(function(carry, item) {
// check if the item is actually an object and does contain the field
if (typeof item === 'object' && field in item) {
carry.push(item[field]);
}
// return the 'carry' (which is the list of matched field values)
return carry;
}, []);
}
This would work even if one of the items in the provided list is not an object or does not contain the field.
It can even be made more flexible by negotiating a default value should an item not be an object or not contain the field.
function getFields(list, field, otherwise) {
// reduce the provided list to an array containing either the requested field or the alternative value
return list.reduce(function(carry, item) {
// If item is an object and contains the field, add its value and the value of otherwise if not
carry.push(typeof item === 'object' && field in item ? item[field] : otherwise);
// return the 'carry' (which is the list of matched field values)
return carry;
}, []);
}
This would be the same with map, as the length of the returned array would be the same as the provided array. (In which case a map
is slightly cheaper than a reduce
):
function getFields(list, field, otherwise) {
// map the provided list to an array containing either the requested field or the alternative value
return list.map(function(item) {
// If item is an object and contains the field, add its value and the value of otherwise if not
return typeof item === 'object' && field in item ? item[field] : otherwise;
}, []);
}
And then there is the most flexible solution, one which lets you switch between both behaviours simply by providing an alternative value.
function getFields(list, field, otherwise) {
// determine once whether or not to use the 'otherwise'
var alt = typeof otherwise !== 'undefined';
// reduce the provided list to an array only containing the requested field
return list.reduce(function(carry, item) {
// If item is an object and contains the field, add its value and the value of 'otherwise' if it was provided
if (typeof item === 'object' && field in item) {
carry.push(item[field]);
}
else if (alt) {
carry.push(otherwise);
}
// return the 'carry' (which is the list of matched field values)
return carry;
}, []);
}
As the examples above (hopefully) shed some light on the way this works, lets shorten the function a bit by utilising the Array.concat
function.
function getFields(list, field, otherwise) {
var alt = typeof otherwise !== 'undefined';
return list.reduce(function(carry, item) {
return carry.concat(typeof item === 'object' && field in item ? item[field] : (alt ? otherwise : []));
}, []);
}
The above answer is totally true but not working for me.
I solved my problem with the following things.
Actually My XML is like that:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/confirm_order_mail_layout"
android:layout_width="match_parent"
android:layout_height="fill_parent">
<android.support.design.widget.AppBarLayout
android:id="@+id/confirm_order_appbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/confirm_order_list_collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:layout_scrollFlags="scroll|enterAlways">
<android.support.v7.widget.Toolbar
android:id="@+id/confirm_order_toolbar_layout"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
I have tried all the option and after all I just removed CollapsingToolbarLayout
because of i do not need to use in that particular XML
So My Final XML is like:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/confirm_order_mail_layout"
android:layout_width="match_parent"
android:layout_height="fill_parent">
<android.support.design.widget.AppBarLayout
android:id="@+id/confirm_order_appbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/confirm_order_toolbar_layout"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
Now you have to use setTitle()
like above answer:
mActionBarToolbar = (Toolbar) findViewById(R.id.confirm_order_toolbar_layout);
setSupportActionBar(mActionBarToolbar);
getSupportActionBar().setTitle("My Title");
Now If you want to use CollapsingToolbarLayout
and Toolbar
together then you have to use setTitle()
of CollapsingToolbarLayout
CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.confirm_order_mail_layout);
collapsingToolbarLayout.setTitle("My Title");
May it will helps you. Thank you.
Check out strptime in the time module. It is the inverse of strftime.
$ python
>>> import time
>>> my_time = time.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
time.struct_time(tm_year=2005, tm_mon=6, tm_mday=1,
tm_hour=13, tm_min=33, tm_sec=0,
tm_wday=2, tm_yday=152, tm_isdst=-1)
timestamp = time.mktime(my_time)
# convert time object to datetime
from datetime import datetime
my_datetime = datetime.fromtimestamp(timestamp)
# convert time object to date
from datetime import date
my_date = date.fromtimestamp(timestamp)
Even better, use DEFAULT instead of NULL. You want to store the default value, not a NULL that might trigger a default value.
But you'd better name all columns, with a piece of SQL you can create all the INSERT, UPDATE and DELETE's you need. Just check the information_schema and construct the queries you need. There is no need to do it all by hand, SQL can help you out.
Just another viewpoint. Performing an "or" in Prolog can also be done with the "disjunct" operator or semi-colon:
registered(X, Y) :-
X = ct101; X = ct102; X = ct103.
For a fuller explanation:
To add on to Andrea's solution, if you are passing an array of JSONs for instance
[
{"name":"value"},
{"name":"value2"}
]
Then you will need to set up the Spring Boot Controller like so:
@RequestMapping(
value = "/process",
method = RequestMethod.POST)
public void process(@RequestBody Map<String, Object>[] payload)
throws Exception {
System.out.println(payload);
}
If you looking to reset, try this simply:
$('element option').removeAttr('selected');
To set desire value, try like this:
$(element).val('1');
>>> import time
>>> print(time.strftime('%a %H:%M:%S'))
Mon 06:23:14
I think you can use
sys.exit(0)
You may check it here in the python 2.7 doc:
The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like.
If you want to display date time on view without model, just write this:
Date : @DateTime.Now
The output will be:
Date : 16-Aug-17 2:32:10 PM
The possible reason can also be that you have not inherited Controller from ApiController. Happened with me took a while to understand the same.
Application.CutCopyMode = False
In 2010 it is Ctrl+k, Ctrl+d. See image below.
Took me a minute to figure this out so here it is in case it might help someone:
In SQL Server 2012 and better you can use this function:
SELECT DATEFROMPARTS(2013, 8, 19);
Here's how I ended up extracting the parts of the date to put into this function:
select
DATEFROMPARTS(right(cms.projectedInstallDate,4),left(cms.ProjectedInstallDate,2),right( left(cms.ProjectedInstallDate,5),2)) as 'dateFromParts'
from MyTable
You're setting the background of the image to another image. Which is fine, but the foreground (SRC attribute of the IMG) still overlays everything else.
.nkhome{
margin-left:260px;
top:170px;
position:absolute;
}
.nkhome a {
background:url(Images/btnhome.png);
display:block; /* Necessary, since A is not a block element */
width:59px;
height:59px;
}
.nkhome a:hover {
background:url(Images/btnhomeh.png);
}
<div class="nkhome">
<a href="Home.html"></a>
</div>
I wrote two functions to flatten
and unflatten
a JSON object.
var flatten = (function (isArray, wrapped) {
return function (table) {
return reduce("", {}, table);
};
function reduce(path, accumulator, table) {
if (isArray(table)) {
var length = table.length;
if (length) {
var index = 0;
while (index < length) {
var property = path + "[" + index + "]", item = table[index++];
if (wrapped(item) !== item) accumulator[property] = item;
else reduce(property, accumulator, item);
}
} else accumulator[path] = table;
} else {
var empty = true;
if (path) {
for (var property in table) {
var item = table[property], property = path + "." + property, empty = false;
if (wrapped(item) !== item) accumulator[property] = item;
else reduce(property, accumulator, item);
}
} else {
for (var property in table) {
var item = table[property], empty = false;
if (wrapped(item) !== item) accumulator[property] = item;
else reduce(property, accumulator, item);
}
}
if (empty) accumulator[path] = table;
}
return accumulator;
}
}(Array.isArray, Object));
Performance:
function unflatten(table) {
var result = {};
for (var path in table) {
var cursor = result, length = path.length, property = "", index = 0;
while (index < length) {
var char = path.charAt(index);
if (char === "[") {
var start = index + 1,
end = path.indexOf("]", start),
cursor = cursor[property] = cursor[property] || [],
property = path.slice(start, end),
index = end + 1;
} else {
var cursor = cursor[property] = cursor[property] || {},
start = char === "." ? index + 1 : index,
bracket = path.indexOf("[", start),
dot = path.indexOf(".", start);
if (bracket < 0 && dot < 0) var end = index = length;
else if (bracket < 0) var end = index = dot;
else if (dot < 0) var end = index = bracket;
else var end = index = bracket < dot ? bracket : dot;
var property = path.slice(start, end);
}
}
cursor[property] = table[path];
}
return result[""];
}
Performance:
Flatten and unflatten a JSON object:
Overall my solution performs either equally well or even better than the current solution.
Performance:
Output format:
A flattened object uses the dot notation for object properties and the bracket notation for array indices:
{foo:{bar:false}} => {"foo.bar":false}
{a:[{b:["c","d"]}]} => {"a[0].b[0]":"c","a[0].b[1]":"d"}
[1,[2,[3,4],5],6] => {"[0]":1,"[1][0]":2,"[1][1][0]":3,"[1][1][1]":4,"[1][2]":5,"[2]":6}
In my opinion this format is better than only using the dot notation:
{foo:{bar:false}} => {"foo.bar":false}
{a:[{b:["c","d"]}]} => {"a.0.b.0":"c","a.0.b.1":"d"}
[1,[2,[3,4],5],6] => {"0":1,"1.0":2,"1.1.0":3,"1.1.1":4,"1.2":5,"2":6}
Advantages:
Disadvantages:
The current JSFiddle demo gave the following values as output:
Nested : 132175 : 63
Flattened : 132175 : 564
Nested : 132175 : 54
Flattened : 132175 : 508
My updated JSFiddle demo gave the following values as output:
Nested : 132175 : 59
Flattened : 132175 : 514
Nested : 132175 : 60
Flattened : 132175 : 451
I'm not really sure what that means, so I'll stick with the jsPerf results. After all jsPerf is a performance benchmarking utility. JSFiddle is not.
I think the main difference I can describe relates to record oriented vs. column oriented formats. Record oriented formats are what we're all used to -- text files, delimited formats like CSV, TSV. AVRO is slightly cooler than those because it can change schema over time, e.g. adding or removing columns from a record. Other tricks of various formats (especially including compression) involve whether a format can be split -- that is, can you read a block of records from anywhere in the dataset and still know it's schema? But here's more detail on columnar formats like Parquet.
Parquet, and other columnar formats handle a common Hadoop situation very efficiently. It is common to have tables (datasets) having many more columns than you would expect in a well-designed relational database -- a hundred or two hundred columns is not unusual. This is so because we often use Hadoop as a place to denormalize data from relational formats -- yes, you get lots of repeated values and many tables all flattened into a single one. But it becomes much easier to query since all the joins are worked out. There are other advantages such as retaining state-in-time data. So anyway it's common to have a boatload of columns in a table.
Let's say there are 132 columns, and some of them are really long text fields, each different column one following the other and use up maybe 10K per record.
While querying these tables is easy with SQL standpoint, it's common that you'll want to get some range of records based on only a few of those hundred-plus columns. For example, you might want all of the records in February and March for customers with sales > $500.
To do this in a row format the query would need to scan every record of the dataset. Read the first row, parse the record into fields (columns) and get the date and sales columns, include it in your result if it satisfies the condition. Repeat. If you have 10 years (120 months) of history, you're reading every single record just to find 2 of those months. Of course this is a great opportunity to use a partition on year and month, but even so, you're reading and parsing 10K of each record/row for those two months just to find whether the customer's sales are > $500.
In a columnar format, each column (field) of a record is stored with others of its kind, spread all over many different blocks on the disk -- columns for year together, columns for month together, columns for customer employee handbook (or other long text), and all the others that make those records so huge all in their own separate place on the disk, and of course columns for sales together. Well heck, date and months are numbers, and so are sales -- they are just a few bytes. Wouldn't it be great if we only had to read a few bytes for each record to determine which records matched our query? Columnar storage to the rescue!
Even without partitions, scanning the small fields needed to satisfy our query is super-fast -- they are all in order by record, and all the same size, so the disk seeks over much less data checking for included records. No need to read through that employee handbook and other long text fields -- just ignore them. So, by grouping columns with each other, instead of rows, you can almost always scan less data. Win!
But wait, it gets better. If your query only needed to know those values and a few more (let's say 10 of the 132 columns) and didn't care about that employee handbook column, once it had picked the right records to return, it would now only have to go back to the 10 columns it needed to render the results, ignoring the other 122 of the 132 in our dataset. Again, we skip a lot of reading.
(Note: for this reason, columnar formats are a lousy choice when doing straight transformations, for example, if you're joining all of two tables into one big(ger) result set that you're saving as a new table, the sources are going to get scanned completely anyway, so there's not a lot of benefit in read performance, and because columnar formats need to remember more about the where stuff is, they use more memory than a similar row format).
One more benefit of columnar: data is spread around. To get a single record, you can have 132 workers each read (and write) data from/to 132 different places on 132 blocks of data. Yay for parallelization!
And now for the clincher: compression algorithms work much better when it can find repeating patterns. You could compress AABBBBBBCCCCCCCCCCCCCCCC
as 2A6B16C
but ABCABCBCBCBCCCCCCCCCCCCCC
wouldn't get as small (well, actually, in this case it would, but trust me :-) ). So once again, less reading. And writing too.
So we read a lot less data to answer common queries, it's potentially faster to read and write in parallel, and compression tends to work much better.
Columnar is great when your input side is large, and your output is a filtered subset: from big to little is great. Not as beneficial when the input and outputs are about the same.
But in our case, Impala took our old Hive queries that ran in 5, 10, 20 or 30 minutes, and finished most in a few seconds or a minute.
Hope this helps answer at least part of your question!
You can refresh using JavaScript. Rather than the complete page refresh, you can give the contents to be refreshed in a div. Then by using JavaScript you can refresh that particular div only, and it works faster than the complete page refresh.
/*
If your delimiters are slash-based, escape it:
\/*
*
means "0 or more of the previous repeatable pattern", which can be a single character, a character class or a group.
Is something along these lines what you are looking for?
x1 = function(x){
mu = mean(x)
l1 = list(s1=table(x),std=sd(x))
return(list(l1,mu))
}
library(Ecdat)
data(Fair)
x1(Fair$age)
You can try MIMEText
msg = MIMEText('text')
msg['to'] =
msg['cc'] =
then send msg.as_string()
To be pedantic, it's probably not good to hardcode either / or \ as the path separator. Maybe this would be best?
mypath = os.path.join('c:%s' % os.sep, 'sourcedir')
or
mypath = os.path.join('c:' + os.sep, 'sourcedir')
Also, your compare function is incorrect. It needs to return -1, 0, or 1, not a boolean as you have it. The correct compare function would be:
def compare(item1, item2):
if fitness(item1) < fitness(item2):
return -1
elif fitness(item1) > fitness(item2):
return 1
else:
return 0
# Calling
list.sort(key=compare)
Or you can use:
echo "1: " | awk '/1/{print $1-":"}'
This is a really funny equation.
The user that is running your web server does not have permissions to write to the directory that Wordpress is intending to create the plugin directory in. You should chown the directory in question to the user that is running Wordpress. It is most likely not root.
In short, this is a permissions issue. Your touch command is working because you're using it as root, and root has global permissions to write wherever it wants.
Session.Abandon()
destroys the session and the Session_OnEnd event is triggered.
Session.Clear()
just removes all values (content) from the Object. The session with the same key is still alive.
So, if you use Session.Abandon()
, you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.
Use Session.Clear()
, if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.
I'm guessing the reason you're asking is performance? There's the instr function. But that's likely to work pretty much the same behind the scenes.
Maybe you could look into full text search.
As last resorts you'd be looking at caching or precomputed columns/an indexed view.
in eloquent you can use this
$users = User::select('name')->groupBy('name')->get()->toArray() ;
groupBy is actually fetching the distinct values, in fact the groupBy will categorize the same values, so that we can use aggregate functions on them. but in this scenario we have no aggregate functions, we are just selecting the value which will cause the result to have distinct values
After you extract your "selenium-java-.zip" file you need to configure your build path from your IDE. Import all the jar files under "lib" folder and both selenium standalone server & Selenium java version jar files.
I think the problem is the realpath of the file. For example your script is working on './', your file is inside the directory './xml'. So better check if the file exists or not, before you get filemtime or unlink it:
function deleteOldFiles(){
if ($handle = opendir('./xml')) {
while (false !== ($file = readdir($handle))) {
if(preg_match("/^.*\.(xml|xsl)$/i", $file)){
$fpath = 'xml/'.$file;
if (file_exists($fpath)) {
$filelastmodified = filemtime($fpath);
if ( (time() - $filelastmodified ) > 24*3600){
unlink($fpath);
}
}
}
}
closedir($handle);
}
}
Even though you asked for wait()
and notify()
specifically, I feel that this quote is still important enough:
Josh Bloch, Effective Java 2nd Edition, Item 69: Prefer concurrency utilities to wait
and notify
(emphasis his):
Given the difficulty of using
wait
andnotify
correctly, you should use the higher-level concurrency utilities instead [...] usingwait
andnotify
directly is like programming in "concurrency assembly language", as compared to the higher-level language provided byjava.util.concurrent
. There is seldom, if ever, reason to usewait
andnotify
in new code.
I changed the permission of my .ssh/id_rsa (private key) to 604. chmod 700 id_rsa
If you are using PHP >= 5.1.0 Just do something like this with the ErrorException class:
<?php
// Define an error handler
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
// Set your error handler
set_error_handler("exception_error_handler");
/* Trigger exception */
try
{
// Try to do something like finding the end of the internet
}
catch(ErrorException $e)
{
// Anything you want to do with $e
}
?>
If array
is truly an array, then you can "zero it out" with:
memset(array, 0, sizeof array);
But there are two points you should know:
array
is really a "two-d array", i.e., was declared T array[M][N];
for some type T
.array
was declared. If you pass it to a function, then the name array
decays to a pointer, and sizeof
will not give you the size of the array.Let's do an experiment:
#include <stdio.h>
void f(int (*arr)[5])
{
printf("f: sizeof arr: %zu\n", sizeof arr);
printf("f: sizeof arr[0]: %zu\n", sizeof arr[0]);
printf("f: sizeof arr[0][0]: %zu\n", sizeof arr[0][0]);
}
int main(void)
{
int arr[10][5];
printf("main: sizeof arr: %zu\n", sizeof arr);
printf("main: sizeof arr[0]: %zu\n", sizeof arr[0]);
printf("main: sizeof arr[0][0]: %zu\n\n", sizeof arr[0][0]);
f(arr);
return 0;
}
On my machine, the above prints:
main: sizeof arr: 200
main: sizeof arr[0]: 20
main: sizeof arr[0][0]: 4
f: sizeof arr: 8
f: sizeof arr[0]: 20
f: sizeof arr[0][0]: 4
Even though arr
is an array, it decays to a pointer to its first element when passed to f()
, and therefore the sizes printed in f()
are "wrong". Also, in f()
the size of arr[0]
is the size of the array arr[0]
, which is an "array [5] of int
". It is not the size of an int *
, because the "decaying" only happens at the first level, and that is why we need to declare f()
as taking a pointer to an array of the correct size.
So, as I said, what you were doing originally will work only if the two conditions above are satisfied. If not, you will need to do what others have said:
memset(array, 0, m*n*sizeof array[0][0]);
Finally, memset()
and the for
loop you posted are not equivalent in the strict sense. There could be (and have been) compilers where "all bits zero" does not equal zero for certain types, such as pointers and floating-point values. I doubt that you need to worry about that though.
I'm not crazy about the other answers here; they're too vague and abstract for me. I think more in stories. Here's my attempt at a better answer.
Let's say it's 1985 and you write a short BASIC program on an Apple II:
] 10 PRINT "HELLO WORLD!"
] 20 GOTO 10
So far, your program is just source code. It's not running, and we would say there is no "runtime" involved with it.
But now I run it:
] RUN
How is it actually running? How does it know how to send the string parameter from PRINT
to the physical screen? I certainly didn't provide any system information in my code, and PRINT
itself doesn't know anything about my system.
Instead, RUN
is actually a program itself -- its code tells it how to parse my code, how to execute it, and how to send any relevant requests to the computer's operating system. The RUN
program provides the "runtime" environment that acts as a layer between the operating system and my source code. The operating system itself acts as part of this "runtime", but we usually don't mean to include it when we talk about a "runtime" like the RUN
program.
In some languages, your source code must be compiled before it can be run. Some languages compile your code into machine language -- it can be run by your operating system directly. This compiled code is often called "binary" (even though every other kind of file is also in binary :).
In this case, there is still a minimal "runtime" involved -- but that runtime is provided by the operating system itself. The compile step means that many statements that would cause your program to crash are detected before the code is ever run.
C is one such language; when you run a C program, it's totally able to send illegal requests to the operating system (like, "give me control of all of the memory on the computer, and erase it all"). If an illegal request is hit, usually the OS will just kill your program and not tell you why, and dump the contents of that program's memory at the time it was killed to a .dump
file that's pretty hard to make sense of. But sometimes your code has a command that is a very bad idea, but the OS doesn't consider it illegal, like "erase a random bit of memory this program is using"; that can cause super weird problems that are hard to get to the bottom of.
Other languages compile your code into a language that the operating system can't read directly, but a specific runtime program can read your compiled code. This compiled code is often called "bytecode".
The more elaborate this runtime program is, the more extra stuff it can do on the side that your code did not include (even in the libraries you use) -- for instance, the Java runtime environment ("JRE") can keep track of memory assignments that are no longer needed, and tell the operating system it's safe to reuse that memory for something else, and it can catch situations where your code would try to send an illegal request to the operating system, and instead exit with a readable error.
All of this overhead makes them slower than compiled binary languages, but it makes the runtime powerful and flexible; in some cases, it can even pull in other code after it starts running, without having to start over. The compile step means that many statements that would cause your program to crash are detected before the code is ever run; and the powerful runtime can keep your code from doing stupid things (e.g., you can't "erase a random bit of memory this program is using").
Still other languages don't precompile your code at all; the runtime does all of the work of reading your code line by line, interpreting it and executing it. This makes them even slower than "bytecode" languages, but also even more flexible; in some cases, you can even fiddle with your source code as it runs! Though it also means that you can have a totally illegal statement in your code, and it could sit there in your production code without drawing attention, until one day it is run and causes a crash.
These are generally called "scripting" languages; they include Javascript, Python, Perl, and PHP. Some of these provide cases where you can choose to compile the code to improve its speed (e.g., Javascript's WebAssembly project, and Python's trans-compilation to C code). So Javascript can allow users on a website to see the exact code that is running, since their browser is providing the runtime.
This flexibility also allows for innovations in runtime environments, like node.js, which is both a code library and a runtime environment that can run your Javascript code as a server, which involves behaving very differently than if you tried to run the same code on a browser.
As usually, there are multiple ways of doing the same thing but I would avoid using Number.prototype.toLocaleString
since it can return different values based on the user settings.
I also don't recommend extending the Number.prototype
- extending native objects prototypes is a bad practice since it can cause conflicts with other people code (e.g. libraries/frameworks/plugins) and may not be compatible with future JavaScript implementations/versions.
I believe that Regular Expressions are the best approach for the problem, here is my implementation:
/**
* Converts number into currency format
* @param {number} number Number that should be converted.
* @param {string} [decimalSeparator] Decimal separator, defaults to '.'.
* @param {string} [thousandsSeparator] Thousands separator, defaults to ','.
* @param {int} [nDecimalDigits] Number of decimal digits, defaults to `2`.
* @return {string} Formatted string (e.g. numberToCurrency(12345.67) returns '12,345.67')
*/
function numberToCurrency(number, decimalSeparator, thousandsSeparator, nDecimalDigits){
//default values
decimalSeparator = decimalSeparator || '.';
thousandsSeparator = thousandsSeparator || ',';
nDecimalDigits = nDecimalDigits == null? 2 : nDecimalDigits;
var fixed = number.toFixed(nDecimalDigits), //limit/add decimal digits
parts = new RegExp('^(-?\\d{1,3})((?:\\d{3})+)(\\.(\\d{'+ nDecimalDigits +'}))?$').exec( fixed ); //separate begin [$1], middle [$2] and decimal digits [$4]
if(parts){ //number >= 1000 || number <= -1000
return parts[1] + parts[2].replace(/\d{3}/g, thousandsSeparator + '$&') + (parts[4] ? decimalSeparator + parts[4] : '');
}else{
return fixed.replace('.', decimalSeparator);
}
}
edited on 2010/08/30: added option to set number of decimal digits. edited on 2011/08/23: added option to set number of decimal digits to zero.
After years of using XAMPP finally I've given up, and started looking for alternatives. XAMPP has not received any updates for quite a while and it kept breaking down once every two weeks.
The one I've just found and I could absolutely recommend is The Uniform Server
It's really frequently updated, has much more emphasis on security and looks like a much more mature project compared to XAMPP.
They have a wiki where they list all the latest versions of packages. As the time of writing, their newest release is only 4 days old!
Versions in Uniform Server as of today:
Versions in XAMPP as of today:
Use ng-click
in place of onclick
. and its as simple as that:
<a href="www.mysite.com" ng-click="return theFunction();">Item</a>
<script type="text/javascript">
function theFunction () {
// return true or false, depending on whether you want to allow
// the`href` property to follow through or not
}
</script>
It took me a while to combine everything, make it a bit secure, and have it work with Gmail. I hope this answer saves someone some time.
Create a file with the encrypted server password:
In Powershell, enter the following command (replace myPassword with your actual password):
"myPassword" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\EmailPassword.txt"
Create a powershell script (Ex. sendEmail.ps1):
$User = "[email protected]"
$File = "C:\EmailPassword.txt"
$cred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $File | ConvertTo-SecureString)
$EmailTo = "[email protected]"
$EmailFrom = "[email protected]"
$Subject = "Email Subject"
$Body = "Email body text"
$SMTPServer = "smtp.gmail.com"
$filenameAndPath = "C:\fileIwantToSend.csv"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($cred.UserName, $cred.Password);
$SMTPClient.Send($SMTPMessage)
Automate with Task Scheduler:
Create a batch file (Ex. emailFile.bat) with the following:
powershell -ExecutionPolicy ByPass -File C:\sendEmail.ps1
Create a task to run the batch file. Note: you must have the task run with the same user account that you used to encrypted the password! (Aka, probably the logged in user)
That's all; you now have a way to automate and schedule sending an email and an attachment with Windows Task Scheduler and Powershell. No 3rd party software and the password is not stored as plain text (though granted, not terribly secure either).
You can also read this article on the level of security this provides for your email password.
There are detailed notes on this that helped me completely, located here.
Jonathon Reinhart has already answered with the key bit, to edit /etc/gitlab/gitlab.rb, alter the external_url and then run sudo gitlab-ctl reconfigure; sudo gitlab-ctl restart
However I needed to go a bit further and docs I linked above explained it. So what I ended up with looks like:
external_url 'https://gitlab.toilethumor.com'
nginx['ssl_certificate'] = "/www/ssl/star_toilethumor.com-chained.crt"
nginx['ssl_certificate_key'] = "/www/ssl/star_toilethumor.com.key"
nginx['proxy_set_headers'] = {
"X-Forwarded-Proto" => "http",
"CUSTOM_HEADER" => "VALUE"
}
Above, I've explicitly declared where my SSL goodies are on this server. And that's of course followed by
sudo gitlab-ctl reconfigure
sudo gitlab-ctl restart
Also, when you switch the omnibus package to https, the bundled nginx will only serve on port 443. Since all my stuff is reached via reverse proxy, this part was potentially significant.
As I went through this, I screwed something up and it helpful to find the actual nginx logs, this lead me there:
sudo gitlab-ctl tail nginx
You just have to ask for the legend once, outside of your loop.
For example, in this case I have 4 subplots, with the same lines, and a single legend.
from matplotlib.pyplot import *
ficheiros = ['120318.nc', '120319.nc', '120320.nc', '120321.nc']
fig = figure()
fig.suptitle('concentration profile analysis')
for a in range(len(ficheiros)):
# dados is here defined
level = dados.variables['level'][:]
ax = fig.add_subplot(2,2,a+1)
xticks(range(8), ['0h','3h','6h','9h','12h','15h','18h','21h'])
ax.set_xlabel('time (hours)')
ax.set_ylabel('CONC ($\mu g. m^{-3}$)')
for index in range(len(level)):
conc = dados.variables['CONC'][4:12,index] * 1e9
ax.plot(conc,label=str(level[index])+'m')
dados.close()
ax.legend(bbox_to_anchor=(1.05, 0), loc='lower left', borderaxespad=0.)
# it will place the legend on the outer right-hand side of the last axes
show()
Or, you may exclude the options in quotes:
FOR /F %%i IN (myfile.txt) DO ECHO %%i
So what will happen if two threads attack a volatile primitive variable at same time?
Usually each one can increment the value. However sometime, both will update the value at the same time and instead of incrementing by 2 total, both thread increment by 1 and only 1 is added.
Does this mean that whosoever takes lock on it, that will be setting its value first.
There is no lock. That is what synchronized
is for.
And in if meantime, some other thread comes up and read old value while first thread was changing its value, then doesn't new thread will read its old value?
Yes,
What is the difference between Atomic and volatile keyword?
AtomicXxxx wraps a volatile so they are basically same, the difference is that it provides higher level operations such as CompareAndSwap which is used to implement increment.
AtomicXxxx also supports lazySet. This is like a volatile set, but doesn't stall the pipeline waiting for the write to complete. It can mean that if you read a value you just write you might see the old value, but you shouldn't be doing that anyway. The difference is that setting a volatile takes about 5 ns, bit lazySet takes about 0.5 ns.
Prompt% cat t1
This is "Unix"
This is "Unix sed"
Prompt% sed -i 's/\"Unix\"/\"Linux\"/g' t1
Prompt% sed -i 's/\"Unix sed\"/\"Linux SED\"/g' t1
Prompt% cat t1
This is "Linux"
This is "Linux SED"
Prompt%
It is much better to use
$value = mb_convert_encode($value,'HTML-ENTITIES','UTF-8');
Specially when you are using AJAX call for submitting 'ISO-8859-1' characters. It works for Chinese, Japanese, Czech, German and many more languages.
Yet another reason: fragility.
If you have a class, most people expect to be able to create it and use it at will.
You can document it's not the case, or protect against it (singleton/factory pattern) - but that's extra work, and therefore an additional cost. Even then, in a big company, chances are someone will try at some point to use your class without fully paying attention to all the nice comments or the factory.
If you're using static variables a lot, that will break. Bugs are expensive.
Between a .0001% performance improvement and robustness to change by potentially clueless developers, in a lot of cases robustness is the good choice.
Assuming a string 's'
palin = lambda s: s[:(len(s)/2 + (0 if len(s)%2==0 else 1)):1] == s[:len(s)/2-1:-1]
# Test
palin('654456') # True
palin('malma') # False
palin('ab1ba') # True
Downloaded Eclipse Luna and installed WTP using http://download.eclipse.org/webtools/repository/luna
Downloaded Tomcat 8 and configured new server in Eclipse. I am able to setup tomcat 8 now in Eclipse luna
You've simply got it backwards. Specifying a minimum width would make the select menu always be at least that width, so it will continue expanding to 90% no matter what the window size is, also being at least the size of its longest option.
You need to use max-width
instead. This way, it will let the select menu expand to its longest option, but if that expands past your set maximum of 90% width, crunch it down to that width.
If Clean/Rebuild Project doesn't work try to check our package name in AndroidManifest.xml.
The problem "R cannot be resolved" happens when you change your package name in the AndroidManifest.xml file. It uses your Android package name to create a subdirectory under the "gen" directory where it stores the R.java file.
I came up with a mix of defining a class like David's answer, but not requiring a Where class to go with it. It looks something like:
var resultsGroupings = resultsRecords.GroupBy(r => new { r.IdObj1, r.IdObj2, r.IdObj3})
.Select(r => new ResultGrouping {
IdObj1= r.Key.IdObj1,
IdObj2= r.Key.IdObj2,
IdObj3= r.Key.IdObj3,
Results = r.ToArray(),
Count = r.Count()
});
private class ResultGrouping
{
public short IdObj1{ get; set; }
public short IdObj2{ get; set; }
public int IdObj3{ get; set; }
public ResultCsvImport[] Results { get; set; }
public int Count { get; set; }
}
Where resultRecords
is my initial list I'm grouping, and its a List<ResultCsvImport>
. Note that the idea here to is that, I'm grouping by 3 columns, IdObj1 and IdObj2 and IdObj3
If you already have filled columns and have added new one or you want to fill out old column with new mock values , do this:
public function up()
{
DB::table('foydabars')->update(
array(
'status' => '0'
)
);
}
Seems like the problem is with the date format.
var d = "17-09-2013 10:08",
dArr = d.split('-'),
ts = new Date(dArr[1] + "-" + dArr[0] + "-" + dArr[2]).getTime(); // 1379392680000
This answer is not exactly what you want, but it might be useful in some cases. If you know the element has some dimensions when displayed, you can also use this:
var hasDisplayNone = (element.offsetHeight === 0 && element.offsetWidth === 0);
EDIT: Why this might be better than direct check of CSS display
property? Because you do not need to check all parent elements. If some parent element has display: none
, its children are hidden too but still has element.style.display !== 'none'
.
SUMIF didn't worked for me, had to use SUMIFS.
=SUMIFS(TableAmount,TableMonth,"January")
TableAmount is the table to sum the values, TableMonth the table where we search the condition and January, of course, the condition to meet.
Hope this can help someone!
List membersList = Arrays.asList(membersArray);
returns immutable list, what you need to do is
new ArrayList<>(Arrays.asList(membersArray)); to make it mutable
public void clearData() {
mylist.removeAll(mylist);
mAdapter.notifyDataSetChanged();
recyclerView.setAdapter(mAdapter);
}
The following main steps are required to achieve a secured connection from Certification Authorities which are not considered as trusted by the android platform.
As requested by many users, I've mirrored the most important parts from my blog article here:
java.net.ssl.HttpsURLConnection
(easier to understand, more performant)You have to obtain all certificates that build a chain from the endpoint certificate the whole way up to the Root CA. This means, any (if present) Intermediate CA certs and also the Root CA cert. You don’t need to obtain the endpoint certificate.
Download the BouncyCastle Provider and store it to a known location. Also ensure that you can invoke the keytool command (usually located under the bin folder of your JRE installation).
Now import the obtained certs (don’t import the endpoint cert) into a BouncyCastle formatted keystore.
I didn’t test it, but I think the order of importing the certificates is important. This means, import the lowermost Intermediate CA certificate first and then all the way up to the Root CA certificate.
With the following command a new keystore (if not already present) with the password mysecret will be created and the Intermediate CA certificate will be imported. I also defined the BouncyCastle provider, where it can be found on my file system and the keystore format. Execute this command for each certificate in the chain.
keytool -importcert -v -trustcacerts -file "path_to_cert/interm_ca.cer" -alias IntermediateCA -keystore "res/raw/mykeystore.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "path_to_bouncycastle/bcprov-jdk16-145.jar" -storetype BKS -storepass mysecret
Verify if the certificates were imported correctly into the keystore:
keytool -list -keystore "res/raw/mykeystore.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "path_to_bouncycastle/bcprov-jdk16-145.jar" -storetype BKS -storepass mysecret
Should output the whole chain:
RootCA, 22.10.2010, trustedCertEntry, Thumbprint (MD5): 24:77:D9:A8:91:D1:3B:FA:88:2D:C2:FF:F8:CD:33:93
IntermediateCA, 22.10.2010, trustedCertEntry, Thumbprint (MD5): 98:0F:C3:F8:39:F7:D8:05:07:02:0D:E3:14:5B:29:43
Now you can copy the keystore as a raw resource in your android app under res/raw/
First of all we have to create a custom Apache HttpClient that uses our keystore for HTTPS connections:
import org.apache.http.*
public class MyHttpClient extends DefaultHttpClient {
final Context context;
public MyHttpClient(Context context) {
this.context = context;
}
@Override
protected ClientConnectionManager createClientConnectionManager() {
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
// Register for port 443 our SSLSocketFactory with our keystore
// to the ConnectionManager
registry.register(new Scheme("https", newSslSocketFactory(), 443));
return new SingleClientConnManager(getParams(), registry);
}
private SSLSocketFactory newSslSocketFactory() {
try {
// Get an instance of the Bouncy Castle KeyStore format
KeyStore trusted = KeyStore.getInstance("BKS");
// Get the raw resource, which contains the keystore with
// your trusted certificates (root and any intermediate certs)
InputStream in = context.getResources().openRawResource(R.raw.mykeystore);
try {
// Initialize the keystore with the provided trusted certificates
// Also provide the password of the keystore
trusted.load(in, "mysecret".toCharArray());
} finally {
in.close();
}
// Pass the keystore to the SSLSocketFactory. The factory is responsible
// for the verification of the server certificate.
SSLSocketFactory sf = new SSLSocketFactory(trusted);
// Hostname verification from certificate
// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
return sf;
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
We have created our custom HttpClient, now we can use it for secure connections. For example when we make a GET call to a REST resource:
// Instantiate the custom HttpClient
DefaultHttpClient client = new MyHttpClient(getApplicationContext());
HttpGet get = new HttpGet("https://www.mydomain.ch/rest/contacts/23");
// Execute the GET call and obtain the response
HttpResponse getResponse = client.execute(get);
HttpEntity responseEntity = getResponse.getEntity();
That's it ;)
You can use array_agg
function for that:
SELECT "Movie",
array_to_string(array_agg(distinct "Actor"),',') AS Actor
FROM Table1
GROUP BY "Movie";
Result:
MOVIE | ACTOR |
---|---|
A | 1,2,3 |
B | 4 |
See this SQLFiddle
For more See 9.18. Aggregate Functions
Let maven generate a batch file to start your application. This is the simplest way to this.
You can use the appassembler-maven-plugin for such purposes.
I just wanted to add to Alper's answer what I had to do to get this stuff working:
On Mac, you'll need brew install coreutils
, so we can use gdate
. Otherwise on Linux, it's just date
. And this function will help you time commands without having to create temporary files or anything:
function timeit() {
start=`gdate +%s%N`
bash -c $1
end=`gdate +%s%N`
runtime=$(((end-start)/1000000000.0))
echo " seconds"
}
And you can use it with a string:
timeit 'tsc --noEmit'
ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));
why do u want to write a code like this? If you have a class 'ReportClass' is available, you can instantiate it directly as shown below.
ReportClass report = new ReportClass();
The code ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));
is used when you dont have the necessary class available, but you want to instantiate and or or invoke a method dynamically.
I mean it is useful when u know the assembly but while writing the code you dont have the class ReportClass
available.