Use MyISAM for very unimportant data or if you really need those minimal performance advantages. The read performance is not better in every case for MyISAM.
I would personally never use MyISAM at all anymore. Choose InnoDB and throw a bit more hardware if you need more performance. Another idea is to look at database systems with more features like PostgreSQL if applicable.
EDIT: For the read-performance, this link shows that innoDB often is actually not slower than MyISAM: https://www.percona.com/blog/2007/01/08/innodb-vs-myisam-vs-falcon-benchmarks-part-1/
In general case you need to compare DateTimes
with the same Kind
:
if (date1.ToUniversalTime() < date2.ToUniversalTime())
Console.WriteLine("date1 is earlier than date2");
Explanation from MSDN about DateTime.Compare
(This is also relevant for operators like >
, <
, ==
and etc.):
To determine the relationship of t1 to t2, the Compare method compares the Ticks property of t1 and t2 but ignores their Kind property. Before comparing DateTime objects, ensure that the objects represent times in the same time zone.
Thus, a simple comparison may give an unexpected result when dealing with DateTimes
that are represented in different timezones.
Execute in a terminal:
mongo // To go to shell
show databases // To show all existing databases.
use <DATA_BASE> // To switch to the wanted database.
db.dropDatabase() // To remove the current database.
app = Celery('proj',
broker='amqp://',
backend='amqp://',
include=['proj.tasks'])
please include=['proj.tasks'] You need go to the top dir, then exec this
celery -A app.celery_module.celeryapp worker --loglevel=info
not
celery -A celeryapp worker --loglevel=info
in your celeryconfig.py input imports = ("path.ptah.tasks",)
please in other module invoke task!!!!!!!!
Hope this can help you.
I can offer only an example of the layout solution already pointed out.
layout(matrix(c(1,2), nrow = 1), widths = c(0.7, 0.3))
par(mar = c(5, 4, 4, 2) + 0.1)
plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")
par(mar = c(5, 0, 4, 2) + 0.1)
plot(1:3, rnorm(3), pch = 1, lty = 1, ylim=c(-2,2), type = "n", axes = FALSE, ann = FALSE)
legend(1, 1, c("group A", "group B"), pch = c(1,2), lty = c(1,2))
You can try below code:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim j As Integer = 0
Dim hfc As HttpFileCollection = Request.Files
Dim PathName As String
For i As Integer = 0 To hfc.Count - 1
Dim hpf As HttpPostedFile = hfc(i)
If hpf.ContentLength > 0 Then
hpf.SaveAs(Server.MapPath("~/E:\") & System.IO.Path.GetFileName(hpf.FileName))
PathName = Server.MapPath(hpf.FileName)
If j < hfc.Count Then
Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim sqlquery As String
sqlquery = "Insert_proc"
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand(sqlquery, con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("@FilePath", SqlDbType.VarChar).Value = PathName
j = j + 1
Try
con.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Throw ex
Finally
con.Close()
con.Dispose()
End Try
If j = hfc.Count Then
Exit Sub
End If
End If
End If
Next
Catch generatedExceptionName As Exception
Throw
End Try
End Sub
I deleted the entire Config folder but preserved the files repositories.yml repository-cache repository-grouping.yml. after running SmartGit, it created the config folder (i think it used the config from an older build (to save things like my git credentials)), then i copied back my three files and i had all my repositories which is the most important info i needed.
This can be done in java 8 using Stream.
import java.util.stream.Stream;
String[] stringList = {"Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue"};
boolean contains = Stream.of(stringList).anyMatch(x -> x.equals(say.getText());
Communication between controllers is done though $emit
+ $on
/ $broadcast
+ $on
methods.
So in your case you want to call a method of Controller "One" inside Controller "Two", the correct way to do this is:
app.controller('One', ['$scope', '$rootScope'
function($scope) {
$rootScope.$on("CallParentMethod", function(){
$scope.parentmethod();
});
$scope.parentmethod = function() {
// task
}
}
]);
app.controller('two', ['$scope', '$rootScope'
function($scope) {
$scope.childmethod = function() {
$rootScope.$emit("CallParentMethod", {});
}
}
]);
While $rootScope.$emit
is called, you can send any data as second parameter.
you can always convert your varchar-column to bigint as integer might be too short...
select cast([yourvarchar] as BIGINT)
but you should always care for alpha characters
where ISNUMERIC([yourvarchar] +'e0') = 1
the +'e0' comes from http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/isnumeric-isint-isnumber
this would lead to your statement
SELECT
*
FROM
Table
ORDER BY
ISNUMERIC([yourvarchar] +'e0') DESC
, LEN([yourvarchar]) ASC
the first sorting column will put numeric on top. the second sorts by length, so 10 will preceed 0001 (which is stupid?!)
this leads to the second version:
SELECT
*
FROM
Table
ORDER BY
ISNUMERIC([yourvarchar] +'e0') DESC
, RIGHT('00000000000000000000'+[yourvarchar], 20) ASC
the second column now gets right padded with '0', so natural sorting puts integers with leading zeros (0,01,10,0100...) in correct order (correct!) - but all alphas would be enhanced with '0'-chars (performance)
so third version:
SELECT
*
FROM
Table
ORDER BY
ISNUMERIC([yourvarchar] +'e0') DESC
, CASE WHEN ISNUMERIC([yourvarchar] +'e0') = 1
THEN RIGHT('00000000000000000000' + [yourvarchar], 20) ASC
ELSE LTRIM(RTRIM([yourvarchar]))
END ASC
now numbers first get padded with '0'-chars (of course, the length 20 could be enhanced) - which sorts numbers right - and alphas only get trimmed
The answers like the one from @mark-wilkins using \ to continue lines and ; to terminate them in the shell or like the ones from @kenorb changing this to one line are good and will fix this problem.
there's a simpler answer to the original problem (as @alexey-polonsky pointed out). Use the -f flag to rm so that it won't trigger an error
rm -f myApp
this is simpler, faster and more reliable. Just be careful not to end up with a slash and an empty variable
rm -f /$(myAppPath) #NEVER DO THIS
you might end up deleting your system.
XCode 8.1, Swift 3
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
UISegmentedControl.appearance().setTitleTextAttributes(NSDictionary(objects: [UIFont.systemFont(ofSize: 24.0)],
forKeys: [NSFontAttributeName as NSCopying]) as? [AnyHashable : Any],
for: UIControlState.normal)
}
}
just change the number value (ofSize: 24.0)
Try this query it ll change the records ends with .com
UPDATE tablename SET email = replace(email, '.com', '.org') WHERE email LIKE '%.com';
It seems that your action needs k
but ModelBinder can not find it (from form, or request or view data or ..)
Change your action to this:
public ActionResult DetailsData(int? k)
{
EmployeeContext Ec = new EmployeeContext();
if (k != null)
{
Employee emp = Ec.Employees.Single(X => X.EmpId == k.Value);
return View(emp);
}
return View();
}
You must use the fa
class:
<i class="fa">

</i>
<i class="fa fa-2x">

</i>
The better and correct solution is to have a directive. The scope is the same, whether in the controller of the directive or the main controller. Use $element
to do DOM operations. The method defined in the directive controller is accessible in the main controller.
Example, finding a child element:
var app = angular.module('myapp', []);
app.directive("testDir", function () {
function link(scope, element) {
}
return {
restrict: "AE",
link: link,
controller:function($scope,$element){
$scope.name2 = 'this is second name';
var barGridSection = $element.find('#barGridSection'); //helps to find the child element.
}
};
})
app.controller('mainController', function ($scope) {
$scope.name='this is first name'
});
No, no, no.
These answers are all wrong. There is a fundamental absence of knowledge in your brain that I'm going to remedy right now.
Your major issue here is your naming scheme. It's verbose, contains undesirable characters, and is horribly inconsistent.
First: A table that is called Salesperson
does not need to have each field in the table called Salesperson.Salesperson number
, Salesperson.Salesperson email
. You're already in the table Salesperson
. Everything in this table relates to Salesperson
. You don't have to keep saying it.
Instead use ID
, Email
. Don't use Number
because that's probably a reserved word. Do you really endeavour to type [] around every field name for the lifespan of your database?
Primary keys on a table called Student
can either be ID
or StudentID
but be consistent. Foreign keys should only be named by the table it points to followed by ID
. For example: Student.ID
and Appointment.StudentID
. ID
is always capitalized. I don't care if your IDE tells you not to because everywhere but your IDE will be ID
. Even Access likes ID
.
Second: Name all your fields without spaces or special characters and keep them as short as possible and if they conflict with a reserved word, find another word.
Instead of: phone number
use PhoneNumber
or even better, simply, Phone
. If you choose what time user made the withdrawal
, you're going to have to type that in every single time.
Third: And this one is the most important one: Always be consistent in whatever naming scheme you choose. You should be able to say, "I need the postal code from that table; its name is going to be PostalCode." You should know that without even having to look it up because you were consistent in your naming convention.
Recap: Terse, not verbose. Keep names short with no spaces, don't repeat the table name, don't use reserved words, and capitalize each word. Above all, be consistent.
I hope you take my advice. This is the right way to do it. My answer is the right one. You should be extremely pedantic with your naming scheme to the point of absolute obsession for the rest of your lives on this planet.
NOTE:You actually have to change the field name in the design view of the table and in the query.
There are two basic techniques. The first uses PSAPI; MSDN has an example that uses EnumProcesses
, OpenProcess
, EnumProcessModules
, and GetModuleBaseName
.
The other uses Toolhelp, which I prefer. Use CreateToolhelp32Snapshot
to get a snapshot of the process list, walk over it with Process32First
and Process32Next
, which provides module name and process ID, until you find the one you want, and then call OpenProcess
to get a handle.
Important! Difference between Oracle and Mysql: Let's say that t1 t2 don't have duplicate rows between them but they have duplicate rows individual. Example: t1 has sales from 2017 and t2 from 2018
SELECT T1.YEAR, T1.PRODUCT FROM T1
UNION ALL
SELECT T2.YEAR, T2.PRODUCT FROM T2
In ORACLE UNION ALL fetches all rows from both tables. The same will occur in MySQL.
However:
SELECT T1.YEAR, T1.PRODUCT FROM T1
UNION
SELECT T2.YEAR, T2.PRODUCT FROM T2
In ORACLE, UNION fetches all rows from both tables because there are no duplicate values between t1 and t2. On the other hand in MySQL the resultset will have fewer rows because there will be duplicate rows within table t1 and also within table t2!
Look at java.lang.BigDecimal, may solve your problem.
http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
The command you want is Edit.Duplicate. It is mapped to CtrlE, CtrlV. This will not overwrite your clipboard.
You can use the "system( string $command[, int &$return_var] ) : string" function. For Windows system( "time" );, system( "time > output.txt" ); to put the response in the output.txt file. If you plan on deploying your website on someone else's server, then you may not want to hardcode the server time, as the server may move to an unknown timezone. Then it may be best to set the default time zone in the php.ini file. I use Hostinger and they allow you to configure that php.ini value.
This is trivial when you use SUMPRODUCT
. Por ejemplo:
=SUMPRODUCT((worksheet2!A:A=A3)*1)
You could put the above formula in cell B3, where A3 is the name you want to find in worksheet2
.
maybe this trick will help somebody
SELECT
[id],
[code],
[created_at]
FROM
( SELECT
[id],
[code],
[created_at],
(ROW_NUMBER() OVER (
ORDER BY
created_at DESC)) AS Row
FROM
[Code_tbl]
WHERE
[created_at] BETWEEN '2009-11-17 00:00:01' AND '2010-11-17 23:59:59'
) Rows
WHERE
Row BETWEEN 10 AND 20;
here inner subquery ordered by field created_at (could be any from your table)
Use the below link for wrap into two lines check the link
Insert ellipsis (...) into HTML tag if content too wide
That needs the below jquery
Only static functions are called with class name.
classname::Staicfunction();
Non static functions have to be called using objects.
classname obj;
obj.Somefunction();
This is exactly what your error means. Since your function is non static you have to use a object reference to invoke it.
As stated here: Why use Fragment#setRetainInstance(boolean)?
you can also use fragments method setRetainInstance(true)
like this:
public class MyFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// keep the fragment and all its data across screen rotation
setRetainInstance(true);
}
}
If you want to do this without adding and populating a new column, without reordering the columns, and with almost no downtime because no data is changing on the table, let's do some magic with partitioning functionality (but since no partitions are used you don't need Enterprise edition):
ALTER TABLE [Original] SWITCH TO [Original2]
exec sys.sp_rename
to rename the various schema objects back to the original names, and then you can recreate your foreign keys.For example, given:
CREATE TABLE Original
(
Id INT IDENTITY PRIMARY KEY
, Value NVARCHAR(300)
);
CREATE NONCLUSTERED INDEX IX_Original_Value ON Original (Value);
INSERT INTO Original
SELECT 'abcd'
UNION ALL
SELECT 'defg';
You can do the following:
--create new table with no IDENTITY
CREATE TABLE Original2
(
Id INT PRIMARY KEY
, Value NVARCHAR(300)
);
CREATE NONCLUSTERED INDEX IX_Original_Value2 ON Original2 (Value);
--data before switch
SELECT 'Original', *
FROM Original
UNION ALL
SELECT 'Original2', *
FROM Original2;
ALTER TABLE Original SWITCH TO Original2;
--data after switch
SELECT 'Original', *
FROM Original
UNION ALL
SELECT 'Original2', *
FROM Original2;
--clean up
IF NOT EXISTS (SELECT * FROM Original) DROP TABLE Original;
EXEC sys.sp_rename 'Original2.IX_Original_Value2', 'IX_Original_Value', 'INDEX';
EXEC sys.sp_rename 'Original2', 'Original', 'OBJECT';
UPDATE Original
SET Id = Id + 1;
SELECT *
FROM Original;
In regards to Gordon M's answer above, the 1st and 2nd parameter in mysqli_real_escape_string ()
call should be swapped for the newer php versions,
according to: http://php.net/manual/en/mysqli.real-escape-string.php
The code below worked for me.
df.append(pd.Series([np.nan]), ignore_index = True)
You can use Humanizer package with Humanize Enums possiblity. An eaxample:
enum PublishStatusses
{
[Description("Custom description")]
NotCompleted,
AlmostCompleted,
Error
};
then you can use Humanize
extension method on enum directly:
var st1 = PublishStatusses.NotCompleted;
var str1 = st1.Humanize(); // will result in Custom description
var st2 = PublishStatusses.AlmostCompleted;
var str2 = st2.Humanize(); // will result in Almost completed (calculated automaticaly)
The accepted answer only shows files in the current directory's tree. To show all of the tracked files that have been committed (on the current branch), use
git ls-tree --full-tree --name-only -r HEAD
--full-tree
makes the command run as if you were in the repo's root directory.-r
recurses into subdirectories. Combined with --full-tree
, this gives you all committed, tracked files.--name-only
removes SHA / permission info for when you just want the file paths.HEAD
specifies which branch you want the list of tracked, committed files for. You could change this to master
or any other branch name, but HEAD
is the commit you have checked out right now.This is the method from the accepted answer to the ~duplicate question https://stackoverflow.com/a/8533413/4880003.
You also have to delete the local branch:
git branch -d 6796
Another way is to prune all stale branches from your local repository. This will delete all local branches that already have been removed from the remote:
git remote prune origin --dry-run
I think this is the official solution: https://docs.anaconda.com/anaconda/install/uninstall/
[Unfortunately I did the simple remove (Uninstall-Anaconda.exe in C:\Users\username\Anaconda3 following the answers in stack overflow) before I found the official article, so I have to get rid of everything manually.]
But for the rest of you the official full removal could be interesting, so I copied it here:
To uninstall Anaconda, you can do a simple remove of the program. This will leave a few files behind, which for most users is just fine. See Option A.
If you also want to remove all traces of the configuration files and directories from Anaconda and its programs, you can download and use the Anaconda-Clean program first, then do a simple remove. See Option B.
Option A. Use simple remove to uninstall Anaconda:
- Windows–In the Control Panel, choose Add or Remove Programs or Uninstall a program, and then select Python 3.6 (Anaconda) or your version of Python.
- [... also solutions for Mac and Linux are provided here: https://docs.anaconda.com/anaconda/install/uninstall/ ]
Option B: Full uninstall using Anaconda-Clean and simple remove.
NOTE: Anaconda-Clean must be run before simple remove.
Install the Anaconda-Clean package from Anaconda Prompt (Terminal on Linux or macOS):
conda install anaconda-clean
In the same window, run one of these commands:
Remove all Anaconda-related files and directories with a confirmation prompt before deleting each one:
anaconda-clean
Or, remove all Anaconda-related files and directories without being prompted to delete each one:
anaconda-clean --yes
Anaconda-Clean creates a backup of all files and directories that might be removed in a folder named .anaconda_backup in your home directory. Also note that Anaconda-Clean leaves your data files in the AnacondaProjects directory untouched.
After using Anaconda-Clean, follow the instructions above in Option A to uninstall Anaconda.
If there isn't any .gitmodules
file, but a submodules configuration exists in .git/modules/
:
find .git/modules/ -name config -exec grep url {} \;
I prefer using PHPMailer script to send emails from localhost as it lets me use my Gmail account as SMTP. You can find the PHPMailer from http://phpmailer.worxware.com/ . Help regarding how to use gmail as SMTP or any other SMTP can be found at http://www.mittalpatel.co.in/php_send_mail_from_localhost_using_gmail_smtp . Hope this helps!
This is in VB, but it seems to work well for me. It looks for a 0 byte return like the previous post.
Private Sub RecData(ByVal AR As IAsyncResult)
Dim Socket As Socket = AR.AsyncState
If Socket.Connected = False And Socket.Available = False Then
Debug.Print("Detected Disconnected Socket - " + Socket.RemoteEndPoint.ToString)
Exit Sub
End If
Dim BytesRead As Int32 = Socket.EndReceive(AR)
If BytesRead = 0 Then
Debug.Print("Detected Disconnected Socket - Bytes Read = 0 - " + Socket.RemoteEndPoint.ToString)
UpdateText("Client " + Socket.RemoteEndPoint.ToString + " has disconnected from Server.")
Socket.Close()
Exit Sub
End If
Dim msg As String = System.Text.ASCIIEncoding.ASCII.GetString(ByteData)
Erase ByteData
ReDim ByteData(1024)
ClientSocket.BeginReceive(ByteData, 0, ByteData.Length, SocketFlags.None, New AsyncCallback(AddressOf RecData), ClientSocket)
UpdateText(msg)
End Sub
If I may add a comment here...
<c:out value="${param.accountID}"></c:out>
doesn't work for me (it prints a 0).
Instead, this works:
<c:out value="${param['accountID']}"></c:out>
IF NOT USING THE SHORT HAND VERSION: Make sure the animation-fill-mode: forwards
is AFTER the animation declaration or it will not work...
animation-fill-mode: forwards;
animation-name: appear;
animation-duration: 1s;
animation-delay: 1s;
vs
animation-name: appear;
animation-duration: 1s;
animation-fill-mode: forwards;
animation-delay: 1s;
There is a little trick to pass an object by reference, even though the language doesn't make it possible. It works in Java too, it's the list with one item. ;-)
class PassByReference:
def __init__(self, name):
self.name = name
def changeRef(ref):
ref[0] = PassByReference('Michael')
obj = PassByReference('Peter')
print obj.name
p = [obj] # A pointer to obj! ;-)
changeRef(p)
print p[0].name # p->name
It's an ugly hack, but it works. ;-P
Without a for loop
, only using Map()
.
You can also return the duplicates.
(function(a){
let map = new Map();
a.forEach(e => {
if(map.has(e)) {
let count = map.get(e);
console.log(count)
map.set(e, count + 1);
} else {
map.set(e, 1);
}
});
let hasDup = false;
let dups = [];
map.forEach((value, key) => {
if(value > 1) {
hasDup = true;
dups.push(key);
}
});
console.log(dups);
return hasDup;
})([2,4,6,2,1,4]);
You need to :
dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
Then :
dataGridView1.ColumnHeadersHeight = 60;
For bootstrap 4 I have to add media query with max-width: none
@media (min-width: 576px) {
.modal-dialog { max-width: none; }
}
.modal-dialog {
width: 98%;
height: 92%;
padding: 0;
}
.modal-content {
height: 99%;
}
Wikipedia has a very good answer http://en.wikipedia.org/wiki/Universally_unique_identifier#Collisions
the number of random version 4 UUIDs which need to be generated in order to have a 50% probability of at least one collision is 2.71 quintillion, computed as follows:
...
This number is equivalent to generating 1 billion UUIDs per second for about 85 years, and a file containing this many UUIDs, at 16 bytes per UUID, would be about 45 exabytes, many times larger than the largest databases currently in existence, which are on the order of hundreds of petabytes.
...
Thus, for there to be a one in a billion chance of duplication, 103 trillion version 4 UUIDs must be generated.
Thanks for the reply. I was using "mvn clean install" in the maven build configuration. we no need to use "mvn" command if running through eclipse.
After buiding the application using the command "clean install" , I got one more error -
"No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?"
I followed this link:- No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
now application building is fine in eclipse.
Another approach to this is to use my service, http://ipinfo.io, which returns the city, region and country name based on the user's current IP address. Here's a simple example:
$.get("http://ipinfo.io", function(response) {
console.log(response.city, response.country);
}, "jsonp");
Here's a more detailed JSFiddle example that also prints out the full response information, so you can see all of the available details: http://jsfiddle.net/zK5FN/2/
int n = 13;
String binary = "";
//decimal to binary
while (n > 0) {
int d = n & 1;
binary = d + binary;
n = n >> 1;
}
System.out.println(binary);
//binary to decimal
int power = 1;
n = 0;
for (int i = binary.length() - 1; i >= 0; i--) {
n = n + Character.getNumericValue(binary.charAt(i)) * power;
power = power * 2;
}
System.out.println(n);
you can use command
date | awk '{print $4}'| cut -d ':' -f3
as you mentioned using only the date|awk '{print $4}'
pipeline gives you something like this
20:18:19
so as we can see if we want to extract some part of this string then we need a delimiter , for our case it is :
, so we decide to chop on the basis of :
.
Now this delimiter will chop the string into three parts i.e. 20 ,18 and 19 , as we want the second one we use -f2 in our command.
to sum up ,
cut
: chops some string based on delimeter.
-d
: delimeter (here :
)
-f2
: the chopped off token that we want.
You can use:
var tomorrow = new Date();
tomorrow.setDate(new Date().getDate()+1);
For example, since there are 30 days in April, the following code will output May 1:
var day = new Date('Apr 30, 2000');
console.log(day); // Apr 30 2000
var nextDay = new Date(day);
nextDay.setDate(day.getDate() + 1);
console.log(nextDay); // May 01 2000
See fiddle.
Those are called #include guards.
Once the header is included, it checks if a unique value (in this case HEADERFILE_H
) is defined. Then if it's not defined, it defines it and continues to the rest of the page.
When the code is included again, the first ifndef
fails, resulting in a blank file.
That prevents double declaration of any identifiers such as types, enums and static variables.
The Standard Library provides an input function called ws
, which consumes whitespace from an input stream. You can use it like this:
std::string s;
std::getline(std::cin >> std::ws, s);
You can improve performance significant the following way if group by contains mostly one item:
SELECT
[ID],
CASE WHEN MAX( [Name]) = MIN( [Name]) THEN
MAX( [Name]) NameValues
ELSE
STUFF((
SELECT ', ' + [Name] + ':' + CAST([Value] AS VARCHAR(MAX))
FROM #YourTable
WHERE (ID = Results.ID)
FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
,1,2,'') AS NameValues
END
FROM #YourTable Results
GROUP BY ID
It is also worth taking a look at:
var el = document.getElementById('hello');
if(el) {
el.className += el.className ? ' someClass' : 'someClass';
}
Or use the FileInfo as suggested in In C# check that filename is possibly valid (not that it exists).
From Visual Studio 2015 consider to use out of the box Memory Usage diagnostic tool to collect and analyze memory usage data.
The Memory Usage tool lets you take one or more snapshots of the managed and native memory heap to help understand the memory usage impact of object types.
Do you have the required permission set in your Manifest?
<uses-permission android:name="android.permission.WAKE_LOCK" />
Try invoking your command with Invoke-Expression
:
Invoke-Expression $cmd1
Here is a working example on my machine:
$cmd = "& 'C:\Program Files\7-zip\7z.exe' a -tzip c:\temp\test.zip c:\temp\test.txt"
Invoke-Expression $cmd
iex
is an alias for Invoke-Expression
so you could do:
iex $cmd1
For a full list :
Visit https://ss64.com/ps/ for more Powershell
stuff.
Good Luck...
Further to the other answers suggesting LINQ, another alternative in this case would be to use the FindAll
instance method:
List<SampleClass> results = myList.FindAll(x => x.Name == nameToExtract);
This implementation supports insert, find and delete operations without destroy the structure of the tree. This is not a banlanced tree.
# Class for construct the nodes of the tree. (Subtrees)
class Node:
def __init__(self, key, parent_node = None):
self.left = None
self.right = None
self.key = key
if parent_node == None:
self.parent = self
else:
self.parent = parent_node
# Class with the structure of the tree.
# This Tree is not balanced.
class Tree:
def __init__(self):
self.root = None
# Insert a single element
def insert(self, x):
if(self.root == None):
self.root = Node(x)
else:
self._insert(x, self.root)
def _insert(self, x, node):
if(x < node.key):
if(node.left == None):
node.left = Node(x, node)
else:
self._insert(x, node.left)
else:
if(node.right == None):
node.right = Node(x, node)
else:
self._insert(x, node.right)
# Given a element, return a node in the tree with key x.
def find(self, x):
if(self.root == None):
return None
else:
return self._find(x, self.root)
def _find(self, x, node):
if(x == node.key):
return node
elif(x < node.key):
if(node.left == None):
return None
else:
return self._find(x, node.left)
elif(x > node.key):
if(node.right == None):
return None
else:
return self._find(x, node.right)
# Given a node, return the node in the tree with the next largest element.
def next(self, node):
if node.right != None:
return self._left_descendant(node.right)
else:
return self._right_ancestor(node)
def _left_descendant(self, node):
if node.left == None:
return node
else:
return self._left_descendant(node.left)
def _right_ancestor(self, node):
if node.key <= node.parent.key:
return node.parent
else:
return self._right_ancestor(node.parent)
# Delete an element of the tree
def delete(self, x):
node = self.find(x)
if node == None:
print(x, "isn't in the tree")
else:
if node.right == None:
if node.left == None:
if node.key < node.parent.key:
node.parent.left = None
del node # Clean garbage
else:
node.parent.right = None
del Node # Clean garbage
else:
node.key = node.left.key
node.left = None
else:
x = self.next(node)
node.key = x.key
x = None
# tests
t = Tree()
t.insert(5)
t.insert(8)
t.insert(3)
t.insert(4)
t.insert(6)
t.insert(2)
t.delete(8)
t.delete(5)
t.insert(9)
t.insert(1)
t.delete(2)
t.delete(100)
# Remember: Find method return the node object.
# To return a number use t.find(nº).key
# But it will cause an error if the number is not in the tree.
print(t.find(5))
print(t.find(8))
print(t.find(4))
print(t.find(6))
print(t.find(9))
If you don't have to store more than 24 hours you can just store time, since SQL Server 2008 and later the mapping is
time (SQL Server) <-> TimeSpan(.NET)
No conversions needed if you only need to store 24 hours or less.
Source: http://msdn.microsoft.com/en-us/library/cc716729(v=vs.110).aspx
But, if you want to store more than 24h, you are going to need to store it in ticks, retrieve the data and then convert to TimeSpan. For example
int timeData = yourContext.yourTable.FirstOrDefault();
TimeSpan ts = TimeSpan.FromMilliseconds(timeData);
I have the following lines in my .vimrc
:
" comment line, selection with Ctrl-N,Ctrl-N
au BufEnter *.py nnoremap <C-N><C-N> mn:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR>:noh<CR>`n
au BufEnter *.py inoremap <C-N><C-N> <C-O>mn<C-O>:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR><C-O>:noh<CR><C-O>`n
au BufEnter *.py vnoremap <C-N><C-N> mn:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR>:noh<CR>gv`n
" uncomment line, selection with Ctrl-N,N
au BufEnter *.py nnoremap <C-N>n mn:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR>:s/^#$//ge<CR>:noh<CR>`n
au BufEnter *.py inoremap <C-N>n <C-O>mn<C-O>:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR><C-O>:s/^#$//ge<CR><C-O>:noh<CR><C-O>`n
au BufEnter *.py vnoremap <C-N>n mn:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR>gv:s/#\n/\r/ge<CR>:noh<CR>gv`n
The shortcuts preserve your cursor position and your comments as long as they start with #
(there is space after #). For example:
# variable x
x = 0
After commenting:
# variable x
#x = 0
After uncomennting:
# variable x
x = 0
If you scale 1600x900
to 1280x720
you have
scale_x = 1280.0/1600
scale_y = 720.0/900
Then you can use it to find button size, and button position
button_width = 300 * scale_x
button_height = 300 * scale_y
button_x = 1440 * scale_x
button_y = 860 * scale_y
If you scale 1280x720
to 1600x900
you have
scale_x = 1600.0/1280
scale_y = 900.0/720
and rest is the same.
I add .0
to value to make float
- otherwise scale_x
, scale_y
will be rounded to integer
- in this example to 0
(zero) (Python 2.x)
import os
import tempfile
path = tempfile.mktemp(dir=path)
os.makedirs(path)
os.rmdir(path)
if you want to kill a specific node process , you can go to command line route and type:
ps aux | grep node
to get a list of all node process ids. now you can get your process id(pid), then do:
kill -9 PID
and if you want to kill all node processes then do:
killall -9 node
-9 switch is like end task on windows. it will force the process to end. you can do:
kill -l
to see all switches of kill command and their comments.
Starting with elif option == 2:
, you indented one time too many. In a decent text editor, you should be able to highlight these lines and press Shift+Tab to fix the issue.
Additionally, there is no statement after for x in range(x, 1, 1):
. Insert an indented pass
to do nothing in the for
loop.
Also, in the first line, you wrote option == 1
. ==
tests for equality, but you meant =
( a single equals sign), which assigns the right value to the left name, i.e.
option = 1
See this : What Python version can I use with Django?¶ https://docs.djangoproject.com/en/2.0/faq/install/
if you are using python27 you must to set django version :
try: $pip install django==1.9
Try this : Using this you can select date by last 30 days,
SELECT DATEADD(DAY,-30,GETDATE())
Short answer: No.
The switch statement takes an expression that is only evaluated once. Based on the result, another piece of code is executed.
So what? => String.StartsWith is a function. Together with a given parameter, it is an expression. However, for your case you need to pass a different parameter for each case, so it cannot be evaluated only once.
Long answer #1 has been given by others.
Long answer #2:
Depending on what you're trying to achieve, you might be interested in the Command Pattern/Chain-of-responsibility pattern. Applied to your case, each piece of code would be represented by an implementation of a Command. In addition to the execute method, the command can provide a boolean Accept method, which checks whether the given string starts with the respective parameter.
Advantage: Instead of your hardcoded switch statement, hardcoded StartsWith evaluations and hardcoded strings, you'd have lot more flexibility.
The example you gave in your question would then look like this:
var commandList = new List<Command>() { new MyABCCommand() };
foreach (Command c in commandList)
{
if (c.Accept(mystring))
{
c.Execute(mystring);
break;
}
}
class MyABCCommand : Command
{
override bool Accept(string mystring)
{
return mystring.StartsWith("abc");
}
}
Back in the good ole days, there were just two types of languages: compiled and interpreted.
Compiled languages utilized a "compiler" to read the language syntax and convert it into identical assembly language code, which could than just directly on the CPU. Interpreted languages used a couple of different schemes, but essentially the language syntax was converted into an intermediate form, and then run in a "interpreter", an environment for executing the code.
Thus, in a sense, there was another "layer" -- the interpreter -- between the code and the machine. And, as always the case in a computer, more means more resources get used. Interpreters were slower, because they had to perform more operations.
More recently, we've seen more hybrid languages like Java, that employ both a compiler and an interpreter to make them work. It's complicated, but a JVM is faster, more sophisticated and way more optimized than the old interpreters, so it stands a much better change of performing (over time) closer to just straight compiled code. Of course, the newer compilers also have more fancy optimizing tricks so they tend to generate way better code than they used to as well. But most optimizations, most often (although not always) make some type of trade-off such that they are not always faster in all circumstances. Like everything else, nothing comes for free, so the optimizers must get their boast from somewhere (although often times it using compile-time CPU to save runtime CPU).
Getting back to C, it is a simple language, that can be compiled into fairly optimized assembly and then run directly on the target machine. In C, if you increment an integer, it's more than likely that it is only one assembler step in the CPU, in Java however, it could end up being a lot more than that (and could include a bit of garbage collection as well :-) C offers you an abstraction that is way closer to the machine (assembler is the closest), but you end up having to do way more work to get it going and it is not as protected, easy to use or error friendly. Most other languages give you a higher abstraction and take care of more of the underlying details for you, but in exchange for their advanced functionality they require more resources to run. As you generalize some solutions, you have to handle a broader range of computing, which often requires more resources.
Paul.
the reason of the exception has been explained already, however the suggested solution isn't really the best.
You should create a class that keeps a Scanner as private using Singleton Pattern, that makes that scanner unique on your code.
Then you can implement the methods you need or you can create a getScanner ( not recommended ) and you can control it with a private boolean, something like alreadyClosed.
If you are not aware how to use Singleton Pattern, here's a example:
public class Reader {
private Scanner reader;
private static Reader singleton = null;
private boolean alreadyClosed;
private Reader() {
alreadyClosed = false;
reader = new Scanner(System.in);
}
public static Reader getInstance() {
if(singleton == null) {
singleton = new Reader();
}
return singleton;
}
public int nextInt() throws AlreadyClosedException {
if(!alreadyClosed) {
return reader.nextInt();
}
throw new AlreadyClosedException(); //Custom exception
}
public double nextDouble() throws AlreadyClosedException {
if(!alreadyClosed) {
return reader.nextDouble();
}
throw new AlreadyClosedException();
}
public String nextLine() throws AlreadyClosedException {
if(!alreadyClosed) {
return reader.nextLine();
}
throw new AlreadyClosedException();
}
public void close() {
alreadyClosed = true;
reader.close();
}
}
If you want the effect of a nested for loop, use:
import itertools
for i, j in itertools.product(range(x), range(y)):
# Stuff...
If you just want to loop simultaneously, use:
for i, j in zip(range(x), range(y)):
# Stuff...
Note that if x
and y
are not the same length, zip
will truncate to the shortest list. As @abarnert pointed out, if you don't want to truncate to the shortest list, you could use itertools.zip_longest
.
UPDATE
Based on the request for "a function that will read lists "t1" and "t2" and return all elements that are identical", I don't think the OP wants zip
or product
. I think they want a set
:
def equal_elements(t1, t2):
return list(set(t1).intersection(set(t2)))
# You could also do
# return list(set(t1) & set(t2))
The intersection
method of a set
will return all the elements common to it and another set (Note that if your lists contains other list
s, you might want to convert the inner list
s to tuples
first so that they are hashable; otherwise the call to set
will fail.). The list
function then turns the set back into a list.
UPDATE 2
OR, the OP might want elements that are identical in the same position in the lists. In this case, zip
would be most appropriate, and the fact that it truncates to the shortest list is what you would want (since it is impossible for there to be the same element at index 9 when one of the lists is only 5 elements long). If that is what you want, go with this:
def equal_elements(t1, t2):
return [x for x, y in zip(t1, t2) if x == y]
This will return a list containing only the elements that are the same and in the same position in the lists.
Definitely, we cannot override static methods in Java. Because JVM resolves correct overridden method based upon the object at run-time by using dynamic binding in Java.
However, the static method in Java is associated with Class rather than the object and resolved and bonded during compile time.
String
is a special built-in class of the language. It is for the String
class only in which you should avoid saying
String s = new String("Polish");
Because the literal "Polish"
is already of type String
, and you're creating an extra unnecessary object. For any other class, saying
CaseInsensitiveString cis = new CaseInsensitiveString("Polish");
is the correct (and only, in this case) thing to do.
Optimyth Software has just launched a static analysis service in the cloud www.checkinginthecloud.com. Just securely upload your code run the analysis and get the results. No hassles.
It supports several languages including C# more info can be found at wwww.optimyth.com
I was never able to get this to work simple using annotations. To get it to work, I created a ContextResolver
for ObjectMapper
, then I added the JSR310Module
(update: now it is JavaTimeModule
instead), along with one more caveat, which was the need to set write-date-as-timestamp to false. See more at the documentation for the JSR310 module. Here's an example of what I used.
Dependency
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.4.0</version>
</dependency>
Note: One problem I faced with this is that the jackson-annotation
version pulled in by another dependency, used version 2.3.2, which cancelled out the 2.4 required by the jsr310
. What happened was I got a NoClassDefFound for ObjectIdResolver
, which is a 2.4 class. So I just needed to line up the included dependency versions
ContextResolver
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JSR310Module;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper MAPPER;
public ObjectMapperContextResolver() {
MAPPER = new ObjectMapper();
// Now you should use JavaTimeModule instead
MAPPER.registerModule(new JSR310Module());
MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
}
@Override
public ObjectMapper getContext(Class<?> type) {
return MAPPER;
}
}
Resource class
@Path("person")
public class LocalDateResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getPerson() {
Person person = new Person();
person.birthDate = LocalDate.now();
return Response.ok(person).build();
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createPerson(Person person) {
return Response.ok(
DateTimeFormatter.ISO_DATE.format(person.birthDate)).build();
}
public static class Person {
public LocalDate birthDate;
}
}
Test
curl -v http://localhost:8080/api/person
Result:{"birthDate":"2015-03-01"}
curl -v -POST -H "Content-Type:application/json" -d "{\"birthDate\":\"2015-03-01\"}" http://localhost:8080/api/person
Result:2015-03-01
See also here for JAXB solution.
The JSR310Module
is deprecated as of version 2.7 of Jackson. Instead, you should register the module JavaTimeModule
. It is still the same dependency.
Alex summarized well but, surprisingly, was too succinct.
First, let me reiterate the main points in Alex’s post:
__repr__
goal is to be unambiguous__str__
goal is to be readable__str__
uses contained objects’ __repr__
Default implementation is useless
This is mostly a surprise because Python’s defaults tend to be fairly useful. However, in this case, having a default for __repr__
which would act like:
return "%s(%r)" % (self.__class__, self.__dict__)
would have been too dangerous (for example, too easy to get into infinite recursion if objects reference each other). So Python cops out. Note that there is one default which is true: if __repr__
is defined, and __str__
is not, the object will behave as though __str__=__repr__
.
This means, in simple terms: almost every object you implement should have a functional __repr__
that’s usable for understanding the object. Implementing __str__
is optional: do that if you need a “pretty print” functionality (for example, used by a report generator).
The goal of __repr__
is to be unambiguous
Let me come right out and say it — I do not believe in debuggers. I don’t really know how to use any debugger, and have never used one seriously. Furthermore, I believe that the big fault in debuggers is their basic nature — most failures I debug happened a long long time ago, in a galaxy far far away. This means that I do believe, with religious fervor, in logging. Logging is the lifeblood of any decent fire-and-forget server system. Python makes it easy to log: with maybe some project specific wrappers, all you need is a
log(INFO, "I am in the weird function and a is", a, "and b is", b, "but I got a null C — using default", default_c)
But you have to do the last step — make sure every object you implement has a useful repr, so code like that can just work. This is why the “eval” thing comes up: if you have enough information so eval(repr(c))==c
, that means you know everything there is to know about c
. If that’s easy enough, at least in a fuzzy way, do it. If not, make sure you have enough information about c
anyway. I usually use an eval-like format: "MyClass(this=%r,that=%r)" % (self.this,self.that)
. It does not mean that you can actually construct MyClass, or that those are the right constructor arguments — but it is a useful form to express “this is everything you need to know about this instance”.
Note: I used %r
above, not %s
. You always want to use repr()
[or %r
formatting character, equivalently] inside __repr__
implementation, or you’re defeating the goal of repr. You want to be able to differentiate MyClass(3)
and MyClass("3")
.
The goal of __str__
is to be readable
Specifically, it is not intended to be unambiguous — notice that str(3)==str("3")
. Likewise, if you implement an IP abstraction, having the str of it look like 192.168.1.1 is just fine. When implementing a date/time abstraction, the str can be "2010/4/12 15:35:22", etc. The goal is to represent it in a way that a user, not a programmer, would want to read it. Chop off useless digits, pretend to be some other class — as long is it supports readability, it is an improvement.
Container’s __str__
uses contained objects’ __repr__
This seems surprising, doesn’t it? It is a little, but how readable would it be if it used their __str__
?
[moshe is, 3, hello
world, this is a list, oh I don't know, containing just 4 elements]
Not very. Specifically, the strings in a container would find it way too easy to disturb its string representation. In the face of ambiguity, remember, Python resists the temptation to guess. If you want the above behavior when you’re printing a list, just
print "[" + ", ".join(l) + "]"
(you can probably also figure out what to do about dictionaries.
Summary
Implement __repr__
for any class you implement. This should be second nature. Implement __str__
if you think it would be useful to have a string version which errs on the side of readability.
UPDATE table_name
SET field = replace(field, 'string-to-find', 'string-that-will-replace-it');
I had the same problem too. This formula also works equally well:-
=INDIRECT(CONCATENATE("$G$",(14+(COUNTA($G$14:$G$65535)-1))))
14 being the row number of the first row in the rows you want to count.
Chronic Clawtooth
Just install this package and your code will work:=> Install-Package Microsoft.Owin.Host.SystemWeb -Version 2.1.0
For Mac users (find doesn't have -executable and xargs doesn't have -d):
echo $PATH | tr ':' '\n' | xargs -I {} find {} -maxdepth 1 -type f -perm '++x'
eumiro's answer is better, however I'm just posting this for variety:
>>> "%08d" % int(bin(6)[2:])
00000110
Eclipse loads plug-ins lazily, and most common plug-ins, like Subclipse, don't do anything if you don't use them. They don't slow Eclipse down at all during run time, and it won't help you to disable them. In fact, Mylyn was shown to reduce Eclipse's memory footprint when used correctly.
I run Eclipse with tons of plug-ins without any performance penalty at all.
It's not only the memory that you need to increase with the -Xmx switch, it's also the perm gen size. I think that problem was solved in Eclipse 3.4.
When I run your program, it doesn't even get me to the point where I can enter the second date.
This is simpler and less error prone.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test001 {
public static void main(String[] args) throws Exception {
BufferedReader br = null;
br = new BufferedReader(new InputStreamReader(System.in));
SimpleDateFormat sdf = new SimpleDateFormat("dd MM yyyy");
System.out.println("Insert first date : ");
Date dt1 = sdf.parse(br.readLine().trim());
System.out.println("Insert second date : ");
Date dt2 = sdf.parse(br.readLine().trim());
long diff = dt2.getTime() - dt1.getTime();
System.out.println("Days: " + diff / 1000L / 60L / 60L / 24L);
if (br != null) {
br.close();
}
}
}
Add float:left;
property in both divs.
Add display:inline-block;
property.
Add display:flex;
property in parent div.
You really don't need to do:
[self.view setNeedsDisplay];
Honestly, I think it's "let's hope for the best" type of solution, in this case. There are several approaches to update your UIView
s:
Each one has is pros and cons. Depending of what you are updating and what kind of "connection" you have between your business layer (the server connectivity) and the UIViewController
, I can recommend one that would suit your needs.
Try this code
<html>
<head>
<script type="text/javascript">
function validate() {
if(myform.fname.value.length==0)
{
document.getElementById('errfn').innerHTML="this is invalid name";
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type=text id=fname name=fname onblur="validate()"> </input><div id="errfn"> </div>
<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"> </input>
<br>
<input type=button value=check>
</form>
</body>
</html>
That seems to work for me:
<html>
<head><style>
#monkey {color:blue}
#ape {color:purple}
</style></head>
<body>
<span id="monkey" onclick="changeid()">
fruit
</span>
<script>
function changeid ()
{
var e = document.getElementById("monkey");
e.id = "ape";
}
</script>
</body>
</html>
The expected behaviour is to change the colour of the word "fruit".
Perhaps your document was not fully loaded when you called the routine?
In many environments (e.g. Heroku), and as a convention, you can set the environment variable PORT
to tell your web server what port to listen on.
So process.env.PORT || 3000
means: whatever is in the environment variable PORT, or 3000 if there's nothing there.
So you pass that to app.listen
, or to app.set('port', ...)
, and that makes your server able to accept a "what port to listen on" parameter from the environment.
If you pass 3000
hard-coded to app.listen()
, you're always listening on port 3000, which might be just for you, or not, depending on your requirements and the requirements of the environment in which you're running your server.
Create bitmap from file path:
File sd = Environment.getExternalStorageDirectory();
File image = new File(sd+filePath, imageName);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);
imageView.setImageBitmap(bitmap);
If you want to scale the bitmap to the parent's height and width then use Bitmap.createScaledBitmap
function.
I think you are giving the wrong file path. :) Hope this helps.
for replace all (') in your string, use
.replace(/\'/g,"''")
example:
sample = "St. Mary's and St. John's";
escapedSample = sample.replace(/\'/g,"''")
JavaScript equivalent for PHP's die
. BTW it just calls exit()
(thanks splattne):
function exit( status ) {
// http://kevin.vanzonneveld.net
// + original by: Brett Zamir (http://brettz9.blogspot.com)
// + input by: Paul
// + bugfixed by: Hyam Singer (http://www.impact-computing.com/)
// + improved by: Philip Peterson
// + bugfixed by: Brett Zamir (http://brettz9.blogspot.com)
// % note 1: Should be considered expirimental. Please comment on this function.
// * example 1: exit();
// * returns 1: null
var i;
if (typeof status === 'string') {
alert(status);
}
window.addEventListener('error', function (e) {e.preventDefault();e.stopPropagation();}, false);
var handlers = [
'copy', 'cut', 'paste',
'beforeunload', 'blur', 'change', 'click', 'contextmenu', 'dblclick', 'focus', 'keydown', 'keypress', 'keyup', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'resize', 'scroll',
'DOMNodeInserted', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument', 'DOMNodeInsertedIntoDocument', 'DOMAttrModified', 'DOMCharacterDataModified', 'DOMElementNameChanged', 'DOMAttributeNameChanged', 'DOMActivate', 'DOMFocusIn', 'DOMFocusOut', 'online', 'offline', 'textInput',
'abort', 'close', 'dragdrop', 'load', 'paint', 'reset', 'select', 'submit', 'unload'
];
function stopPropagation (e) {
e.stopPropagation();
// e.preventDefault(); // Stop for the form controls, etc., too?
}
for (i=0; i < handlers.length; i++) {
window.addEventListener(handlers[i], function (e) {stopPropagation(e);}, true);
}
if (window.stop) {
window.stop();
}
throw '';
}
in my jenkins/jenkins docker sudo always generates error:
bash: sudo: command not found
I needed update repo list with:
curl -sL https://deb.nodesource.com/setup_10.x | apt-get update
then,
apt-get install nodejs
All the command line results like this:
root@76e6f92724d1:/# curl -sL https://deb.nodesource.com/setup_10.x | apt-get update
Ign:1 http://deb.debian.org/debian stretch InRelease
Get:2 http://security.debian.org/debian-security stretch/updates InRelease [94.3 kB]
Get:3 http://deb.debian.org/debian stretch-updates InRelease [91.0 kB]
Get:4 http://deb.debian.org/debian stretch Release [118 kB]
Get:5 http://security.debian.org/debian-security stretch/updates/main amd64 Packages [520 kB]
Get:6 http://deb.debian.org/debian stretch-updates/main amd64 Packages [27.9 kB]
Get:8 http://deb.debian.org/debian stretch Release.gpg [2410 B]
Get:9 http://deb.debian.org/debian stretch/main amd64 Packages [7083 kB]
Get:7 https://packagecloud.io/github/git-lfs/debian stretch InRelease [23.2 kB]
Get:10 https://packagecloud.io/github/git-lfs/debian stretch/main amd64 Packages [4675 B]
Fetched 7965 kB in 20s (393 kB/s)
Reading package lists... Done
root@76e6f92724d1:/# apt-get install nodejs
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
libicu57 libuv1
The following NEW packages will be installed:
libicu57 libuv1 nodejs
0 upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
Need to get 11.2 MB of archives.
After this operation, 45.2 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://deb.debian.org/debian stretch/main amd64 libicu57 amd64 57.1-6+deb9u3 [7705 kB]
Get:2 http://deb.debian.org/debian stretch/main amd64 libuv1 amd64 1.9.1-3 [84.4 kB]
Get:3 http://deb.debian.org/debian stretch/main amd64 nodejs amd64 4.8.2~dfsg-1 [3440 kB]
Fetched 11.2 MB in 26s (418 kB/s)
debconf: delaying package configuration, since apt-utils is not installed
Selecting previously unselected package libicu57:amd64.
(Reading database ... 12488 files and directories currently installed.)
Preparing to unpack .../libicu57_57.1-6+deb9u3_amd64.deb ...
Unpacking libicu57:amd64 (57.1-6+deb9u3) ...
Selecting previously unselected package libuv1:amd64.
Preparing to unpack .../libuv1_1.9.1-3_amd64.deb ...
Unpacking libuv1:amd64 (1.9.1-3) ...
Selecting previously unselected package nodejs.
Preparing to unpack .../nodejs_4.8.2~dfsg-1_amd64.deb ...
Unpacking nodejs (4.8.2~dfsg-1) ...
Setting up libuv1:amd64 (1.9.1-3) ...
Setting up libicu57:amd64 (57.1-6+deb9u3) ...
Processing triggers for libc-bin (2.24-11+deb9u4) ...
Setting up nodejs (4.8.2~dfsg-1) ...
update-alternatives: using /usr/bin/nodejs to provide /usr/bin/js (js) in auto mode
Unfortunately, the best method to approach this is to use Internet Explorer as it's a browser that is guaranteed to be on Windows based machines. This will also bring compatibility of other users which might have alternative browsers such as Firefox, Chrome, Opera..etc,
start "iexplore.exe" http://www.website.com
Try this it's simple and fast
SELECT T.name AS [TABLE NAME], I.rows AS [ROWCOUNT]
FROM sys.tables AS T
INNER JOIN sys.sysindexes AS I ON T.object_id = I.id
AND I.indid < 2 ORDER BY I.rows DESC
if you remove the float: left
from the a
and add white-space: nowrap
to the outer div
#myWorkContent{
width:530px;
height:210px;
border: 13px solid #bed5cd;
overflow-x: scroll;
overflow-y: hidden;
white-space: nowrap;
}
#myWorkContent a {
display: inline;
}
this should work for any size or amount of images..
or even:
#myWorkContent a {
display: inline-block;
vertical-align: middle;
}
which would also vertically align images of different heights if required
I had the same problem. Even after updating the password using sudo passwd it was not working. I had to give "multiple" roles for my user through IAM & Admin Refer Screen Shot on IAM & Admin screen of google cloud
After that i restarted the VM. Then again changed the password and then it worked.
user1@sap-hanaexpress-public-1-vm:~> sudo passwd
New password:
Retype new password:
passwd: password updated successfully
user1@sap-hanaexpress-public-1-vm:~> su
Password:
sap-hanaexpress-public-1-vm:/home/user1 # whoami
root
sap-hanaexpress-public-1-vm:/home/user1 #
@controller is a singleton object, and if inject a prototype bean to a singleton class will make the prototype bean also as singleton unless u specify using lookup-method property which actually create a new instance of prototype bean for every call you make.
Simply, this should do the task:
import pandas as pd
grouped_df = df1.groupby( [ "Name", "City"] )
pd.DataFrame(grouped_df.size().reset_index(name = "Group_Count"))
Here, grouped_df.size()
pulls up the unique groupby count, and reset_index()
method resets the name of the column you want it to be.
Finally, the pandas Dataframe()
function is called upon to create a DataFrame object.
No need to do so much of trouble! Its simple
This will create 2 * 3 matrix of string.
var array=[];
var x = 2, y = 3;
var s = 'abcdefg';
for(var i = 0; i<x; i++){
array[i]=new Array();
for(var j = 0; j<y; j++){
array[i].push(s.charAt(counter++));
}
}
Hello here Code For Get Distance and Time Using Two Different Lat and Long
$url ="https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=16.538048,80.613266&destinations=23.0225,72.5714";
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
$result_array=json_decode($result);
print_r($result_array);
You can check Example Below Link get time between two different locations using latitude and longitude in php
The claims that you have to mock it at the top of your file are false.
Mock a named ES Import:
// import the named module
import { useWalkthroughAnimations } from '../hooks/useWalkthroughAnimations';
// mock the file and its named export
jest.mock('../hooks/useWalkthroughAnimations', () => ({
useWalkthroughAnimations: jest.fn()
}));
// do whatever you need to do with your mocked function
useWalkthroughAnimations.mockReturnValue({ pageStyles, goToNextPage, page });
dstat -C 0,1,2,3
Will also give you the CPU usage of first 4 cores. Of course, if you have 32 cores then this command gets a little bit longer but useful if you only interested in few cores.
For example, if you only interested in core 3 and 7 then you could do
dstat -C 3,7
You can get the position of the last -
with str.LastIndexOf('-')
. So the next step is obvious:
var result = str.Substring(str.LastIndexOf('-') + 1);
Correction:
As Brian states below, using this on a string with no dashes will result in the same string being returned.
@{
List<CategoryModel> CategoryList = CategoryModel.GetCategoryList(UserID);
IEnumerable<SelectListItem> CategorySelectList = CategoryList.Select(x => new SelectListItem() { Text = x.CategoryName.Trim(), Value = x.CategoryID.Trim() });
}
<tr>
<td>
<B>Assigned Category:</B>
</td>
<td>
@Html.DropDownList("CategoryList", CategorySelectList, "Select a Category (Optional)")
</td>
</tr>
Source: http://www.java2s.com/Code/Java/File-Input-Output/Getextensionpathandfilename.htm
such an utility class :
class Filename {
private String fullPath;
private char pathSeparator, extensionSeparator;
public Filename(String str, char sep, char ext) {
fullPath = str;
pathSeparator = sep;
extensionSeparator = ext;
}
public String extension() {
int dot = fullPath.lastIndexOf(extensionSeparator);
return fullPath.substring(dot + 1);
}
public String filename() { // gets filename without extension
int dot = fullPath.lastIndexOf(extensionSeparator);
int sep = fullPath.lastIndexOf(pathSeparator);
return fullPath.substring(sep + 1, dot);
}
public String path() {
int sep = fullPath.lastIndexOf(pathSeparator);
return fullPath.substring(0, sep);
}
}
usage:
public class FilenameDemo {
public static void main(String[] args) {
final String FPATH = "/home/mem/index.html";
Filename myHomePage = new Filename(FPATH, '/', '.');
System.out.println("Extension = " + myHomePage.extension());
System.out.println("Filename = " + myHomePage.filename());
System.out.println("Path = " + myHomePage.path());
}
}
You can also try to get the column names from panda data frame that returns columnn name as well dtype. here i'll read csv file from https://mlearn.ics.uci.edu/databases/autos/imports-85.data but you have define header that contain columns names.
import pandas as pd
url="https://mlearn.ics.uci.edu/databases/autos/imports-85.data"
df=pd.read_csv(url,header = None)
headers=["symboling","normalized-losses","make","fuel-type","aspiration","num-of-doors","body-style",
"drive-wheels","engine-location","wheel-base","length","width","height","curb-weight","engine-type",
"num-of-cylinders","engine-size","fuel-system","bore","stroke","compression-ratio","horsepower","peak-rpm"
,"city-mpg","highway-mpg","price"]
df.columns=headers
print df.columns
You can resolve this in several ways:
g++
in stead of gcc
: g++ -g -o MatSim MatSim.cpp
-lstdc++
: gcc -g -o MatSim MatSim.cpp -lstdc++
<string.h>
by <string>
This is a linker problem, not a compiler issue. The same problem is covered in the question iostream linker error – it explains what is going on.
Easy peasy:
var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));
Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings
string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");
Adding the following on top of your JS file will tell JSHint to supress the radix warning:
/*jshint -W065 */
See also: http://jshint.com/docs/#options
A different take on authentication is Passwordless, a token-based authentication module for express that circumvents the inherent problem of passwords [1]. It's fast to implement, doesn't require too many forms, and offers better security for the average user (full disclosure: I'm the author).
The right answer is
Decoupled the build-specific components of the Android SDK from the platform-tools component, so that the build tools can be updated independently of the integrated development environment (IDE) components.
public String getLocalIpAddress() {
try {
for (Enumeration < NetworkInterface > en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration < InetAddress > enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}
String String_firstNumber = JOptionPane.showInputDialog("Input Semisecond");
int Int_firstNumber = Integer.parseInt(firstNumber);
Now your Int_firstnumber
contains integer value of String_fristNumber
.
hope it helped
Based on previous answers, here are reusable "procedures" and a usage example for calculating the elapsed time:
@echo off
setlocal
set starttime=%TIME%
echo Start Time: %starttime%
REM ---------------------------------------------
REM --- PUT THE CODE YOU WANT TO MEASURE HERE ---
REM ---------------------------------------------
set endtime=%TIME%
echo End Time: %endtime%
call :elapsed_time %starttime% %endtime% duration
echo Duration: %duration%
endlocal
echo on & goto :eof
REM --- HELPER PROCEDURES ---
:time_to_centiseconds
:: %~1 - time
:: %~2 - centiseconds output variable
setlocal
set _time=%~1
for /F "tokens=1-4 delims=:.," %%a in ("%_time%") do (
set /A "_result=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)
endlocal & set %~2=%_result%
goto :eof
:centiseconds_to_time
:: %~1 - centiseconds
:: %~2 - time output variable
setlocal
set _centiseconds=%~1
rem now break the centiseconds down to hors, minutes, seconds and the remaining centiseconds
set /A _h=%_centiseconds% / 360000
set /A _m=(%_centiseconds% - %_h%*360000) / 6000
set /A _s=(%_centiseconds% - %_h%*360000 - %_m%*6000) / 100
set /A _hs=(%_centiseconds% - %_h%*360000 - %_m%*6000 - %_s%*100)
rem some formatting
if %_h% LSS 10 set _h=0%_h%
if %_m% LSS 10 set _m=0%_m%
if %_s% LSS 10 set _s=0%_s%
if %_hs% LSS 10 set _hs=0%_hs%
set _result=%_h%:%_m%:%_s%.%_hs%
endlocal & set %~2=%_result%
goto :eof
:elapsed_time
:: %~1 - time1 - start time
:: %~2 - time2 - end time
:: %~3 - elapsed time output
setlocal
set _time1=%~1
set _time2=%~2
call :time_to_centiseconds %_time1% _centi1
call :time_to_centiseconds %_time2% _centi2
set /A _duration=%_centi2%-%_centi1%
call :centiseconds_to_time %_duration% _result
endlocal & set %~3=%_result%
goto :eof
For Centos 7 and PHP 7.3 on Remi
Search for the zip extension:
$ yum search php73 | grep zip
php73-php-pecl-zip.x86_64 : A ZIP archive management extension
The extension name is php73-php-pecl-zip.x86_64. To install it in server running single version of PHP, remove the prefix php73:
$ sudo yum --enablerepo=remi-php73 install php-pecl-zip #for server running single PHP7.3 version
$ #sudo yum --enablerepo=remi-php73 install php73-php-pecl-zip # for server running multiple PHP versions
Restart PHP:
$ sudo systemctl restart php-fpm
Check installed PHP extensions:
$ php -m
[PHP Modules]
apcu
bcmath
bz2
...
zip
zlib
u can do lik
var config = {
// TODO: Add common Configuration
module: {},
};
var x= Object.assign({}, config, {
name: "x",
entry: "./public/x/js/x.js",
output: {
path: __dirname+"/public/x/jsbuild",
filename: "xbundle.js"
},
});
var y= Object.assign({}, config, {
name: "y",
entry: "./public/y/js/FBRscript.js",
output: {
path: __dirname+"/public/fbr/jsbuild",
filename: "ybundle.js"
},
});
let list=[x,y];
for(item of list){
module.exports =item;
}
There's a few things that could get in the way - is your data clean?
It could be that you have spaces at the end of the first name field, which then means you have two spaces between the firstname and lastname when you concat them? Using trim(first_name)/trim(last_name) will fix this - although the real fix is to update your data.
You could also this to match where two words both occur but not necessarily together (assuming you are in php - which the $search_term variable suggests you are)
$whereclauses=array();
$terms = explode(' ', $search_term);
foreach ($terms as $term) {
$term = mysql_real_escape_string($term);
$whereclauses[] = "CONCAT(first_name, ' ', last_name) LIKE '%$term%'";
}
$sql = "select * from table where";
$sql .= implode(' and ', $whereclauses);
Like @user293153 I only just discovered this question and it didn't seem to be answered correctly.
His answer was best. But you can also animate to the element as well.
$('html, body').animate({ scrollTop: $("#some_element").offset().top }, 500);
HTTP sends bytes. If the resource in question is text, the character encoding is normally specified, either by the Content-Type HTTP header or by another mechanism (an RFC, HTML meta http-equiv
,...).
urllib
should know how to encode the bytes to a string, but it's too naïve—it's a horribly underpowered and un-Pythonic library.
Dive Into Python 3 provides an overview about the situation.
Your "work-around" is fine—although it feels wrong, it's the correct way to do it.
You can "cast" to number using the Number constructor..
var number = new Number("8"); // 8 number
You can also call parseInt builtin function:
var number = parseInt("153"); // 153 number
You were on the right track with response.getOutputStream()
, but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:
@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
// convert JSON to Employee
Employee emp = convertSomehow(json);
// generate the file
PdfUtil.showHelp(emp);
// retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
byte[] contents = (...);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
// Here you have to set the actual filename of your pdf
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
return response;
}
Notes:
showHelp
is not a good ideabyte[]
: example hereshowHelp()
to avoid overwriting the file if two users send a request at the same time$TEST="ok"
read MYTEXT <<EOT
this bash trick
should preserve
newlines $TEST
long live perl
EOT
echo -e $MYTEXT
JavaScript is duck-typed, so if you just copy a readable stream's API, it'll work just fine. In fact, you can probably not implement most of those methods or just leave them as stubs; all you'll need to implement is what the library uses. You can use Node's pre-built EventEmitter
class to deal with events, too, so you don't have to implement addListener
and such yourself.
Here's how you might implement it in CoffeeScript:
class StringStream extends require('events').EventEmitter
constructor: (@string) -> super()
readable: true
writable: false
setEncoding: -> throw 'not implemented'
pause: -> # nothing to do
resume: -> # nothing to do
destroy: -> # nothing to do
pipe: -> throw 'not implemented'
send: ->
@emit 'data', @string
@emit 'end'
Then you could use it like so:
stream = new StringStream someString
doSomethingWith stream
stream.send()
The solutions using hasattr(obj, '__call__')
and callable(.)
mentioned in some of the answers have a main drawback: both also return True
for classes and instances of classes with a __call__()
method. Eg.
>>> import collections
>>> Test = collections.namedtuple('Test', [])
>>> callable(Test)
True
>>> hasattr(Test, '__call__')
True
One proper way of checking if an object is a user-defined function (and nothing but a that) is to use isfunction(.)
:
>>> import inspect
>>> inspect.isfunction(Test)
False
>>> def t(): pass
>>> inspect.isfunction(t)
True
If you need to check for other types, have a look at inspect — Inspect live objects.
In addition to install the build tools and restart the update manager I also had to restart Eclipse to make this work.
Try this, at the end of the each loop, ids array will contain all the hexcodes.
var ids = [];
$(document).ready(function($) {
var $div = $("<div id='hexCodes'></div>").appendTo(document.body), code;
$(".color_cell").each(function() {
code = $(this).attr('id');
ids.push(code);
$div.append(code + "<br />");
});
});
While refresh token is retained by the Authorization server. Access token are self-contained so resource server can verify it without storing it which saves the effort of retrieval in case of validation. Another point missing in discussion is from rfc6749#page-55
"For example, the authorization server could employ refresh token rotation in which a new refresh token is issued with every access token refresh response.The previous refresh token is invalidated but retained by the authorization server. If a refresh token is compromised and subsequently used by both the attacker and the legitimate client, one of them will present an invalidated refresh token, which will inform the authorization server of the breach."
I think the whole point of using refresh token is that even if attacker somehow manages to get refresh token, client ID and secret combination. With subsequent calls to get new access token from attacker can be tracked in case if every request for refresh result in new access token and refresh token.
Hi, This is my example of calculating the difference between two dates
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://code.jquery.com/jquery.min.js"></script>
<title>JS Bin</title>
</head>
<body>
<br>
<input class='fromdate' type="date" />
<input class='todate' type="date" />
<div class='calculated' /><br>
<div class='minim' />
<input class='todate' type="submit" onclick='showDays()' />
</body>
</html>
This is the function that calculates the difference :
function showDays(){
var start = $('.fromdate').val();
var end = $('.todate').val();
var startDay = new Date(start);
var endDay = new Date(end);
var millisecondsPerDay = 1000 * 60 * 60 * 24;
var millisBetween = endDay.getTime() - startDay.getTime();
var days = millisBetween / millisecondsPerDay;
// Round down.
alert( Math.floor(days));
}
I hope I have helped you
MozWebSocket
MozWebSocket
Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.
See caniuse for the current status of WebSockets support in desktop and mobile browsers.
See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.
It depends on which language you use.
In Java/Java EE:
V 7.5 supports RFC6455
- Jetty 9.1 supports javax.websocket / JSR 356)V 3.1.2 supports RFC6455
V 4.0.25 supports RFC6455
V 7.0.28 supports RFC6455
Some other Java implementations:
V 5.6 supports RFC6455
V 2.10 supports RFC6455
In C#:
In PHP:
In Python:
In C:
In Node.js:
Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :
Pusher.com is a Websocket cloud service accessible through a REST API.
DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.
Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.
For other language implementations, see the Wikipedia article for more information.
The RFC for Websockets : RFC6455
Another issue is that your database may be in a "non-trusted" location. Go to the trust center settings and add your database location to the trusted locations list.
you can use
@Html.Raw(str)
See MSDN for more
Returns markup that is not HTML encoded.
This method wraps HTML markup using the IHtmlString class, which renders unencoded HTML.
Also in addition to above solutions, also check the location where the tnsname ora file exists and compare with the path in the environment variable
You definitely need to put in the column order, otherwise how is SQL Server supposed to know which one goes first? Here's what you would need to do in your code:
public class MyTable
{
[Key, Column(Order = 0)]
public string SomeId { get; set; }
[Key, Column(Order = 1)]
public int OtherId { get; set; }
}
You can also look at this SO question. If you want official documentation, I would recommend looking at the official EF website. Hope this helps.
EDIT: I just found a blog post from Julie Lerman with links to all kinds of EF 6 goodness. You can find whatever you need here.
Single quoted php string variable works.
$str = 'http://www.domain.com/data/images\flags/en.gif';
$str = str_replace('\\', '/', $str);
the simple way is passing through constructor
RadioButton radioButton = new RadioButton(this,null,R.style.radiobutton_material_quiz);
You can use this to figure out keyCodes easily:
$(document).keyup(function(e) {
// Displays the keycode of the last pressed key in the body
$(document.body).html(e.keyCode);
});
<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %> <i class="fa fa-facebook"> Facebook Share </i> <%end%>
I am assuming that current_article_url
is http://0.0.0.0:4567/link_to_title
Have you checked MZTools?? It does a lot of cool stuff...
If I'm not wrong, one of the functionalities it offers is to set your own shortcuts.
That is a very strange way to organize things. If you stored in a dictionary, this is easy:
# This example should work in any version of Python.
# urls_d will contain URL keys, with counts as values, like: {'http://www.google.fr/' : 1 }
urls_d = {}
for url in list_of_urls:
if not url in urls_d:
urls_d[url] = 1
else:
urls_d[url] += 1
This code for updating a dictionary of counts is a common "pattern" in Python. It is so common that there is a special data structure, defaultdict
, created just to make this even easier:
from collections import defaultdict # available in Python 2.5 and newer
urls_d = defaultdict(int)
for url in list_of_urls:
urls_d[url] += 1
If you access the defaultdict
using a key, and the key is not already in the defaultdict
, the key is automatically added with a default value. The defaultdict
takes the callable you passed in, and calls it to get the default value. In this case, we passed in class int
; when Python calls int()
it returns a zero value. So, the first time you reference a URL, its count is initialized to zero, and then you add one to the count.
But a dictionary full of counts is also a common pattern, so Python provides a ready-to-use class: containers.Counter
You just create a Counter
instance by calling the class, passing in any iterable; it builds a dictionary where the keys are values from the iterable, and the values are counts of how many times the key appeared in the iterable. The above example then becomes:
from collections import Counter # available in Python 2.7 and newer
urls_d = Counter(list_of_urls)
If you really need to do it the way you showed, the easiest and fastest way would be to use any one of these three examples, and then build the one you need.
from collections import defaultdict # available in Python 2.5 and newer
urls_d = defaultdict(int)
for url in list_of_urls:
urls_d[url] += 1
urls = [{"url": key, "nbr": value} for key, value in urls_d.items()]
If you are using Python 2.7 or newer you can do it in a one-liner:
from collections import Counter
urls = [{"url": key, "nbr": value} for key, value in Counter(list_of_urls).items()]
Type ctor, and then press the Tab key.
Plus, you should make sure the MySQL server's config (/etc/mysql/my.cnf, /etc/default/mysql on Debian) doesn't have "skip-networking" activated and is not binded exclusively to the loopback interface (127.0.0.1) but also to the interface/IP address you want connect to.
Here is very simple javascript. It works fine for me :
// JavaScript:
function sFocus (field) {
if(field.value == 'Enter your search') {
field.value = '';
}
field.className = "darkinput";
}
function sBlur (field) {
if (field.value == '') {
field.value = 'Enter your search';
field.className = "lightinput";
}
else {
field.className = "darkinput";
}
}
// HTML
<form>
<label class="screen-reader-text" for="s">Search for</label>
<input
type="text"
class="lightinput"
onfocus="sFocus(this)"
onblur="sBlur(this)"
value="Enter your search" name="s" id="s"
/>
</form>
Yes, there is a problem with pointers. Very likely you're using one that's not initialized properly, but it's also possible that you're messing up your memory management with double frees or some such.
To avoid uninitialized pointers as local variables, try declaring them as late as possible, preferably (and this isn't always possible) when they can be initialized with a meaningful value. Convince yourself that they will have a value before they're being used, by examining the code. If you have difficulty with that, initialize them to a null pointer constant (usually written as NULL
or 0
) and check them.
To avoid uninitialized pointers as member values, make sure they're initialized properly in the constructor, and handled properly in copy constructors and assignment operators. Don't rely on an init
function for memory management, although you can for other initialization.
If your class doesn't need copy constructors or assignment operators, you can declare them as private member functions and never define them. That will cause a compiler error if they're explicitly or implicitly used.
Use smart pointers when applicable. The big advantage here is that, if you stick to them and use them consistently, you can completely avoid writing delete
and nothing will be double-deleted.
Use C++ strings and container classes whenever possible, instead of C-style strings and arrays. Consider using .at(i)
rather than [i]
, because that will force bounds checking. See if your compiler or library can be set to check bounds on [i]
, at least in debug mode. Segmentation faults can be caused by buffer overruns that write garbage over perfectly good pointers.
Doing those things will considerably reduce the likelihood of segmentation faults and other memory problems. They will doubtless fail to fix everything, and that's why you should use valgrind now and then when you don't have problems, and valgrind and gdb when you do.
See my comment. You need to include the full org.json library when running as android.jar only contains stubs to compile against.
In addition, you must remove the two instances of extra }
in your JSON data following longitude
.
private final static String JSON_DATA =
"{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " ]"
+ "}";
Apart from that, geodata
is in fact not a JSONObject
but a JSONArray
.
Here is the fully working and tested corrected code:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class ShowActivity {
private final static String JSON_DATA =
"{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " ]"
+ "}";
public static void main(final String[] argv) throws JSONException {
final JSONObject obj = new JSONObject(JSON_DATA);
final JSONArray geodata = obj.getJSONArray("geodata");
final int n = geodata.length();
for (int i = 0; i < n; ++i) {
final JSONObject person = geodata.getJSONObject(i);
System.out.println(person.getInt("id"));
System.out.println(person.getString("name"));
System.out.println(person.getString("gender"));
System.out.println(person.getDouble("latitude"));
System.out.println(person.getDouble("longitude"));
}
}
}
Here's the output:
C:\dev\scrap>java -cp json.jar;. ShowActivity
1
Julie Sherman
female
37.33774833333334
-121.88670166666667
2
Johnny Depp
male
37.336453
-121.884985
{
// any valid js expression
}
If you wonder why does it work? it's because everything that's inside curly braces { } is a javascript expression,
so this is fine as well:
{ /*
yet another js expression
*/ }
You can use CURL for this purpose see the example code:
$url = "your url";
$content = json_encode("your data to be sent");
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, true);
No, the dataType
option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify
and set the processData
option to false
.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON
object, and although jQuery has .parseJSON
, it has no stringifier included; you'll need another polyfill library.
This is a server side issue. You don't need to add any headers in angular for cors. You need to add header on the server side:
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *
First two answers here: How to enable CORS in AngularJs
http://jsfiddle.net/mpalpha/71Lhcb5q/
.container {
display: flex;
background: blue;
padding: 10px;
max-height: 200px;
max-width: 200px;
}
img {
object-fit: contain;
max-height: 100%;
max-width: 100%;
}
_x000D_
<div class="container">
<img src="http://placekitten.com/400/500" />
</div>
_x000D_
It's not out yet, but the next version of cocos2d (2d game framework) will support variable length bitmap fonts as character maps.
http://code.google.com/p/cocos2d-iphone/issues/detail?id=317
The author doesn't have a nailed down release date for this version, but I did see a posting that indicated it would be in the next month or two.
Untested....but should work.
Dim lastrow as long
lastrow = range("D65000").end(xlup).Row
ActiveCell.FormulaR1C1 = _
"=IF(MONTH(RC[-1])>3,"" ""&YEAR(RC[-1])&""-""&RIGHT(YEAR(RC[-1])+1,2),"" ""&YEAR(RC[-1])-1&""-""&RIGHT(YEAR(RC[-1]),2))"
Selection.AutoFill Destination:=Range("E2:E" & lastrow)
'Selection.AutoFill Destination:=Range("E2:E"& lastrow)
Range("E2:E1344").Select
Only exception being are you sure your Autofill code is perfect...
realpath
is probably best
But ...
The initial question was very confused to start with, with an example poorly related to the question as stated.
The selected answer actually answers the example given, and not at all the question in the title. The first command is that answer (is it really ? I doubt), and could do as well without the '/'. And I fail to see what the second command is doing.
Several issues are mixed :
changing a relative pathname into an absolute one, whatever it
denotes, possibly nothing.
(Typically, if you issue a command such as touch foo/bar
, the
pathname foo/bar
must exist for you, and possibly be used in
computation, before the file is actually created.)
there may be several absolute pathname that denote the same file (or potential file), notably because of symbolic links (symlinks) on the path, but possibly for other reasons (a device may be mounted twice as read-only). One may or may not want to resolve explicity such symlinks.
getting to the end of a chain of symbolic links to a non-symlink file or name. This may or may not yield an absolute path name, depending on how it is done. And one may, or may not want to resolve it into an absolute pathname.
The command readlink foo
without option gives an answer only if its
argument foo
is a symbolic link, and that answer is the value of that
symlink. No other link is followed. The answer may be a relative path:
whatever was the value of the symlink argument.
However, readlink
has options (-f -e or -m) that will work for all
files, and give one absolute pathname (the one with no symlinks) to
the file actually denoted by the argument.
This works fine for anything that is not a symlink, though one might
desire to use an absolute pathname without resolving the intermediate
symlinks on the path. This is done by the command realpath -s foo
In the case of a symlink argument, readlink
with its options will
again resolve all symlinks on the absolute path to the argument, but
that will also include all symlinks that may be encountered by
following the argument value. You may not want that if you desired an
absolute path to the argument symlink itself, rather than to whatever
it may link to. Again, if foo
is a symlink, realpath -s foo
will
get an absolute path without resolving symlinks, including the one
given as argument.
Without the -s
option, realpath
does pretty much the same as
readlink
, except for simply reading the value of a link, as well as several
other things. It is just not clear to me why readlink
has its
options, creating apparently an undesirable redundancy with
realpath
.
Exploring the web does not say much more, except that there may be some variations across systems.
Conclusion : realpath
is the best command to use, with the most
flexibility, at least for the use requested here.
Somewhere in your code there is a line #include <string>
. This by itself tells you that the program is written in C++. So using g++
is better than gcc
.
For the missing library: you should look around in the file system if you can find a file called libl.so
. Use the locate
command, try /usr/lib
, /usr/local/lib
, /opt/flex/lib
, or use the brute-force find / | grep /libl
.
Once you have found the file, you have to add the directory to the compiler command line, for example:
g++ -o scan lex.yy.c -L/opt/flex/lib -ll
The problem is somewhere else in your code, because this works:
string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));
cout << "* size of the vector: " << strs.size() << endl;
for (size_t i = 0; i < strs.size(); i++)
cout << strs[i] << endl;
and testing your approach, which uses a vector iterator also works:
string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));
cout << "* size of the vector: " << strs.size() << endl;
for (vector<string>::iterator it = strs.begin(); it != strs.end(); ++it)
{
cout << *it << endl;
}
Again, your problem is somewhere else. Maybe what you think is a \t
character on the string, isn't. I would fill the code with debugs, starting by monitoring the insertions on the vector to make sure everything is being inserted the way its supposed to be.
Output:
* size of the vector: 3
test
test2
test3
Run in a subshell to remove notifications and close STDOUT and STDERR:
(&>/dev/null script.sh &)
After playing with it for a very long time, this is what I came up with:
jQuery.fn.scrollTo = function (elem) {
var b = $(elem);
this.scrollTop(b.position().top + b.height() - this.height());
};
and I call it like this
$("#basketListGridHolder").scrollTo('tr[data-uid="' + basketID + '"]');
Just encase someone else ran into the issues I did I was using Response.End() an async trigger button
<asp:AsyncPostBackTrigger ControlID="btn_login" />
in an update panel. I switched to regular post back not the best but it worked.
<asp:PostBackTrigger ControlID="btn_login" />.
Since I was only redirecting on the page this was a viable solution.
building '_mysql' extension
creating build\temp.win-amd64-2.7
creating build\temp.win-amd64-2.7\Release
C:\Users\TimHuang\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" -Ic:\python27\include -Ic:\python27\PC /Tc_mysql.c /Fobuild\temp.win-amd64-2.7\Release\_mysql.obj /Zl
_mysql.c
_mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory
If you see this when you try pip install mysql-python
, the easiest way is to copy
C:\Program Files\MySQL\MySQL Connector C 6.0.2
to C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2
I tried to create the symbolic link but Windows keeps throwing me
C:\WINDOWS\system32>mklink /d "C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" "C:\Program Files\MySQL\MySQL Connector C 6.0.2\include"
The system cannot find the path specified.
This will change your current working directory to so that opening relative paths will work:
import os
os.chdir("/home/udi/foo")
However, you asked how to change into whatever directory your Python script is located, even if you don't know what directory that will be when you're writing your script. To do this, you can use the os.path
functions:
import os
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
This takes the filename of your script, converts it to an absolute path, then extracts the directory of that path, then changes into that directory.
in normal time, checkboxes return an on/off value.
you can verify it with this code:
<form action method="POST">
<input type="checkbox" name="hello"/>
</form>
<?php
if(isset($_POST['hello'])) echo('<p>'.$_POST['hello'].'</p>');
?>
this will return
<p>off</p>
or
<p>on</p>
For Visual Studio 2005:
If you do have an installed Visual Studio 2005 however, and want to find out the serial number you’ve used to install it because you don’t have a clue where you put that shiny sticker, you can. It is, like most things in Windows, in the registry.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\8.0\Registration\PIDKEY
In order to convert the value in that key to an actual serial number you have to put a dash ( – ) after evert 5 characters of the code.
From: http://www.gooli.org/blog/visual-studio-2005-serial-number/
For Visual Studio 2008 it's supposed to be:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Registration\PIDKEY
However I noted that the the Data field for PIDKEY is only filled in the 1000.0x000
(or 2000.0x000) sub folder of the above paths.
If this is a submit button, use <input type="image" src="..." ... />
.
http://www.htmlcodetutorial.com/forms/_INPUT_TYPE_IMAGE.html
If you want to specify the image with CSS, you'll have to use type="submit"
.
The situation is essentially that VS
is not set up to go through a proxy to get to the resources it's trying to get to (when using FTP). This is the cause of the 407 error you're getting. I did some research on this and there are a few things that you can try to get this debugged. Fundamentally this is a bit of a flawed area in the product that is supposed to be reviewed in a later release.
Here are some solutions, in order of less complex to more complex:
VS
.devenv.exe.config
add <servicePointManager expect100Continue="false" />
as laid out below:<configuration>
<system.net>
<settings>
<servicePointManager expect100Continue="false" />
</settings>
</system.net>
</configuration>
defaultProxy
settings as follows:<system.net>
<defaultProxy useDefaultCredentials="true" enabled="true">
<proxy proxyaddress="http://your.proxyserver.ip:port"/>
</defaultProxy>
<settings>
...
<defaultProxy useDefaultCredentials="true" enabled="true">
<proxy usesystemdefault="True" />
</defaultProxy>
Hope this solves it for you.
the above is not bad, however its kinda different for 11.10
sudo apt-get install ruby1.9 rubygems1.9
that will install ruby 1.9
when linking, you just use ls /usr/bin | grep ruby
it should output ruby1.9.1
so then you sudo ln -sf /usr/bin/ruby1.9.1 /usr/bin/ruby
and your off to the races.
use flex
.parent{
display: flex
}
.fit-parent{
display: flex;
flex-grow: 1
}
This works in my case:
@RequestMapping(value = "/savedata",
params = {"textArea", "localKey", "localFile"})
@ResponseBody
public void saveData(@RequestParam(value = "textArea") String textArea,
@RequestParam(value = "localKey") String localKey,
@RequestParam(value = "localFile") String localFile) {
}
I faced this exact same issue with Laravel 8.x on Ubuntu 20.
I run: sudo apt install php7.4-xml
and composer update
within the project directory. This fixed the issue.
And, if you don't want to instantiate Class2, declare UpdateEmployee as static and call it like this:
Class2.UpdateEmployee();
However, you'll normally want to do what @parag said.
As your error states, you have to define drawable attibute for the items (for some reason it is required when it comes to background definitions), so:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/red"/> <!-- pressed -->
<item android:state_focused="true" android:drawable="@color/blue"/> <!-- focused -->
<item android:drawable="@color/black"/> <!-- default -->
</selector>
Also note that drawable attribute doesn't accept raw color values, so you have to define the colors as resources. Create colors.xml file at res/values folder:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="black">#000</color>
<color name="blue">#00f</color>
<color name="red">#f00</color>
</resources>
And to add multiple library files you can write as below:
INCLUDEPATH *= E:/DebugLibrary/VTK E:/DebugLibrary/VTK/Common E:/DebugLibrary/VTK/Filtering E:/DebugLibrary/VTK/GenericFiltering E:/DebugLibrary/VTK/Graphics E:/DebugLibrary/VTK/GUISupport/Qt E:/DebugLibrary/VTK/Hybrid E:/DebugLibrary/VTK/Imaging E:/DebugLibrary/VTK/IO E:/DebugLibrary/VTK/Parallel E:/DebugLibrary/VTK/Rendering E:/DebugLibrary/VTK/Utilities E:/DebugLibrary/VTK/VolumeRendering E:/DebugLibrary/VTK/Widgets E:/DebugLibrary/VTK/Wrapping
LIBS *= -LE:/DebugLibrary/VTKBin/bin/release -lvtkCommon -lvtksys -lQVTK -lvtkWidgets -lvtkRendering -lvtkGraphics -lvtkImaging -lvtkIO -lvtkFiltering -lvtkDICOMParser -lvtkpng -lvtktiff -lvtkzlib -lvtkjpeg -lvtkexpat -lvtkNetCDF -lvtkexoIIc -lvtkftgl -lvtkfreetype -lvtkHybrid -lvtkVolumeRendering -lQVTKWidgetPlugin -lvtkGenericFiltering
Not really answering your question but if you want the benefits of Distributed Revision Control - it sounds like you do - and you're using Windows I think you'd be better off using Mercurial rather that Git as Mercurial has much better Windows support. Mercurial does have a Mac port too.
Firstly, Stack structure can be examined. For the launch mode:singleTop
If an instance of the same activity is already on top of the task stack, then this instance will be reused to respond to the intent.
All activities are hold in the stack("first in last out") so if your current activity is at the top of stack and if you define it in the manifest.file as singleTop
android:name=".ActivityA"
android:launchMode="singleTop"
if you are in the ActivityA recreate the activity it will not enter onCreate will resume onNewIntent() and you can see by creating a notification Not:If you do not implement onNewIntent(Intent) you will not get new intent.
Intent activityMain = new Intent(ActivityA.this,
ActivityA.class);
activityMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(activityMain);
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
notify("onNewIntent");
}
private void notify(String methodName) {
String name = this.getClass().getName();
String[] strings = name.split("\\.");
Notification noti = new Notification.Builder(this)
.setContentTitle(methodName + "" + strings[strings.length - 1])
.setAutoCancel(true).setSmallIcon(R.drawable.ic_launcher)
.setContentText(name).build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify((int) System.currentTimeMillis(), noti);
}
Just add margin: 0 auto;
to the inside div.
After wasting many hours, I came across this!
It translates tap events as click events. Remember to load the script after jquery.
I got this working on the iPad and iPhone
$('#movable').draggable({containment: "parent"});
def square(a):
squares = []
for i in a:
squares.append(i**2)
return squares
so how would i do the square of numbers from 1-20 using the above function
HTML--
<div class="col-sm-12" id="my_styles">
<button type="submit" class="btn btn-warning" id="1">Button1</button>
<button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>
css--
.active{
background:red;
}
button.btn:active{
background:red;
}
jQuery--
jQuery("#my_styles .btn").click(function(){
jQuery("#my_styles .btn").removeClass('active');
jQuery(this).toggleClass('active');
});
view the live demo on jsfiddle
If you have UTF8, use this (actually works with SVG source), like:
btoa(unescape(encodeURIComponent(str)))
example:
var imgsrc = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(markup)));
var img = new Image(1, 1); // width, height values are optional params
img.src = imgsrc;
If you need to decode that base64, use this:
var str2 = decodeURIComponent(escape(window.atob(b64)));
console.log(str2);
Example:
var str = "äöüÄÖÜçéèñ";
var b64 = window.btoa(unescape(encodeURIComponent(str)))
console.log(b64);
var str2 = decodeURIComponent(escape(window.atob(b64)));
console.log(str2);
Note: if you need to get this to work in mobile-safari, you might need to strip all the white-space from the base64 data...
function b64_to_utf8( str ) {
str = str.replace(/\s/g, '');
return decodeURIComponent(escape(window.atob( str )));
}
2017 Update
This problem has been bugging me again.
The simple truth is, atob doesn't really handle UTF8-strings - it's ASCII only.
Also, I wouldn't use bloatware like js-base64.
But webtoolkit does have a small, nice and very maintainable implementation:
/**
*
* Base64 encode / decode
* http://www.webtoolkit.info
*
**/
var Base64 = {
// private property
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
// public method for encoding
, encode: function (input)
{
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length)
{
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2))
{
enc3 = enc4 = 64;
}
else if (isNaN(chr3))
{
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
} // Whend
return output;
} // End Function encode
// public method for decoding
,decode: function (input)
{
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length)
{
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64)
{
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64)
{
output = output + String.fromCharCode(chr3);
}
} // Whend
output = Base64._utf8_decode(output);
return output;
} // End Function decode
// private method for UTF-8 encoding
,_utf8_encode: function (string)
{
var utftext = "";
string = string.replace(/\r\n/g, "\n");
for (var n = 0; n < string.length; n++)
{
var c = string.charCodeAt(n);
if (c < 128)
{
utftext += String.fromCharCode(c);
}
else if ((c > 127) && (c < 2048))
{
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else
{
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
} // Next n
return utftext;
} // End Function _utf8_encode
// private method for UTF-8 decoding
,_utf8_decode: function (utftext)
{
var string = "";
var i = 0;
var c, c1, c2, c3;
c = c1 = c2 = 0;
while (i < utftext.length)
{
c = utftext.charCodeAt(i);
if (c < 128)
{
string += String.fromCharCode(c);
i++;
}
else if ((c > 191) && (c < 224))
{
c2 = utftext.charCodeAt(i + 1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else
{
c2 = utftext.charCodeAt(i + 1);
c3 = utftext.charCodeAt(i + 2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
} // Whend
return string;
} // End Function _utf8_decode
}
https://www.fileformat.info/info/unicode/utf8.htm
For any character equal to or below 127 (hex 0x7F), the UTF-8 representation is one byte. It is just the lowest 7 bits of the full unicode value. This is also the same as the ASCII value.
For characters equal to or below 2047 (hex 0x07FF), the UTF-8 representation is spread across two bytes. The first byte will have the two high bits set and the third bit clear (i.e. 0xC2 to 0xDF). The second byte will have the top bit set and the second bit clear (i.e. 0x80 to 0xBF).
For all characters equal to or greater than 2048 but less that 65535 (0xFFFF), the UTF-8 representation is spread across three bytes.
Here is how to synchronize PHP (>=5.3) and MySQL timezones per session and user settings. Put this where it runs when you need set and synchronized timezones.
date_default_timezone_set($my_timezone);
$n = new \DateTime();
$h = $n->getOffset()/3600;
$i = 60*($h-floor($h));
$offset = sprintf('%+d:%02d', $h, $i);
$this->db->query("SET time_zone='$offset'");
Where $my_timezone is one in the list of PHP timezones: http://www.php.net/manual/en/timezones.php
The PHP timezone has to be converted into the hour and minute offset for MySQL. That's what lines 1-4 do.
The problem is that when you are doing additions and multiplications of numbers all with two decimal places, you expect there will be no rounding errors, but remember the internal representation of double is in base 2, not in base 10 ! So a number like 0.1 in base 10 may be in base 2 : 0.101010101010110011... with an infinite number of decimals (the value stored in the double will be a number N with :
0.1-Math.Pow(2,-64) < N < 0.1+Math.Pow(2,-64)
As a consequence an operation like 12.3 + 0.1 may be not the same exact 64 bits double value as 12.4 (or 12.456 * 10 may be not the same as 124.56) because of rounding errors. For example if you store in a Database the result of 12.3 +0.1 into a table/column field of type double precision number and then SELECT WHERE xx=12.4 you may realize that you stored a number that is not exactly 12.4 and the Sql select will not return the record; So if you cannot use the decimal datatype (which has internal representation in base 10) and must use the 'double' datatype, you have to do some normalization after each addition or multiplication :
double freqMHz= freqkHz.MulRound(0.001); // freqkHz*0.001
double amountEuro= amountEuro.AddRound(delta); // amountEuro+delta
public static double AddRound(this double d,double val)
{
return double.Parse(string.Format("{0:g14}", d+val));
}
public static double MulRound(this double d,double val)
{
return double.Parse(string.Format("{0:g14}", d*val));
}
Simplest way I've found:
in your activity XML add these lines:
<ListView
...
android:choiceMode="singleChoice"
android:listSelector="#666666"
/>
or programatically set these properties:
listView.setSelector(Drawable selector)
listView.setSelector(int resourceId)
My particular example:
<ListView
android:choiceMode="singleChoice"
android:listSelector="#666666"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/listView"/>
thanks to AJG: https://stackoverflow.com/a/25131125/1687010
It's possible without jQuery too! :)
let countries = ['United States', 'Canada', 'Argentina', 'Armenia', 'Aruba'];_x000D_
_x000D_
// The <ul> that we will add <li> elements to:_x000D_
let myList = document.querySelector('ul.mylist');_x000D_
_x000D_
// Loop over the Array of country names:_x000D_
countries.forEach(function(value, index, array) {_x000D_
// Create an <li> element:_x000D_
let li = document.createElement('li');_x000D_
_x000D_
// Give it the desired classes & attributes:_x000D_
li.classList.add('ui-menu-item');_x000D_
li.setAttribute('role', 'menuitem');_x000D_
_x000D_
// Now create an <a> element:_x000D_
let a = document.createElement('a');_x000D_
_x000D_
// Give it the desired classes & attributes:_x000D_
a.classList.add('ui-all');_x000D_
a.tabIndex = -1;_x000D_
a.innerText = value; // <--- the country name from our Array_x000D_
a.href = "#"_x000D_
_x000D_
// Now add the <a> to the <li>, and add the <li> to the <ul>_x000D_
li.appendChild(a);_x000D_
myList.appendChild(li);_x000D_
});
_x000D_
<ul class="mylist"></ul>
_x000D_
Use defaultValue and onChange like this
const [myValue, setMyValue] = useState('');
<select onChange={(e) => setMyValue(e.target.value)} defaultValue={props.myprop}>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
I assume you mean the <select>
input element?
Support for that is pretty new, but FF 3.6, Chrome and IE 8 render this all right:
<select name="select">
<option value="1" style="background-color: blue">Test</option>
<option value="2" style="background-color: green">Test</option>
</select>
_x000D_
The way I usually do it is subtracting the two DateTime and this gets me a TimeSpan that will tell me the diff.
Here's an example:
DateTime start = DateTime.Now;
// Do some work
TimeSpan timeDiff = DateTime.Now - start;
timeDiff.TotalMilliseconds;
Quick n Short Answer
If you want to return a view, you should be in "Controller".
Normal Controller - ASP.NET MVC: you deal with normal "Controller" if you are in ASP.net Web Application. You can create Controller-Actions and you can return Views().
ApiController Controller: you create ApiControllers when you are developing ASP.net REST APIs. you can't return Views (though you can return Json/Data for HTML as string). These apis are considered as backend and their functions are called to return data not the view
Please dont forgt to mark this as answer, take care
If you don't want to convert the entire Map into an array beforehand, and/or destructure key-value arrays, you can use this silly function:
/**_x000D_
* Map over an ES6 Map._x000D_
*_x000D_
* @param {Map} map_x000D_
* @param {Function} cb Callback. Receives two arguments: key, value._x000D_
* @returns {Array}_x000D_
*/_x000D_
function mapMap(map, cb) {_x000D_
let out = new Array(map.size);_x000D_
let i = 0;_x000D_
map.forEach((val, key) => {_x000D_
out[i++] = cb(key, val);_x000D_
});_x000D_
return out;_x000D_
}_x000D_
_x000D_
let map = new Map([_x000D_
["a", 1],_x000D_
["b", 2],_x000D_
["c", 3]_x000D_
]);_x000D_
_x000D_
console.log(_x000D_
mapMap(map, (k, v) => `${k}-${v}`).join(', ')_x000D_
); // a-1, b-2, c-3
_x000D_
The (un)safe way to do this - if you are ok with not using option explicit - is...
Not TypeName(myObj) = "Empty"
This also handles the case if the object has not been declared. This is useful if you want to just comment out a declaration to switch off some behaviour...
Dim myObj as Object
Not TypeName(myObj) = "Empty" '/ true, the object exists - TypeName is Object
'Dim myObj as Object
Not TypeName(myObj) = "Empty" '/ false, the object has not been declared
This works because VBA will auto-instantiate an undeclared variable as an Empty Variant type. It eliminates the need for an auxiliary Boolean to manage the behaviour.
How to delete only the content of file in python
There is several ways of set the logical size of a file to 0, depending how you access that file:
To empty an open file:
def deleteContent(pfile):
pfile.seek(0)
pfile.truncate()
To empty a open file whose file descriptor is known:
def deleteContent(fd):
os.ftruncate(fd, 0)
os.lseek(fd, 0, os.SEEK_SET)
To empty a closed file (whose name is known)
def deleteContent(fName):
with open(fName, "w"):
pass
I have a temporary file with some content [...] I need to reuse that file
That being said, in the general case it is probably not efficient nor desirable to reuse a temporary file. Unless you have very specific needs, you should think about using tempfile.TemporaryFile
and a context manager to almost transparently create/use/delete your temporary files:
import tempfile
with tempfile.TemporaryFile() as temp:
# do whatever you want with `temp`
# <- `tempfile` guarantees the file being both closed *and* deleted
# on exit of the context manager
Step by step solution:
Change directory to directory of the keytool file location. Change directory by using command cd <directory path>
. (Note: if any directory name has space then add \ between the two words. Example cd /Applications/Android\ Studio.app//Contents/jre/jdk/Contents/Home/bin/
)
To find the location of your keytool, you go to android studio..open your project. And go to
File>project Structure>SDK location..and find JDK location.
Run the keytool by this command:
keytool -list -v –keystore <your jks file path>
(Note: if any directory name has space then add \ between the two words. example
keytool -list -v -keystore /Users/username/Desktop/tasmiah\ mobile/v3/jordanos.jks
)
Command prompt you to key in the password.. so key in your password.. then you get the result
Use FileInfo.Exists
Property:
DirectoryInfo di = new DirectoryInfo(ProcessingDirectory);
FileInfo[] TXTFiles = di.GetFiles("*.xml");
if (TXTFiles.Length == 0)
{
log.Info("no files present")
}
foreach (var fi in TXTFiles)
log.Info(fi.Exists);
or File.Exists
Method:
string curFile = @"c:\temp\test.txt";
Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");
(Note: An official API was added in API 14: See this answer https://stackoverflow.com/a/29786451/119733)
DO NOT USE PREVIOUS (waqas716) answer.
You will have memory leak problem, because of the static reference to the activity. For more detail see the following link http://android-developers.blogspot.fr/2009/01/avoiding-memory-leaks.html
To avoid this, you should manage activities references. Add the name of the application in the manifest file:
<application
android:name=".MyApp"
....
</application>
Your application class :
public class MyApp extends Application {
public void onCreate() {
super.onCreate();
}
private Activity mCurrentActivity = null;
public Activity getCurrentActivity(){
return mCurrentActivity;
}
public void setCurrentActivity(Activity mCurrentActivity){
this.mCurrentActivity = mCurrentActivity;
}
}
Create a new Activity :
public class MyBaseActivity extends Activity {
protected MyApp mMyApp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMyApp = (MyApp)this.getApplicationContext();
}
protected void onResume() {
super.onResume();
mMyApp.setCurrentActivity(this);
}
protected void onPause() {
clearReferences();
super.onPause();
}
protected void onDestroy() {
clearReferences();
super.onDestroy();
}
private void clearReferences(){
Activity currActivity = mMyApp.getCurrentActivity();
if (this.equals(currActivity))
mMyApp.setCurrentActivity(null);
}
}
So, now instead of extending Activity class for your activities, just extend MyBaseActivity. Now, you can get your current activity from application or Activity context like that :
Activity currentActivity = ((MyApp)context.getApplicationContext()).getCurrentActivity();
File "C:\pythonwork\readthefile080410.py", line 120, in medications_minimum3
counter[row[11]]+=1
TypeError: unhashable type: 'list'
row[11]
is unhashable. It's a list. That is precisely (and only) what the error message means. You might not like it, but that is the error message.
Do this
counter[tuple(row[11])]+=1
Also, simplify.
d= [ row for row in c if counter[tuple(row[11])]>=sample_cutoff ]
To start things off, the error QApplication: no such file or directory
means your compiler was not able to find this header. It is not related to the linking process as you mentioned in the question.
The -I
flag (uppercase i) is used to specify the include (headers) directory (which is what you need to do), while the -L
flag is used to specify the libraries directory. The -l
flag (lowercase L) is used to link your application with a specified library.
But you can use Qt to your advantage: Qt has a build system named qmake which makes things easier. For instance, when I want to compile main.cpp I create a main.pro file. For educational purposes, let's say this source code is a simple project that uses only QApplication
and QDeclarativeView
. An appropriate .pro file would be:
TEMPLATE += app
QT += gui declarative
SOURCES += main.cpp
Then, execute the qmake
inside that directory to create the Makefile that will be used to compile your application, and finally execute make
to get the job done.
On my system this make
outputs:
g++ -c -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_DECLARATIVE_LIB -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/opt/qt_47x/mkspecs/linux-g++ -I. -I/opt/qt_47x/include/QtCore -I/opt/qt_47x/include/QtGui -I/opt/qt_47x/include/QtDeclarative -I/opt/qt_47x/include -I/usr/X11R6/include -I. -o main.o main.cpp
g++ -Wl,-O1 -Wl,-rpath,/opt/qt_47x/lib -o main main.o -L/opt/qt_47x/lib -L/usr/X11R6/lib -lQtDeclarative -L/opt/qt_47x/lib -lQtScript -lQtSvg -L/usr/X11R6/lib -lQtSql -lQtXmlPatterns -lQtNetwork -lQtGui -lQtCore -lpthread
Note: I installed Qt in another directory --> /opt/qt_47x
Edit: Qt 5.x and later
Add QT += widgets
to the .pro file and solve this problem.
I guess a generic client-side JavaScript compression implementation would be a very expensive operation in terms of processing time as opposed to transfer time of a few more HTTP packets with uncompressed payload.
Have you done any testing that would give you an idea how much time there is to save? I mean, bandwidth savings can't be what you're after, or can it?
lapply is pretty much designed for this
unfactorize<-c("colA","colB")
df[,unfactorize]<-lapply(unfactorize, function(x) as.numeric(as.character(df[,x])))