you can use something like this....div
container
<script type="text/javascript">
function hide(){
document.getElementById("test").innerHTML.style.display="none";
}
</script>
<div id="test">
<form method="post" >
<table width="60%" border="0" cellspacing="2" cellpadding="2" >
<tr style="background:url(../images/nav.png) repeat-x; color:#fff; font-weight:bold" align="center">
<td>Ample Id</td>
<td>Find</td>
</tr>
<tr align="center" bgcolor="#E8F8FF" style="color:#006" >
<td><input type="text" name="ampid" id="ampid" value="<?php echo $_POST['ampid'];?>" /></td>
<td><input type="image" src="../images/btnFind.png" id="find" name="find" onclick="javascript:hide();"/></td>
</tr>
</table>
</form>
</div>
In my case was Promise with no reject neither resolve, because my Promise function threw an exception. This mistake cause UnhandledPromiseRejectionWarning message.
My 50 cents for getting a pip freeze
-like list from a Python script:
import pip
installed_packages = pip.get_installed_distributions()
installed_packages_list = sorted(["%s==%s" % (i.key, i.version)
for i in installed_packages])
print(installed_packages_list)
As a (too long) one liner:
sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])
Giving:
['behave==1.2.4', 'enum34==1.0', 'flask==0.10.1', 'itsdangerous==0.24',
'jinja2==2.7.2', 'jsonschema==2.3.0', 'markupsafe==0.23', 'nose==1.3.3',
'parse-type==0.3.4', 'parse==1.6.4', 'prettytable==0.7.2', 'requests==2.3.0',
'six==1.6.1', 'vioozer-metadata==0.1', 'vioozer-users-server==0.1',
'werkzeug==0.9.4']
This solution applies to the system scope or to a virtual environment scope, and covers packages installed by setuptools
, pip
and (god forbid) easy_install
.
I added the result of this call to my flask server, so when I call it with http://example.com/exampleServer/environment
I get the list of packages installed on the server's virtualenv. It makes debugging a whole lot easier.
I have noticed a strange behaviour of this technique - when the Python interpreter is invoked in the same directory as a setup.py
file, it does not list the package installed by setup.py
.
$ cd /tmp
$ virtualenv test_env
New python executable in test_env/bin/python
Installing setuptools, pip...done.
$ source test_env/bin/activate
(test_env) $
Clone a git repo with setup.py
(test_env) $ git clone https://github.com/behave/behave.git
Cloning into 'behave'...
remote: Reusing existing pack: 4350, done.
remote: Total 4350 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (4350/4350), 1.85 MiB | 418.00 KiB/s, done.
Resolving deltas: 100% (2388/2388), done.
Checking connectivity... done.
We have behave's setup.py
in /tmp/behave
:
(test_env) $ ls /tmp/behave/setup.py
/tmp/behave/setup.py
Install the python package from the git repo
(test_env) $ cd /tmp/behave && pip install .
running install
...
Installed /private/tmp/test_env/lib/python2.7/site-packages/enum34-1.0-py2.7.egg
Finished processing dependencies for behave==1.2.5a1
/tmp
>>> import pip
>>> sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])
['behave==1.2.5a1', 'enum34==1.0', 'parse-type==0.3.4', 'parse==1.6.4', 'six==1.6.1']
>>> import os
>>> os.getcwd()
'/private/tmp'
/tmp/behave
>>> import pip
>>> sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])
['enum34==1.0', 'parse-type==0.3.4', 'parse==1.6.4', 'six==1.6.1']
>>> import os
>>> os.getcwd()
'/private/tmp/behave'
behave==1.2.5a1
is missing from the second example, because the working directory contains behave
's setup.py
file.
I could not find any reference to this issue in the documentation. Perhaps I shall open a bug for it.
ActiveX resolved in Chrome!
Hello all this is not the solution but the successful workaround and I have implemented as well.
This required some implementation on client machine as well that why is most suitable for intranet environment and not recommended for public sites. Even though one can implement it for public sites as well the only problem is end user has to download/implement solution.
Lets understand the key problem
Chrome cannot communicate with ActiceX
Solution: Since Chorme cannot communicate with ActiveX but still it can communicate with the API hosted on the client machine. So develop API using .Net MVC or any other technology so that through Ajax call it can communicate with the API and API communicate with the ActiveX object situated on the client machine. Since API also resides in Client machine that why there is no problem in communication. This API works as mediator between Chrome browser and ActiveX.
During API implementation you might encounter CORS issues, Use JSONP to deal with it.
Pictorial view of the solution
Other solution : Use URI Scheme like MailTo: or MS-Word to deal with outlook and word application. If your requirement is different then you can implement your customized URI Scheme.
To extend Jamie Flournoy's solution to a directory tree, you can put this .gitignore in the top-level directory and touch .keepdir
in each subdirectory that git should track. All other files are ignored. This is useful to ensure a consistent structure for build directories.
# Ignore files but not directories. * matches both files and directories
# but */ matches only directories. Both match at every directory level
# at or below this one.
*
!*/
# Git doesn't track empty directories, so track .keepdir files, which also
# tracks the containing directory.
!.keepdir
# Keep this file and the explanation of how this works
!.gitignore
!Readme.md
localStorage.removeItem(key); //item
localStorage.clear(); //all items
I'm not expert enough in the inner workings of Postgres to know why your query with the double condition in the WHERE
clause be not working. But one way to get around this would be to use a UNION
of the two queries which you know do work:
SELECT * FROM table_name WHERE boolean_column IS NULL
UNION
SELECT * FROM table_name WHERE boolean_column = FALSE
You could also try using COALESCE
:
SELECT * FROM table_name WHERE COALESCE(boolean_column, FALSE) = FALSE
This second query will replace all NULL
values with FALSE
and then compare against FALSE
in the WHERE
condition.
Just the same as what should be but change the button component to be label like so
<form id='uploadForm'
action='http://localhost:8000/upload'
method='post'
encType="multipart/form-data">
<input type="file" id="sampleFile" style="display: none;" />
<Button htmlFor="sampleFile" component="label" type={'submit'}>Upload</Button>
</form>
Place this meta tag after head tag
<meta http-equiv="x-ua-compatible" content="IE=edge">
The easiest way
import re
txt='this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>. and there are many other lines in the txt files with<[3> such tags </[3>'
out = re.sub("(<[^>]+>)", '', txt)
print out
SQL is Structured Query Language
MySQL is a relational database management system. You can submit SQL queries to the MySQL database to store, retrieve, modify or delete data.
This is working nicely.
UPDATE state SET name = CONCAT(UCASE(LEFT(name, 1)), LCASE(SUBSTRING(name, 2)));
Java EE is actually a collection of technologies and APIs for the Java platform designed to support "Enterprise" Applications which can generally be classed as large-scale, distributed, transactional and highly-available applications designed to support mission-critical business requirements.
In terms of what an employee is looking for in specific techs, it is quite hard to say, because the playing field has kept changing over the last five years. It really is about the class of problems that are being solved more than anything else. Transactions and distribution are key.
$date = '2014-02-25';
date('D', strtotime($date));
You can do this using the splat operator:
some_func(*params)
This causes the function to receive each list item as a separate parameter. There's a description here: http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists
It's the only solution to map a ManyToMany association : you need a join table between the two entities tables to map the association.
It's also used for OneToMany (usually unidirectional) associations when you don't want to add a foreign key in the table of the many side and thus keep it independent of the one side.
Search for @JoinTable in the hibernate documentation for explanations and examples.
You can use Generic Webhook Trigger Plugin for this.
With a variable like changed_files
and expression $.commits[*].['modified','added','removed'][*]
.
You can have a filter text like $changed_files
and filter regexp like "folder/subfolder/[^"]+?"
if folder/subfolder
is the folder that should trigger builds.
You can use javascript Number method to parse it to an number,
var num=Number (num_str);
This is the fastest and easiest way that I have found;
while (tableModel.getRowCount()>0)
{
tableModel.removeRow(0);
}
This clears the table lickety split and leaves it ready for new data.
I've made an answer with some more details here : https://stackoverflow.com/a/11045462/592477
Or you can read it there ==>
When you use loadbalancing it means you have several instances of tomcat and you need to divide loads.
Since it hasn't been mentioned so far, as of Java 10 you can use the new copyOf
factory method:
List.copyOf(set);
From the Javadoc:
Returns an unmodifiable List containing the elements of the given Collection, in its iteration order.
Note that this creates a new list (ImmutableCollections$ListN
to be precise) under the hood by
Collection#toArray()
on the given set and thenThe usual way to swap two items in Python is:
a, b = b, a
So it would seem to me that you would just do the same with an extended slice. However, it is slightly complicated because strings aren't mutable; so you have to convert to a list and then back to a string.
Therefore, I would do the following:
>>> s = 'badcfe'
>>> t = list(s)
>>> t[::2], t[1::2] = t[1::2], t[::2]
>>> ''.join(t)
'abcdef'
After like three (3) hours of google..ing.This is the solution to the problem: First, I run this command;
$mysqladmin -u root -p[your root password here] version
Which outputs:
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Server version 5.5.49-0ubuntu0.14.04.1
Protocol version 10
Connection Localhost via UNIX socket
UNIX socket /var/run/mysqld/mysqld.sock
Uptime: 1 hour 54 min 3 sec
Finally, I changed the connect_type
parameter from tcp
to socket
and added the parameter socket
in config.inc.php
:
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['connect_type'] = 'socket';
$cfg['Servers'][$i]['socket'] = '/var/run/mysqld/mysqld.sock';
All credit goes to this person: This is the correct solution
I just had this problem setting up my new laptop. The issue for me was that my toolchain (CodeSourcery) is 32bit and I had not installed the 32bit libs.
sudo apt-get install ia32-libs
For current date just use UNIX_TIMESTAMP()
in your MySQL query.
If you want to append contents of 3 files into one file, then the following command will be a good choice:
cat file1 file2 file3 | tee -a file4 > /dev/null
It will combine the contents of all files into file4, throwing console output to /dev/null
.
select
distinct
e1.enddate,
e3.startdate,
DATEDIFF(DAY,e1.enddate,e3.startdate)-1 as [Datediff]
from #temp e1
join #temp e3 on e1.enddate < e3.startdate
/* Finds the next start Time */
and e3.startdate = (select min(startdate) from #temp e5
where e5.startdate > e1.enddate)
and not exists (select * /* Eliminates e1 rows if it is overlapped */
from #temp e5
where e5.startdate < e1.enddate and e5.enddate > e1.enddate);
str = "aaaaabbbb"
newstr = str[-4:]
There is a way to achieve this which is quite simple, but I wouldn't suggest it is a good approach for an app you are going to let other people see. But if you had some developer need to show the console and windows forms at the same time, it can be done quite easily.
This method also supports showing only the Console window, but does not support showing only the Windows Form - i.e. the Console will always be shown. You can only interact (i.e. receive data - Console.ReadLine()
, Console.Read()
) with the console window if you do not show the windows forms; output to Console - Console.WriteLine()
- works in both modes.
This is provided as is; no guarantees this won't do something horrible later on, but it does work.
Start from a standard Console Application.
Mark the Main
method as [STAThread]
Add a reference in your project to System.Windows.Forms
Add a Windows Form to your project.
Add the standard Windows start code to your Main
method:
You will have an application that shows the Console and optionally windows forms.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ConsoleApplication9 {
class Program {
[STAThread]
static void Main(string[] args) {
if (args.Length > 0 && args[0] == "console") {
Console.WriteLine("Hello world!");
Console.ReadLine();
}
else {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ConsoleApplication9 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Click(object sender, EventArgs e) {
Console.WriteLine("Clicked");
}
}
}
$imgReload.data('self', $self);
$imgReload.click(function (e) {
var $p = $(this).data('self');
$p._reloadTable();
});
Set javaScript object to onclick element:
$imgReload.data('self', $self);
get Object from "this" element:
var $p = $(this).data('self');
Iterating over a dictionary object itself actually gives you an iterator over its keys. Python is trying to unpack keys, which you get from m.type + m.purity
into (m, k)
.
My crystal ball says m.type
and m.purity
are both strings, so your keys are also strings. Strings are iterable, so they can be unpacked; but iterating over the string gives you an iterator over its characters. So whenever m.type + m.purity
is more than two characters long, you have too many values to unpack. (And whenever it's shorter, you have too few values to unpack.)
To fix this, you can iterate explicitly over the items
of the dict, which are the (key, value) pairs that you seem to be expecting. But if you only want the values, then just use the values.
(In 2.x, itervalues
, iterkeys
, and iteritems
are typically a better idea; the non-iter
versions create a new list object containing the values/keys/items. For large dictionaries and trivial tasks within the iteration, this can be a lot slower than the iter
versions which just set up an iterator.)
You can use:
ImageView imgView = new ImageView(this);
InputStream is = getClass().getResourceAsStream("/drawable/" + fileName);
imgView.setImageDrawable(Drawable.createFromStream(is, ""));
To fetch the network id from the OpenStack Neutron:
#!/usr/bin/python
import os
netid = "nova net-list | awk '/ External / { print $2 }'"
temp = os.popen(netid).read() /* Here temp also contains new line (\n) */
networkId = temp.rstrip()
print(networkId)
Output of nova net-list
+--------------------------------------+------------+------+
| ID | Label | CIDR |
+--------------------------------------+------------+------+
| 431c9014-5b5d-4b51-a357-66020ffbb123 | test1 | None |
| 27a74fcd-37c0-4789-9414-9531b7e3f126 | External | None |
| 5a2712e9-70dc-4b0e-9281-17e02f4684c9 | management | None |
| 7aa697f5-0e60-4c15-b4cc-9cb659698512 | Internal | None |
+--------------------------------------+------------+------+
Output of print(networkId)
27a74fcd-37c0-4789-9414-9531b7e3f126
This is kind of a hack but the best solution that I have found is to use a description tag with no \item. This will produce an error from the latex compiler; however, the error does not prevent the pdf from being generated.
\begin{description}
<YOUR TEXT HERE>
\end{description}
SELECT id, payer_email FROM paypal_ipn_orders
WHERE payer_email IN (
SELECT payer_email FROM papypal_ipn_orders GROUP BY payer_email HAVING COUNT(*) > 1)
General sibling combinator
The general sibling combinator selector is very similar to the adjacent sibling combinator selector. The difference is that the element being selected doesn't need to immediately succeed the first element, but can appear anywhere after it.
Seems to be a common feature of the prevalent asymmetric cryptography; the generation of public/private keys involves generating the private key, which contains the key pair:
openssl genrsa -out mykey.pem 1024
Then publish the public key:
openssl rsa -in mykey.pem -pubout > mykey.pub
or
openssl rsa -in mykey.pem -pubout -out mykey.pub
DSA & EC crypto keys have same feature: eg.
openssl genpkey -algorithm ed25519 -out pvt.pem
Then
openssl pkey -in pvt.pem -pubout > public.pem
or
openssl ec -in ecprivkey.pem -pubout -out ecpubkey.pem
The public component is involved in decryption, and keeping it as part of the private key makes decryption faster; it can be removed from the private key and calculated when needed (for decryption), as an alternative or complement to encrypting or protecting the private key with a password/key/phrase. eg.
openssl pkey -in key.pem -des3 -out keyout.pem
or
openssl ec -aes-128-cbc -in pk8file.pem -out tradfile.pem
You can replace the first argument "aes-128-cbc" with any other valid openssl cipher name
The log cat output can be filtered to only display messages from your package by using these arguments.
adb com.your.package:I *:s
Edit - I spoke to soon.
adb com.your.package:v
If I understand what you're trying to do correctly, then I don't think this is possible with CSS while keeping the children absolutely positioned.
Absolutely positioned elements are completely removed from the document flow, and thus their dimensions cannot alter the dimensions of their parents.
If you really had to achieve this affect while keeping the children as position: absolute
, you could do so with JavaScript by finding the height of the absolutely positioned children after they have rendered, and using that to set the height of the parent.
Alternatively, just use float: left
/float:right
and margins to get the same positioning effect while keeping the children in the document flow, you can then use overflow: hidden
on the parent (or any other clearfix technique) to cause its height to expand to that of its children.
article {
position: relative;
overflow: hidden;
}
.one {
position: relative;
float: left;
margin-top: 10px;
margin-left: 10px;
background: red;
width: 30px;
height: 30px;
}
.two {
position: relative;
float: right;
margin-top: 10px;
margin-right: 10px;
background: blue;
width: 30px;
height: 30px;
}
Your file seems quite small (297 lines) so you can read and write them quite quickly. You refer to Excel CSV, which does not exists, and you show space delimited data in your example. Furthermore, Access is limited to 255 columns, and a CSV is not, so there is no guarantee this will work
Sub StripHeaderAndFooter()
Dim fs As Object ''FileSystemObject
Dim tsIn As Object, tsOut As Object ''TextStream
Dim sFileIn As String, sFileOut As String
Dim aryFile As Variant
sFileIn = "z:\docs\FileName.csv"
sFileOut = "z:\docs\FileOut.csv"
Set fs = CreateObject("Scripting.FileSystemObject")
Set tsIn = fs.OpenTextFile(sFileIn, 1) ''ForReading
sTmp = tsIn.ReadAll
Set tsOut = fs.CreateTextFile(sFileOut, True) ''Overwrite
aryFile = Split(sTmp, vbCrLf)
''Start at line 3 and end at last line -1
For i = 3 To UBound(aryFile) - 1
tsOut.WriteLine aryFile(i)
Next
tsOut.Close
DoCmd.TransferText acImportDelim, , "NewCSV", sFileOut, False
End Sub
Edit re various comments
It is possible to import a text file manually into MS Access and this will allow you to choose you own cell delimiters and text delimiters. You need to choose External data from the menu, select your file and step through the wizard.
About importing and linking data and database objects -- Applies to: Microsoft Office Access 2003
Introduction to importing and exporting data -- Applies to: Microsoft Access 2010
Once you get the import working using the wizards, you can save an import specification and use it for you next DoCmd.TransferText as outlined by @Olivier Jacot-Descombes. This will allow you to have non-standard delimiters such as semi colon and single-quoted text.
Because on Unix, usually, the current directory is not in $PATH
.
When you type a command the shell looks up a list of directories, as specified by the PATH
variable. The current directory is not in that list.
The reason for not having the current directory on that list is security.
Let's say you're root and go into another user's directory and type sl
instead of ls
. If the current directory is in PATH
, the shell will try to execute the sl
program in that directory (since there is no other sl
program). That sl
program might be malicious.
It works with ./
because POSIX specifies that a command name that contain a /
will be used as a filename directly, suppressing a search in $PATH
. You could have used full path for the exact same effect, but ./
is shorter and easier to write.
EDIT
That sl
part was just an example. The directories in PATH
are searched sequentially and when a match is made that program is executed. So, depending on how PATH
looks, typing a normal command may or may not be enough to run the program in the current directory.
In your case, you are creating an array on the stack and once you leave the function scope, the array will be deallocated. Instead, create a dynamically allocated array and return a pointer to it.
char * returnArray(char *arr, int size) {
char *new_arr = malloc(sizeof(char) * size);
for(int i = 0; i < size; ++i) {
new_arr[i] = arr[i];
}
return new_arr;
}
int main() {
char arr[7]= {1,0,0,0,0,1,1};
char *new_arr = returnArray(arr, 7);
// don't forget to free the memory after you're done with the array
free(new_arr);
}
Assuming that < 600px means mobile to you, you can use this observable and subscribe to it:
First we need the current window size. So we create an observable which only emits a single value: the current window size.
initial$ = Observable.of(window.innerWidth > 599 ? false : true);
Then we need to create another observable, so that we know when the window size was changed. For this we can use the "fromEvent" operator. To learn more about rxjs`s operators please visit: rxjs
resize$ = Observable.fromEvent(window, 'resize').map((event: any) => {
return event.target.innerWidth > 599 ? false : true;
});
Merg these two streams to receive our observable:
mobile$ = Observable.merge(this.resize$, this.initial$).distinctUntilChanged();
Now you can subscribe to it like this:
mobile$.subscribe((event) => { console.log(event); });
Remember to unsubscribe :)
This problem is quite easily solved using min-width
and max-width
within a css rule.
HTML
<table>
<tr>
<td class="name">Peter</td>
<td class="hobby">Photography</td>
<td class="comment">A long comment about something...</td>
</td>
</table>
CSS
.name {
max-width: 80px;
min-width: 80px;
}
This will force the first column to be 80px wide. Usually I only use max-width without min-width to reign in text that is very occasionally too long from creating a table that has a super wide column that is mostly empty. The OP's question was about setting to a fixed width though, hence both rules together. On many browsers width:80px;
in CSS is ignored for table columns. Setting the width within the HTML does work, but is not the way you should do things.
I would recommend using min and max width rules, and not set them the same but rather set a range. This way the table can do it's thing, but you can give it some hints on what to do with overly long content.
If I want to keep the text from wrapping and increasing the height of a row - but still make it possible for a user to see the full text, I use white-space: nowrap;
on the main rule, then apply a hover rule that removes the width and nowrap rules so that the user can see the full content when they over their mouse over it.
Something like this:
CSS
.name {
max-width: 80px;
white-space: nowrap;
overflow: hidden;
}
.name:hover {
max-width: none;
white-space: normal;
overflow:auto;
}
It just depends on exactly what you are trying to achieve. I hope this helps someone. PS As an aside, for iOS there is a fix for hover not working - see CSS Hover Not Working on iOS Safari and Chrome
boolean isWithinRange(Date testDate) {
return !(testDate.before(startDate) || testDate.after(endDate));
}
Doesn't seem that awkward to me. Note that I wrote it that way instead of
return testDate.after(startDate) && testDate.before(endDate);
so it would work even if testDate was exactly equal to one of the end cases.
Use the modern version of the Fisher–Yates shuffle algorithm:
/**
* Shuffles array in place.
* @param {Array} a items An array containing the items.
*/
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
/**
* Shuffles array in place. ES6 version
* @param {Array} a items An array containing the items.
*/
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
Note however, that swapping variables with destructuring assignment causes significant performance loss, as of October 2017.
var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);
Using Object.defineProperty
(method taken from this SO answer) we can also implement this function as a prototype method for arrays, without having it show up in loops such as for (i in arr)
. The following will allow you to call arr.shuffle()
to shuffle the array arr
:
Object.defineProperty(Array.prototype, 'shuffle', {
value: function() {
for (let i = this.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[this[i], this[j]] = [this[j], this[i]];
}
return this;
}
});
Or more simple without having to name the element (with 'button' element):
<button onclick="toggleLog(this)">Stop logs</button>
and script :
var bWriteLog = true;
function toggleLog(elt) {
bWriteLog = !bWriteLog;
elt.innerHTML = bWriteLog ? 'Stop logs' : 'Watch logs';
}
I am covering most of the examples of Dependency Injection in ASP.NET Web API 2
public interface IShape
{
string Name { get; set; }
}
public class NoShape : IShape
{
public string Name { get; set; } = "I have No Shape";
}
public class Circle : IShape
{
public string Name { get; set; } = "Circle";
}
public class Rectangle : IShape
{
public Rectangle(string name)
{
this.Name = name;
}
public string Name { get; set; } = "Rectangle";
}
In DIAutoV2Controller.cs Auto Injection mechanism is used
[RoutePrefix("api/v2/DIAutoExample")]
public class DIAutoV2Controller : ApiController
{
private string ConstructorInjected;
private string MethodInjected1;
private string MethodInjected2;
private string MethodInjected3;
[Dependency]
public IShape NoShape { get; set; }
[Dependency("Circle")]
public IShape ShapeCircle { get; set; }
[Dependency("Rectangle")]
public IShape ShapeRectangle { get; set; }
[Dependency("PiValueExample1")]
public double PiValue { get; set; }
[InjectionConstructor]
public DIAutoV2Controller([Dependency("Circle")]IShape shape1, [Dependency("Rectangle")]IShape shape2, IShape shape3)
{
this.ConstructorInjected = shape1.Name + " & " + shape2.Name + " & " + shape3.Name;
}
[NonAction]
[InjectionMethod]
public void Initialize()
{
this.MethodInjected1 = "Default Initialize done";
}
[NonAction]
[InjectionMethod]
public void Initialize2([Dependency("Circle")]IShape shape1)
{
this.MethodInjected2 = shape1.Name;
}
[NonAction]
[InjectionMethod]
public void Initialize3(IShape shape1)
{
this.MethodInjected3 = shape1.Name;
}
[HttpGet]
[Route("constructorinjection")]
public string constructorinjection()
{
return "Constructor Injected: " + this.ConstructorInjected;
}
[HttpGet]
[Route("GetNoShape")]
public string GetNoShape()
{
return "Property Injected: " + this.NoShape.Name;
}
[HttpGet]
[Route("GetShapeCircle")]
public string GetShapeCircle()
{
return "Property Injected: " + this.ShapeCircle.Name;
}
[HttpGet]
[Route("GetShapeRectangle")]
public string GetShapeRectangle()
{
return "Property Injected: " + this.ShapeRectangle.Name;
}
[HttpGet]
[Route("GetPiValue")]
public string GetPiValue()
{
return "Property Injected: " + this.PiValue;
}
[HttpGet]
[Route("MethodInjected1")]
public string InjectionMethod1()
{
return "Method Injected: " + this.MethodInjected1;
}
[HttpGet]
[Route("MethodInjected2")]
public string InjectionMethod2()
{
return "Method Injected: " + this.MethodInjected2;
}
[HttpGet]
[Route("MethodInjected3")]
public string InjectionMethod3()
{
return "Method Injected: " + this.MethodInjected3;
}
}
In DIV2Controller.cs everything will be injected from the Dependency Configuration Resolver class
[RoutePrefix("api/v2/DIExample")]
public class DIV2Controller : ApiController
{
private string ConstructorInjected;
private string MethodInjected1;
private string MethodInjected2;
public string MyPropertyName { get; set; }
public double PiValue1 { get; set; }
public double PiValue2 { get; set; }
public IShape Shape { get; set; }
// MethodInjected
[NonAction]
public void Initialize()
{
this.MethodInjected1 = "Default Initialize done";
}
// MethodInjected
[NonAction]
public void Initialize2(string myproperty1, IShape shape1, string myproperty2, IShape shape2)
{
this.MethodInjected2 = myproperty1 + " & " + shape1.Name + " & " + myproperty2 + " & " + shape2.Name;
}
public DIV2Controller(string myproperty1, IShape shape1, string myproperty2, IShape shape2)
{
this.ConstructorInjected = myproperty1 + " & " + shape1.Name + " & " + myproperty2 + " & " + shape2.Name;
}
[HttpGet]
[Route("constructorinjection")]
public string constructorinjection()
{
return "Constructor Injected: " + this.ConstructorInjected;
}
[HttpGet]
[Route("PropertyInjected")]
public string InjectionProperty()
{
return "Property Injected: " + this.MyPropertyName;
}
[HttpGet]
[Route("GetPiValue1")]
public string GetPiValue1()
{
return "Property Injected: " + this.PiValue1;
}
[HttpGet]
[Route("GetPiValue2")]
public string GetPiValue2()
{
return "Property Injected: " + this.PiValue2;
}
[HttpGet]
[Route("GetShape")]
public string GetShape()
{
return "Property Injected: " + this.Shape.Name;
}
[HttpGet]
[Route("MethodInjected1")]
public string InjectionMethod1()
{
return "Method Injected: " + this.MethodInjected1;
}
[HttpGet]
[Route("MethodInjected2")]
public string InjectionMethod2()
{
return "Method Injected: " + this.MethodInjected2;
}
}
Configuring the Dependency Resolver
public static void Register(HttpConfiguration config)
{
var container = new UnityContainer();
RegisterInterfaces(container);
config.DependencyResolver = new UnityResolver(container);
// Other Web API configuration not shown.
}
private static void RegisterInterfaces(UnityContainer container)
{
var dbContext = new SchoolDbContext();
// Registration with constructor injection
container.RegisterType<IStudentRepository, StudentRepository>(new InjectionConstructor(dbContext));
container.RegisterType<ICourseRepository, CourseRepository>(new InjectionConstructor(dbContext));
// Set constant/default value of Pi = 3.141
container.RegisterInstance<double>("PiValueExample1", 3.141);
container.RegisterInstance<double>("PiValueExample2", 3.14);
// without a name
container.RegisterInstance<IShape>(new NoShape());
// with circle name
container.RegisterType<IShape, Circle>("Circle", new InjectionProperty("Name", "I am Circle"));
// with rectangle name
container.RegisterType<IShape, Rectangle>("Rectangle", new InjectionConstructor("I am Rectangle"));
// Complex type like Constructor, Property and method injection
container.RegisterType<DIV2Controller, DIV2Controller>(
new InjectionConstructor("Constructor Value1", container.Resolve<IShape>("Circle"), "Constructor Value2", container.Resolve<IShape>()),
new InjectionMethod("Initialize"),
new InjectionMethod("Initialize2", "Value1", container.Resolve<IShape>("Circle"), "Value2", container.Resolve<IShape>()),
new InjectionProperty("MyPropertyName", "Property Value"),
new InjectionProperty("PiValue1", container.Resolve<double>("PiValueExample1")),
new InjectionProperty("Shape", container.Resolve<IShape>("Rectangle")),
new InjectionProperty("PiValue2", container.Resolve<double>("PiValueExample2")));
}
If you are using linux and faced such problem during creating link, try to change jar file path of original jmeter file.
+ java -server -XX:+HeapDumpOnOutOfMemoryError -Xms512m -Xmx512m -XX:NewSize=128m -XX:MaxNewSize=128m -XX:MaxTenuringThreshold=2 -XX:PermSize=64m -XX:MaxPermSize=128m -XX:+CMSClassUnloadingEnabled -jar ./ApacheJMeter.jar -help
Change to:
java $ARGS $JVM_ARGS -jar "/opt/apache-jmeter-2.11/bin/ApacheJMeter.jar" "$@"
Its blank because you are writing to file
. you should write to output
using php://output
instead and also send header information to indicate that it's csv.
Example
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$data = array(
'aaa,bbb,ccc,dddd',
'123,456,789',
'"aaa","bbb"'
);
$fp = fopen('php://output', 'wb');
foreach ( $data as $line ) {
$val = explode(",", $line);
fputcsv($fp, $val);
}
fclose($fp);
In one line, answer is as below;
[ CASE WHEN COLUMN_NAME = 'VALUE' THEN 'SHOW_THIS' ELSE 'SHOW_OTHER' END as ALIAS ]
In addition to Juliano's answer about behavior of "or": it's "fast"
>>> 1 or 5/0
1
So sometimes it's might be a useful shortcut for things like
object = getCachedVersion() or getFromDB()
per various post... you cannot trigger a download via XHR. I needed to implement condition for the download, so, My solution was:
//make the call to the api with the ID to validate
someResource.get( { id: someId }, function(data) {
//confirm that the ID is validated
if (data.isIdConfirmed) {
//get the token from the validation and issue another call
//to trigger the download
window.open('someapi/print/:someId?token='+ data.token);
}
});
I wish that somehow, or someday the download can be triggered using XHR to avoid the second call. // _e
Or the same thing, with a slightly different (IMO friendlier) syntax:
DELETE FROM posts
USING posts, projects
WHERE projects.project_id = posts.project_id AND projects.client_id = :client_id;
BTW, with mysql using joins is almost always a way faster than subqueries...
Using imagemagick, you can try:
convert page.png page.pdf
Or for multiple images:
convert page*.png mydoc.pdf
This is how I changed in Xcode 4:
This is hacky, but:
resetPar <- function() {
dev.new()
op <- par(no.readonly = TRUE)
dev.off()
op
}
works after a fashion, but it does flash a new device on screen temporarily...
E.g.:
> par(mfrow = c(2,2)) ## some random par change
> par("mfrow")
[1] 2 2
> par(resetPar()) ## reset the pars to defaults
> par("mfrow") ## back to default
[1] 1 1
None of these suggestions above worked for me as-is. I had to use the following to center a checkbox with the label text displayed to the right of the box:
<style>
.checkboxes {
display: flex;
justify-content: center;
align-items: center;
vertical-align: middle;
word-wrap: break-word;
}
</style>
<label for="checkbox1" class="checkboxes"><input type="checkbox" id="checkbox1" name="checked" value="yes" class="checkboxes"/>
Check the box.</label>
setInterval()
function that repeats itself in every n milliseconds
Javascript
setInterval(function(){ Console.log("A Kiss every 5 seconds"); }, 5000);
Approximate java Equivalent
new Timer().scheduleAtFixedRate(new TimerTask(){
@Override
public void run(){
Log.i("tag", "A Kiss every 5 seconds");
}
},0,5000);
setTimeout()
function that works only after n milliseconds
Javascript
setTimeout(function(){ Console.log("A Kiss after 5 seconds"); },5000);
Approximate java Equivalent
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
Log.i("tag","A Kiss after 5 seconds");
}
}, 5000);
For people live in 2020, and want a clean answer...
delegate
: defines a function pointer.event
: defines
+=
, -=
), andnew
keyword anymore.Regarding the adjective protected:
// eventTest.SomeoneSay = null; // Compile Error.
// eventTest.SomeoneSay = new Say(SayHello); // Compile Error.
Also notice this section from Microsoft: https://docs.microsoft.com/en-us/dotnet/standard/events/#raising-multiple-events
delegate
:public class DelegateTest
{
public delegate void Say(); // Define a pointer type "void <- ()" named "Say".
private Say say;
public DelegateTest() {
say = new Say(SayHello); // Setup the field, Say say, first.
say += new Say(SayGoodBye);
say.Invoke();
}
public void SayHello() { /* display "Hello World!" to your GUI. */ }
public void SayGoodBye() { /* display "Good bye!" to your GUI. */ }
}
event
:public class EventTest
{
public delegate void Say();
public event Say SomeoneSay; // Use the type "Say" to define event, an
// auto-setup-everything-good field for you.
public EventTest() {
SomeoneSay += SayHello;
SomeoneSay += SayGoodBye;
SomeoneSay();
}
public void SayHello() { /* display "Hello World!" to your GUI. */ }
public void SayGoodBye() { /* display "Good bye!" to your GUI. */ }
}
Event vs. Delegate - Explaining the important differences between the Event and Delegate patterns in C# and why they're useful.: https://dzone.com/articles/event-vs-delegate
You can use the following multiplot
function from Winston Chang's R cookbook
multiplot(plot1, plot2, cols=2)
multiplot <- function(..., plotlist=NULL, cols) {
require(grid)
# Make a list from the ... arguments and plotlist
plots <- c(list(...), plotlist)
numPlots = length(plots)
# Make the panel
plotCols = cols # Number of columns of plots
plotRows = ceiling(numPlots/plotCols) # Number of rows needed, calculated from # of cols
# Set up the page
grid.newpage()
pushViewport(viewport(layout = grid.layout(plotRows, plotCols)))
vplayout <- function(x, y)
viewport(layout.pos.row = x, layout.pos.col = y)
# Make each plot, in the correct location
for (i in 1:numPlots) {
curRow = ceiling(i/plotCols)
curCol = (i-1) %% plotCols + 1
print(plots[[i]], vp = vplayout(curRow, curCol ))
}
}
You may try this code for you to take comma separated values / an array of values to get back a JSON from webAPI
public class CategoryController : ApiController
{
public List<Category> Get(String categoryIDs)
{
List<Category> categoryRepo = new List<Category>();
String[] idRepo = categoryIDs.Split(',');
foreach (var id in idRepo)
{
categoryRepo.Add(new Category()
{
CategoryID = id,
CategoryName = String.Format("Category_{0}", id)
});
}
return categoryRepo;
}
}
public class Category
{
public String CategoryID { get; set; }
public String CategoryName { get; set; }
}
Output :
[
{"CategoryID":"4","CategoryName":"Category_4"},
{"CategoryID":"5","CategoryName":"Category_5"},
{"CategoryID":"3","CategoryName":"Category_3"}
]
This is a quirk of the C grammar. A label (Cleanup:
) is not allowed to appear immediately before a declaration (such as char *str ...;
), only before a statement (printf(...);
). In C89 this was no great difficulty because declarations could only appear at the very beginning of a block, so you could always move the label down a bit and avoid the issue. In C99 you can mix declarations and code, but you still can't put a label immediately before a declaration.
You can put a semicolon immediately after the label's colon (as suggested by Renan) to make there be an empty statement there; this is what I would do in machine-generated code. Alternatively, hoist the declaration to the top of the function:
int main (void)
{
char *str;
printf("Hello ");
goto Cleanup;
Cleanup:
str = "World\n";
printf("%s\n", str);
return 0;
}
From the docs:
_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.
So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.
Edit: Further reading led me here:
http://www.analyticsmarket.com/blog/edit-ecommerce-data
Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.
Variables declared inside a function are local to that function. For instance:
foo <- function() {
bar <- 1
}
foo()
bar
gives the following error: Error: object 'bar' not found
.
If you want to make bar
a global variable, you should do:
foo <- function() {
bar <<- 1
}
foo()
bar
In this case bar
is accessible from outside the function.
However, unlike C, C++ or many other languages, brackets do not determine the scope of variables. For instance, in the following code snippet:
if (x > 10) {
y <- 0
}
else {
y <- 1
}
y
remains accessible after the if-else
statement.
As you well say, you can also create nested environments. You can have a look at these two links for understanding how to use them:
Here you have a small example:
test.env <- new.env()
assign('var', 100, envir=test.env)
# or simply
test.env$var <- 100
get('var') # var cannot be found since it is not defined in this environment
get('var', envir=test.env) # now it can be found
If you want to know a property's underlying type, try this:
propInfo.PropertyType.UnderlyingSystemType.GenericTypeArguments[0]
Why not just:
import seaborn as sns
sns.barplot(list(D.keys()), list(D.values()))
Here is what worked for me (Angular 7):
First import HttpClientModule in your app.module.ts if you didn't:
import { HttpClientModule } from '@angular/common/http';
...
imports: [
HttpClientModule
],
Then change your service
@Injectable()
export class FooService {
to
@Injectable({
providedIn: 'root'
})
export class FooService {
Hope it helps.
Edit:
providedIn
Determines which injectors will provide the injectable, by either associating it with an @NgModule or other InjectorType, or by specifying that this injectable should be provided in one of the following injectors:
'root' : The application-level injector in most apps.
'platform' : A special singleton platform injector shared by all applications on the page.
'any' : Provides a unique instance in every module (including lazy modules) that injects the token.
Be careful platform
is available only since Angular 9 (https://blog.angular.io/version-9-of-angular-now-available-project-ivy-has-arrived-23c97b63cfa3)
Read more about Injectable here: https://angular.io/api/core/Injectable
It is easy to change the implementation to List
to Set
:
Collection<String> stringList = new ArrayList<String>();
//Client side
stringList = new LinkedList<String>();
stringList = new HashSet<String>();
//stringList = new HashSet<>(); java 1.7 and 1.8
Some more details in relation with the response from Cody Gray. As it took me some time to digest it I though it might be usefull to others.
First, some definitions:
Bar
is a TypeName in Public Class Bar
, or in Dim Foo as Bar
. TypeNames could be seen as "labels" used in the code to tell the compiler which type definition to look for in a dictionary where all available types would be described.System.Type
objects which contain a value. This value indicates a type; just like a String
would take some text or an Int
would take a number, except we are storing types instead of text or numbers. Type
objects contain the type definitions, as well as its corresponding TypeName.Second, the theory:
Foo.GetType()
returns a Type
object which contains the type for the variable Foo
. In other words, it tells you what Foo
is an instance of.GetType(Bar)
returns a Type
object which contains the type for the TypeName Bar
.In some instances, the type an object has been Cast
to is different from the type an object was first instantiated from. In the following example, MyObj is an Integer
cast into an Object
:
Dim MyVal As Integer = 42
Dim MyObj As Object = CType(MyVal, Object)
So, is MyObj
of type Object
or of type Integer
? MyObj.GetType()
will tell you it is an Integer
.
Type Of Foo Is Bar
feature, which allows you to ascertain a variable Foo
is compatible with a TypeName Bar
. Type Of MyObj Is Integer
and Type Of MyObj Is Object
will both return True. For most cases, TypeOf will indicate a variable is compatible with a TypeName if the variable is of that Type or a Type that derives from it.
More info here: https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/typeof-operator#remarksThe test below illustrate quite well the behaviour and usage of each of the mentionned keywords and properties.
Public Sub TestMethod1()
Dim MyValInt As Integer = 42
Dim MyValDble As Double = CType(MyValInt, Double)
Dim MyObj As Object = CType(MyValDble, Object)
Debug.Print(MyValInt.GetType.ToString) 'Returns System.Int32
Debug.Print(MyValDble.GetType.ToString) 'Returns System.Double
Debug.Print(MyObj.GetType.ToString) 'Returns System.Double
Debug.Print(MyValInt.GetType.GetType.ToString) 'Returns System.RuntimeType
Debug.Print(MyValDble.GetType.GetType.ToString) 'Returns System.RuntimeType
Debug.Print(MyObj.GetType.GetType.ToString) 'Returns System.RuntimeType
Debug.Print(GetType(Integer).GetType.ToString) 'Returns System.RuntimeType
Debug.Print(GetType(Double).GetType.ToString) 'Returns System.RuntimeType
Debug.Print(GetType(Object).GetType.ToString) 'Returns System.RuntimeType
Debug.Print(MyValInt.GetType = GetType(Integer)) '# Returns True
Debug.Print(MyValInt.GetType = GetType(Double)) 'Returns False
Debug.Print(MyValInt.GetType = GetType(Object)) 'Returns False
Debug.Print(MyValDble.GetType = GetType(Integer)) 'Returns False
Debug.Print(MyValDble.GetType = GetType(Double)) '# Returns True
Debug.Print(MyValDble.GetType = GetType(Object)) 'Returns False
Debug.Print(MyObj.GetType = GetType(Integer)) 'Returns False
Debug.Print(MyObj.GetType = GetType(Double)) '# Returns True
Debug.Print(MyObj.GetType = GetType(Object)) 'Returns False
Debug.Print(TypeOf MyObj Is Integer) 'Returns False
Debug.Print(TypeOf MyObj Is Double) '# Returns True
Debug.Print(TypeOf MyObj Is Object) '# Returns True
End Sub
EDIT
You can also use Information.TypeName(Object)
to get the TypeName of a given object. For example,
Dim Foo as Bar
Dim Result as String
Result = TypeName(Foo)
Debug.Print(Result) 'Will display "Bar"
Here is some code using java 6 to get you started:
JSONObject jo = new JSONObject();
jo.put("firstName", "John");
jo.put("lastName", "Doe");
JSONArray ja = new JSONArray();
ja.put(jo);
JSONObject mainObj = new JSONObject();
mainObj.put("employees", ja);
Edit: Since there has been a lot of confusion about put
vs add
here I will attempt to explain the difference. In java 6 org.json.JSONArray contains the put
method and in java 7 javax.json contains the add
method.
An example of this using the builder pattern in java 7 looks something like this:
JsonObject jo = Json.createObjectBuilder()
.add("employees", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("firstName", "John")
.add("lastName", "Doe")))
.build();
$month = 10; // october
$firstday = date('01-' . $month . '-Y');
$lastday = date(date('t', strtotime($firstday)) .'-' . $month . '-Y');
In Android, application-level meta data is accessed through the Context
reference, which an activity is a descendant of.
For example, you can get the source directory via the getApplicationInfo().sourceDir
property.
There are methods for other folders as well (assets directory, data dir, database dir, etc.).
Import specific methods inside of curly brackets
import { map, tail, times, uniq } from 'lodash';
Pros:
- Only one import line(for a decent amount of functions)
- More readable usage: map() instead of _.map() later in the javascript code.
Cons:
- Every time we want to use a new function or stop using another - it needs to be maintained and managed
Copied from:The Correct Way to Import Lodash Libraries - A Benchmark article written by Alexander Chertkov.
I use a generic query I call "dump" (why? I don't know) that looks like this:
SET NEWPAGE NONE
SET PAGESIZE 0
SET SPACE 0
SET LINESIZE 16000
SET ECHO OFF
SET FEEDBACK OFF
SET VERIFY OFF
SET HEADING OFF
SET TERMOUT OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET COLSEP |
spool &1..txt
@@&1
spool off
exit
I then call SQL*Plus passing the actual SQL script I want to run as an argument:
sqlplus -S user/password@database @dump.sql my_real_query.sql
The result is written to a file
my_real_query.sql.txt
.
You can use anonymous types for example:
var empData = from res in _db.EMPLOYEEs
where res.EMAIL == givenInfo || res.USER_NAME == givenInfo
select new { res.EMAIL, res.USER_NAME };
Example:
Process process = Process.Start(@"Data\myApp.exe");
int id = process.Id;
Process tempProc = Process.GetProcessById(id);
this.Visible = false;
tempProc.WaitForExit();
this.Visible = true;
Maybe this example listed here can help you out. Statement from the author
about 24 lines of code to encrypt, 23 to decrypt
Due to the fact that the link in the original posting is dead - here the needed code parts (c&p without any change to the original source)
/*
Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
#region Usings
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
#endregion
namespace Utilities.Encryption
{
/// <summary>
/// Utility class that handles encryption
/// </summary>
public static class AESEncryption
{
#region Static Functions
/// <summary>
/// Encrypts a string
/// </summary>
/// <param name="PlainText">Text to be encrypted</param>
/// <param name="Password">Password to encrypt with</param>
/// <param name="Salt">Salt to encrypt with</param>
/// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
/// <param name="PasswordIterations">Number of iterations to do</param>
/// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
/// <param name="KeySize">Can be 128, 192, or 256</param>
/// <returns>An encrypted string</returns>
public static string Encrypt(string PlainText, string Password,
string Salt = "Kosher", string HashAlgorithm = "SHA1",
int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
int KeySize = 256)
{
if (string.IsNullOrEmpty(PlainText))
return "";
byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
RijndaelManaged SymmetricKey = new RijndaelManaged();
SymmetricKey.Mode = CipherMode.CBC;
byte[] CipherTextBytes = null;
using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
{
using (MemoryStream MemStream = new MemoryStream())
{
using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
{
CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
CryptoStream.FlushFinalBlock();
CipherTextBytes = MemStream.ToArray();
MemStream.Close();
CryptoStream.Close();
}
}
}
SymmetricKey.Clear();
return Convert.ToBase64String(CipherTextBytes);
}
/// <summary>
/// Decrypts a string
/// </summary>
/// <param name="CipherText">Text to be decrypted</param>
/// <param name="Password">Password to decrypt with</param>
/// <param name="Salt">Salt to decrypt with</param>
/// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
/// <param name="PasswordIterations">Number of iterations to do</param>
/// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
/// <param name="KeySize">Can be 128, 192, or 256</param>
/// <returns>A decrypted string</returns>
public static string Decrypt(string CipherText, string Password,
string Salt = "Kosher", string HashAlgorithm = "SHA1",
int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
int KeySize = 256)
{
if (string.IsNullOrEmpty(CipherText))
return "";
byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
byte[] CipherTextBytes = Convert.FromBase64String(CipherText);
PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
RijndaelManaged SymmetricKey = new RijndaelManaged();
SymmetricKey.Mode = CipherMode.CBC;
byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
int ByteCount = 0;
using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
{
using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
{
using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
{
ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
MemStream.Close();
CryptoStream.Close();
}
}
}
SymmetricKey.Clear();
return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
}
#endregion
}
}
...this is obviously performing a 'string' comparison
No - if the date/time format matches the supported format, MySQL performs implicit conversion to convert the value to a DATETIME, based on the column it is being compared to. Same thing happens with:
WHERE int_column = '1'
...where the string value of "1" is converted to an INTeger because int_column
's data type is INT, not CHAR/VARCHAR/TEXT.
If you want to explicitly convert the string to a DATETIME, the STR_TO_DATE function would be the best choice:
WHERE expires_at <= STR_TO_DATE('2010-10-15 10:00:00', '%Y-%m-%d %H:%i:%s')
I know that this question is about 6+ years old, but the answer by @Kyle doesn't work.
Using this
setSize(width - (getInsets().left + getInsets().right), height - (getInsets().top + getInsets().bottom));
But this always work in any size:
setSize(width + 14, height + 7);
If you don't want the border to border, and only want the white area, here:
setSize(width + 16, height + 39);
Also this only works on Windows 10, for MacOS users, use @ben's answer.
You can do
a=[1,2,3,4]
if 6 in a:
a.remove(6)
but above need to search 6 in list a 2 times, so try except would be faster
try:
a.remove(6)
except:
pass
I would EXPECT the first query to be quicker, mainly because you have an equivalence and an explicit JOIN. In my experience IN
is a very slow operator, since SQL normally evaluates it as a series of WHERE
clauses separated by "OR" (WHERE x=Y OR x=Z OR...
).
As with ALL THINGS SQL though, your mileage may vary. The speed will depend a lot on indexes (do you have indexes on both ID columns? That will help a lot...) among other things.
The only REAL way to tell with 100% certainty which is faster is to turn on performance tracking (IO Statistics is especially useful) and run them both. Make sure to clear your cache between runs!
make sure you add {} around Html.RenderPartial, as:
@{Html.RenderPartial("FullName", new { firstName = model.FirstName, lastName = model.LastName});}
not
@Html.RenderPartial("FullName", new { firstName = model.FirstName, lastName = model.LastName});
You can use browser default prompt window.
Instead of basic <input type="submit" (...) >
try:
<button onClick="if(confirm(\'are you sure ?\')){ this.form.submit() }">Save</button>
The print
statement in Python converts its arguments to strings, and outputs those strings to stdout. To save the string to a variable instead, only convert it to a string:
a = str(tag.getArtist())
For those using Xamarin, here is the C# equivalent to aaronvargas's answer above.
using Android.Content;
using Android.Database;
using Android.Views;
using Android.Widget;
using Java.Lang;
namespace MyNamespace.Droid
{
public class NothingSelectedSpinnerAdapter : BaseAdapter, ISpinnerAdapter, IListAdapter
{
protected static readonly int EXTRA = 1;
protected ISpinnerAdapter adapter;
protected Context context;
protected int nothingSelectedLayout;
protected int nothingSelectedDropdownLayout;
protected LayoutInflater layoutInflater;
public NothingSelectedSpinnerAdapter(ISpinnerAdapter spinnerAdapter, int nothingSelectedLayout, Context context) : this(spinnerAdapter, nothingSelectedLayout, -1, context)
{
}
public NothingSelectedSpinnerAdapter(ISpinnerAdapter spinnerAdapter, int nothingSelectedLayout, int nothingSelectedDropdownLayout, Context context)
{
this.adapter = spinnerAdapter;
this.context = context;
this.nothingSelectedLayout = nothingSelectedLayout;
this.nothingSelectedDropdownLayout = nothingSelectedDropdownLayout;
layoutInflater = LayoutInflater.From(context);
}
protected View GetNothingSelectedView(ViewGroup parent)
{
return layoutInflater.Inflate(nothingSelectedLayout, parent, false);
}
protected View GetNothingSelectedDropdownView(ViewGroup parent)
{
return layoutInflater.Inflate(nothingSelectedDropdownLayout, parent, false);
}
public override Object GetItem(int position)
{
return position == 0 ? null : adapter.GetItem(position - EXTRA);
}
public override long GetItemId(int position)
{
return position >= EXTRA ? adapter.GetItemId(position - EXTRA) : position - EXTRA;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
// This provides the View for the Selected Item in the Spinner, not
// the dropdown (unless dropdownView is not set).
if (position == 0)
{
return GetNothingSelectedView(parent);
}
// Could re-use the convertView if possible.
return this.adapter.GetView(position - EXTRA, null, parent);
}
public override int Count
{
get
{
int count = this.adapter.Count;
return count == 0 ? 0 : count + EXTRA;
}
}
public override View GetDropDownView(int position, View convertView, ViewGroup parent)
{
// Android BUG! http://code.google.com/p/android/issues/detail?id=17128 -
// Spinner does not support multiple view types
if (position == 0)
{
return nothingSelectedDropdownLayout == -1 ?
new View(context) :
GetNothingSelectedDropdownView(parent);
}
// Could re-use the convertView if possible, use setTag...
return adapter.GetDropDownView(position - EXTRA, null, parent);
}
public override int GetItemViewType(int position)
{
return 0;
}
public override int ViewTypeCount => 1;
public override bool HasStableIds => this.adapter.HasStableIds;
public override bool IsEmpty => this.adapter.IsEmpty;
public override void RegisterDataSetObserver(DataSetObserver observer)
{
adapter.RegisterDataSetObserver(observer);
}
public override void UnregisterDataSetObserver(DataSetObserver observer)
{
adapter.UnregisterDataSetObserver(observer);
}
public override bool AreAllItemsEnabled()
{
return false;
}
public override bool IsEnabled(int position)
{
return position > 0;
}
}
}
I think what's missing in the answers above is the need to specify a different value for the step
attribute, which has a default value of 1
. If you want the input's validation algorithm to allow floating-point values, specify a step accordingly.
For example, I wanted dollar amounts, so I specified a step like this:
<input type="number" name="price"
pattern="[0-9]+([\.,][0-9]+)?" step="0.01"
title="This should be a number with up to 2 decimal places.">
There's nothing wrong with using jQuery to retrieve the value, but you will find it useful to use the DOM API directly to get the elements's validity.valid
property.
I had a similar issue with the decimal point, but the reason I realized there was an issue was because of the styling that Twitter Bootstrap adds to a number input with an invalid value.
Here's a fiddle demonstrating that the adding of the step
attribute makes it work, and also testing whether the current value is valid:
TL;DR: Set the a step
attribute to a floating-point value, because it defaults to 1
.
NOTE: The comma doesn't validate for me, but I suspect that if I set my OS language/region settings to somewhere that uses a comma as the decimal separator, it would work. *note in note*: that was not the case for OS language/keyboard settings *German* in Ubuntu/Gnome 14.04.
def ruota_orario(matrix):
ruota=list(zip(*reversed(matrix)))
return[list(elemento) for elemento in ruota]
def ruota_antiorario(matrix):
ruota=list(zip(*reversed(matrix)))
return[list(elemento)[::-1] for elemento in ruota][::-1]
I think it may be a bug in chrome. There was a similar issue long back: See this.
Try in a different browser. I think it should work fine.
Use nested dictionaries. Take a look:
INI File: example.ini
[Section]
Key = Value
Code:
class IniOpen:
def __init__(self, file):
self.parse = {}
self.file = file
self.open = open(file, "r")
self.f_read = self.open.read()
split_content = self.f_read.split("\n")
section = ""
pairs = ""
for i in range(len(split_content)):
if split_content[i].find("[") != -1:
section = split_content[i]
section = string_between(section, "[", "]") # define your own function
self.parse.update({section: {}})
elif split_content[i].find("[") == -1 and split_content[i].find("="):
pairs = split_content[i]
split_pairs = pairs.split("=")
key = split_pairs[0].trim()
value = split_pairs[1].trim()
self.parse[section].update({key: value})
def read(self, section, key):
try:
return self.parse[section][key]
except KeyError:
return "Sepcified Key Not Found!"
def write(self, section, key, value):
if self.parse.get(section) is None:
self.parse.update({section: {}})
elif self.parse.get(section) is not None:
if self.parse[section].get(key) is None:
self.parse[section].update({key: value})
elif self.parse[section].get(key) is not None:
return "Content Already Exists"
Apply code like so:
ini_file = IniOpen("example.ini")
print(ini_file.parse) # prints the entire nested dictionary
print(ini_file.read("Section", "Key") # >> Returns Value
ini_file.write("NewSection", "NewKey", "New Value"
apache commons lang has a class SystemUtils.java you can use :
SystemUtils.IS_OS_LINUX
SystemUtils.IS_OS_WINDOWS
The time complexity of ArrayList.clear()
is O(n)
and of removeAll
is O(n^2)
.
So yes, ArrayList.clear
is much faster.
Simple way of creating newtonsoft JObject from Properties.
This is a Sample User Properties
public class User
{
public string Name;
public string MobileNo;
public string Address;
}
and i want this property in newtonsoft JObject is:
JObject obj = JObject.FromObject(new User()
{
Name = "Manjunath",
MobileNo = "9876543210",
Address = "Mumbai, Maharashtra, India",
});
Output will be like this:
{"Name":"Manjunath","MobileNo":"9876543210","Address":"Mumbai, Maharashtra, India"}
The default class constructor is called unless you explicitly call another constructor in the derived class. the language specifies this.
Rectangle(int h,int w):
Shape(h,w)
{...}
Will call the other base class constructor.
JSP stands for JAVA SERVER PAGE........ jsp is not a servlet. Jsp uses code and HTML tag both in itself you dont need to make a HTML and a servlet seprately.Jsp are playing magnificent role in web application. Servlet is a java class plays an role to make your HTML page from static to dynamic .
Here is the code for changing the color of ProgressBar by programatically.
ProgressBar progressBar = (ProgressBar) findViewById(R.id.pb_listProgressBar);
int colorCodeDark = Color.parseColor("#F44336");
progressBar.setIndeterminateTintList(ColorStateList.valueOf(colorCodeDark));
You can just do
array_filter($array)
array_filter: "If no callback is supplied, all entries of input equal to FALSE will be removed." This means that elements with values NULL, 0, '0', '', FALSE, array() will be removed too.
The other option is doing
array_diff($array, array(''))
which will remove elements with values NULL, '' and FALSE.
Hope this helps :)
Here is an example.
$a = array(0, '0', NULL, FALSE, '', array());
var_dump(array_filter($a));
// array()
var_dump(array_diff($a, array(0))) // 0 / '0'
// array(NULL, FALSE, '', array());
var_dump(array_diff($a, array(NULL))) // NULL / FALSE / ''
// array(0, '0', array())
To sum up:
For IE8 support, the "content" property cannot be empty.
To get around this I've done the following :
.ul li:after {
content:"icon";
text-indent:-999em;
display:block;
width:32px;
height:32px;
background:url(../img/icons/spritesheet.png) 0 -620px no-repeat;
margin:5% 0 0 45%;
}
Note : This works with image sprites too
There's a strong culture of tuples being for heterogeneous collections, similar to what you'd use struct
s for in C, and lists being for homogeneous collections, similar to what you'd use arrays for. But I've never quite squared this with the mutability issue mentioned in the other answers. Mutability has teeth to it (you actually can't change a tuple), while homogeneity is not enforced, and so seems to be a much less interesting distinction.
The syntax is the following:
function clickOnUpload() {
$timeout(function() {
angular.element('#myselector').triggerHandler('click');
});
};
// Using Angular Extend
angular.extend($scope, {
clickOnUpload: clickOnUpload
});
// OR Using scope directly
$scope.clickOnUpload = clickOnUpload;
More info on Angular Extend way here.
If you are using old versions of angular, you should use trigger instead of triggerHandler.
If you need to apply stop propagation you can use this method as follows:
<a id="myselector" ng-click="clickOnUpload(); $event.stopPropagation();">
Something
</a>
If you are only doing insertions, and want one from the same session, do as per peirix's answer. If you are doing modifications, you will need to modify your database schema to store which entry was most recently updated.
If you want the id from the last modification, which may have been from a different session (i.e. not the one that was just done by the PHP code running at present, but one done in response to a different request), you can add a TIMESTAMP column to your table called last_modified (see http://dev.mysql.com/doc/refman/5.1/en/datetime.html for information), and then when you update, set last_modified=CURRENT_TIME.
Having set this, you can then use a query like: SELECT id FROM table ORDER BY last_modified DESC LIMIT 1; to get the most recently modified row.
You just have to remove the parent menu in the page init event.
Protected Sub navMenu_Init(sender As Object, e As System.EventArgs) Handles navMenu.Init
'Remove the admin menu for the norms
Dim cUser As Boolean = HttpContext.Current.User.IsInRole("Admin")
'If user is not in the Admin role removes the 1st menu at index 0
If cUser = False Then
navMenu.Items.RemoveAt(0)
End If
End Sub
I have do something like this to get date in local device timezone from UTC time stamp.
private long UTC_TIMEZONE=1470960000;
private String OUTPUT_DATE_FORMATE="dd-MM-yyyy - hh:mm a"
getDateFromUTCTimestamp(UTC_TIMEZONE,OUTPUT_DATE_FORMATE);
Here is the function
public String getDateFromUTCTimestamp(long mTimestamp, String mDateFormate) {
String date = null;
try {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.setTimeInMillis(mTimestamp * 1000L);
date = DateFormat.format(mDateFormate, cal.getTimeInMillis()).toString();
SimpleDateFormat formatter = new SimpleDateFormat(mDateFormate);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = formatter.parse(date);
SimpleDateFormat dateFormatter = new SimpleDateFormat(mDateFormate);
dateFormatter.setTimeZone(TimeZone.getDefault());
date = dateFormatter.format(value);
return date;
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
Result :
12-08-2016 - 04:30 PM
Hope this will work for others.
The length function will do it. See http://www.techonthenet.com/oracle/functions/length.php
For myself, this problem was caused by using the prettier
VSCode plugin without having a prettier config file in the workspace.
Disabling the plugin fixed the problem. It could have also probably been fixed by relying on the prettier config.
As it's said, you need an Activity as context for the dialog, use "YourActivity.this" for a static context or check here for how to use a dynamic one in a safe mode
In the latest version of Pandas there is an easy way to do exactly this. Column names (which are strings) can be sliced in whatever manner you like.
columns = ['b', 'c']
df1 = pd.DataFrame(df, columns=columns)
Or this:
f(x)=\begin{cases}
0, & -\pi\leqslant x <0\\
\pi, & 0 \leqslant x \leqslant +\pi
\end{cases}
try following to see all instances of python
whereis python
which python
Then remove all instances using:
sudo apt autoremove python
repeat sudo apt autoremove python(for all versions) that should do it, then install Anaconda and manage Pythons however you like if you need to reinstall it.
Below line will randomly select n number of rows out of the total existing row numbers from the dataframe df without replacement.
df=df.take(np.random.permutation(len(df))[:n])
As the other answers state there is no way getting query string parameters using servlet api.
So, I think the best way to get query parameters is parsing the query string yourself. ( It is more complicated iterating over parameters and checking if query string contains the parameter)
I wrote below code to get query string parameters. Using apache StringUtils and ArrayUtils which supports CSV separated query param values as well.
Example: username=james&username=smith&password=pwd1,pwd2
will return
password : [pwd1, pwd2]
(length = 2)
username : [james, smith]
(length = 2)
public static Map<String, String[]> getQueryParameters(HttpServletRequest request) throws UnsupportedEncodingException {
Map<String, String[]> queryParameters = new HashMap<>();
String queryString = request.getQueryString();
if (StringUtils.isNotEmpty(queryString)) {
queryString = URLDecoder.decode(queryString, StandardCharsets.UTF_8.toString());
String[] parameters = queryString.split("&");
for (String parameter : parameters) {
String[] keyValuePair = parameter.split("=");
String[] values = queryParameters.get(keyValuePair[0]);
//length is one if no value is available.
values = keyValuePair.length == 1 ? ArrayUtils.add(values, "") :
ArrayUtils.addAll(values, keyValuePair[1].split(",")); //handles CSV separated query param values.
queryParameters.put(keyValuePair[0], values);
}
}
return queryParameters;
}
You can try:
\bcat\b.*\bmat\b
\b
is an anchor and matches a word boundary. It will look for words cat and mat anywhere in the string with mat following cat. It will not match:
Therez caterpillar on the mat
.
but will match
The cat slept on the mat in front of the fire
If you want to match strings which have letters cat followed by mat, you can try:
cat.*mat
This will match both the above example strings.
According to the 1999 ISO C standard (C99),
size_t
is an unsigned integer type of at least 16 bit (see sections 7.17 and 7.18.3).
size_t
is an unsigned data type defined by several C/C++ standards, e.g. the C99 ISO/IEC 9899 standard, that is defined instddef.h
.1 It can be further imported by inclusion ofstdlib.h
as this file internally sub includesstddef.h
.This type is used to represent the size of an object. Library functions that take or return sizes expect them to be of type or have the return type of
size_t
. Further, the most frequently used compiler-based operator sizeof should evaluate to a constant value that is compatible withsize_t
.
As an implication, size_t
is a type guaranteed to hold any array index.
No need for jQuery. And it isn't necessary to open a new window. Protocols which doesn't return HTTP data to the browser (mailto:
, irc://
, magnet:
, ftp://
(<- it depends how it is implemented, normally the browser has an FTP client built in)) can be queried in the same window without losing the current content. In your case:
function redirect()
{
window.location.href = "mailto:[email protected]";
}
<body onload="javascript: redirect();">
Or just directly
<body onload="javascript: window.location.href='mailto:[email protected]';">
I have had same problem with my scripts. But when I did some modifications it worked for me. I did like this :-
export k=$(date "+%k");
if [ $k -ge 16 ]
then exit 0;
else
echo "good job for nothing";
fi;
that way I resolved my problem. Hope that will help for you too.
If we wanted to return the same matrix we would write:
return [[ m[row][col] for col in range(0,width) ] for row in range(0,height) ]
What this does is it iterates over a matrix m by going through each row and returning each element in each column. So the order would be like:
[[1,2,3],
[4,5,6],
[7,8,9]]
Now for question 3, we instead want to go column by column, returning each element in each row. So the order would be like:
[[1,4,7],
[2,5,8],
[3,6,9]]
Therefore just switch the order in which we iterate:
return [[ m[row][col] for row in range(0,height) ] for col in range(0,width) ]
This works
<a href="#" id="sampleApp" onclick="myFunction(); return false;">Click Here</a>
You can do the following:
Assuming your container div has a class "yellow".
.yellow div {
// Apply margin to every child in this container
margin: 10px;
}
.yellow div:first-child, .yellow div:nth-child(3n+1) {
// Remove the margin on the left side on the very first and then every fourth element (for example)
margin-left: 0;
}
.yellow div:last-child {
// Remove the right side margin on the last element
margin-right: 0;
}
The number 3n+1 equals every fourth element outputted and will clearly only work if you know how many will be displayed in a row, but it should illustrate the example. More details regarding nth-child here.
Note: For :first-child to work in IE8 and earlier, a <!DOCTYPE>
must be declared.
Note2: The :nth-child() selector is supported in all major browsers, except IE8 and earlier.
use panTo(x,y).This will help u
I think this is closer to the answer you're looking for:
<input type="file">
$file = $(file);
var filename = fileElement[0].files[0].name;
I know this reply is too late, I had the same issue and i was adding the System.Net.Http.Formatting.Extension
Nuget, after checking here and there I found that the Nuget is added but the System.Net.Http.Formatting.dll
was not added to the references, I just reinstalled the Nuget
Excerpted from Josh Stodola's Setting keyboard caret Position in a Textbox or TextArea with Javascript
A generic function that will allow you to insert the caret at any position of a textbox or textarea that you wish:
function setCaretPosition(elemId, caretPos) {
var elem = document.getElementById(elemId);
if(elem != null) {
if(elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else {
if(elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
}
else
elem.focus();
}
}
}
The first expected parameter is the ID of the element you wish to insert the keyboard caret on. If the element is unable to be found, nothing will happen (obviously). The second parameter is the caret positon index. Zero will put the keyboard caret at the beginning. If you pass a number larger than the number of characters in the elements value, it will put the keyboard caret at the end.
Tested on IE6 and up, Firefox 2, Opera 8, Netscape 9, SeaMonkey, and Safari. Unfortunately on Safari it does not work in combination with the onfocus event).
An example of using the above function to force the keyboard caret to jump to the end of all textareas on the page when they receive focus:
function addLoadEvent(func) {
if(typeof window.onload != 'function') {
window.onload = func;
}
else {
if(func) {
var oldLoad = window.onload;
window.onload = function() {
if(oldLoad)
oldLoad();
func();
}
}
}
}
// The setCaretPosition function belongs right here!
function setTextAreasOnFocus() {
/***
* This function will force the keyboard caret to be positioned
* at the end of all textareas when they receive focus.
*/
var textAreas = document.getElementsByTagName('textarea');
for(var i = 0; i < textAreas.length; i++) {
textAreas[i].onfocus = function() {
setCaretPosition(this.id, this.value.length);
}
}
textAreas = null;
}
addLoadEvent(setTextAreasOnFocus);
Today 2020.12.31 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v84 for chosen solutions for getting last character case (last N letters case results, for clarity I present in separate answer).
For all browsers
I perform 2 tests cases:
Below snippet presents solutions A B C D E F G (my), H (my)
//https://stackoverflow.com/questions/5873810/how-can-i-get-last-characters-of-a-string
// https://stackoverflow.com/a/30916653/860099
function A(s) {
return s.substr(-1)
}
// https://stackoverflow.com/a/5873890/860099
function B(s) {
return s.substr(s.length - 1)
}
// https://stackoverflow.com/a/17489443/860099
function C(s) {
return s.substring(s.length - 1, s.length);
}
// https://stackoverflow.com/a/50395190/860099
function D(s) {
return s.slice(-1);
}
// https://stackoverflow.com/a/50374396/860099
function E(s) {
return s.charAt(s.length-1);
}
// https://stackoverflow.com/a/17489443/860099
function F(s) {
return s[s.length-1];
}
// my
function G(s) {
return s.match(/.$/);
}
// my
function H(s) {
return [...s].pop();
}
// --------------------
// TEST
// --------------------
[A,B,C,D,E,F,G,H].map(f=> {
console.log(
f.name + ' ' + f('ctl03_Tabs1')
)})
_x000D_
This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
And here are example results for chrome
Applying the full_extent()
function in an answer by @Joe 3 years later from here, you can get exactly what the OP was looking for. Alternatively, you can use Axes.get_tightbbox()
which gives a little tighter bounding box
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from matplotlib.transforms import Bbox
def full_extent(ax, pad=0.0):
"""Get the full extent of an axes, including axes labels, tick labels, and
titles."""
# For text objects, we need to draw the figure first, otherwise the extents
# are undefined.
ax.figure.canvas.draw()
items = ax.get_xticklabels() + ax.get_yticklabels()
# items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label]
items += [ax, ax.title]
bbox = Bbox.union([item.get_window_extent() for item in items])
return bbox.expanded(1.0 + pad, 1.0 + pad)
# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')
ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')
# Save the full figure...
fig.savefig('full_figure.png')
# Save just the portion _inside_ the second axis's boundaries
extent = full_extent(ax2).transformed(fig.dpi_scale_trans.inverted())
# Alternatively,
# extent = ax.get_tightbbox(fig.canvas.renderer).transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)
I'd post a pic but I lack the reputation points
instead of modifying adb_usb.ini file I made changes on the file android_winusb.inf under directory android-sdk\extras\google\usb_driver\ alone and it worked for the tablet MID Q88 but i copied both sections [Google.NTamd64] and [Google.NTx86]
;Google MID Q88
%SingleAdbInterface% = USB_INSTALL, USB\VID_18D1&PID_0003&MI_01
%CompositeAdbInterface% = USB_INSTALL, USB\VID_18D1&PID_0003&REV_0230&MI_01
You can use Arrays.sort() method. Here's the example,
import java.util.Arrays;
public class Test
{
public static void main(String[] args)
{
String arrString[] = { "peter", "taylor", "brooke", "frederick", "cameron" };
orderedGuests(arrString);
}
public static void orderedGuests(String[] hotel)
{
Arrays.sort(hotel);
System.out.println(Arrays.toString(hotel));
}
}
Output
[brooke, cameron, frederick, peter, taylor]
One thing i've noticed is: spring CronTrigger is not cron. You may end up with 7 parameters in a valid cron expression (wich you can validate on cronmaker.com) and then spring not accept it. Most of cases you just delete the last parameter and everything works fine.
Gilean's answer is great, but I just wanted to add that sometimes there are rare exceptions to best practices, and you might want to test your environment both ways to see what will work best.
In one case, I found that query
worked faster for my purposes because I was bulk transferring trusted data from an Ubuntu Linux box running PHP7 with the poorly supported Microsoft ODBC driver for MS SQL Server.
I arrived at this question because I had a long running script for an ETL that I was trying to squeeze for speed. It seemed intuitive to me that query
could be faster than prepare
& execute
because it was calling only one function instead of two. The parameter binding operation provides excellent protection, but it might be expensive and possibly avoided if unnecessary.
Given a couple rare conditions:
If you can't reuse a prepared statement because it's not supported by the Microsoft ODBC driver.
If you're not worried about sanitizing input and simple escaping is acceptable. This may be the case because binding certain datatypes isn't supported by the Microsoft ODBC driver.
PDO::lastInsertId
is not supported by the Microsoft ODBC driver.
Here's a method I used to test my environment, and hopefully you can replicate it or something better in yours:
To start, I've created a basic table in Microsoft SQL Server
CREATE TABLE performancetest (
sid INT IDENTITY PRIMARY KEY,
id INT,
val VARCHAR(100)
);
And now a basic timed test for performance metrics.
$logs = [];
$test = function (String $type, Int $count = 3000) use ($pdo, &$logs) {
$start = microtime(true);
$i = 0;
while ($i < $count) {
$sql = "INSERT INTO performancetest (id, val) OUTPUT INSERTED.sid VALUES ($i,'value $i')";
if ($type === 'query') {
$smt = $pdo->query($sql);
} else {
$smt = $pdo->prepare($sql);
$smt ->execute();
}
$sid = $smt->fetch(PDO::FETCH_ASSOC)['sid'];
$i++;
}
$total = (microtime(true) - $start);
$logs[$type] []= $total;
echo "$total $type\n";
};
$trials = 15;
$i = 0;
while ($i < $trials) {
if (random_int(0,1) === 0) {
$test('query');
} else {
$test('prepare');
}
$i++;
}
foreach ($logs as $type => $log) {
$total = 0;
foreach ($log as $record) {
$total += $record;
}
$count = count($log);
echo "($count) $type Average: ".$total/$count.PHP_EOL;
}
I've played with multiple different trial and counts in my specific environment, and consistently get between 20-30% faster results with query
than prepare
/execute
5.8128969669342 prepare
5.8688418865204 prepare
4.2948560714722 query
4.9533629417419 query
5.9051351547241 prepare
4.332102060318 query
5.9672858715057 prepare
5.0667371749878 query
3.8260300159454 query
4.0791549682617 query
4.3775160312653 query
3.6910600662231 query
5.2708210945129 prepare
6.2671611309052 prepare
7.3791449069977 prepare
(7) prepare Average: 6.0673267160143
(8) query Average: 4.3276024162769
I'm curious to see how this test compares in other environments, like MySQL.
Python 2.x ignores commas if found after the last element of the sequence:
>>> a_tuple_for_instance = (0,1,2,3,)
>>> another_tuple = (0,1,2,3)
>>> a_tuple_for_instance == another_tuple
True
A trailing comma causes a single parenthesized element to be treated as a sequence:
>>> a_tuple_with_one_element = (8,)
You want to init an array of ints in your constructor? Point it to a static array.
class C
{
public:
int *cArray;
};
C::C {
static int c_init[]{1,2,3};
cArray = c_init;
}
Ran into issues like, while running sudo apt-get install python3-env
on Ubuntu WSL:
Err:1 http://security.ubuntu.com/ubuntu xenial-security/universe amd64 python3.5-venv amd64 3.5.2-2ubuntu0~16.04.9
404 Not Found [IP: 2001:67c:1360:8001::23 80]
Running
sudo apt-get update
fixed those issues.
Just these three commands will get all the branches:
git clone --mirror repo.git .git (gets just .git - bare repository)
git config --bool core.bare false
git reset --hard
The answer is simple and I am surprised it has yet to be answered here.
Use a Header View
or/and Footer View
on the list itself.
Don't mix a ScrollView
with a ListView
or anything that can scroll. It's meant to be used with headers and footers :)
Essentially, take all the content above your ListView, put it in another .xml file as a layout and then in code inflate it and add it to the list as a header view.
i.e.
View header = getLayoutInflater().inflate(R.layout.header, null);
View footer = getLayoutInflater().inflate(R.layout.footer, null);
listView.addHeaderView(header);
listView.addFooterView(footer);
The simple answer to your question is that there is no Annotation-Inheritance in Java. However, there is a way to use the Spring annotations in a way that I think will help solve your problem.
@RequestMapping is supported at both the type level and at the method level.
When you put @RequestMapping
at the type level, most of the attributes are 'inherited' for each method in that class. This is mentioned in the Spring reference documentation. Look at the api docs for details on how each attribute is handled when adding @RequestMapping
to a type. I've summarized this for each attribute below:
name
: Value at Type level is concatenated with value at method level using '#' as a separator.value
: Value at Type level is inherited by method.path
: Value at Type level is inherited by method.method
: Value at Type level is inherited by method.params
: Value at Type level is inherited by method.headers
: Value at Type level is inherited by method.consumes
: Value at Type level is overridden by method.produces
: Value at Type level is overridden by method.Here is a brief example Controller that showcases how you could use this:
package com.example;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(path = "/",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE,
method = {RequestMethod.GET, RequestMethod.POST})
public class JsonProducingEndpoint {
private FooService fooService;
@RequestMapping(path = "/foo", method = RequestMethod.POST)
public String postAFoo(@RequestBody ThisIsAFoo theFoo) {
fooService.saveTheFoo(theFoo);
return "http://myservice.com/foo/1";
}
@RequestMapping(path = "/foo/{id}", method = RequestMethod.GET)
public ThisIsAFoo getAFoo(@PathVariable String id) {
ThisIsAFoo foo = fooService.getAFoo(id);
return foo;
}
@RequestMapping(path = "/foo/{id}", produces = MediaType.APPLICATION_XML_VALUE, method = RequestMethod.GET)
public ThisIsAFooXML getAFooXml(@PathVariable String id) {
ThisIsAFooXML foo = fooService.getAFoo(id);
return foo;
}
}
I had the same issue (same error on heroku, working on local machine) and I tried all the solutions listed here including
heroku run rails console
which ran without error messages. I tried heroku run rake db:migrate
and heroku run rake db:migrate:reset
a few times. None of this solved the problem. On going through some files that are used in production but not in dev environment, I found some whitespace in the puma.rb file to be the culprit. Hope this helps someone who has the same issue.
Changing this made it work
ActiveRecord::Base.establish_connection
End
to
ActiveRecord::Base.establish_connection
end
I avoid using natural keys for one simple reason -- human error. Although natural unique identifiers are often available (SSN, VIN, Account Number, etc.), they require a human to enter them correctly. If you're using SSNs as a primary key, someone transposes a couple of numbers during data entry, and the error isn't discovered immediately, then you're faced with changing your primary key.
My primary keys are all handled by the database program in the background and the user is never aware of them.
Look. This is way old, but on the off chance that someone from Google finds this, absolutely the best solution to this - (and it is AWESOME) - is to use ConEmu (or a package that includes and is built on top of ConEmu called cmder) and then either use plink or putty itself to connect to a specific machine, or, even better, set up a development environment as a local VM using Vagrant.
This is the only way I can ever see myself developing from a Windows box again.
I am confident enough to say that every other answer - while not necessarily bad answers - offer garbage solutions compared to this.
Update: As Of 1/8/2020 not all other solutions are garbage - Windows Terminal is getting there and WSL exists.
Simple 2 steps for scrolling down to end or bottom.
Step1: get the full height of scrollable(conversation) div.
Step2: apply scrollTop on that scrollable(conversation) div using the value obtained in step1.
var fullHeight = $('#conversation')[0].scrollHeight;
$('#conversation').scrollTop(fullHeight);
Above steps must be applied for every append on the conversation div.
Thread.sleep can throw an InterruptedException which is a checked exception. All checked exceptions must either be caught and handled or else you must declare that your method can throw it. You need to do this whether or not the exception actually will be thrown. Not declaring a checked exception that your method can throw is a compile error.
You either need to catch it:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
// handle the exception...
// For example consider calling Thread.currentThread().interrupt(); here.
}
Or declare that your method can throw an InterruptedException
:
public static void main(String[]args) throws InterruptedException
Related
Closes a socket connection and allows for re-use of the socket:
tcpClient.Client.Disconnect(false);
I tried the code by @alex-martelli but found some discrepancies
python -mtimeit -s "xs=range(123456)" "map(hex, xs)"
1000000 loops, best of 5: 218 nsec per loop
python -mtimeit -s "xs=range(123456)" "[hex(x) for x in xs]"
10 loops, best of 5: 19.4 msec per loop
map takes the same amount of time even for very large ranges while using list comprehension takes a lot of time as is evident from my code. So apart from being considered "unpythonic", I have not faced any performance issues relating to usage of map.
To remove/clear docker container logs we can use below command
$(docker inspect container_id|grep "LogPath"|cut -d """ -f4) or $(docker inspect container_name|grep "LogPath"|cut -d """ -f4)
The miniature from-serialize library doesn't rely on a framework. Other than something like that, you'll need to implement the serialization function yourself. (though at a weight of 1.2 kilobytes, why not use it?)
You can trim simply with echo
:
foo=" qsdqsd qsdqs q qs "
# Not trimmed
echo \'$foo\'
# Trim
foo=`echo $foo`
# Trimmed
echo \'$foo\'
Hemnath
If your variable is the percentage:
var myWidth = 70;
$('div#somediv').width(myWidth + '%');
If your variable is in pixels, and you want the percentage it take up of the parent:
var myWidth = 140;
var myPercentage = (myWidth / $('div#somediv').parent().width()) * 100;
$('div#somediv').width(myPercentage + '%');
On Solaris the limit has been about 3.5 GB since Solaris 2.5. (about 10 years ago)
Please see the logs as this way,
Log.e("ApiUrl = ", "MyApiUrl") (error)
Log.w("ApiUrl = ", "MyApiUrl") (warning)
Log.i("ApiUrl = ", "MyApiUrl") (information)
Log.d("ApiUrl = ", "MyApiUrl") (debug)
Log.v("ApiUrl = ", "MyApiUrl") (verbose)
$find="Topsite";
$list=array("Tope","Ajayi","Topsite","Infotech");
$list_count=count($list);
sort($list);
for($i=0;$i<$list_count;$i++)
{
if($list[$i]==$find){
$position=$i;
}
}
echo $position;
Simple - the csv module works with lists, too:
>>> a=["1,2,3","4,5,6"] # or a = "1,2,3\n4,5,6".split('\n')
>>> import csv
>>> x = csv.reader(a)
>>> list(x)
[['1', '2', '3'], ['4', '5', '6']]
Virtual destructors are useful when you might potentially delete an instance of a derived class through a pointer to base class:
class Base
{
// some virtual methods
};
class Derived : public Base
{
~Derived()
{
// Do some important cleanup
}
};
Here, you'll notice that I didn't declare Base's destructor to be virtual
. Now, let's have a look at the following snippet:
Base *b = new Derived();
// use b
delete b; // Here's the problem!
Since Base's destructor is not virtual
and b
is a Base*
pointing to a Derived
object, delete b
has undefined behaviour:
[In
delete b
], if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.
In most implementations, the call to the destructor will be resolved like any non-virtual code, meaning that the destructor of the base class will be called but not the one of the derived class, resulting in a resources leak.
To sum up, always make base classes' destructors virtual
when they're meant to be manipulated polymorphically.
If you want to prevent the deletion of an instance through a base class pointer, you can make the base class destructor protected and nonvirtual; by doing so, the compiler won't let you call delete
on a base class pointer.
You can learn more about virtuality and virtual base class destructor in this article from Herb Sutter.
Following are few options available to change Heap Size.
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
-Xss<size> set java thread stack size
java -Xmx256m TestData.java
Math.Floor()
: Returns the largest integer less than or equal to the specified double-precision floating-point number.
Math.Round()
: Rounds a value to the nearest integer or to the specified number of fractional digits.
You can specify the whole day by doing a range, like so:
WHERE bk_date >= TO_DATE('2012-03-18', 'YYYY-MM-DD')
AND bk_date < TO_DATE('2012-03-19', 'YYYY-MM-DD')
More simply you can use TRUNC:
WHERE TRUNC(bk_date) = TO_DATE('2012-03-18', 'YYYY-MM-DD')
TRUNC without parameter removes hours, minutes and seconds from a DATE.
You append a newline to both the username and the password, i.e. the output would be something like
Sebastian
password
John
hfsjaijn
use fwrite($fh,$user." ".$password."\n");
instead to have them both on one line.
Or use fputcsv() to write the data and fgetcsv()
to fetch it. This way you would at least avoid encoding problems like e.g. with $username='Charles, III';
...i.e. setting aside all the things that are wrong about storing plain passwords in plain files and using _GET for this type of operation (use _POST instead) ;-)
You can also use react helmet
import React from "react";
import {Helmet} from "react-helmet";
class Application extends React.Component {
render () {
return (
<div className="application">
<Helmet>
<meta charSet="utf-8" />
<title>My Title</title>
<link rel="canonical" href="http://example.com/example" />
<script src="/path/to/resource.js" type="text/javascript" />
</Helmet>
...
</div>
);
}
};
Helmet takes plain HTML tags and outputs plain HTML tags. It's dead simple, and React beginner friendly.
While I think the regex-based solution is probably the way I'd go, I'd be tempted to encapsulate this in a type.
public class AlphaNumericString
{
public AlphaNumericString(string s)
{
Regex r = new Regex("^[a-zA-Z0-9]*$");
if (r.IsMatch(s))
{
value = s;
}
else
{
throw new ArgumentException("Only alphanumeric characters may be used");
}
}
private string value;
static public implicit operator string(AlphaNumericString s)
{
return s.value;
}
}
Now, when you need a validated string, you can have the method signature require an AlphaNumericString, and know that if you get one, it is valid (apart from nulls). If someone attempts to pass in a non-validated string, it will generate a compiler error.
You can get fancier and implement all of the equality operators, or an explicit cast to AlphaNumericString from plain ol' string, if you care.
Expanding a bit on the answers from @Guru and @Ronnis, you can hide the sequence and make it look more like an auto-increment using a trigger, and have a procedure that does the insert for you and returns the generated ID as an out parameter.
create table batch(batchid number,
batchname varchar2(30),
batchtype char(1),
source char(1),
intarea number)
/
create sequence batch_seq start with 1
/
create trigger batch_bi
before insert on batch
for each row
begin
select batch_seq.nextval into :new.batchid from dual;
end;
/
create procedure insert_batch(v_batchname batch.batchname%TYPE,
v_batchtype batch.batchtype%TYPE,
v_source batch.source%TYPE,
v_intarea batch.intarea%TYPE,
v_batchid out batch.batchid%TYPE)
as
begin
insert into batch(batchname, batchtype, source, intarea)
values(v_batchname, v_batchtype, v_source, v_intarea)
returning batchid into v_batchid;
end;
/
You can then call the procedure instead of doing a plain insert, e.g. from an anoymous block:
declare
l_batchid batch.batchid%TYPE;
begin
insert_batch(v_batchname => 'Batch 1',
v_batchtype => 'A',
v_source => 'Z',
v_intarea => 1,
v_batchid => l_batchid);
dbms_output.put_line('Generated id: ' || l_batchid);
insert_batch(v_batchname => 'Batch 99',
v_batchtype => 'B',
v_source => 'Y',
v_intarea => 9,
v_batchid => l_batchid);
dbms_output.put_line('Generated id: ' || l_batchid);
end;
/
Generated id: 1
Generated id: 2
You can make the call without an explicit anonymous block, e.g. from SQL*Plus:
variable l_batchid number;
exec insert_batch('Batch 21', 'C', 'X', 7, :l_batchid);
... and use the bind variable :l_batchid
to refer to the generated value afterwards:
print l_batchid;
insert into some_table values(:l_batch_id, ...);
This code works fine:
import os
def readFile(filename):
filehandle = open(filename)
print filehandle.read()
filehandle.close()
fileDir = os.path.dirname(os.path.realpath('__file__'))
print fileDir
#For accessing the file in the same folder
filename = "same.txt"
readFile(filename)
#For accessing the file in a folder contained in the current folder
filename = os.path.join(fileDir, 'Folder1.1/same.txt')
readFile(filename)
#For accessing the file in the parent folder of the current folder
filename = os.path.join(fileDir, '../same.txt')
readFile(filename)
#For accessing the file inside a sibling folder.
filename = os.path.join(fileDir, '../Folder2/same.txt')
filename = os.path.abspath(os.path.realpath(filename))
print filename
readFile(filename)
char = split_string_to_char(text)(index)
------
Function split_string_to_char(text) As String()
Dim chars() As String
For char_count = 1 To Len(text)
ReDim Preserve chars(char_count - 1)
chars(char_count - 1) = Mid(text, char_count, 1)
Next
split_string_to_char = chars
End Function
Using subset
:
missing<-subset(a1, !(a %in% a2$a))
add JAVA_HOME to the file:
/etc/environment
for it to be available to the entire system (you would need to restart Ubuntu though)
Matlab allows you to return multiple values as well as receive them inline.
When you call it, receive individual variables inline:
[array, listp, freep] = initialize(size)
I found one elegant solution as well, have not tested it rigorously though:
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (m_webView.getProgress() == 100) {
progressBar.setVisibility(View.GONE);
m_webView.setVisibility(View.VISIBLE);
}
}
From The Java™ Tutorials - Abstract Classes Compared to Interfaces
Which should you use, abstract classes or interfaces?
- Consider using abstract classes if any of these statements apply to your situation:
- You want to share code among several closely related classes.
- You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
- You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
- Consider using interfaces if any of these statements apply to your situation:
- You expect that unrelated classes would implement your interface. For example, the interfaces
Comparable
andCloneable
are implemented by many unrelated classes.- You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
- You want to take advantage of multiple inheritance of type.
An example of an abstract class in the JDK is
AbstractMap
, which is part of the Collections Framework. Its subclasses (which includeHashMap
,TreeMap
, andConcurrentHashMap
) share many methods (includingget
,put
,isEmpty
,containsKey
, andcontainsValue
) thatAbstractMap
defines.
It just happend to me. I solved the problem by tracing backward from the point ng-click is coded. Found out that an extra
</div>
was placed in the html to prematurely close the div block that contains the ng-click.
Removed the extra
</div>
then everything is working fine.
-webkit-animation-fill-mode: forwards; /* Safari 4.0 - 8.0 */ animation-fill-mode: forwards;
Browser Support
Usage:-
.fadeIn {
animation-name: fadeIn;
-webkit-animation-name: fadeIn;
animation-duration: 1.5s;
-webkit-animation-duration: 1.5s;
animation-timing-function: ease;
-webkit-animation-timing-function: ease;
animation-fill-mode: forwards;
-webkit-animation-fill-mode: forwards;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@-webkit-keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
You can call the method getBoundingClientRect()
on a reference to the element. Then you can examine the top
, left
, right
and/or bottom
properties...
var offsets = document.getElementById('11a').getBoundingClientRect();
var top = offsets.top;
var left = offsets.left;
If using jQuery, you can use the more succinct code...
var offsets = $('#11a').offset();
var top = offsets.top;
var left = offsets.left;
for refresh data gridview in any where you just need this code:
datagridview1.DataSource = "your DataSource";
datagridview1.Refresh();
You could try Mobilenium (https://github.com/rafpyprog/Mobilenium), a python package that binds BrowserMob Proxy and Selenium.
An usage example:
>>> from mobilenium import mobidriver
>>>
>>> browsermob_path = 'path/to/browsermob-proxy'
>>> mob = mobidriver.Firefox(browsermob_binary=browsermob_path)
>>> mob.get('http://python-requests.org')
301
>>> mob.response['redirectURL']
'http://docs.python-requests.org'
>>> mob.headers['Content-Type']
'application/json; charset=utf8'
>>> mob.title
'Requests: HTTP for Humans \u2014 Requests 2.13.0 documentation'
>>> mob.find_elements_by_tag_name('strong')[1].text
'Behold, the power of Requests'
Using git 2.9 (precisely 2.9.2.windows.1)
git reset HEAD^
prompts for more; not sure what is expected input here. Please refer below screenshot
Found other solution git reset HEAD~#numberOfCommits
using which we can choose to select number of local commits you want to reset by keeping your changes intact. Hence, we get an opportunity to throw away all local commits as well as limited number of local commits.
For multiple times of execution of our model, random state make sure that data values will be same for training and testing data sets. It fixes the order of data for train_test_split
From Auth0.com
Token-Based Authentication, relies on a signed token that is sent to the server on each request.
What are the benefits of using a token-based approach?
Cross-domain / CORS: cookies + CORS don't play well across different domains. A token-based approach allows you to make AJAX calls to any server, on any domain because you use an HTTP header to transmit the user information.
Stateless (a.k.a. Server side scalability): there is no need to keep a session store, the token is a self-contained entity that conveys all the user information. The rest of the state lives in cookies or local storage on the client side.
CDN: you can serve all the assets of your app from a CDN (e.g. javascript, HTML, images, etc.), and your server side is just the API.
Decoupling: you are not tied to any particular authentication scheme. The token might be generated anywhere, hence your API can be called from anywhere with a single way of authenticating those calls.
Mobile ready: when you start working on a native platform (iOS, Android, Windows 8, etc.) cookies are not ideal when consuming a token-based approach simplifies this a lot.
CSRF: since you are not relying on cookies, you don't need to protect against cross site requests (e.g. it would not be possible to sib your site, generate a POST request and re-use the existing authentication cookie because there will be none).
Performance: we are not presenting any hard perf benchmarks here, but a network roundtrip (e.g. finding a session on database) is likely to take more time than calculating an HMACSHA256 to validate a token and parsing its contents.
By definition, file: URLs are system-dependent, and they have little use. A URL as in your example works when used locally, i.e. the linking page itself is in the user’s computer. But browsers generally refuse to follow file: links on a page that it has fetched with the HTTP protocol, so that the page's own URL is an http: URL. When you click on such a link, nothing happens. The purpose is presumably security: to prevent a remote page from accessing files in the visitor’s computer. (I think this feature was first implemented in Mozilla, then copied to other browsers.)
So if you work with HTML documents in your computer, the file: URLs should work, though there are system-dependent issues in their syntax (how you write path names and file names in such a URL).
If you really need to work with an HTML document on your computers and another HTML document on a web server, the way to make links work is to use the local file as primary and, if needed, use client-side scripting to fetch the document from the server,
This can be done very easily using a PostBackUrl and a regular button.
<asp:Button ID="Button1" runat="server" Text="Name of web location" PostBackUrl="web address" />
I would like to do this without attaching a class to every td
Personally, I would go with the the class-on-each-td/th/col approach. Then you can switch columns on and off using a single write to className on the container, assuming style rules like:
table.hide1 .col1 { display: none; }
table.hide2 .col2 { display: none; }
...
This is going to be faster than any JS loop approach; for really long tables it can make a significant difference to responsiveness.
If you can get away with not supporting IE6, you could use adjacency selectors to avoid having to add the class attributes to tds. Or alternatively, if your concern is making the markup cleaner, you could add them from JavaScript automatically in an initialisation step.
For 2020.1.4 Ultimate edition, I had to do the following
View -> Maven -> Generate Sources and Update Folders For all Projects
The issue for me was the libraries were not getting populated with mvn -U clean install
from the terminal.
Just some bits addition from my side to all available answers
Need of AndroidX
With the current naming convention, it isn’t clear which packages are bundled with the Android operating system, and which are packaged with your application’s APK (Android Package Kit). To clear up this confusion, all the unbundled libraries will be moved to AndroidX’s androidx.* namespace, while the android.* package hierarchy will be reserved for packages that ship with the Android operating system.
Other than this,
Initially, the name of each package indicated the minimum API level supported by that package, for example support-v4. However, version 26.0.0 of the Support Library increased the minimum API to 14, so today many of the package names have nothing to do with the minimum supported API level. When support-v4 and the support-v7 packages both have a minimum API of 14, it’s easy to see why people get confused!. So now with AndroidX, there is no dependence on the API level.
Another important change is that the AndroidX artifacts will update independently, so you’ll be able to update individual AndroidX libraries in your project, rather than having to change every dependency at once. Those frustrating “All com.android.support libraries must use the exact same version specification” messages should become a thing of the past!
You can use the workbook.get_worksheet_by_name() feature: https://xlsxwriter.readthedocs.io/workbook.html#get_worksheet_by_name
According to https://xlsxwriter.readthedocs.io/changes.html the feature has been added on May 13, 2016.
"Release 0.8.7 - May 13 2016
-Fix for issue when inserting read-only images on Windows. Issue #352.
-Added get_worksheet_by_name() method to allow the retrieval of a worksheet from a workbook via its name.
-Fixed issue where internal file creation and modification dates were in the local timezone instead of UTC."
New average = old average * (n-1)/n + new value /n
This is assuming the count only changed by one value. In case it is changed by M values then:
new average = old average * (n-len(M))/n + (sum of values in M)/n).
This is the mathematical formula (I believe the most efficient one), believe you can do further code by yourselves
You can also use translate(). If the third argument is too short, the corresponding characters from the second argument are deleted. Unlike regexp_replace() you don't need to worry about special characters. Source code.
First convert all your pdf files to text files:
for file in *.pdf;do pdftotext "$file"; done
Then use grep
as normal. This is especially good as it is fast when you have multiple queries and a lot of PDF files.
The prefered way is using 2018-04-23T18:25:43.511Z
...
The picture below shows why this is the prefered way:
So as you see Date has a native Method toJSON
, which return
in this format and can be easily converted to Date
again...
For me what worked by combining all the posts I have read is:
1.Enable OLE automation - if not enabled
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
2.Create a folder where the generated files will be stored:
C:\GREGTESTING
3.Create DocTable that will be used for file generation and store there the blobs in Doc_Content
CREATE TABLE [dbo].[Document](
[Doc_Num] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[Extension] [varchar](50) NULL,
[FileName] [varchar](200) NULL,
[Doc_Content] [varbinary](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
INSERT [dbo].[Document] ([Extension] ,[FileName] , [Doc_Content] )
SELECT 'pdf', 'SHTP Notional hire - January 2019.pdf', 0x....(varbinary blob)
Important note!
Don't forget to add in Doc_Content column the varbinary of file you want to generate!
4.Run the below script
DECLARE @outPutPath varchar(50) = 'C:\GREGTESTING'
, @i bigint
, @init int
, @data varbinary(max)
, @fPath varchar(max)
, @folderPath varchar(max)
--Get Data into temp Table variable so that we can iterate over it
DECLARE @Doctable TABLE (id int identity(1,1), [Doc_Num] varchar(100) , [FileName] varchar(100), [Doc_Content] varBinary(max) )
INSERT INTO @Doctable([Doc_Num] , [FileName],[Doc_Content])
Select [Doc_Num] , [FileName],[Doc_Content] FROM [dbo].[Document]
SELECT @i = COUNT(1) FROM @Doctable
WHILE @i >= 1
BEGIN
SELECT
@data = [Doc_Content],
@fPath = @outPutPath + '\' + [Doc_Num] +'_' +[FileName],
@folderPath = @outPutPath + '\'+ [Doc_Num]
FROM @Doctable WHERE id = @i
EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @data; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @fPath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources
print 'Document Generated at - '+ @fPath
--Reset the variables for next use
SELECT @data = NULL
, @init = NULL
, @fPath = NULL
, @folderPath = NULL
SET @i -= 1
END
If your business class is directly used by your UI is preferrable to use IDataErrorInfo because it put logic closer to their owner.
If your business class is a stub class created by a reference to an WCF/XmlWeb service then you can not/must not use IDataErrorInfo nor throw Exception for use with ExceptionValidationRule. Instead you can:
You want to use css float for this, you can put it directly in your code.
<body>
<img src="website_art.png" height= "75" width="235" style="float:left;"/>
<h3 style="float:right;">The Art of Gaming</h3>
</body>
But I would really suggest learning the basics of css and splitting all your styling out to a separate style sheet, and use classes. It will help you in the future. A good place to start is w3schools or, perhaps later down the path, Mozzila Dev. Network (MDN).
HTML:
<body>
<img src="website_art.png" class="myImage"/>
<h3 class="heading">The Art of Gaming</h3>
</body>
CSS:
.myImage {
float: left;
height: 75px;
width: 235px;
font-family: Veranda;
}
.heading {
float:right;
}
#include <climits>
#include <iostream>
using namespace std;
int main() {
cout << INT_MAX << endl;
}
There are two branches lets say
Being in branch A you can type
git diff --color B
then this will give you a output of
The important point about this is
Text in green is inside present in Branch A
Text in red is present in Branch B
Tweaked version from Techie Delight:
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& str, char delim) {
std::vector<std::string> strings;
size_t start;
size_t end = 0;
while ((start = str.find_first_not_of(delim, end)) != std::string::npos) {
end = str.find(delim, start);
strings.push_back(str.substr(start, end - start));
}
return strings;
}
With C++17 (or later), you can use the "structured bindings" feature, which lets you define multiple variables, with different names, using a single tuple/pair. Example:
for (const auto& [name, description] : planet_descriptions) {
std::cout << "Planet " << name << ":\n" << description << "\n\n";
}
The original proposal (by luminaries Bjarne Stroustrup, Herb Sutter and Gabriel Dos Reis) is fun to read (and the suggested syntax is more intuitive IMHO); there's also the proposed wording for the standard which is boring to read but is closer to what will actually go in.
I used RecyclerView inside a NestedScrollView and it worked for me. The only gotcha I had to keep in mind was that a NestedScrollView takes only one child view. So in my case I used of LienearLayout viewgroup which was housing my RecyclerView plus a number of other views that I needed.
I experience one issue putting my RecyclerView inside the NestedScrollView. I realized that scrolling the content of my RecyclerView slacked.
I later realized that my RecyclerView was receiving the scrolling event and therefore was conflicting with the scrolling behavior of the NestedScrollView.
So to solve that problem, I had to disable the scroll functionality of my RecyclerView with this method movieListNewRecyclerView.setNestedScrollingEnabled(false);
You can checkout my Instagram for a short video of what I actually did. This is my instagram handle ofelix03
If you don't need to display exact result "running" / "not runnuning", you could simply:
ps notepad -ErrorAction SilentlyContinue | kill -PassThru
If the process was not running, you'll get no results. If it was running, you'll receive get-process
output, and the process will be stopped.
May be it helps.
You can
SET @somevar := '';
SELECT @somevar AS user_name FROM users WHERE (@somevar := `u_name`) = "john";
It works.
BUT MAKE SURE WHAT YOU DO!
But, may be it helps in some cases
This answer is more like an addition and a slight modification to the answers above.
In some versions of Visual Studio (and possibly other compilers) there is a bug that is really annoying and doesn't make sense. So if you declare/define your swap
function like this:
friend void swap(A& first, A& second) {
std::swap(first.size, second.size);
std::swap(first.arr, second.arr);
}
... the compiler will yell at you when you call the swap
function:
This has something to do with a friend
function being called and this
object being passed as a parameter.
A way around this is to not use friend
keyword and redefine the swap
function:
void swap(A& other) {
std::swap(size, other.size);
std::swap(arr, other.arr);
}
This time, you can just call swap
and pass in other
, thus making the compiler happy:
After all, you don't need to use a friend
function to swap 2 objects. It makes just as much sense to make swap
a member function that has one other
object as a parameter.
You already have access to this
object, so passing it in as a parameter is technically redundant.
Yeah I think the best way to transparent the background colour (make opacity only for the background) is using
.style{
background-color: rgba(100, 100, 100, 0.5);
}
Above statement 0.5 is the opacity value.
It only apply the opacity changes to the background colour (not all elements')
The "opacity" attribute in the CSS will transparent all the elements in the block.
This way you only need to free the structure because the fields are arrays with static sizes which will be allocated as part of the structure. This is also the reason that the addresses you see match: the array is the first thing in that structure. If you declared the fields as char * you would have to manually malloc and free them as well.
Save your sorting order in a ViewState.
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection) ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
private void SortGridView(string sortExpression,string direction)
{
// You can cache the DataTable for improving performance
DataTable dt = GetData().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}
Why you don't want to use existing sorting functionality? You can always customize it.
Sorting Data in a GridView Web Server Control at MSDN
Here is an example with customization:
Take a look at highlight (jQuery plugin).