using System;
using System.Drawing;
public struct MyColor
{
private byte a, r, g, b;
public byte A
{
get
{
return this.a;
}
}
public byte R
{
get
{
return this.r;
}
}
public byte G
{
get
{
return this.g;
}
}
public byte B
{
get
{
return this.b;
}
}
public MyColor SetAlpha(byte value)
{
this.a = value;
return this;
}
public MyColor SetRed(byte value)
{
this.r = value;
return this;
}
public MyColor SetGreen(byte value)
{
this.g = value;
return this;
}
public MyColor SetBlue(byte value)
{
this.b = value;
return this;
}
public int ToArgb()
{
return (int)(A << 24) || (int)(R << 16) || (int)(G << 8) || (int)(B);
}
public override string ToString ()
{
return string.Format ("[MyColor: A={0}, R={1}, G={2}, B={3}]", A, R, G, B);
}
public static MyColor FromArgb(byte alpha, byte red, byte green, byte blue)
{
return new MyColor().SetAlpha(alpha).SetRed(red).SetGreen(green).SetBlue(blue);
}
public static MyColor FromArgb(byte red, byte green, byte blue)
{
return MyColor.FromArgb(255, red, green, blue);
}
public static MyColor FromArgb(byte alpha, MyColor baseColor)
{
return MyColor.FromArgb(alpha, baseColor.R, baseColor.G, baseColor.B);
}
public static MyColor FromArgb(int argb)
{
return MyColor.FromArgb(argb & 255, (argb >> 8) & 255, (argb >> 16) & 255, (argb >> 24) & 255);
}
public static implicit operator Color(MyColor myColor)
{
return Color.FromArgb(myColor.ToArgb());
}
public static implicit operator MyColor(Color color)
{
return MyColor.FromArgb(color.ToArgb());
}
}
For hexadecimal code try this
& 0x00FFFFFF
For RGB one
Red
, Green
, Blue
valuesImplementation
private static string HexConverter(Color c) {
return String.Format("#{0:X6}", c.ToArgb() & 0x00FFFFFF);
}
public static string RgbConverter(Color c) {
return String.Format("RGB({0},{1},{2})", c.R, c.G, c.B);
}
Here's a method you can use to check if a value is a boolean:
boolean isBoolean(String value) {
return value != null && Arrays.stream(new String[]{"true", "false", "1", "0"})
.anyMatch(b -> b.equalsIgnoreCase(value));
}
Examples of using it:
System.out.println(isBoolean(null)); //false
System.out.println(isBoolean("")); //false
System.out.println(isBoolean("true")); //true
System.out.println(isBoolean("fALsE")); //true
System.out.println(isBoolean("asdf")); //false
System.out.println(isBoolean("01truefalse")); //false
In Ubuntu 18.04 the QtCreator examples and API docs missing, This is my way to solve this problem, should apply to almost every Ubuntu release.
For QtCreator and Examples and API Docs:
sudo apt install `apt-cache search 5-examples | grep qt | grep example | awk '{print $1 }' | xargs `
sudo apt install `apt-cache search 5-doc | grep "Qt 5 " | awk '{print $1}' | xargs`
sudo apt-get install build-essential qtcreator qt5-default
If something is also missing, then:
sudo apt install `apt-cache search qt | grep 5- | grep ^qt | awk '{print $1}' | xargs `
Hope to be helpful.
Also posted in Ask Ubuntu: https://askubuntu.com/questions/450983/ubuntu-14-04-qtcreator-qt5-examples-missing
I've run into the same problem, I found the solution at http://developer.android.com/tools/devices/emulator.html#vm-windows
Just follow this simple steps:
Start the Android SDK Manager, select Extras and then select Intel Hardware Accelerated Execution Manager
.
After the download completes, run [sdk]/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM.exe
Follow the on-screen instructions to complete installation.
this tells the script where is python directory !
#! /usr/bin/env python
You tried to start Tomcat and got the following error:
Could not load the Tomcat server configuration at /Servers/Tomcat v7.0 Server at localhost-config. The configuration may be corrupt or incomplete
How to solve:
.button {
border: none;
background: url('/forms/up.png') no-repeat top left;
padding: 2px 8px;
}
NOTE: As of July 2020, text-overflow: ellipsis
works for <select>
on Chrome
HTML is limited in what it specifies for form controls. That leaves room for operating system and browser makers to do what they think is appropriate on that platform (like the iPhone’s modal select
which, when open, looks totally different from the traditional pop-up menu).
If it bugs you, you can use a customizable replacement, like Chosen, which looks distinct from the native select
.
Or, file a bug against a major operating system or browser. For all we know, the way text is cut off in select
s might be the result of a years-old oversight that everyone copied, and it might be time for a change.
i founded this tool to auto generate wsdl to android code,
http://www.wsdl2code.com/Example.aspx
public void callWebService(){
SampleService srv1 = new SampleService();
Request req = new Request();
req.companyId = "1";
req.userName = "userName";
req.password = "pas";
Response response = srv1.ServiceSample(req);
}
The syntax you used is problematic. In html, an attribute (ex: style) has a value delimited by double quotes. In that case, the value of the style attribute is a css list of selectors. Try this:
<h2 style="text-align:center; font-family:tahoma">TITLE</h2>
The .values()
method will return you a result of type ValuesQuerySet
which is typically what you need in most cases.
But if you wish, you could turn ValuesQuerySet
into a native Python list using Python list comprehension as illustrated in the example below.
result = Blog.objects.values() # return ValuesQuerySet object
list_result = [entry for entry in result] # converts ValuesQuerySet into Python list
return list_result
I find the above helps if you are writing unit tests and need to assert that the expected return value of a function matches the actual return value, in which case both expected_result
and actual_result
must be of the same type (e.g. dictionary).
actual_result = some_function()
expected_result = {
# dictionary content here ...
}
assert expected_result == actual_result
This is the Method to get contact list Name and Number
private void getAllContacts() {
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id},
null);
if (phoneCursor != null) {
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//At here You can add phoneNUmber and Name to you listView ,ModelClass,Recyclerview
phoneCursor.close();
}
}
}
}
}
}
If the class is marked final
, it means that the class' structure can't be modified by anything external. Where this is the most visible is when you're doing traditional polymorphic inheritance, basically class B extends A
just won't work. It's basically a way to protect some parts of your code (to extent).
To clarify, marking class final
doesn't mark its fields as final
and as such doesn't protect the object properties but the actual class structure instead.
Downloading Wget is not necessary; the .NET Framework has web client classes built in.
$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")
For all Spring users out there, this is how I usually do my integration tests nowadays, where async behaviour is involved:
Fire an application event in production code, when an async task (such as an I/O call) has finished. Most of the time this event is necessary anyway to handle the response of the async operation in production.
With this event in place, you can then use the following strategy in your test case:
To break this down, you'll first need some kind of domain event to fire. I'm using a UUID here to identify the task that has completed, but you're of course free to use something else as long as it's unique.
(Note, that the following code snippets also use Lombok annotations to get rid of boiler plate code)
@RequiredArgsConstructor
class TaskCompletedEvent() {
private final UUID taskId;
// add more fields containing the result of the task if required
}
The production code itself then typically looks like this:
@Component
@RequiredArgsConstructor
class Production {
private final ApplicationEventPublisher eventPublisher;
void doSomeTask(UUID taskId) {
// do something like calling a REST endpoint asynchronously
eventPublisher.publishEvent(new TaskCompletedEvent(taskId));
}
}
I can then use a Spring @EventListener
to catch the published event in test code. The event listener is a little bit more involved, because it has to handle two cases in a thread safe manner:
A CountDownLatch
is used for the second case as mentioned in other answers here. Also note, that the @Order
annotation on the event handler method makes sure, that this event handler method gets called after any other event listeners used in production.
@Component
class TaskCompletionEventListener {
private Map<UUID, CountDownLatch> waitLatches = new ConcurrentHashMap<>();
private List<UUID> eventsReceived = new ArrayList<>();
void waitForCompletion(UUID taskId) {
synchronized (this) {
if (eventAlreadyReceived(taskId)) {
return;
}
checkNobodyIsWaiting(taskId);
createLatch(taskId);
}
waitForEvent(taskId);
}
private void checkNobodyIsWaiting(UUID taskId) {
if (waitLatches.containsKey(taskId)) {
throw new IllegalArgumentException("Only one waiting test per task ID supported, but another test is already waiting for " + taskId + " to complete.");
}
}
private boolean eventAlreadyReceived(UUID taskId) {
return eventsReceived.remove(taskId);
}
private void createLatch(UUID taskId) {
waitLatches.put(taskId, new CountDownLatch(1));
}
@SneakyThrows
private void waitForEvent(UUID taskId) {
var latch = waitLatches.get(taskId);
latch.await();
}
@EventListener
@Order
void eventReceived(TaskCompletedEvent event) {
var taskId = event.getTaskId();
synchronized (this) {
if (isSomebodyWaiting(taskId)) {
notifyWaitingTest(taskId);
} else {
eventsReceived.add(taskId);
}
}
}
private boolean isSomebodyWaiting(UUID taskId) {
return waitLatches.containsKey(taskId);
}
private void notifyWaitingTest(UUID taskId) {
var latch = waitLatches.remove(taskId);
latch.countDown();
}
}
Last step is to execute the system under test in a test case. I'm using a SpringBoot test with JUnit 5 here, but this should work the same for all tests using a Spring context.
@SpringBootTest
class ProductionIntegrationTest {
@Autowired
private Production sut;
@Autowired
private TaskCompletionEventListener listener;
@Test
void thatTaskCompletesSuccessfully() {
var taskId = UUID.randomUUID();
sut.doSomeTask(taskId);
listener.waitForCompletion(taskId);
// do some assertions like looking into the DB if value was stored successfully
}
}
Note, that in contrast to other answers here, this solution will also work if you execute your tests in parallel and multiple threads exercise the async code at the same time.
You cannot have two TIMESTAMP column with the same default value of CURRENT_TIMESTAMP on your table. Please refer to this link: http://www.mysqltutorial.org/mysql-timestamp.aspx
Here is my implementation.
#include <iostream>
using namespace std;
template< class T>
struct node{
T m_data;
node* m_next_node;
node(T t_data, node* t_node) :
m_data(t_data), m_next_node(t_node){}
~node(){
std::cout << "Address :" << this << " Destroyed" << std::endl;
}
};
template<class T>
class linked_list {
public:
node<T>* m_list;
linked_list(): m_list(nullptr){}
void add_node(T t_data) {
node<T>* _new_node = new node<T>(t_data, nullptr);
_new_node->m_next_node = m_list;
m_list = _new_node;
}
void populate_nodes(node<T>* t_node) {
if (t_node != nullptr) {
std::cout << "Data =" << t_node->m_data
<< ", Address =" << t_node->m_next_node
<< std::endl;
populate_nodes(t_node->m_next_node);
}
}
void delete_nodes(node<T>* t_node) {
if (t_node != nullptr) {
delete_nodes(t_node->m_next_node);
}
delete(t_node);
}
};
int main()
{
linked_list<float>* _ll = new linked_list<float>();
_ll->add_node(1.3);
_ll->add_node(5.5);
_ll->add_node(10.1);
_ll->add_node(123);
_ll->add_node(4.5);
_ll->add_node(23.6);
_ll->add_node(2);
_ll->populate_nodes(_ll->m_list);
_ll->delete_nodes(_ll->m_list);
delete(_ll);
return 0;
}
In IntelliJ Idea 2019 you can find scope "Problems" under the "Project" view. Default scope is "Project".
I like prettyPhoto
prettyPhoto is a jQuery lightbox clone. Not only does it support images, it also support for videos, flash, YouTube, iframes and ajax. It’s a full blown media lightbox
i have a solution for dynamically created variable value and combined all value in a variable.
if($_SERVER['REQUEST_METHOD']=='POST'){
$r=0;
for($i=1; $i<=4; $i++){
$a = $_POST['a'.$i];
$r .= $a;
}
echo $r;
}
map
keeps iterators to all elements stable, in C++17 you can even move elements from one map
to the other without invalidating iterators to them (and if properly implemented without any potential allocation).map
timings for single operations are typically more consistent since they never need large allocations.unordered_map
using std::hash
as implemented in the libstdc++ is vulnerable to DoS if fed with untrusted input (it uses MurmurHash2 with a constant seed - not that seeding would really help, see https://emboss.github.io/blog/2012/12/14/breaking-murmur-hash-flooding-dos-reloaded/).You can't change the height of the br
tag itself, as it's not an element that takes up space in the page. It's just an instruction to create a new line.
You can change the line height using the line-height
style. That will change the distance between the text blocks that you have separated by empty lines, but natually also the distance between lines in a text block.
For completeness: Text blocks in HTML is usually done using the p
tag around text blocks. That way you can control the line height inside the p
tag, and also the spacing between the p
tags.
This is clearly a classpath problem. Take into consideration that the classpath must change a bit when you run your program outside the IDE. This is because the IDE loads the other JARs relative to the root folder of your project, while in the case of the final JAR this is usually not true.
What I like to do in these situations is build the JAR manually. It takes me at most 5 minutes and it always solves the problem. I do not suggest you do this. Find a way to use Maven, that's its purpose.
If you're using less , and it's not loading the icons font you must check out the font path go to the file variable.less and change the @icon-font-path path , that worked for me.
I am running VirtualBox 5.1.20, and had a similar issue. Here is a url to where I found the fix, and the fix I implemented:
# https://dsin.wordpress.com/2016/08/17/ubuntu-wrong-fs-type-bad-option-bad-superblock/
if [ "5.1.20" == "${VBOXVER}" ]; then
rm /sbin/mount.vboxsf
ln -s /usr/lib/VBoxGuestAdditions/mount.vboxsf /sbin/mount.vboxsf
fi
The link had something similar to /usr/lib/VBoxGuestAdditions/other/mount.vboxsf, rather than what I have in the script excerpt.
For a build script I use in vagrant for the additions:
https://github.com/rburkholder/vagrant/blob/master/scripts/additions.sh
Seems to be a fix at https://www.virtualbox.org/ticket/16670
For SQL 2005, delete the file:
C:\Documents and Settings\<USER>\Application Data\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat
For SQL 2008, the file location, format and name changed:
C:\Documents and Settings\<USER>\Application Data\Microsoft\Microsoft SQL Server\100\Tools\Shell\SqlStudio.bin
How to clear the list:
This request is registered on Microsoft Connect
To get Sunday as 1 through Saturday as 7, this is the simplest solution to your question:
datetime.date.today().toordinal()%7 + 1
All of them:
import datetime
today = datetime.date.today()
sunday = today - datetime.timedelta(today.weekday()+1)
for i in range(7):
tmp_date = sunday + datetime.timedelta(i)
print tmp_date.toordinal()%7 + 1, '==', tmp_date.strftime('%A')
Output:
1 == Sunday
2 == Monday
3 == Tuesday
4 == Wednesday
5 == Thursday
6 == Friday
7 == Saturday
So it was a simple fix. Just had to move the ng-click
to a scope click handler:
<input id="upload"
type="file"
ng-file-select="onFileSelect($files)"
style="display: none;">
<button type="button"
ng-click="clickUpload()">Upload</button>
$scope.clickUpload = function(){
angular.element('#upload').trigger('click');
};
The problem you're having, is that you are using a Group Selector
, whereas you should be using a Multiples selector
! To be more specific, you're using $('.a, .b')
whereas you should be using $('.a.b')
.
For more information, see the overview of the different ways to combine selectors herebelow!
Select all <h1>
elements AND all <p>
elements AND all <a>
elements :
$('h1, p, a')
Select all <input>
elements of type
text
, with classes code
and red
:
$('input[type="text"].code.red')
Select all <i>
elements inside <p>
elements:
$('p i')
Select all <ul>
elements that are immediate children of a <li>
element:
$('li > ul')
Select all <a>
elements that are placed immediately after <h2>
elements:
$('h2 + a')
Select all <span>
elements that are siblings of <div>
elements:
$('div ~ span')
Use this code to generate horizontal scrolling blocks contents. I got this from here http://www.htmlexplorer.com/2014/02/horizontal-scrolling-webpage-content.html
<html>
<title>HTMLExplorer Demo: Horizontal Scrolling Content</title>
<head>
<style type="text/css">
#outer_wrapper {
overflow: scroll;
width:100%;
}
#outer_wrapper #inner_wrapper {
width:6000px; /* If you have more elements, increase the width accordingly */
}
#outer_wrapper #inner_wrapper div.box { /* Define the properties of inner block */
width: 250px;
height:300px;
float: left;
margin: 0 4px 0 0;
border:1px grey solid;
}
</style>
</head>
<body>
<div id="outer_wrapper">
<div id="inner_wrapper">
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<!-- more boxes here -->
</div>
</div>
</body>
</html>
While I find most answers here quite correct, many of them contain unnecessary Bashisms. POSIX parameter expansion gives you all you need:
[ "${host#user}" != "${host}" ]
and
[ "${host#node}" != "${host}" ]
${var#expr}
strips the smallest prefix matching expr
from ${var}
and returns that. Hence if ${host}
does not start with user
(node
), ${host#user}
(${host#node}
) is the same as ${host}
.
expr
allows fnmatch()
wildcards, thus ${host#node??}
and friends also work.
var element = $("#parentDiv .myClassNameOfInterest")
Fastest on my tests:
conn.row_factory = lambda c, r: dict(zip([col[0] for col in c.description], r))
c = conn.cursor()
%timeit c.execute('SELECT * FROM table').fetchall()
19.8 µs ± 1.05 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
vs:
conn.row_factory = lambda c, r: dict([(col[0], r[idx]) for idx, col in enumerate(c.description)])
c = conn.cursor()
%timeit c.execute('SELECT * FROM table').fetchall()
19.4 µs ± 75.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
You decide :)
You can just do git merge <commit-number>
or git cherry-pick <commit> <commit> ...
As suggested by Ryan Stewart you may also create a branch from the current HEAD:
git branch brand-name
Or just a tag:
git tag tag-name
Use the ::before
pseudo element. This way only you don't have to deal with Javascript or creating links for each cell. Using the following table
structure
<table>
<tr>
<td><a href="http://domain.tld" class="rowlink">Cell</a></td>
<td>Cell</td>
<td>Cell</td>
</tr>
</table>
all we have to do is create a block element spanning the entire width of the table using ::before
on the desired link (.rowlink
) in this case.
table {
position: relative;
}
.rowlink::before {
content: "";
display: block;
position: absolute;
left: 0;
width: 100%;
height: 1.5em; /* don't forget to set the height! */
}
The ::before
is highlighted in red in the demo so you can see what it's doing.
You could add a method to String to make it more semantic:
String.metaClass.getNotBlank = { !delegate.allWhitespace }
which let's you do:
groovy:000> foo = ''
===>
groovy:000> foo.notBlank
===> false
groovy:000> foo = 'foo'
===> foo
groovy:000> foo.notBlank
===> true
Check the lib of your project. It may be that you have include two such jar files in which same class is available or say one class in code can be refrenced in two jar files. In such case also eclipse stops assisting code as it is totally confused.
Better way to check this is go to the file where assist is not working and comment all imports there, than add imports one by one and check at each import if code-assist is working or not.You can easily find the class with duplicate refrences.
You can use $.isEmptyObject(json)
This acronym might help you to remember the ASP.NET life cycle stages which I wrote about in the below blog post.
R-SIL-VP-RU
- Request
- Start
- Initialization
- Load
- Validation
- Post back handling
- Rendering
- Unload
From my blog: Understand ASP.NET Page life cycle and remember stages in easy way
18 May 2014
In the project I'm working on, audit log also started from the very minimalistic design, like the one you described:
event ID
event date/time
event type
user ID
description
The idea was the same: to keep things simple.
However, it quickly became obvious that this minimalistic design was not sufficient. The typical audit was boiling down to questions like this:
Who the heck created/updated/deleted a record
with ID=X in the table Foo and when?
So, in order to be able to answer such questions quickly (using SQL), we ended up having two additional columns in the audit table
object type (or table name)
object ID
That's when design of our audit log really stabilized (for a few years now).
Of course, the last "improvement" would work only for tables that had surrogate keys. But guess what? All our tables that are worth auditing do have such a key!
Or you can do the following shortcut :
MAC : Shift + Command + A (Enter Action menu pops up)
And write : Optimize Imports
Simply alter your table, no need to any thing. just run this query on database.
ALTER TABLE table_name
CONVERT TO CHARACTER SET utf8
it will definately work.
This does the same, enhanced with CONTAINS:
Function SingleCellExtract(LookupValue As String, LookupRange As Range, ColumnNumber As Integer, Char As String)
Dim I As Long
Dim xRet As String
For I = 1 To LookupRange.Columns(1).Cells.Count
If InStr(1, LookupRange.Cells(I, 1), LookupValue) > 0 Then
If xRet = "" Then
xRet = LookupRange.Cells(I, ColumnNumber) & Char
Else
xRet = xRet & "" & LookupRange.Cells(I, ColumnNumber) & Char
End If
End If
Next
SingleCellExtract = Left(xRet, Len(xRet) - 1)
End Function
Avoid the for loopfor XY in xy:
Instead read up how the numpy arrays are indexed and handled.
Also try and avoid .txt files if you are dealing with matrices. Try to use .csv or .npy files, and use Pandas dataframework to load them just for clarity.
def popular(L):
C={}
for a in L:
C[a]=L.count(a)
for b in C.keys():
if C[b]==max(C.values()):
return b
L=[2,3,5,3,6,3,6,3,6,3,7,467,4,7,4]
print popular(L)
You're declaring a virtual
function and not defining it:
virtual void calculateCredits();
Either define it or declare it as:
virtual void calculateCredits() = 0;
Or simply:
virtual void calculateCredits() { };
Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table
The ability to search commits has recently been added to GitHub.
To search for a hash, just enter at least the first 7 characters in the search box. Then on the results page, click the "Commits" tab to see matching commits (but only on the default branch, usually master
), or the "Issues" tab to see pull requests containing the commit.
To be more explicit you can add the hash:
prefix to the search, but it's not really necessary.
There is also a REST API (at the time of writing it is still in preview).
You use input.files
property. It's a collection of File objects and each file has a name
property:
onmouseout="for (var i = 0; i < this.files.length; i++) alert(this.files[i].name);"
You can run from Java code.
try {
File file = new File(keystore location);
InputStream is = new FileInputStream(file);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
String password = "password";
keystore.load(is, password.toCharArray());
Enumeration<String> enumeration = keystore.aliases();
while(enumeration.hasMoreElements()) {
String alias = enumeration.nextElement();
System.out.println("alias name: " + alias);
Certificate certificate = keystore.getCertificate(alias);
System.out.println(certificate.toString());
}
} catch (java.security.cert.CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(null != is)
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Certificate class holds all information about the keystore.
UPDATE- OBTAIN PRIVATE KEY
Key key = keyStore.getKey(alias, password.toCharArray());
String encodedKey = new Base64Encoder().encode(key.getEncoded());
System.out.println("key ? " + encodedKey);
@prateek Hope this is what you looking for!
I also had to setup connection to 2 datasources from Spring Boot application, and it was not easy - the solution mentioned in the Spring Boot documentation didn't work. After a long digging through the internet I made it work and the main idea was taken from this article and bunch of other places.
The following solution is written in Kotlin and works with Spring Boot 2.1.3 and Hibernate Core 5.3.7. Main issue was that it was not enough just to setup different DataSource configs, but it was also necessary to configure EntityManagerFactory and TransactionManager for both databases.
Here is config for the first (Primary) database:
@Configuration
@EnableJpaRepositories(
entityManagerFactoryRef = "firstDbEntityManagerFactory",
transactionManagerRef = "firstDbTransactionManager",
basePackages = ["org.path.to.firstDb.domain"]
)
@EnableTransactionManagement
class FirstDbConfig {
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource.firstDb")
fun firstDbDataSource(): DataSource {
return DataSourceBuilder.create().build()
}
@Primary
@Bean(name = ["firstDbEntityManagerFactory"])
fun firstDbEntityManagerFactory(
builder: EntityManagerFactoryBuilder,
@Qualifier("firstDbDataSource") dataSource: DataSource
): LocalContainerEntityManagerFactoryBean {
return builder
.dataSource(dataSource)
.packages(SomeEntity::class.java)
.persistenceUnit("firstDb")
// Following is the optional configuration for naming strategy
.properties(
singletonMap(
"hibernate.naming.physical-strategy",
"org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl"
)
)
.build()
}
@Primary
@Bean(name = ["firstDbTransactionManager"])
fun firstDbTransactionManager(
@Qualifier("firstDbEntityManagerFactory") firstDbEntityManagerFactory: EntityManagerFactory
): PlatformTransactionManager {
return JpaTransactionManager(firstDbEntityManagerFactory)
}
}
And this is config for second database:
@Configuration
@EnableJpaRepositories(
entityManagerFactoryRef = "secondDbEntityManagerFactory",
transactionManagerRef = "secondDbTransactionManager",
basePackages = ["org.path.to.secondDb.domain"]
)
@EnableTransactionManagement
class SecondDbConfig {
@Bean
@ConfigurationProperties("spring.datasource.secondDb")
fun secondDbDataSource(): DataSource {
return DataSourceBuilder.create().build()
}
@Bean(name = ["secondDbEntityManagerFactory"])
fun secondDbEntityManagerFactory(
builder: EntityManagerFactoryBuilder,
@Qualifier("secondDbDataSource") dataSource: DataSource
): LocalContainerEntityManagerFactoryBean {
return builder
.dataSource(dataSource)
.packages(EntityFromSecondDb::class.java)
.persistenceUnit("secondDb")
.build()
}
@Bean(name = ["secondDbTransactionManager"])
fun secondDbTransactionManager(
@Qualifier("secondDbEntityManagerFactory") secondDbEntityManagerFactory: EntityManagerFactory
): PlatformTransactionManager {
return JpaTransactionManager(secondDbEntityManagerFactory)
}
}
The properties for datasources are like this:
spring.datasource.firstDb.jdbc-url=
spring.datasource.firstDb.username=
spring.datasource.firstDb.password=
spring.datasource.secondDb.jdbc-url=
spring.datasource.secondDb.username=
spring.datasource.secondDb.password=
Issue with properties was that I had to define jdbc-url instead of url because otherwise I had an exception.
p.s. Also you might have different naming schemes in your databases, which was the case for me. Since Hibernate 5 does not support all previous naming schemes, I had to use solution from this answer - maybe it will also help someone as well.
To be specific, to remove tableviewHeader space from top i made these changes:
YouStoryboard.storyboard > YouViewController > Select TableView > Size inspector > Content insets - Set it to never.
change your
return @str1+'present in the string' ;
to
set @r = @str1+'present in the string'
If you're dealing with natural language text and need to replace a word, not just part of a string, you have to add a pinch of regular expressions to your gsub as a plain text substitution can lead to disastrous results:
'mislocated cat, vindicating'.gsub('cat', 'dog')
=> "mislodoged dog, vindidoging"
Regular expressions have word boundaries, such as \b
which matches start or end of a word. Thus,
'mislocated cat, vindicating'.gsub(/\bcat\b/, 'dog')
=> "mislocated dog, vindicating"
In Ruby, unlike some other languages like Javascript, word boundaries are UTF-8-compatible, so you can use it for languages with non-Latin or extended Latin alphabets:
'???? ? ??????, ??? ??????'.gsub(/\b????\b/, '?????')
=> "????? ? ??????, ??? ??????"
Jackson appears to support some amount of JSON parsing straight from an InputStream
. My understanding is that it runs on Android and is fairly quick. On the other hand, it is an extra JAR to include with your app, increasing download and on-flash size.
To access the entity body of a POST or PUT request (or any other HTTP method):
$entityBody = file_get_contents('php://input');
Also, the STDIN
constant is an already-open stream to php://input
, so you can alternatively do:
$entityBody = stream_get_contents(STDIN);
From the PHP manual entry on I/O streamsdocs:
php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of
$HTTP_RAW_POST_DATA
as it does not depend on special php.ini directives. Moreover, for those cases where$HTTP_RAW_POST_DATA
is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".
Specifically you'll want to note that the php://input
stream, regardless of how you access it in a web SAPI, is not seekable. This means that it can only be read once. If you're working in an environment where large HTTP entity bodies are routinely uploaded you may wish to maintain the input in its stream form (rather than buffering it like the first example above).
To maintain the stream resource something like this can be helpful:
<?php
function detectRequestBody() {
$rawInput = fopen('php://input', 'r');
$tempStream = fopen('php://temp', 'r+');
stream_copy_to_stream($rawInput, $tempStream);
rewind($tempStream);
return $tempStream;
}
php://temp
allows you to manage memory consumption because it will transparently switch to filesystem storage after a certain amount of data is stored (2M by default). This size can be manipulated in the php.ini file or by appending /maxmemory:NN
, where NN
is the maximum amount of data to keep in memory before using a temporary file, in bytes.
Of course, unless you have a really good reason for seeking on the input stream, you shouldn't need this functionality in a web application. Reading the HTTP request entity body once is usually enough -- don't keep clients waiting all day while your app figures out what to do.
Note that php://input is not available for requests specifying a Content-Type: multipart/form-data
header (enctype="multipart/form-data"
in HTML forms). This results from PHP already having parsed the form data into the $_POST
superglobal.
there is another way wich you don't have to overwrite uibModal classes and use them if needed : you call $uibModal.open function with your own size type like "xlg" and then you define a class named "modal-xlg" like below :
.modal-xlg{
width:1200px;
}
call $uibModal.open as :
var modalInstance = $uibModal.open({
...
size: "xlg",
});
and this will work . because whatever string you pass as size bootstrap will cocant it with "modal-" and this will play the role of class for window.
You could do this:
NSNumberFormatter* f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
[f setFormat:@0.00"];
// test
NSNumber* a = @12;
NSString* s = [f stringFromNumber:a];
NSLog(@"%@", s);
Select count(*) from table_name into @var1;
Select @var1;
This could happen if you are not running the command prompt in administrator mode. If you are using windows 7, you can go to run, type cmd and hit Ctrl+Shift+enter. This will open the command prompt in administrator mode. If not, you can also go to start -> all programs -> accessories -> right click command prompt and click 'run as administrator'.
It doesn't - the C# compiler does :)
So this code:
string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;
actually gets compiled as:
string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);
(Gah - intervening edit removed other bits accidentally.)
The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y
which then needs to be copied again as part of the concatenation of (x + y)
and z
. Instead, we get it all done in one go.
EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:
string x = "";
foreach (string y in strings)
{
x += y;
}
just ends up as equivalent to:
string x = "";
foreach (string y in strings)
{
x = string.Concat(x, y);
}
... so this does generate a lot of garbage, and it's why you should use a StringBuilder
for such cases. I have an article going into more details about the two which will hopefully answer further questions.
Assuming this example HTML:
<input type="text" name="email" id="email" />
<input type="text" name="first_name" id="first_name" />
<input type="text" name="last_name" id="last_name" />
You could have this javascript:
$("#email").bind("change", function(e){
$.getJSON("http://yourwebsite.com/lokup.php?email=" + $("#email").val(),
function(data){
$.each(data, function(i,item){
if (item.field == "first_name") {
$("#first_name").val(item.value);
} else if (item.field == "last_name") {
$("#last_name").val(item.value);
}
});
});
});
Then just you have a PHP script (in this case lookup.php) that takes an email in the query string and returns a JSON formatted array back with the values you want to access. This is the part that actually hits the database to look up the values:
<?php
//look up the record based on email and get the firstname and lastname
...
//build the JSON array for return
$json = array(array('field' => 'first_name',
'value' => $firstName),
array('field' => 'last_name',
'value' => $last_name));
echo json_encode($json );
?>
You'll want to do other things like sanitize the email input, etc, but should get you going in the right direction.
Some of the Answers are correct, but in case of working with new xampp or with some one not working other answers try this:
just go to the xampp folder:
xampp/apache/conf/extra/httpd-xampp.conf
and if you are trying to access from local ip in your network so change,
Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
<Directory "C:/xampp/phpMyAdmin">
AllowOverride AuthConfig
Require local
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>
Change to :
Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
<Directory "C:/xampp/phpMyAdmin">
AllowOverride AuthConfig
Require all granted
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>
Note: this is just for text, for the security of the xampp has some search....
For MAC users
After some research, this worked for me:
I am very familiar with Mercurial's locking code (as of 1.9.1). The above advice is good, but I'd add that:
(For the curious: I haven't yet been able to catch the cause of this problem, but suspect it's either an older version of Mercurial accessing the repository or a problem in Python's socket.gethostname() call on certain versions of Windows.)
Here is an alternative solution:
class AttrDict(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__dict__ = self
a = AttrDict()
a.a = 1
a.b = 2
Please check this https://stackoverflow.com/a/9519493/1074944 and try this way also $('input[type="date"]').datepicker().prop('type','text');
check the demo
There are several ways of consoling out the variable within a string.
Method 1 :
console.log("story", name, "story");
Benefit : if name is a JSON object, it will not be printed as "story" [object Object] "story"
Method 2 :
console.log("story " + name + " story");
Method 3: When using ES6 as mentioned above
console.log(`story ${name} story`);
Benefit: No need of extra , or +
Method 4:
console.log('story %s story',name);
Benefit: the string becomes more readable.
std::string str = "10";
int number = std::stoi(str);
std::string str = "10";
int number;
std::istringstream(str) >> number
#include <boost/lexical_cast.hpp>
std::string str = "10";
int number;
try
{
number = boost::lexical_cast<int>(str);
std::cout << number << std::endl;
}
catch (boost::bad_lexical_cast const &e) // bad input
{
std::cout << "error" << std::endl;
}
std::string str = "10";
int number = std::atoi(str.c_str());
std::string str = "10";
int number;
if (sscanf(str .c_str(), "%d", &number) == 1)
{
std::cout << number << '\n';
}
else
{
std::cout << "Bad Input";
}
I'm using gcc as a preprocessor (for html files.) It does just what you want. It expands "#--" directives, then outputs a readable file. (NONE of the other C/HTML preprocessors I've tried do this- they concatenate lines, choke on special characters, etc.) Asuming you have gcc installed, the command line is:
gcc -E -x c -P -C -traditional-cpp code_before.cpp > code_after.cpp
(Doesn't have to be 'cpp'.) There's an excellent description of this usage at http://www.cs.tut.fi/~jkorpela/html/cpre.html.
The "-traditional-cpp" preserves whitespace & tabs.
For Java 8 it's very easy:
List < UserEntity > vList= new ArrayList<>();
vList= service(...);
Set<UserEntity> vSet= vList.stream().collect(Collectors.toSet());
I think this single awk call is equivalent to your grep|grep|awk|awk
pipeline: please test it. Your last awk command appears to change nothing at all.
The problem with COUNTER is that the while loop is running in a subshell, so any changes to the variable vanish when the subshell exits. You need to access the value of COUNTER in that same subshell. Or take @DennisWilliamson's advice, use a process substitution, and avoid the subshell altogether.
awk '
/GET \/log_/ && /upstream timed out/ {
split($0, a, ", ")
split(a[2] FS a[4] FS $0, b)
print "http://example.com" b[5] "&ip=" b[2] "&date=" b[7] "&time=" b[8] "&end=1"
}
' | {
while read WFY_URL
do
echo $WFY_URL #Some more action
(( COUNTER++ ))
done
echo $COUNTER
}
I am late, but i want tell the library which i have ended with.
RxPermission is best library with reactive code, which makes permission code unexpected just 1 line.
RxPermissions rxPermissions = new RxPermissions(this);
rxPermissions
.request(Manifest.permission.CAMERA,
Manifest.permission.READ_PHONE_STATE)
.subscribe(granted -> {
if (granted) {
// All requested permissions are granted
} else {
// At least one permission is denied
}
});
add in your build.gradle
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.tbruyelle:rxpermissions:0.10.1'
implementation 'com.jakewharton.rxbinding2:rxbinding:2.1.1'
}
The accepted answer above:
-Duser.timezone="Europe/Sofia"
Didn't work for me exactly. I only was able to successfully change my timezone when I didn't have quotes around the parameters:
-Duser.timezone=Europe/Sofia
You can use many different queries to check if a table exists. Below is a comparison between several:
mysql_query('select 1 from `table_name` group by 1'); or
mysql_query('select count(*) from `table_name`');
mysql_query("DESCRIBE `table_name`");
70000 rows: 24ms
1000000 rows: 24ms
5000000 rows: 24ms
mysql_query('select 1 from `table_name`');
70000 rows: 19ms
1000000 rows: 23ms
5000000 rows: 29ms
mysql_query('select 1 from `table_name` group by 1'); or
mysql_query('select count(*) from `table_name`');
70000 rows: 18ms
1000000 rows: 18ms
5000000 rows: 18ms
These benchmarks are only averages:
This commonly happened use case for any developer.
It is better to have it as function in your local system. (So better to keep this script in one of the shell profile like ksh/zsh or bash profile based on the user preference)
function killport {
kill -9 `lsof -i tcp:"$1" | grep LISTEN | awk '{print $2}'`
}
Usage:
killport port_number
Example:
killport 8080
/**
* execute suppliers as future tasks then wait / join for getting results
* @param functors a supplier(s) to execute
* @return a list of results
*/
private List getResultsInFuture(Supplier<?>... functors) {
CompletableFuture[] futures = stream(functors)
.map(CompletableFuture::supplyAsync)
.collect(Collectors.toList())
.toArray(new CompletableFuture[functors.length]);
CompletableFuture.allOf(futures).join();
return stream(futures).map(a-> {
try {
return a.get();
} catch (InterruptedException | ExecutionException e) {
//logger.error("an error occurred during runtime execution a function",e);
return null;
}
}).collect(Collectors.toList());
};
A new (Keller) method is supposed to improve speed over the -9999px method:
.hide-text {
text-indent: 100%;
white-space: nowrap;
overflow: hidden;
}
recommended here:http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/
If this helps anybody, I encountered this while using purr::map() with a function I wrote which was something like this:
find_nearby_shops <- function(base_account) {
states_table %>%
filter(state == base_account$state) %>%
left_join(target_locations, by = c('border_states' = 'state')) %>%
mutate(x_latitude = base_account$latitude,
x_longitude = base_account$longitude) %>%
mutate(dist_miles = geosphere::distHaversine(p1 = cbind(longitude, latitude),
p2 = cbind(x_longitude, x_latitude))/1609.344)
}
nearby_shop_numbers <- base_locations %>%
split(f = base_locations$id) %>%
purrr::map_df(find_nearby_shops)
I would get this error sometimes with samples, but most times I wouldn't. The root of the problem is that some of the states in the base_locations table (PR) did not exist in the states_table, so essentially I had filtered out everything, and passed an empty table on to mutate. The moral of the story is that you may have a data issue and not (just) a code problem (so you may need to clean your data.)
Thanks for agstudy and zx8754's answers above for helping with the debug.
function calcSize($size,$accuracy=2) {
$units = array('b','Kb','Mb','Gb');
foreach($units as $n=>$u) {
$div = pow(1024,$n);
if($size > $div) $output = number_format($size/$div,$accuracy).$u;
}
return $output;
}
The button isn't called the "browse button" — that's just the name your browser gives for it. Browsers are free to implement the file upload control however they like. In Safari, for example, it's called "Choose File" and it's on the opposite side of whatever you're probably using.
You can implement a custom look for the upload control using the technique outlined on QuirksMode, but that goes beyond just changing the button's text.
The simplest solution is to follow the installation instruction from pip's home site.
Basically, this consists in:
sudo python get-pip.py
The main advantage of that solution is that it install pip for the python version that has been used to run get-pip.py
, which means that if you use the default OS X installation of python to run get-pip.py
you will install pip for the python install from the system.
Most solutions that use a package manager (homebrew or macport) on OS X create a redundant installation of python in the environment of the package manager which can create inconsistencies in your system since, depending on what you are doing, you may call one installation of python instead of another.
That's because the browser doesn't transmit that part to the server, sorry.
A GridView is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.
This is what you'd want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen. GridViews, much like ListViews reuse and recycle their views for better performance.
Whereas a GridLayout is a layout that places its children in a rectangular grid.
It was introduced in API level 14, and was recently backported in the Support Library. Its main purpose is to solve alignment and performance problems in other layouts. Check out this tutorial if you want to learn more about GridLayout.
There is no need for jQuery here, regular JavaScript will do:
var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);
Or, the .split()
and .pop()
version:
var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();
Or, the regex version (several variants of this):
var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];
To summarise the other answers here – if you want finer control over the space between bullets and the text in a <li>
list item, your options are:
(1) Use a background image:
<style type="text/css">
li {
list-style-type:none;
background-image:url(bullet.png);
}
</style>
<ul>
<li>Some text</li>
</ul>
Advantages:
background-position
to position the image pretty much anywhere you want in relation to the text, using pixels, ems or %Disadvantages:
2. Use padding on the <li>
tag
<style type="text/css">
ul {padding-left:1em}
li {padding-left:1em}
</style>
<ul>
<li>Some text</li>
</ul>
Advantages:
<li>
, you can add as much extra horizontal space between the bullet and the text as you likeDisadvantages:
(3) Wrap the text in an extra <span>
element
<style type="text/css">
li {
padding-left:1em;
color:#f00; /* red bullet */
}
li span {
display:block;
margin-left:-0.5em;
color:#000; /* black text */
}
</style>
<ul>
<li><span>Some text</span></li>
</ul>
Advantages:
padding-top
to the <span>
. Someone else may have a workaround for this, though...)Disadvantages:
Here's hoping for some new list-style features in CSS4, so we can create smarter bullets without resorting to images or exta mark-up :)
Here is an illustration of your first import cycle problem.
project/controllers/account
^ \
/ \
/ \
/ \/
project/components/mux <--- project/controllers/base
As you can see with my bad ASCII chart is that you are creating an import cycle when project/components/mux
imports project/controllers/account
. Since Go does not support circular dependencies you get the import cycle not allowed
error during compile time.
Sample code for case: @throw([NSException exceptionWithName:...
- (void)parseError:(NSError *)error
completionBlock:(void (^)(NSString *error))completionBlock {
NSString *resultString = [NSString new];
@try {
NSData *errorData = [NSData dataWithData:error.userInfo[@"SomeKeyForData"]];
if(!errorData.bytes) {
@throw([NSException exceptionWithName:@"<Set Yours exc. name: > Test Exc" reason:@"<Describe reason: > Doesn't contain data" userInfo:nil]);
}
NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:errorData
options:NSJSONReadingAllowFragments
error:&error];
resultString = dictFromData[@"someKey"];
...
} @catch (NSException *exception) {
NSLog( @"Caught Exception Name: %@", exception.name);
NSLog( @"Caught Exception Reason: %@", exception.reason );
resultString = exception.reason;
} @finally {
completionBlock(resultString);
}
}
Using:
[self parseError:error completionBlock:^(NSString *error) {
NSLog(@"%@", error);
}];
Another more advanced use-case:
- (void)parseError:(NSError *)error completionBlock:(void (^)(NSString *error))completionBlock {
NSString *resultString = [NSString new];
NSException* customNilException = [NSException exceptionWithName:@"NilException"
reason:@"object is nil"
userInfo:nil];
NSException* customNotNumberException = [NSException exceptionWithName:@"NotNumberException"
reason:@"object is not a NSNumber"
userInfo:nil];
@try {
NSData *errorData = [NSData dataWithData:error.userInfo[@"SomeKeyForData"]];
if(!errorData.bytes) {
@throw([NSException exceptionWithName:@"<Set Yours exc. name: > Test Exc" reason:@"<Describe reason: > Doesn't contain data" userInfo:nil]);
}
NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:errorData
options:NSJSONReadingAllowFragments
error:&error];
NSArray * array = dictFromData[@"someArrayKey"];
for (NSInteger i=0; i < array.count; i++) {
id resultString = array[i];
if (![resultString isKindOfClass:NSNumber.class]) {
[customNotNumberException raise]; // <====== HERE is just the same as: @throw customNotNumberException;
break;
} else if (!resultString){
@throw customNilException; // <======
break;
}
}
} @catch (SomeCustomException * sce) {
// most specific type
// handle exception ce
//...
} @catch (CustomException * ce) {
// most specific type
// handle exception ce
//...
} @catch (NSException *exception) {
// less specific type
// do whatever recovery is necessary at his level
//...
// rethrow the exception so it's handled at a higher level
@throw (SomeCustomException * customException);
} @finally {
// perform tasks necessary whether exception occurred or not
}
}
simply use..
location.reload(true/false);
If false, the page will be reloaded from cache, else from the server.
You can make a alias in your ~/.bashrc file :
alias curl="curl -x <proxy_host>:<proxy_port>"
Another solution is to use (maybe the better solution) the ~/.curlrc
file (create it if it does not exist) :
proxy = <proxy_host>:<proxy_port>
Read Scott Hanselman's post on the issue: http://www.hanselman.com/blog/AReminderOnThreeMultiTierLayerArchitectureDesignBroughtToYouByMyLateNightFrustrations.aspx
Remember though, that in "Scott World" (which is hopefully your world also :) ) a "Tier" is a unit of deployment, while a "Layer" is a logical separation of responsibility within code. You may say you have a "3-tier" system, but be running it on one laptop. You may say your have a "3-layer" system, but have only ASP.NET pages that talk to a database. There's power in precision, friends.
echo ($result ->vocation == 1) ? 'Sorcerer'
: ($result->vocation == 2) ? 'Druid'
: ($result->vocation == 3) ? 'Paladin'
....
;
It’s kind of ugly. You should stick with normal if
statements.
To name a few we can use redux-react-session which is having good API for session management like, initSessionService
, refreshFromLocalStorage
, checkAuth
and many other. It also provide some advanced functionality like Immutable JS
.
Alternatively we can leverage react-web-session which provides options like callback
and timeout
.
My Source: http://htmlhelp.com/tools/validator/problems.html#amp
Another common error occurs when including a URL which contains an ampersand ("&"):
This is invalid:
a href="foo.cgi?chapter=1§ion=2©=3&lang=en"
Explanation:
This example generates an error for "unknown entity section" because the
"&"
is assumed to begin an entity reference. Browsers often recover safely from this kind of error, but real problems do occur in some cases. In this example, many browsers correctly convert ©=3 to ©=3, which may cause the link to fail. Since 〈 is the HTML entity for the left-pointing angle bracket, some browsers also convert &lang=en to <=en. And one old browser even finds the entity §, converting §ion=2 to §ion=2.
So the goal here is to avoid problems when you are trying to validate your website. So you should be replacing your ampersands with &
when writing a URL in your markup.
Note that replacing
&
with&
; is only done when writing the URL in HTML, where"&"
is a special character (along with "<" and ">"). When writing the same URL in a plain text email message or in the location bar of your browser, you would use"&"
and not"&"
. With HTML, the browser translates"&"
to"&"
so the Web server would only see"&"
and not"&"
in the query string of the request.
Hope this helps : )
Inside the wsdl file look for the import element, which looks like this :
`<import namespace="nameSpaceValue" location="Users/myname/.../targetxsdName.xsd"/>`
Change the location attribute in the above element to the location of your xsd files stored locally, and it should work.
HTML href link click:
<a ="{{ route('download',$name->file) }}"> Download </a>
In controller:
public function download($file){
$file_path = public_path('uploads/cv/'.$file);
return response()->download( $file_path);
}
In route:
Route::get('/download/{file}','Controller@download')->name('download');
You can do the following:
echo '<div class="my_class">';
echo ($cart->count_product > 0) ? $cart->count_product : '';
echo '</div>';
If you want to have it inside your statement, do this:
if($cart->count_product > 0)
{
echo '<div class="my_class">'.$cart->count_product.'</div>';
}
You don't need the else
statement, since you're only going to output the above when it's truthy anyway.
dir.Delete(true); // true => recursive delete
If I remember correctly, window.location.reload()
reloads the current page with POST data, while window.location.href=window.location.href
does not include the POST data.
As noted by @W3Max in the comments below, window.location.href=window.location.href
will not reload the page if there's an anchor (#) in the URL - You must use window.location.reload()
in this case.
Also, as noted by @Mic below, window.location.reload()
takes an additional argument skipCache
so that with using window.location.reload(true)
the browser will skip the cache and reload the page from the server. window.location.reload(false)
will do the opposite, and load the page from cache if possible.
The following characters must be escaped in JSON data to avoid any problems:
"
(double quote)\
(backslash)\n
, \t
JSON Parser can help you to deal with JSON.
Easy to write, but not the most effective one:
$array = array_unique(array_merge($array, $array_to_append));
This one is probably faster:
$array = array_merge($array, array_diff($array_to_append, $array));
MappedBy signals hibernate that the key for the relationship is on the other side.
This means that although you link 2 tables together, only 1 of those tables has a foreign key constraint to the other one. MappedBy allows you to still link from the table not containing the constraint to the other table.
I found the solution to this. There is a temporary tablespace called TEMP which is used internally by database for operations like distinct, joins,etc. Since my query(which has 4 joins) fetches almost 50 million records the TEMP tablespace does not have that much space to occupy all data. Hence the query fails even though my tablespace has free space.So, after increasing the size of TEMP tablespace the issue was resolved. Hope this helps someone with the same issue. Thanks :)
00101011 = 43 in decimal
class test {
public static void main(String[] args){
int a= 43;
String b= Integer.toBinaryString(a >> 2);
System.out.println(b);
}
}
Output:
101011 becomes 1010
There's a .val()
method:
If you've got an input with an id of txtEmail
you can use the following code to access the value of the text box:
$("#txtEmail").val()
You can also use the val(string)
method to set that value:
$("#txtEmail").val("something")
I don't know what things were like in the alpha, but I'm using beta 12 right now and this works fine. If you have an array of objects, create a select like this:
<select [(ngModel)]="simpleValue"> // value is a string or number
<option *ngFor="let obj of objArray" [value]="obj.value">{{obj.name}}</option>
</select>
If you want to match on the actual object, I'd do it like this:
<select [(ngModel)]="objValue"> // value is an object
<option *ngFor="let obj of objArray" [ngValue]="obj">{{obj.name}}</option>
</select>
I am using a Cursor so I can not use the DiffUtils as proposed in the popular answers. In order to make it work for me I am disabling animations when the list is not idle. This is the extension that fixes this issue:
fun RecyclerView.executeSafely(func : () -> Unit) {
if (scrollState != RecyclerView.SCROLL_STATE_IDLE) {
val animator = itemAnimator
itemAnimator = null
func()
itemAnimator = animator
} else {
func()
}
}
Then you can update your adapter like that
list.executeSafely {
adapter.updateICursor(newCursor)
}
Font awesome is just a font so you can use the font size attribute in your CSS to change the size of the icon.
So you can just add a class to the icon like this:
.big-icon {
font-size: 32px;
}
Why not model a fake stock market with Brownian Motion?
Plenty of resources for doing it. Easy to implement.
Use this filter mask on email input:
emailMask: /[\w.\-@'"!#$%&'*+/=?^_
{|}~]/i`
That is not HTML, but PHP. It is called the HEREDOC string method, and is an alternative to using quotes for writing multiline strings.
The HTML in your example will be:
<tr>
<td>TEST</td>
</tr>
Read the PHP documentation that explains it.
Let's say you have:
<a></a>
<(.*)>
would match a></a
where as <(.*?)>
would match a
.
The latter stops after the first match of >
. It checks for one
or 0 matches of .*
followed by the next expression.
The first expression <(.*)>
doesn't stop when matching the first >
. It will continue until the last match of >
.
Here's another take on this. contextlib.redirect_stdout
with io.StringIO()
as documented is great, but it's still a bit verbose for every day use. Here's how to make it a one-liner by subclassing contextlib.redirect_stdout
:
import sys
import io
from contextlib import redirect_stdout
class capture(redirect_stdout):
def __init__(self):
self.f = io.StringIO()
self._new_target = self.f
self._old_targets = [] # verbatim from parent class
def __enter__(self):
self._old_targets.append(getattr(sys, self._stream)) # verbatim from parent class
setattr(sys, self._stream, self._new_target) # verbatim from parent class
return self # instead of self._new_target in the parent class
def __repr__(self):
return self.f.getvalue()
Since __enter__ returns self, you have the context manager object available after the with block exits. Moreover, thanks to the __repr__ method, the string representation of the context manager object is, in fact, stdout. So now you have,
with capture() as message:
print('Hello World!')
print(str(message)=='Hello World!\n') # returns True
There is a (somewhat) related question on StackOverflow:
Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeeze
d or sliced into a 2D array.
More generally, the reason for the Exception
TypeError: Invalid dimensions for image data
is shown here: matplotlib.pyplot.imshow()
needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!
You can easily check this with (these checks are done by imshow
, this function is only meant to give a more specific message in case it's not a valid input):
from __future__ import print_function
import numpy as np
def valid_imshow_data(data):
data = np.asarray(data)
if data.ndim == 2:
return True
elif data.ndim == 3:
if 3 <= data.shape[2] <= 4:
return True
else:
print('The "data" has 3 dimensions but the last dimension '
'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
''.format(data.shape[2]))
return False
else:
print('To visualize an image the data must be 2 dimensional or '
'3 dimensional, not "{}".'
''.format(data.ndim))
return False
In your case:
>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False
The np.asarray
is what is done internally by matplotlib.pyplot.imshow
so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list
) it's necessary.
In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()
import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0) # or axis=1
plt.imshow(a)
plt.show()
or just use something that accepts 1D arrays like plot
:
a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()
Python just passes the filename you give it to the operating system, which opens it. If your operating system supports relative paths like main/2091/data.txt
(hint: it does), then that will work fine.
You may find that the easiest way to answer a question like this is to try it and see what happens.
<input type="checkbox" checked />
HTML5 does not require attributes to have values
The following will return true if the element is an input:
$("#elementId").is("input")
or you can use the following to get the name of the tag:
$("#elementId").get(0).tagName
actually, adding the
<archive>
<manifest>
<addClasspath>true</addClasspath>
<packageName>com.some.pkg</packageName>
<mainClass>com.MainClass</mainClass>
</manifest>
</archive>
declaration to maven-jar-plugin does not add the main class entry to the manifest file for me. I had to add it to the maven-assembly-plugin in order to get that in the manifest
After you changed a Mac which are not the origin one who created the disitribution certificate, you will missing the private key.Just delete the origin certificate and recreate a new one, that works for me~
The Header
property of the TreeViewItem
is statically typed to be of type object
.
Therefore the ==
yields false
. You can reproduce this with the following simple snippet:
object s1 = "Hallo";
// don't use a string literal to avoid interning
string s2 = new string(new char[] { 'H', 'a', 'l', 'l', 'o' });
bool equals = s1 == s2; // equals is false
equals = string.Equals(s1, s2); // equals is true
Set your SMTP auth to true if using the PHPmailer class:
$mail->SMTPAuth = true;
rdtsc solution did not work for me.
Firstly, I use Visual Studio 2015 Express, for which installer "modify" query does not propose any "Common Tools for Visual C++ 2015" option you could uncheck.
Secondly, even after 2 uninstall/reinstall (many hours waiting for them to complete...), the problem still remains.
I finally fixed the issue by reinstalling the whole Windows SDK from a standalone installer (independently from Visual C++ 2015 install): https://developer.microsoft.com/fr-fr/windows/downloads/windows-8-1-sdk or https://developer.microsoft.com/fr-fr/windows/downloads/windows-10-sdk
This fixed the issue for me.
The SQL Server equivalent to Oracle's describe
command is the stored proc sp_help
The describe
command gives you the information about the column names, types, length, etc.
In SQL Server, let's say you want to describe a table 'mytable' in schema 'myschema' in the database 'mydb', you can do following:
USE mydb;
exec sp_help 'myschema.mytable';
You can definitely get Boolean value from a SELECT query, you just can't use a Boolean data-type.
You can represent a Boolean with 1/0.
CASE WHEN (10 > 0) THEN 1 ELSE 0 END (It can be used in SELECT QUERY)
SELECT CASE WHEN (10 > 0) THEN 1 ELSE 0 END AS MY_BOOLEAN_COLUMN
FROM DUAL
Returns, 1 (in Hibernate/Mybatis/etc 1 is true). Otherwise, you can get printable Boolean values from a SELECT.
SELECT CASE WHEN (10 > 0) THEN 'true' ELSE 'false' END AS MY_BOOLEAN_COLUMN
FROM DUAL
This returns the string 'true'
.
Trim just removes the trailing and leading whitespace. Use .replace(/ /g, "") if there are just spaces to be replaced.
this.maintabinfo = this.inner_view_data.replace(/ /g, "").toLowerCase();
Modify Mysql encryption
ALTER USER 'lcherukuri'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
Found another solution for the same. It will be more helpful.
START C:\"Program Files (x86)"\Test\"Test Automation"\finger.exe ConfigFile="C:\Users\PCName\Desktop\Automation\Documents\Validation_ZoneWise_Default.finger.Config"
finger.exe is a parent program that is calling config solution. Note: if your path folder name consists of spaces, then do not forget to add "".
This is related to the semantics of the code. By naming the value assigning it to a variable that has a meaningful name (even if it is used only at one place) you give it a meaning. When somebody is reading the code that person will know what that value means.
In general is not a good practice to use constant values across the code. Imagine a code full of string, integer, etc. values. After a time nobody will know what those constants are. Also a typo in a value can be a problem when the value is used on more than one place.
From what it looks like you are trying to do, toggle might better solve your problem.
EDIT: Sorry, toggle is just visibility, I don't think it will help your bg color toggling.
But here you go:
var box = $("#blackbox");
box.css('background') == 'pink' ? box.css({'background':'black'}) : box.css({'background':'pink'});
I've recently improved (open PullRequest) the ternary conditional and null-coalescing operators in the PoweShell lib 'Pscx'
Pls have a look for my solution.
My github topic branch: UtilityModule_Invoke-Operators
Invoke-Ternary
Invoke-TernaryAsPipe
Invoke-NullCoalescing
NullCoalescingAsPipe
Set-Alias :?: Pscx\Invoke-Ternary -Description "PSCX alias"
Set-Alias ?: Pscx\Invoke-TernaryAsPipe -Description "PSCX alias"
Set-Alias :?? Pscx\Invoke-NullCoalescing -Description "PSCX alias"
Set-Alias ?? Pscx\Invoke-NullCoalescingAsPipe -Description "PSCX alias"
<condition_expression> |?: <true_expression> <false_expression>
<variable_expression> |?? <alternate_expression>
As expression you can pass:
$null, a literal, a variable, an 'external' expression ($b -eq 4) or a scriptblock {$b -eq 4}
If a variable in the variable expression is $null or not existing, the alternate expression is evaluated as output.
Other alternative way to reset the windows.timer is using the counter, as follows:
int timerCtr = 0;
Timer mTimer;
private void ResetTimer() => timerCtr = 0;
private void mTimer_Tick()
{
timerCtr++;
// Perform task
}
So if you intend to repeat every 1 second, you can set the timer interval at 100ms, and test the counter to 10 cycles.
This is suitable if the timer should wait for some processes those may be ended at the different time span.
Note, that if you want to pass a variable to an external .js script then you need to precede your script tag with another script tag that declares a global variable.
<script type="text/javascript">
var myVar = "{{ myVar }}"
</script>
<script type="text/javascript" src="{% static "scripts/my_script.js" %}"></script>
data
is defined in the view as usual in the get_context_data
def get_context_data(self, *args, **kwargs):
context['myVar'] = True
return context
try this command in terminal:
sudo ufw enable
ufw allow 12397
I've written a personal library that allows you to order by multiple values, with all the ordering done on the server.
Querybase takes in a Firebase Database Reference and an array of fields you wish to index on. When you create new records it will automatically handle the generation of keys that allow for multiple querying. The caveat is that it only supports straight equivalence (no less than or greater than).
const databaseRef = firebase.database().ref().child('people');
const querybaseRef = querybase.ref(databaseRef, ['name', 'age', 'location']);
// Automatically handles composite keys
querybaseRef.push({
name: 'David',
age: 27,
location: 'SF'
});
// Find records by multiple fields
// returns a Firebase Database ref
const queriedDbRef = querybaseRef
.where({
name: 'David',
age: 27
});
// Listen for realtime updates
queriedDbRef.on('value', snap => console.log(snap));
This error can be caused by an unclosed set of brackets.
int main {
doSomething {}
doSomething else {
}
Not so easy to spot, even in this 4 line example.
This error, in a 150 line main function, caused the bewildering error: "static declaration of ‘savePair’ follows non-static declaration". There was nothing wrong with my definition of function savePair, it was that unclosed bracket.
You can do this using Input.setSelectionRange
, part of the Range API for interacting with text selections and the text cursor:
var searchInput = $('#Search');
// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;
searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);
Demo: Fiddle
At last I managed to achieve what I intended with all your help and the post Change a link style onclick. Here is the code for that. I used JavaScript for doing this.
<html>
<head>
<style type="text/css">
.item {
width:900px;
padding:0;
margin:0;
list-style-type:none;
}
a {
display:block;
width:60;
line-height:25px; /*24px*/
border-bottom:1px none #808080;
font-family:'arial narrow',sans-serif;
color:#00F;
text-align:center;
text-decoration:none;
background:#CCC;
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
margin-bottom:0em;
padding: 0px;
}
a.item {
float:left; /* For horizontal left to right display. */
width:145px; /* For maintaining equal */
margin-right: 5px; /* space between two boxes. */
}
a.selected{
background:orange;
color:white;
}
</style>
</head>
<body>
<a class="item" href="#" >item 1</a>
<a class="item" href="#" >item 2</a>
<a class="item" href="#" >item 3</a>
<a class="item" href="#" >item 4</a>
<a class="item" href="#" >item 5</a>
<a class="item" href="#" >item 6</a>
<script>
var anchorArr=document.getElementsByTagName("a");
var prevA="";
for(var i=0;i<anchorArr.length;i++)
{
anchorArr[i].onclick = function(){
if(prevA!="" && prevA!=this)
{
prevA.className="item";
}
this.className="item selected";
prevA=this;
}
}
</script>
</body>
</html>
First, you need to create a personal access token (PAT). This is described here: https://help.github.com/articles/creating-an-access-token-for-command-line-use/
Laughably, the article tells you how to create it, but gives absolutely no clue what to do with it. After about an hour of trawling documentation and Stack Overflow, I finally found the answer:
$ git clone https://github.com/user-or-organisation/myrepo.git
Username: <my-username>
Password: <my-personal-access-token>
I was actually forced to enable two-factor authentication by company policy while I was working remotely and still had local changes, so in fact it was not clone
I needed, but push
. I read in lots of places that I needed to delete and recreate the remote, but in fact my normal push
command worked exactly the same as the clone
above, and the remote did not change:
$ git push https://github.com/user-or-organisation/myrepo.git
Username: <my-username>
Password: <my-personal-access-token>
(@YMHuang put me on the right track with the documentation link.)
Using a cookie to provide the CSRF token to the client does not allow a successful attack because the attacker cannot read the value of the cookie and therefore cannot put it where the server-side CSRF validation requires it to be.
The attacker will be able to cause a request to the server with both the auth token cookie and the CSRF cookie in the request headers. But the server is not looking for the CSRF token as a cookie in the request headers, it's looking in the payload of the request. And even if the attacker knows where to put the CSRF token in the payload, they would have to read its value to put it there. But the browser's cross-origin policy prevents reading any cookie value from the target website.
The same logic does not apply to the auth token cookie, because the server is expects it in the request headers and the attacker does not have to do anything special to put it there.
I've managed to figure it out :) And down below you can read step-by-step guide so it hopefully can help others with the same problem as I had ;)
zxing src
.ant -f core/build.xml
press enter and let Apache work it's magic [having issues?]core.jar
... hit enter!Now you just have to correct a few errors in the translations and the AndroidManifest.xml file :) Now you can happily compile, and you will now have a working standalone barcode scanner app, based on the ZXing source ;)
Happy coding guys - I hope it can help others :)
To control the precision of floating point arithmetic, you should use java.math.BigDecimal. Read The need for BigDecimal by John Zukowski for more information.
Given your example, the last line would be as following using BigDecimal.
import java.math.BigDecimal;
BigDecimal premium = BigDecimal.valueOf("1586.6");
BigDecimal netToCompany = BigDecimal.valueOf("708.75");
BigDecimal commission = premium.subtract(netToCompany);
System.out.println(commission + " = " + premium + " - " + netToCompany);
This results in the following output.
877.85 = 1586.6 - 708.75
define ANDROID_SDK_ROOT as environment variable where your SDK is residing, default path would be "C:\Program Files (x86)\Android\android-sdk" and restart computer to take effect.
In shell you assign to a variable without the dollar-sign:
TEST=`pwd`
echo $TEST
that's better (and can be nested) but is not as portable as the backtics:
TEST=$(pwd)
echo $TEST
Always remember: the dollar-sign is only used when reading a variable.
I faced similar problem today. So, here's a simple solution: While doing SSH to the machine, just add Ctrl - Y.
ssh user@ip_address -Y
After login, type firefox &
.
And you are good to go.
List<String> oldList = Arrays.asList("a", "b", "c", "d", "e", "f");
List<String> modifiedList = Arrays.asList("a", "b", "c", "d", "e", "g");
List<String> added = new HashSet<>(modifiedList);
List<String> removed = new HashSet<>(oldList);
modifiedList.stream().filter(removed::remove).forEach(added::remove);
// added items
System.out.println(added);
// removed items
System.out.println(removed);
Sqlite can not compare on dates. we need to convert into seconds and cast it as integer.
Example
SELECT * FROM Table
WHERE
CAST(strftime('%s', date_field) AS integer) <=CAST(strftime('%s', '2015-01-01') AS integer) ;
Here is my simple version.
The function draggable takes a jQuery object as argument.
/**
* @param {jQuery} elem
*/
function draggable(elem){
elem.mousedown(function(evt){
var x = parseInt(this.style.left || 0) - evt.pageX;
var y = parseInt(this.style.top || 0) - evt.pageY;
elem.mousemove(function(evt){
elem.css('left', x + evt.pageX);
elem.css('top', y + evt.pageY);
});
});
elem.mouseup(off);
elem.mouseleave(off);
function off(){
elem.off("mousemove");
}
}
Header files can contain any valid C code, since they are injected into the compilation unit by the pre-processor prior to compilation.
If a header file contains a function, and is included by multiple .c
files, each .c
file will get a copy of that function and create a symbol for it. The linker will complain about the duplicate symbols.
It is technically possible to create static
functions in a header file for inclusion in multiple .c
files. Though this is generally not done because it breaks from the convention that code is found in .c
files and declarations are found in .h
files.
See the discussions in C/C++: Static function in header file, what does it mean? for more explanation.
One possibility when ready
stops working is that you have javascript code somewhere that is throwing an exception in a $(document).ready(...)
or $(...)
call, which is stopping processing of the rest of the ready
blocks. Identify a single page on which this is occurring and examine it for possible errors in other places.
List
in c#
has a Count
property. It can be used like so:
if(myList == null) // Checks if list is null
// Wasn't initialized
else if(myList.Count == 0) // Checks if the list is empty
myList.Add("new item");
else // List is valid and has something in it
// You could access the element in the list if you wanted
try to get out grafics with x11()
or win.graph()
and solve this trouble.
For people who find this via search engines, you do not need VBA. You can just:
1.) select the query or table with your mouse
2.) click export data from the ribbon
3.) click excel from the export subgroup
4.) follow the wizard to select the output file and location.
When I try:
<input type="button" id="moreFields" onclick="alert('The text will be show!!'); return false;" value="Give me more fields!" />
It's worked well. So I think the problem is position of moreFields() function. Ensure that function will be define before your input tag.
Pls try:
<script type="text/javascript">
function moreFields() {
alert("The text will be show");
}
</script>
<input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!" />
Hope it helped.
In SQL 2012 you can use OFFSET
and FETCH
:
SELECT *
FROM MyTable
ORDER BY MyColumn
OFFSET @N ROWS
FETCH NEXT @M ROWS ONLY;
DECLARE @CurrentSetNumber int = 0;
DECLARE @NumRowsInSet int = 2;
SELECT *
FROM MyTable
ORDER BY MyColumn
OFFSET @NumRowsInSet * @CurrentSetNumber ROWS
FETCH NEXT @NumRowsInSet ROWS ONLY;
SET @CurrentSetNumber = @CurrentSetNumber + 1;
where @NumRowsInSet
is the number of rows you want returned and @CurrentSetNumber
is the number of @NumRowsInSet
to skip.
Some googling reveals that potentially you've got a corrupt file:
http://bitterolives.blogspot.com/2009/03/excel-interop-comexception-hresult.html
and that you can tell excel to open it anyway with the CorruptLoad parameter, with something like...
Workbook workbook = excelApplicationObject.Workbooks.Open(path, CorruptLoad: true);
<DockPanel>
<Menu DockPanel.Dock="Top">
<MenuItem Header="_File">
<MenuItem Header="_Open"/>
<MenuItem Header="_Close"/>
<MenuItem Header="_Save"/>
</MenuItem>
</Menu>
<StackPanel></StackPanel>
</DockPanel>
If you need just one character and you don't want to keep things in the buffer, you can simply read a whole line and drop everything that isn't needed.
Replace:
stdin.read(1)
with
stdin.readline().strip()[:1]
This will read a line, remove spaces and newlines and just keep the first character.
Try using the net use
command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.
net use \\<network-location>\<some-share> password /USER:username
Don't leave a trailing \ at the end of the
The answer are as below for Window authentication
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$SQLServer;Database=$SQLDBName;Integrated Security=True;"
Add this line top of the header
#pragma warning(disable : 4996)
It is a bad idea to select * from anything, period. This is why SSMS adds every field name, even if there are hundreds, instead of select *. It is extremely inefficient regardless of how large the table is. If you don't know what the fields are, its still more efficient to pull them out of the INFORMATION_SCHEMA database than it is to select *.
A better query would be:
SELECT
COLUMN_NAME,
Case
When DATA_TYPE In ('varchar', 'char', 'nchar', 'nvarchar', 'binary')
Then convert(varchar(MAX), CHARACTER_MAXIMUM_LENGTH)
When DATA_TYPE In ('numeric', 'int', 'smallint', 'bigint', 'tinyint')
Then convert(varchar(MAX), NUMERIC_PRECISION)
When DATA_TYPE = 'bit'
Then convert(varchar(MAX), 1)
When DATA_TYPE IN ('decimal', 'float')
Then convert(varchar(MAX), Concat(Concat(NUMERIC_PRECISION, ', '), NUMERIC_SCALE))
When DATA_TYPE IN ('date', 'datetime', 'smalldatetime', 'time', 'timestamp')
Then ''
End As DATALEN,
DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
Where
TABLE_NAME = ''
You certainly want to hack the header to have a proper Ajax Request :
headers = {'X_REQUESTED_WITH' :'XMLHttpRequest',
'ACCEPT': 'application/json, text/javascript, */*; q=0.01',}
request = urllib2.Request(path, data, headers)
response = urllib2.urlopen(request).read()
And to json.loads the POST on the server-side.
Edit : By the way, you have to urllib.urlencode(mydata_dict)
before sending them. If you don't, the POST won't be what the server expect
add an ALIAS
on the subquery,
SELECT COUNT(made_only_recharge) AS made_only_recharge
FROM
(
SELECT DISTINCT (identifiant) AS made_only_recharge
FROM cdr_data
WHERE CALLEDNUMBER = '0130'
EXCEPT
SELECT DISTINCT (identifiant) AS made_only_recharge
FROM cdr_data
WHERE CALLEDNUMBER != '0130'
) AS derivedTable -- <<== HERE
Oracle Client version 11 cannot connect to 8i databases. You will need a client in version 10 at most.
<system.webServer>
<httpErrors errorMode="DetailedLocalOnly">
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" prefixLanguageFilePath="" path="your page" responseMode="Redirect" />
</httpErrors>
</system.webServer>
If you have changed your launch image from a previous image, and observe the following:
It is likely because of the caching of launch image done by iOS. Rebooting the device should solve the problem.
Definitely works.
if [[ `pgrep -f $0` != "$$" ]]; then
echo "Exiting ! Exist"
exit
fi
import java.io.File;
public class Test {
public static void main( String [] args ) {
File actual = new File(".");
for( File f : actual.listFiles()){
System.out.println( f.getName() );
}
}
}
It displays indistinctly files and folders.
See the methods in File class to order them or avoid directory print etc.
You can use :enabled pseudo-class, but notice IE<9
does not support it:
button:hover:enabled{
/*your styles*/
}
button:active:enabled{
/*your styles*/
}
You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.
So if you want to use your code, you could do:
df = DataFrame(eval(data))
But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:
data = []
for row in result_set:
data.append({'value': row["tag_expression"], 'key': row["tag_name"]})
But probably even this is not needed, as depending on what is exactly in your result_set
you could probably:
DataFrame(result_set)
read_sql_query
function to do this for you (see docs on this)Using Javascript you can download like this in a simple method
var oReq = new XMLHttpRequest();
// The Endpoint of your server
var URLToPDF = "https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf";
// Configure XMLHttpRequest
oReq.open("GET", URLToPDF, true);
// Important to use the blob response type
oReq.responseType = "blob";
// When the file request finishes
// Is up to you, the configuration for error events etc.
oReq.onload = function() {
// Once the file is downloaded, open a new window with the PDF
// Remember to allow the POP-UPS in your browser
var file = new Blob([oReq.response], {
type: 'application/pdf'
});
// Generate file download directly in the browser !
saveAs(file, "mypdffilename.pdf");
};
oReq.send();
for me, it solved just by changing the name of my cell's file into the same as its class.
In Attributes Inspector(Third tab on the right side bar in story board):
Register the cell in your view controller as follow:
tableView.register(UINib(nibName: "MyCellClass", bundle: nil), forCellReuseIdentifier: "MyCellId")
textBox1.Text = "Line1\r\r\Line2";
Solved the problem.
You get one for free, called ROWID. This is in every SQLite table whether you ask for it or not.
If you include a column of type INTEGER PRIMARY KEY, that column points at (is an alias for) the automatic ROWID column.
ROWID (by whatever name you call it) is assigned a value whenever you INSERT a row, as you would expect. If you explicitly assign a non-NULL value on INSERT, it will get that specified value instead of the auto-increment. If you explicitly assign a value of NULL on INSERT, it will get the next auto-increment value.
Also, you should try to avoid:
INSERT INTO people VALUES ("John", "Smith");
and use
INSERT INTO people (first_name, last_name) VALUES ("John", "Smith");
instead. The first version is very fragile — if you ever add, move, or delete columns in your table definition the INSERT will either fail or produce incorrect data (with the values in the wrong columns).
You should read and write data from xml files since you can save a whole object to xml and also you can populate a object from a saved xml. It is better an easy to manipulate objects.
Here is how to do it: Write Object Data to an XML File: https://msdn.microsoft.com/en-us/library/ms172873.aspx Read Object Data from an XML File: https://msdn.microsoft.com/en-us/library/ms172872.aspx
Looks like the path you gave doesn't have any bootstrap files in them.
href="~/lib/bootstrap/dist/css/bootstrap.min.css"
Make sure the files exist over there , else point the files to the correct path, which should be in your case
href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"
What worked for me was disabling the position: fixed;
CSS.
AFAIK, there is nothing built in for searching all columns. You can use Find
only against the primary key. Select
needs specified columns. You can perhaps use LINQ, but ultimately this just does the same looping. Perhaps just unroll it yourself? It'll be readable, at least.
<string.h>
is the old C header. C++ provides <string>
, and then it should be referred to as std::string
.
One of the Related posts gave me the (simple) answer.
Apparently the auto
value on the grid-template-rows
property does exactly what I was looking for.
.grid {
display:grid;
grid-template-columns: 1fr 1.5fr 1fr;
grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
grid-gap:10px;
height: calc(100vh - 10px);
}
Figure sizes are specified in inches and can be included as a global option of the document output format. For example:
---
title: "My Document"
output:
html_document:
fig_width: 6
fig_height: 4
---
And the plot's size in the graphic device can be increased at the chunk level:
```{r, fig.width=14, fig.height=12} #Expand the plot width to 14 inches
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
You can also use the out.width
and out.height
arguments to directly define the size of the plot in the output file:
```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
iconoclast's answer did not work for me.
I upgraded my php from 5.3.* (xampp 1.7.4) to 5.5.* (xampp 1.8.3) and the problem was solved.
Try iconoclast's answer first, if it doesn't work then upgrading might solve the problem.
I spent a lot of time trying different answers all around the internet, and I suspect the reasons why one thing works for some people and not for others is due to very small weird differences in application. For context, I needed to read in file names from a csv file that had strange and/or unmappable unicode characters and write them to a new csv file. For what it's worth, here's what worked for me:
s = '\u00e7\u00a3\u0085\u00e5\u008d\u0095' # csv freaks if you try to write this
s = repr(s.encode('utf-8', 'ignore'))[2:-1]
You can also go to Notepad++ and do the following steps:
Edit->LineOperations-> Remove Empty Lines or Remove Empty Lines(Containing blank characters)
Here example on plain JS:
document.querySelector('#myDiv').addEventListener('keyup', function (e) {_x000D_
console.log(e.key)_x000D_
})
_x000D_
#myDiv {_x000D_
outline: none;_x000D_
}
_x000D_
<div _x000D_
id="myDiv"_x000D_
tabindex="0"_x000D_
>_x000D_
Press me and start typing_x000D_
</div>
_x000D_
One More Thing...
Kyralessa provides great information but I have one other thing to add where I was stumped even after this article.
Under SQL Server Network Configuration > Protocols for Server > TCP/IP Enabled. Right Click TCP/IP and choose properties. Under the IP Addresses you need to set Enabled to Yes for each connection type that you are using.
strings = ("string1", "string2", "string3")
for line in file:
if any(s in line for s in strings):
print "yay!"
The short answer
There is none. They are exactly the same.
The long answer
Both .htm and .html are exactly the same and will work in the same way. The choice is down to personal preference, provided you’re consistent with your file naming you won’t have a problem with either.
Depending on the configuration of the web server, one of the file types will take precedence over the other. This should not be an issue since it’s unlikely that you’ll have both index.htm and index.html sitting in the same folder.
We always use the shorter .htm for our file names since file extensions are typically 3 characters long.
AND MORE ON: http://www.sightspecific.com/~mosh/WWW_FAQ/ext.html or http://www.sightspecific.com/~mosh/WWW_FAQ/ext.htm
I think I should add this part here:
There is one single slight difference between .htm and .html files. Consider a path in your server like: mydomain.com/myfolder. If you create an index.htm file inside that folder and you open that like this:mydomain.com/myfolder/, it will goes crazy and spit out your files as it is in your server,
but if you create an index.html file in there and open that directory in your browser, it will load that file.
I tested this on my VPS and found this
Maybe you could somehow set your server to load index.htm files by default, but I guess the .html file is the default file type for browsers to open in each directory.
Pass the array to a method that sorts it with Arrays.sort()
so it only sorts the array the method is using then sets min to array[0]
and max to array[array.length-1]
.
This doesn't look like your issue, but for the sake of others, for me this was caused by an invalid version number in package.json (had to change 2.4 to 2.4.0).
You can try joda-time.
My preferred way is this. It handles the escaping and parsing for you.
WebClient webClient = new WebClient();
webClient.QueryString.Add("param1", "value1");
webClient.QueryString.Add("param2", "value2");
string result = webClient.DownloadString("http://theurl.com");
Here's a bit of a polyfill that leverages document.CurrentScript
if it exists and falls back to finding the script by ID.
<script id="uniqueScriptId">
(function () {
var thisScript = document.CurrentScript || document.getElementByID('uniqueScriptId');
// your code referencing thisScript here
());
</script>
If you include this at the top of every script tag I believe you'll be able to consistently know which script tag is being fired, and you'll also be able to reference the script tag in the context of an asynchronous callback.
Untested, so leave feedback for others if you try it.
You can use the css below, put this in your custom css to override the bootstrap css.
.modal-header {
padding:9px 15px;
border-bottom:1px solid #eee;
background-color: #0480be;
-webkit-border-top-left-radius: 5px;
-webkit-border-top-right-radius: 5px;
-moz-border-radius-topleft: 5px;
-moz-border-radius-topright: 5px;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
I had the same problem. Initially I had setup Eclipse CDT with Cygwing & was working smoothly. One day there happened a problem due to which I had to reset windows. After that when I opened Eclipse I started facing the issue described above. This is how I solved it.
First I searched that in the error the PATH variable value is same as the PATH variable of windows ( just by manual comparison of both two values ). I found that to be same. Now I realized that it is a PATH problem.
Then started looking for Cygwin whether it is there or not? It was there. I located & found that it exists in
C:\cygwin64\bin>
C:\cygwin64\bin>dir ma*
Volume in drive C is Windows8_OS
Volume Serial Number is 042E-11B5
Directory of C:\cygwin64\bin
16-05-2015 18:34 10,259 mag.exe
13-08-2013 04:57 384 mailmail
11-04-2015 02:56 4,252 make-emacs-shortcut
15-02-2015 23:25 194,579 make.exe
04-05-2015 21:36 40,979 makeconv.exe
29-07-2013 11:57 29,203 makedepend.exe
16-05-2015 18:34 79,891 makeindex.exe
16-05-2015 18:34 34,323 makejvf.exe
07-05-2015 03:04 310 mako-render
18-04-2015 02:07 92,179 man.exe
18-04-2015 02:07 113,683 mandb.exe
13-08-2013 04:57 286 manhole
18-04-2015 02:07 29,203 manpath.exe
24-10-2014 13:31 274,461 mate-terminal.exe
24-10-2014 13:31 1,366 mate-terminal.wrapper
15 File(s) 905,358 bytes
0 Dir(s) 373,012,271,104 bytes free
C:\cygwin64\bin>
Then I simply went ahead & updated the PATH variable to include this path & restarted eclipse.
The code compiles & debugging (GDB ) is working nicely.
Hope this helps.
First,
always define certificates with CURLOPT_CAPATH option,
decide how your POSTed data will be transfered.
By default:
CURLOPT_SSL_VERIFYHOST == 2
which "checks the existence of a common name and also verify that it matches the hostname provided" and
CURLOPT_VERIFYPEER == true
which "verifies the peer's certificate".
So, all you have to do is:
const CAINFO = SERVER_ROOT . '/registry/cacert.pem';
...
\curl_setopt($ch, CURLOPT_CAINFO, self::CAINFO);
taken from a working class where SERVER_ROOT
is a constant defined during application bootstraping like in a custom classloader, another class etc.
Forget things like \curl_setopt($handler, CURLOPT_SSL_VERIFYHOST, 0);
or \curl_setopt($handler, CURLOPT_SSL_VERIFYPEER, 0);
.
Find cacert.pem
there as seen in this question.
There are actually 2 modes when posting data:
the data is transfered with Content-Type
header set to multipart/form-data
or,
the data is a urlencoded string with application/x-www-form-urlencoded
encoding.
In the first case you pass an array while in the second you pass a urlencoded string.
multipart/form-data
ex.:$fields = array('a' => 'sth', 'b' => 'else');
$ch = \curl_init();
\curl_setopt($ch, CURLOPT_POST, 1);
\curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
application/x-www-form-urlencoded
ex.:$fields = array('a' => 'sth', 'b' => 'else');
$ch = \curl_init();
\curl_setopt($ch, CURLOPT_POST, 1);
\curl_setopt($ch, CURLOPT_POSTFIELDS, \http_build_query($fields));
http_build_query
:Test it at your command line as
user@group:$ php -a
php > $fields = array('a' => 'sth', 'b' => 'else');
php > echo \http_build_query($fields);
a=sth&b=else
The other end of the POST request will define the appropriate mode of connection.
You can append the text to $0
in awk if it matches the condition:
awk '/^all:/ {$0=$0" anotherthing"} 1' file
/patt/ {...}
if the line matches the pattern given by patt
, then perform the actions described within {}
./^all:/ {$0=$0" anotherthing"}
if the line starts (represented by ^
) with all:
, then append anotherthing
to the line.1
as a true condition, triggers the default action of awk
: print the current line (print $0
). This will happen always, so it will either print the original line or the modified one.For your given input it returns:
somestuff...
all: thing otherthing anotherthing
some other stuff
Note you could also provide the text to append in a variable:
$ awk -v mytext=" EXTRA TEXT" '/^all:/ {$0=$0mytext} 1' file
somestuff...
all: thing otherthing EXTRA TEXT
some other stuff
Add a width to the .child
elements. I personally would use percentages on the margin-left
if you want to have it always 4 per row.
.child {
display: inline-block;
background: blue;
margin: 10px 0 0 2%;
flex-grow: 1;
height: 100px;
width: calc(100% * (1/4) - 10px - 1px);
}
The overflow property can be used to clear floats with no additional mark-up:
.container { overflow: hidden; }
This works for all browsers except IE6, where all you need to do is enable hasLayout (zoom being my preferred method):
.container { zoom: 1; }
Just about any error will throw an exceptions. The only errors I can think of that wouldn't work with the "pause on exceptions" option are syntax errors, which happen before any of the code gets executed, so there's no place to pause anyway and none of the code will run.
Apparently, Chrome won't pause on the exception if it's inside a try-catch block though. It only pauses on uncaught exceptions. I don't know of any way to change it.
If you just need to know what line the exception happened on (then you could set a breakpoint if the exception is reproducible), the Error
object given to the catch block has a stack
property that shows where the exception happened.
Gulp will do the job for watching your sass files and also adding paths of other file with includePaths. example:
gulp.task('sass', function() {
return gulp.src('scss/app.scss')
.pipe($.sass({
includePaths: sassPaths
})
.pipe(gulp.dest('css'));
});