Presumably from this site:
Internal Fragmentation Internal fragmentation occurs when the memory allocator leaves extra space empty inside of a block of memory that has been allocated for a client. This usually happens because the processor’s design stipulates that memory must be cut into blocks of certain sizes -- for example, blocks may be required to be evenly be divided by four, eight or 16 bytes. When this occurs, a client that needs 57 bytes of memory, for example, may be allocated a block that contains 60 bytes, or even 64. The extra bytes that the client doesn’t need go to waste, and over time these tiny chunks of unused memory can build up and create large quantities of memory that can’t be put to use by the allocator. Because all of these useless bytes are inside larger memory blocks, the fragmentation is considered internal.
External Fragmentation External fragmentation happens when the memory allocator leaves sections of unused memory blocks between portions of allocated memory. For example, if several memory blocks are allocated in a continuous line but one of the middle blocks in the line is freed (perhaps because the process that was using that block of memory stopped running), the free block is fragmented. The block is still available for use by the allocator later if there’s a need for memory that fits in that block, but the block is now unusable for larger memory needs. It cannot be lumped back in with the total free memory available to the system, as total memory must be contiguous for it to be useable for larger tasks. In this way, entire sections of free memory can end up isolated from the whole that are often too small for significant use, which creates an overall reduction of free memory that over time can lead to a lack of available memory for key tasks.
removePeople(e){
var array = this.state.people;
var index = array.indexOf(e.target.value); // Let's say it's Bob.
array.splice(index,1);
}
Redfer doc for more info
If this is an ASP.NET app why not use Server.HtmlEncode() ?
This is caused by the limited support for the MP4 format within the video tag in Firefox. Support was not added until Firefox 21, and it is still limited to Windows 7 and above. The main reason for the limited support revolves around the royalty fee attached to the mp4 format.
Check out Supported media formats and Media formats supported by the audio and video elements directly from the Mozilla crew or the following blog post for more information:
http://pauljacobson.org/2010/01/22/2010122firefox-and-its-limited-html-5-video-support-html/
IMO, the provider is telling you to change the service endpoint (i.e. where to reach the web service), not the client endpoint (I don't understand what this could be). To change the service endpoint, you basically have two options.
The first option is to change the BindingProvider.ENDPOINT_ADDRESS_PROPERTY
property value of the BindingProvider
(every proxy implements javax.xml.ws.BindingProvider
interface):
...
EchoService service = new EchoService();
Echo port = service.getEchoPort();
/* Set NEW Endpoint Location */
String endpointURL = "http://NEW_ENDPOINT_URL";
BindingProvider bp = (BindingProvider)port;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURL);
System.out.println("Server said: " + echo.echo(args[0]));
...
The drawback is that this only works when the original WSDL is still accessible. Not recommended.
The second option is to get the endpoint URL from the WSDL.
...
URL newEndpoint = new URL("NEW_ENDPOINT_URL");
QName qname = new QName("http://ws.mycompany.tld","EchoService");
EchoService service = new EchoService(newEndpoint, qname);
Echo port = service.getEchoPort();
System.out.println("Server said: " + echo.echo(args[0]));
...
cmsjr had the right solution. I just wanted to point out a couple of things for your future trigger development. If you are using the values statement in an insert in a trigger, there is a stong possibility that you are doing the wrong thing. Triggers fire once for each batch of records inserted, deleted, or updated. So if ten records were inserted in one batch, then the trigger fires once. If you are refering to the data in the inserted or deleted and using variables and the values clause then you are only going to get the data for one of those records. This causes data integrity problems. You can fix this by using a set-based insert as cmsjr shows above or by using a cursor. Don't ever choose the cursor path. A cursor in a trigger is a problem waiting to happen as they are slow and may well lock up your table for hours. I removed a cursor from a trigger once and improved an import process from 40 minutes to 45 seconds.
You may think nobody is ever going to add multiple records, but it happens more frequently than most non-database people realize. Don't write a trigger that will not work under all the possible insert, update, delete conditions. Nobody is going to use the one record at a time method when they have to import 1,000,000 sales target records from a new customer or update all the prices by 10% or delete all the records from a vendor whose products you don't sell anymore.
There is also a way to do this with some restrictions. This is the code from the article:
public string RelativePath(string absPath, string relTo)
{
string[] absDirs = absPath.Split('\\');
string[] relDirs = relTo.Split('\\');
// Get the shortest of the two paths
int len = absDirs.Length < relDirs.Length ? absDirs.Length : relDirs.Length;
// Use to determine where in the loop we exited
int lastCommonRoot = -1; int index;
// Find common root
for (index = 0; index < len; index++)
{
if (absDirs[index] == relDirs[index])
lastCommonRoot = index;
else break;
}
// If we didn't find a common prefix then throw
if (lastCommonRoot == -1)
{
throw new ArgumentException("Paths do not have a common base");
}
// Build up the relative path
StringBuilder relativePath = new StringBuilder();
// Add on the ..
for (index = lastCommonRoot + 1; index < absDirs.Length; index++)
{
if (absDirs[index].Length > 0) relativePath.Append("..\\");
}
// Add on the folders
for (index = lastCommonRoot + 1; index < relDirs.Length - 1; index++)
{
relativePath.Append(relDirs[index] + "\\");
}
relativePath.Append(relDirs[relDirs.Length - 1]);
return relativePath.ToString();
}
When executing this piece of code:
string path1 = @"C:\Inetpub\wwwroot\Project1\Master\Dev\SubDir1";
string path2 = @"C:\Inetpub\wwwroot\Project1\Master\Dev\SubDir2\SubDirIWant";
System.Console.WriteLine (RelativePath(path1, path2));
System.Console.WriteLine (RelativePath(path2, path1));
it prints out:
..\SubDir2\SubDirIWant
..\..\SubDir1
You must always override an abstract function.
Thus:
You cannot add a ListView in a scroll View, as list view also scolls and there would be a synchonization problem between listview scroll and scroll view scoll. You can make a CustomList View and add this method into it.
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
/*
* Prevent parent controls from stealing our events once we've gotten a touch down
*/
if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) {
ViewParent p = getParent();
if (p != null) {
p.requestDisallowInterceptTouchEvent(true);
}
}
return false;
}
Use this code so that the dialog activity won't be closed when the user touches outside the dialog box:
this.setFinishOnTouchOutside(false);
requires API level 11
one-liner with streams
Stream.concat(Arrays.stream( array ), Stream.of( newElement )).toArray();
First. It is necessary add static IP address for Computer A AND B. For example in my case Computer A (172.20.14.13) and B (172.20.14.78).
Second. In Computer A with Net Manager add for Listener new address (172.20.14.13) or manually add new record in listener.ora
# listener.ora Network Configuration File: E:\app\user\product\11.2.0\dbhome_1\NETWORK\ADMIN\listener.ora
# Generated by Oracle configuration tools.
SID_LIST_LISTENER =
(SID_LIST =
(SID_DESC =
(SID_NAME = CLRExtProc)
(ORACLE_HOME = E:\app\user\product\11.2.0\dbhome_1)
(PROGRAM = extproc)
(ENVS = "EXTPROC_DLLS=ONLY:E:\app\user\product\11.2.0\dbhome_1\bin\oraclr11.dll")
)
)
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
)
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
)
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = 172.20.14.13)(PORT = 1521))
)
)
ADR_BASE_LISTENER = E:\app\user
Third. With Net Manager create Service Naming with IP address computer B (172.20.14.78) or manually add new record in tnsnames.ora
# tnsnames.ora Network Configuration File: E:\app\user\product\11.2.0\dbhome_1\NETWORK\ADMIN\tnsnames.ora
# Generated by Oracle configuration tools.
ALINADB =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
)
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = alinadb)
)
)
LISTENER_ALINADB =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
LOCAL =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = 172.20.14.13)(PORT = 1521))
)
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = alinadb)
)
)
ORACLR_CONNECTION_DATA =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
)
(CONNECT_DATA =
(SID = CLRExtProc)
(PRESENTATION = RO)
)
)
ORCL =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = 172.20.14.78)(PORT = 1521))
)
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = orcl)
)
)
Fourth. In computer B (172.20.14.78) install win64_11gR2_client (For example it is for me in Windows 10 Pro 64 bit )
Five. Create with Net Configuration Assistant listener (localhost) or manually add record in listener.ora
# listener.ora Network Configuration File: F:\app\alinasoft\product\11.2.0\client_1\network\admin\listener.ora
# Generated by Oracle configuration tools.
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = myserver)(PORT = 1521))
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
)
)
ADR_BASE_LISTENER = F:\app\alinasoft
Six. With Net Manager create Service Naming with IP address computer A (172.20.14.13) or manually add new record in tnsnames.ora.
SERVER-DB =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = 172.20.14.13)(PORT = 1521))
)
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = alinadb)
)
)
Seven (Computer A - (172.20.14.13)) for database operations and connectivity from remote clients, the following executables must be added to the Windows Firewall exception list: (see image) Oracle_home\bin\oracle.exe - Oracle Database executable Oracle_home\bin\tnslsnr.exe - Oracle Listener
Eight Allow connections for port 1158 (Computer A - (172.20.14.13)) for Oracle Enterprise Manager (https://172.20.14.13:1158/em/console/logon/logon)
Ninth Allow connections for port 1521 ( in and out) (Computer A - (172.20.14.17))
Tenth In computer B 172.20.14.78 sqlplus /NOLOG CONNECT system/oracle@//172.20.14.13:1521/alinadb
Mongodb v3.4
You need to do the following to create a secure database:
Make sure the user starting the process has permissions and that the directories exist (/data/db
in this case).
1) Start MongoDB without access control.
mongod --port 27017 --dbpath /data/db
2) Connect to the instance.
mongo --port 27017
3) Create the user administrator (in the admin authentication database).
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
4) Re-start the MongoDB instance with access control.
mongod --auth --port 27017 --dbpath /data/db
5) Connect and authenticate as the user administrator.
mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"
6) Create additional users as needed for your deployment (e.g. in the test authentication database).
use test
db.createUser(
{
user: "myTester",
pwd: "xyz123",
roles: [ { role: "readWrite", db: "test" },
{ role: "read", db: "reporting" } ]
}
)
7) Connect and authenticate as myTester.
mongo --port 27017 -u "myTester" -p "xyz123" --authenticationDatabase "test"
I basically just explained the short version of the official docs here: https://docs.mongodb.com/master/tutorial/enable-authentication/
I know that two threads can not enter in Synchronize block at the same time
Two thread cannot enter a synchronized block on the same object twice. This means that two threads can enter the same block on different objects. This confusion can lead to code like this.
private Integer i = 0;
synchronized(i) {
i++;
}
This will not behave as expected as it could be locking on a different object each time.
if this is true than How this atomic.incrementAndGet() works without Synchronize ?? and is thread safe ??
yes. It doesn't use locking to achieve thread safety.
If you want to know how they work in more detail, you can read the code for them.
And what is difference between internal reading and writing to Volatile Variable / Atomic Variable ??
Atomic class uses volatile fields. There is no difference in the field. The difference is the operations performed. The Atomic classes use CompareAndSwap or CAS operations.
i read in some article that thread has local copy of variables what is that ??
I can only assume that it referring to the fact that each CPU has its own cached view of memory which can be different from every other CPU. To ensure that your CPU has a consistent view of data, you need to use thread safety techniques.
This is only an issue when memory is shared at least one thread updates it.
Yes, there is a shortcut for commenting out lines in Python 3.6 (Spyder).
For Single Line Comment, you can use Ctrl+1. It will look like this #This is a sample piece of code
For multi-line comments, you can use Ctrl+4. It will look like this
#=============
\#your piece of code
\#some more code
\#=============
Note : \
represents that the code is carried to another line.
Drop a pidfile somewhere (e.g. /tmp). Then you can check to see if the process is running by checking to see if the PID in the file exists. Don't forget to delete the file when you shut down cleanly, and check for it when you start up.
#/usr/bin/env python
import os
import sys
pid = str(os.getpid())
pidfile = "/tmp/mydaemon.pid"
if os.path.isfile(pidfile):
print "%s already exists, exiting" % pidfile
sys.exit()
file(pidfile, 'w').write(pid)
try:
# Do some actual work here
finally:
os.unlink(pidfile)
Then you can check to see if the process is running by checking to see if the contents of /tmp/mydaemon.pid are an existing process. Monit (mentioned above) can do this for you, or you can write a simple shell script to check it for you using the return code from ps.
ps up `cat /tmp/mydaemon.pid ` >/dev/null && echo "Running" || echo "Not running"
For extra credit, you can use the atexit module to ensure that your program cleans up its pidfile under any circumstances (when killed, exceptions raised, etc.).
I used a gradient based method in the program below. Added the resulting images. Please note that I'm using a scaled down version of the image for processing.
c++ version
The MIT License (MIT)
Copyright (c) 2014 Dhanushka Dangampola
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
#include "stdafx.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace cv;
using namespace std;
#define INPUT_FILE "1.jpg"
#define OUTPUT_FOLDER_PATH string("")
int _tmain(int argc, _TCHAR* argv[])
{
Mat large = imread(INPUT_FILE);
Mat rgb;
// downsample and use it for processing
pyrDown(large, rgb);
Mat small;
cvtColor(rgb, small, CV_BGR2GRAY);
// morphological gradient
Mat grad;
Mat morphKernel = getStructuringElement(MORPH_ELLIPSE, Size(3, 3));
morphologyEx(small, grad, MORPH_GRADIENT, morphKernel);
// binarize
Mat bw;
threshold(grad, bw, 0.0, 255.0, THRESH_BINARY | THRESH_OTSU);
// connect horizontally oriented regions
Mat connected;
morphKernel = getStructuringElement(MORPH_RECT, Size(9, 1));
morphologyEx(bw, connected, MORPH_CLOSE, morphKernel);
// find contours
Mat mask = Mat::zeros(bw.size(), CV_8UC1);
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(connected, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
// filter contours
for(int idx = 0; idx >= 0; idx = hierarchy[idx][0])
{
Rect rect = boundingRect(contours[idx]);
Mat maskROI(mask, rect);
maskROI = Scalar(0, 0, 0);
// fill the contour
drawContours(mask, contours, idx, Scalar(255, 255, 255), CV_FILLED);
// ratio of non-zero pixels in the filled region
double r = (double)countNonZero(maskROI)/(rect.width*rect.height);
if (r > .45 /* assume at least 45% of the area is filled if it contains text */
&&
(rect.height > 8 && rect.width > 8) /* constraints on region size */
/* these two conditions alone are not very robust. better to use something
like the number of significant peaks in a horizontal projection as a third condition */
)
{
rectangle(rgb, rect, Scalar(0, 255, 0), 2);
}
}
imwrite(OUTPUT_FOLDER_PATH + string("rgb.jpg"), rgb);
return 0;
}
python version
The MIT License (MIT)
Copyright (c) 2017 Dhanushka Dangampola
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
import cv2
import numpy as np
large = cv2.imread('1.jpg')
rgb = cv2.pyrDown(large)
small = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
grad = cv2.morphologyEx(small, cv2.MORPH_GRADIENT, kernel)
_, bw = cv2.threshold(grad, 0.0, 255.0, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 1))
connected = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, kernel)
# using RETR_EXTERNAL instead of RETR_CCOMP
contours, hierarchy = cv2.findContours(connected.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
#For opencv 3+ comment the previous line and uncomment the following line
#_, contours, hierarchy = cv2.findContours(connected.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
mask = np.zeros(bw.shape, dtype=np.uint8)
for idx in range(len(contours)):
x, y, w, h = cv2.boundingRect(contours[idx])
mask[y:y+h, x:x+w] = 0
cv2.drawContours(mask, contours, idx, (255, 255, 255), -1)
r = float(cv2.countNonZero(mask[y:y+h, x:x+w])) / (w * h)
if r > 0.45 and w > 8 and h > 8:
cv2.rectangle(rgb, (x, y), (x+w-1, y+h-1), (0, 255, 0), 2)
cv2.imshow('rects', rgb)
On some sites I need to use css "cursor:help". Only iOS it gave me a lot of irritation. To solve this, change everything af the page to "cursor:pointer". That works for me.
jQuery:
if (/iP(hone|od|ad)/.test(navigator.platform)) {
$("*").css({"cursor":"pointer"});
}
intent.getAction().equals(SMS_RECEIVED)
I have tried it out successfully.
On Windows XP -
rundll32.exe syssetup,SetupOobeBnk
This will reset the 30 day timer for activation back to 30 days so you can enter in the key normally.
You could merge two queries together:
$merged = $query_one->merge($query_two);
yes, sql server doesn't allow to insert single quote in table field due to the sql injection attack. so we must replace single appostrophe by double while saving.
(he doesn't work for me) must be => (he doesn''t work for me)
Use inline shell string replacement. Example:
foo=" "
# replace first blank only
bar=${foo/ /.}
# replace all blanks
bar=${foo// /.}
See http://tldp.org/LDP/abs/html/string-manipulation.html for more details.
As you can see here there is a very simple way to do that.
In your DialogFragment
add an interface listener like:
public interface EditNameDialogListener {
void onFinishEditDialog(String inputText);
}
Then, add a reference to that listener:
private EditNameDialogListener listener;
This will be used to "activate" the listener method(s), and also to check if the parent Activity/Fragment implements this interface (see below).
In the Activity
/FragmentActivity
/Fragment
that "called" the DialogFragment
simply implement this interface.
In your DialogFragment
all you need to add at the point where you'd like to dismiss the DialogFragment
and return the result is this:
listener.onFinishEditDialog(mEditText.getText().toString());
this.dismiss();
Where mEditText.getText().toString()
is what will be passed back to the calling Activity
.
Note that if you want to return something else simply change the arguments the listener takes.
Finally, you should check whether the interface was actually implemented by the parent activity/fragment:
@Override
public void onAttach(Context context) {
super.onAttach(context);
// Verify that the host activity implements the callback interface
try {
// Instantiate the EditNameDialogListener so we can send events to the host
listener = (EditNameDialogListener) context;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(context.toString()
+ " must implement EditNameDialogListener");
}
}
This technique is very flexible and allow calling back with the result even if your don;t want to dismiss the dialog just yet.
Ideally we should not handle/catch errors. But there may be cases where we need to do, based on requirement of framework or application. Say i have a XML Parser daemon which implements DOM Parser which consumes more Memory. If there is a requirement like Parser thread should not be died when it gets OutOfMemoryError, instead it should handle it and send a message/mail to administrator of application/framework.
SilverSkin and Anders are both correct. You can use parentheses to execute multiple commands. However, you have to make sure that the commands themselves (and their parameters) do not contain parentheses. cmd
greedily searches for the first closing parenthesis, instead of handling nested sets of parentheses gracefully. This may cause the rest of the command line to fail to parse, or it may cause some of the parentheses to get passed to the commands (e.g. DEL myfile.txt)
).
A workaround for this is to split the body of the loop into a separate function. Note that you probably need to jump around the function body to avoid "falling through" into it.
FOR /r %%X IN (*.txt) DO CALL :loopbody %%X
REM Don't "fall through" to :loopbody.
GOTO :EOF
:loopbody
ECHO %1
DEL %1
GOTO :EOF
Use & for this. Using & you can put as many variables as you want!
$url = "http://localhost/main.php?event_id=".$event_id."&email=".$email;
Will this work / be faster?
uint32_t swapped, result;
((byte*)&swapped)[0] = ((byte*)&result)[3];
((byte*)&swapped)[1] = ((byte*)&result)[2];
((byte*)&swapped)[2] = ((byte*)&result)[1];
((byte*)&swapped)[3] = ((byte*)&result)[0];
You can create an ExpandoObject like this:
IDictionary<string,object> expando = new ExpandoObject();
expando["Name"] = value;
And after casting it to dynamic, those values will look like properties:
dynamic d = expando;
Console.WriteLine(d.Name);
However, they are not actual properties and cannot be accessed using Reflection. So the following statement will return a null:
d.GetType().GetProperty("Name")
You shouldn't need to let the users specify the margin on your website - Let them do it on their computer. Print dialogs usually (Adobe and Preview, at least) give you an option to scale and center the output on the printable area of the page:
Adobe
Preview
Of course, this assumes that you have computer literate users, which may or may not be the case.
please, be sure your connected to a ubuntu server, I Had the same problem but I was connected to other distro, check the AMI value in your details instance, it should be something like
AMI: ubuntu/images/ebs/ubuntu-precise-12.04-amd64-server-20130411.1
hope it helps
Open your windows search bar, and search for the keyword Tomcat
. If a shortcut file is found instead, you can open the source file location of the shortcut by right-clicking the shortcut file and selecting the Properties.
for a pure shell solution without calling external program:
NL=$'\n' # define a variable to reference 'newline'
testVar=${testVar%$NL} # removes trailing 'NL' from string
Try adding this to your source:
debugger;
It works in most, if not all browsers. Just place it somewhere in your code, and it will act like a breakpoint.
You need to add .toArray()
to the end of your .map()
function
$("#merge_button").click(function(event){
event.preventDefault();
var searchIDs = $("#find-table input:checkbox:checked").map(function(){
return $(this).val();
}).toArray();
console.log(searchIDs);
});
My site faces same issue too.
Using Facebook debug tool is no help at all. Fetch new data but not IMAGE CACHE.
I forced facebook to clear IMAGE CACHE by add www. into image url. In your case is remove www. and config web server redirect.
add/remove www. in image url should solve the problem
Here is a simple and clean solution without using JavaScript or table layout hacks. It is similar to this answer: Input text auto width filling 100% with other elements floating
It is important to wrap the input field with a span which is display:block
. Next thing is that the button has to come first and the the input field second.
Then you can float the button to the right and the input field fills the remaining space.
form {_x000D_
width: 500px;_x000D_
overflow: hidden;_x000D_
background-color: yellow;_x000D_
}_x000D_
input {_x000D_
width: 100%;_x000D_
}_x000D_
span {_x000D_
display: block;_x000D_
overflow: hidden;_x000D_
padding-right:10px;_x000D_
}_x000D_
button {_x000D_
float: right;_x000D_
}
_x000D_
<form method="post">_x000D_
<button>Search</button>_x000D_
<span><input type="text" title="Search" /></span>_x000D_
</form>
_x000D_
A simple fiddle: http://jsfiddle.net/v7YTT/90/
Update 1: If your website is targeted towards modern browsers only, I suggest using flexible boxes. Here you can see the current support.
Update 2: This even works with multiple buttons or other elements that share the full with with the input field. Here is an example.
Turns out that it happened because of the firewall on my computer. Turning it off worked for me.
You're using S_ISREG()
and S_ISDIR()
correctly, you're just using them on the wrong thing.
In your while((dit = readdir(dip)) != NULL)
loop in main
, you're calling stat
on currentPath
over and over again without changing currentPath
:
if(stat(currentPath, &statbuf) == -1) {
perror("stat");
return errno;
}
Shouldn't you be appending a slash and dit->d_name
to currentPath
to get the full path to the file that you want to stat
? Methinks that similar changes to your other stat
calls are also needed.
You can change color programmatically by using this code :
ProgressBar v = (ProgressBar) findViewById(R.id.progress);
v.getIndeterminateDrawable().setColorFilter(0xFFcc0000,
android.graphics.PorterDuff.Mode.MULTIPLY);
If you want to change ProgressDialog's progressbar color, u can use this :
mDilog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
ProgressBar v = (ProgressBar)mDilog.findViewById(android.R.id.progress);
v.getIndeterminateDrawable().setColorFilter(0xFFcc0000,
android.graphics.PorterDuff.Mode.MULTIPLY);
}
});
You just need to get selenium package imported, that you can do from command prompt using the command
pip install selenium
When you have to use it in any IDE just import this package, no other documentation required to be imported
For Eg :
import selenium
print(selenium.__filepath__)
This is just a general command you may use in starting to check the filepath of selenium
How to add new line in Markdown presentation?
Check the following resource Line Return
To force a line return, place two empty spaces at the end of a line.
According to this question, it's totally possible.
Just put all cases that contain the same logic together, and don't put break
behind them.
switch (var) {
case (value1):
case (value2):
case (value3):
//the same logic that applies to value1, value2 and value3
break;
case (value4):
//another logic
break;
}
It's because case
without break
will jump to another case
until break
or return
.
EDIT:
Replying the comment, if we really have 95 values with the same logic, but a way smaller number of cases with different logic, we can do:
switch (var) {
case (96):
case (97):
case (98):
case (99):
case (100):
//your logic, opposite to what you put in default.
break;
default:
//your logic for 1 to 95. we enter default if nothing above is met.
break;
}
If you need finer control, if-else
is the choice.
It cause eclipse kepler SR1 does not support new Java™ 8 language enhancements like lambda expression.
From information here: http://www.eclipse.org/downloads/java8/
I think you should use kepler SR2 with support plugin, or change to Eclipse Luna.
Updated link 16/09/2016: https://wiki.eclipse.org/JDT/Eclipse_Java_8_Support_For_Kepler
You can use query-objects from npm. You can search an array of objects using filters.
const queryable = require('query-objects');
const users = [
{
firstName: 'George',
lastName: 'Eracleous',
age: 28
},
{
firstName: 'Erica',
lastName: 'Archer',
age: 50
},
{
firstName: 'Leo',
lastName: 'Andrews',
age: 20
}
];
const filters = [
{
field: 'age',
value: 30,
operator: 'lt'
},
{
field: 'firstName',
value: 'Erica',
operator: 'equals'
}
];
// Filter all users that are less than 30 years old AND their first name is Erica
const res = queryable(users).and(filters);
// Filter all users that are less than 30 years old OR their first name is Erica
const res = queryable(users).or(filters);
It's always advised to never destructively destroy an existing classpath unless you have a good reason.
The following line preserves the existing classpath and adds onto it.
export CLASSPATH="$CLASSPATH:foo.jar:../bar.jar"
There is no such function; the easiest way to do this is to use a dict comprehension:
my_dictionary = {k: f(v) for k, v in my_dictionary.items()}
In python 2.7, use the .iteritems()
method instead of .items()
to save memory. The dict comprehension syntax wasn't introduced until python 2.7.
Note that there is no such method on lists either; you'd have to use a list comprehension or the map()
function.
As such, you could use the map()
function for processing your dict as well:
my_dictionary = dict(map(lambda kv: (kv[0], f(kv[1])), my_dictionary.iteritems()))
but that's not that readable, really.
To get all column name you can iterate over the data_all2.columns
.
columns = data_all2.columns
for col in columns:
print col
You will get all column names. Or you can store all column names to another list variable and then print list.
Since Android 4.2 (API 17) nested fragments become available http://developer.android.com/about/versions/android-4.2.html#NestedFragments
To place fragment inside other fragment use getChildFragmentManager()
It also available in support library!
onload
use $(window).load
instead (jQuery):$(window).load(function() {
//code
});
I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between
BEGIN
SELECT MONTH(CURDATE()) INTO @curmonth;
SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
SELECT DAY(@checkweekday) INTO @checkday;
SET @daycount = 0;
SET @workdays = 0;
WHILE(@daycount < @totaldays) DO
IF (WEEKDAY(@checkweekday) < 5) THEN
SET @workdays = @workdays+1;
END IF;
SET @daycount = @daycount+1;
SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
END WHILE;
END
Just for others:
If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query
delimiter ;;
drop procedure if exists test2;;
create procedure test2()
begin
select ‘Hello World’;
end
;;
Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.
The first_day function you need is: How to get first day of every corresponding month in mysql?
Showing the Procedure is working Simply add the following line below END WHILE and above END
SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;
Then use the following code in the SQL Query Window.
call test2 /* or whatever you changed the name of the stored procedure to */
NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).
try the toupper()
function (#include <ctype.h>
). it accepts characters as arguments, strings are made up of characters, so you'll have to iterate over each individual character that when put together comprise the string
You can do this using OPENROWSET as suggested in this answer. Reposting Slogmeister Extrarodinare answer:
Use T-SQL
INSERT INTO OPENROWSET ('Microsoft.ACE.OLEDB.12.0','Text;Database=D:\;HDR=YES;FMT=Delimited','SELECT * FROM [FileName.csv]')
SELECT Field1, Field2, Field3 FROM DatabaseName
But, there are couple of caveats:
You need to have the Microsoft.ACE.OLEDB.12.0 provider available. The Jet 4.0 provider will work, too, but it's ancient, so I used this one instead.
The .CSV file will have to exist already. If you're using headers (HDR=YES), make sure the first line of the .CSV file is a delimited list of all the fields.
This will work:
#div{
max-height:300px;
overflow:hidden;
}
#div:hover{
overflow-y:scroll;
}
I fixed this issue starting with @hallodom's answer. All my inputs were contained within li's, so all I had to do was set the li overflow:hidden for it to remove that excess input overflow.
.ie7 form li {
width:100%;
overflow:hidden;
}
.ie7 input {
width:100%;
}
I was able to resolve this problem by cleaning my assets cache:
$ rake assets:clean
this setting worked for me:
Imagine if one went into a store and asked for a device with a power switch. You didn't say whether you wanted a copier, television, vacuum cleaner, desk lamp, waffle maker, or anything. You asked for a device with a power switch. Would you expect the clerk to offer you something that could only be described as "a device with a power switch"?
A typical interface would be analogous to the description "a device with a power switch". Knowing that a piece of equipment is " a device with a power switch" would allow one to do some operations with it (i.e. turn it on and off), and one might plausibly want a list of e.g. "devices with power switches that will need to be turned off at the end of the day", without the devices having to share any characteristic beyond having a power switch, but such situations generally only apply when applying some common operation to devices that were created for some more specific purpose. When creating something from scratch, one would more likely wand a "copier", "television", "vacuum cleaner", or other particular type of device, than some random "device with a power switch".
There are some circumstances where one may want a vaguely-defined object, and really not care about what exactly it is. "Give me your cheapest device that can boil water". It would be nice if one could specify that when someone asks for an arbitrary object with "water boiling" ability, they should be offered an Acme 359 Electric Teakettle, and indeed when using classes it's possible to do that. Note, however, that someone who asks for a "device to boil water" would not be given a "device to boil water", but an "Acme 359 Electric Teakettle".
For me it only worked when I added the following code:
.change();
For me it only worked when I added the following code: As I wanted to "reset" the form, that is, select all the first options of all the selects of the form, I used the following code:
$('form').find('select').each(function(){
$(this).val($("select option:first").val());
$(this).change();
});
Instances of the String
constructor have a .search()
method which accepts a RegExp and returns the index of the first match.
To start the search from a particular position (faking the second parameter of .indexOf()
) you can slice
off the first i
characters:
str.slice(i).search(/re/)
But this will get the index in the shorter string (after the first part was sliced off) so you'll want to then add the length of the chopped off part (i
) to the returned index if it wasn't -1
. This will give you the index in the original string:
function regexIndexOf(text, re, i) {
var indexInSuffix = text.slice(i).search(re);
return indexInSuffix < 0 ? indexInSuffix : indexInSuffix + i;
}
Remove "SSLv2ClientHello" from the enabled protocols on the client SSLSocket or HttpsURLConnection.
This has already been mentioned, but here is a way to place the code within a method:
public static String getMonthName(int monthIndex) {
return new DateFormatSymbols().getMonths()[monthIndex].toString();
}
or if you wanted to create a better error than an ArrayIndexOutOfBoundsException:
public static String getMonthName(int monthIndex) {
//since this is zero based, 11 = December
if (monthIndex < 0 || monthIndex > 11 ) {
throw new IllegalArgumentException(monthIndex + " is not a valid month index.");
}
return new DateFormatSymbols().getMonths()[monthIndex].toString();
}
In my case, same error was coming with JSP. This is how I got to the root of this issue: I went to the Network tab and clearly saw that the browser request to fetch the css was returning response header having "Content-type" : "text/html". I opened another tab and manually hit the request to fetch the css. It ended up returning a html log in form. Turns out that my web application had a url mapping for path = /
Tomcat servlet entry : (@WebServlet({ "/, /index", })
. So, any unmatching request URLs were somehow being matched to /
and the corresponding servlet was returning a Log in html form. I fixed it by removing the mapping to /
Also, the tomcat configuration wrt handling css MIME-TYPE was already present.
I see a lot of complicated answers here. Some of them, fail to knowledge simple, true email address, or have false positives. Below, is the simplest way of testing that the string would be a valid email. It tests against 2 and 3 letter TLD's. Now that you technically can have larger ones, you may wish to increase the 3 to 4, 5 or even 10.
import re
def valid_email(email):
return bool(re.search(r"^[\w\.\+\-]+\@[\w]+\.[a-z]{2,3}$", email))
.data("events") has been removed in versions 1.9 and 2.0beta, so you cant any longer rely on those solutions.
I was getting the same problem on Spring Tool Suite 3.2 and changed the version of jstl to 1.2 (from 1.1.2) manually when adding it to the dependency list, and the error got disappeared.
To make Rajneesh071's code complete, you may also want to set the navigation bar's title color (and font, if you want) since the default behavior changed from iOS 6 to 7:
NSArray *ver = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
if ([[ver objectAtIndex:0] intValue] >= 7)
{
self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
self.navigationController.navigationBar.translucent = NO;
NSMutableDictionary *textAttributes = [[NSMutableDictionary alloc] initWithDictionary:mainNavController.navigationBar.titleTextAttributes];
[textAttributes setValue:[UIColor whiteColor] forKey:UITextAttributeTextColor];
self.navigationController.navigationBar.titleTextAttributes = textAttributes;
}
else
{
self.navigationController.navigationBar.tintColor = [UIColor blackColor];
}
I had this issue with javascript calls. I fixed that with just requiring jquery_ujs into application.js file.
Salvaging (and extending) the list from an old version of the Wikipedia page:
Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.
The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:
Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.
There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),
docutils
)JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.
Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.
The Nim compiler features the commands rst2html
and rst2tex
which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:
Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.
pip
-installable python package requires docutils
, which does the actual rendering. restview
's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
docutils
to render your document(s) to HTMLSome projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.
The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.
rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.
Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.
While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.
The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el
The vim-common
package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:
There is a rst mode for the Jed programmers editor.
gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.
Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).
Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).
It also provides a way to preview the resulting HTML, in a "viewrendered" pane.
The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.
PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.
The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.
NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.
Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.
Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.
Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.
BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.
TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.
Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.
E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.
PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).)
here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:
MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst>
and </rst>
.
MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.
There is a reStructuredText Parser for MoinMoin.
Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.
This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.
rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.
Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.
An Online reStructuredText editor can be used to play with the markup and see the results immediately.
WordPreSt reStructuredText plugin for WordPress. (PHP)
reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)
Pelican is a static blog generator that supports writing articles in ReST. (Python)
Hyde is a static website generator that supports ReST. (Python)
Acrylamid is a static blog generator that supports writing articles in ReST. (Python)
Nikola is a Static Site and Blog Generator that supports ReST. (Python)
Ipsum genera is a static blog generator written in Nim.
Yozuch is a static blog generator written in Python.
.bbg {
/* The image used */
background-image: url('...');
/* Full height */
height: 100%;
/* Center and scale the image nicely */
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
<!doctype html>
<html class="h-100">
.
.
.
<body class="bbg">
</body>
.
.
.
</html>
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.
try the following (in RowDataBound method of GridView):
protected void GridViewUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
// this will only change the rows backgound not the column header
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].BackColor = System.Drawing.Color.LightCyan; //first col
e.Row.Cells[1].BackColor = System.Drawing.Color.Black; // second col
}
}
Here is a very simple and clean way to push your changes after you have already made a git add "your files"
and git commit --amend
:
git push origin master -f
or:
git push origin master --force
Other than the append
function, if by "multiple values" you mean another list, you can simply concatenate them like so.
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a + b
[1, 2, 3, 4, 5, 6]
I've found a more reliable method (at least on Excel 2016 for Mac) is:
Assuming your long list is in column A, and the list of things to be removed from this is in column B, then paste this into all the rows of column C:
= IF(COUNTIF($B$2:$B$99999,A2)>0,"Delete","Keep")
Then just sort the list by column C to find what you have to delete.
MODERN REVISION: you also now need to fix it by changing the little known ''security.limit_extensions' in php-fpm doing this. You will probably already know the well documented mechanism of changing apache to AddHandler/AddType I will not go into that here.
YOU MUST find out where php-fpm/conf is in your set up. I did it by doing this
# grep -rnw '/etc/' -e 'security.limit_extensions'
I got this back
'/etc/php-fpm.d/www.conf:387:;security.limit_extensions = .php .php3 .php4 .php5 .php7'
go to this file, edit it and MAKE SURE YOU REALISE IT IS COMMENTED OUT
EG: change it from ';security.limit_extensions = .php .php3 .php4 .php5 .php7'
<- NB: note the ";"
- this line is actually DISABLED by default - and you do not need all the nonsense extensions, in fact they are probably dangerous.. change it to 'security.limit_extensions = .php .htm'
<- note the semi colon is now removed. then restart apache/(or nginx) and restart php-fpm # service php-fpm restart
# service httpd restart
Only works in IE
$(function(){
var xml = '<?xml version="1.0"?><foo><bar>bar</bar></foo>';
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(xml);
alert(xmlDoc.xml);
});
Then push xmlDoc.xml to your java code.
I recently work on it. Try this function:
/**
* @return array an array of your files uploaded.
*/
private function _upload_files($field='userfile'){
$files = array();
foreach( $_FILES[$field] as $key => $all )
foreach( $all as $i => $val )
$files[$i][$key] = $val;
$files_uploaded = array();
for ($i=0; $i < count($files); $i++) {
$_FILES[$field] = $files[$i];
if ($this->upload->do_upload($field))
$files_uploaded[$i] = $this->upload->data($files);
else
$files_uploaded[$i] = null;
}
return $files_uploaded;
}
in your case:
<input type="file" multiple name="images[]" size="20" />
or
<input type="file" name="images[]">
<input type="file" name="images[]">
<input type="file" name="images[]">
in the controller:
public function do_upload(){
$config['upload_path'] = './Images/';
$config['allowed_types'] = 'gif|jpg|png';
//...
$this->load->library('upload',$config);
if ($_FILES['images']) {
$images= $this->_upload_files('images');
print_r($images);
}
}
Some basic reference from PHP manual: PHP file upload
There's a Microsoft Doc for creating your WCF
proxy from the command line
.
You can find your local copy of wsdl.exe
in a location similar to this: C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools
(Learn more here)
In the end your Command
should look similar to this:
"C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\wsdl.exe"
/language:CS /n:"My.Namespace" https://www.example.com/service/wsdl
A much more secure answer that I'm surprised is not mentioned here yet:
So in the case of the question you can use this to get an email value from the URL get parameters:
$email = filter_input( INPUT_GET, 'email', FILTER_SANITIZE_EMAIL );
For other types of variables, you would want to choose a different/appropriate filter such as FILTER_SANITIZE_STRING
.
I suppose this answer does more than exactly what the question asks for - getting the raw data from the URL parameter. But this is a one-line shortcut that is the same result as this:
$email = $_GET['email'];
$email = filter_var( $email, FILTER_SANITIZE_EMAIL );
Might as well get into the habit of grabbing variables this way.
SQLite does not contain regular expression functionality by default.
It defines a REGEXP
operator, but this will fail with an error message unless you or your framework define a user function called regexp()
. How you do this will depend on your platform.
If you have a regexp()
function defined, you can match an arbitrary integer from a comma-separated list like so:
... WHERE your_column REGEXP "\b" || your_integer || "\b";
But really, it looks like you would find things a whole lot easier if you normalised your database structure by replacing those groups within a single column with a separate row for each number in the comma-separated list. Then you could not only use the =
operator instead of a regular expression, but also use more powerful relational tools like joins that SQL provides for you.
you can build and execute dynamic sql to do this, but its really not ideal
You missed some breaks there:
switch (searchType)
{
case "SearchBooks":
Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
break;
case "SearchAuthors":
Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
break;
}
Without them, the compiler thinks you're trying to execute the lines below case "SearchAuthors":
immediately after the lines under case "SearchBooks":
have been executed, which isn't allowed in C#.
By adding the break
statements at the end of each case, the program exits each case after it's done, for whichever value of searchType
.
May be, it is not the very worst idea to merge (via difftool) from ... yes ... a branch!
> current_branch=$(git status | head -n1 | cut -d' ' -f3)
> stash_branch="$current_branch-stash-$(date +%yy%mm%dd-%Hh%M)"
> git stash branch $stash_branch
> git checkout $current_branch
> git difftool $stash_branch
If you also want to bind closing of infowindow to some event, try something like this
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
windows.push(infowindow)
google.maps.event.addListener(map,'click', function(){
infowindow.close();
});
};
})(marker,content,infowindow));
You would also need a
$i--;
after each unset to not skip an element/
Because when you unset $item[45]
, the next element in the for-loop should be $item[45]
- which was [46]
before unsetting. If you would not do this, you'd always skip an element after unsetting.
If your list of values is to be hard-coded in the script, it's fairly simple to test using case
. Here's a short example, which you can adapt to your requirements:
for item in $list
do
case "$x" in
item1|item2)
echo "In the list"
;;
not_an_item)
echo "Error" >&2
exit 1
;;
esac
done
If the list is an array variable at runtime, one of the other answers is probably a better fit.
This best way is to change Image Tint
in storyboard
If it were me, I would avoid any risky revision editing and do the following instead:
Create a new branch on the SHA where 222 was committed, basically as a bookmark.
Switch back to the main branch. In it, revert commit 222.
Push all the commits that have been made, which will push commit 111 only, because 222 was reverted.
Work on the branch from step #1 if needed. Merge from the trunk to it as needed to keep it up to date. I wouldn't bother with stash.
When it's time for the changes in commit 222 to go in, that branch can be merged to trunk.
CREATE TABLE table_temp_list_objects AS
SELECT o.owner, o.object_name FROM sys.all_objects o WHERE o.object_type ='TABLE';
I don't recommend StartNew
unless you need that level of complexity.
If your async method is dependent on other async methods, the easiest approach is to use the async
keyword:
private static async Task<DateTime> CountToAsync(int num = 10)
{
for (int i = 0; i < num; i++)
{
await Task.Delay(TimeSpan.FromSeconds(1));
}
return DateTime.Now;
}
If your async method is doing CPU work, you should use Task.Run
:
private static async Task<DateTime> CountToAsync(int num = 10)
{
await Task.Run(() => ...);
return DateTime.Now;
}
You may find my async
/await
intro helpful.
Regular javascript can be used to trap the backspace key. You can use the event.keyCode method. The keycode is 8, so the code would look something like this:
if (event.keyCode == 8) {
// Do stuff...
}
If you want to check for both the [delete] (46) as well as the [backspace] (8) keys, use the following:
if (event.keyCode == 8 || event.keyCode == 46) {
// Do stuff...
}
I did all of the above and nothing worked. The overlay icons were appearing in Explorer but not in Total Commander.
Eventually what solved the issue for me was that I discovered a command in Total Commander that refreshed the Overlay Icons. To access it, right click on the toolbar and click on "Change...", and add "cm_SwitchOverlayIcons" as shown in the image below.
After adding the command icon to the toolbar, I click it once, and the overlay icon of TortoiseSVN appeared!
The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.
When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.
Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:
http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database
Update Collation of all fields in database on the fly
http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx
If you need to have different collation on two objects or can't change collations - you can still JOIN
between them using COLLATE
command, and choosing the collation you want for join.
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS
or using default database collation:
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT
EDIT: It seems I was wrong about the performance on the code example. The best performer is whichever snippet runs second in the posted case. This demonstrates what I was trying to explain, and the time differences are not as dramatic:
----------------------------------
-- Monitor time differences
----------------------------------
CREATE CLUSTERED INDEX dtIDX ON #ArbDates (MyDate)
DECLARE @Stopwatch DATETIME
SET @Stopwatch = GETDATE()
-- SARGABLE
SELECT *
FROM #ArbDates
WHERE MyDate > DATEADD(DAY, -364, '2010-01-01')
PRINT DATEDIFF(MS, @Stopwatch, GETDATE())
SET @Stopwatch = GETDATE()
-- NOT SARGABLE
SELECT *
FROM #ArbDates
WHERE DATEDIFF(DAY, MyDate, '2010-01-01') < 365
PRINT DATEDIFF(MS, @Stopwatch, GETDATE())
Excuse me for posting late and my crudely commented example, but I think it important to mention SARG.
SELECT I.Fee
FROM Item I
WHERE I.DateCreated > DATEADD(DAY, -364, GETDATE())
Although the temp table in the code below has no index, the performance is still enhanced by the fact that a comparison is done between an expression and a value in the table and not an expression that modifies the value in the table and a constant. Hope this is found to be useful.
USE tempdb
GO
IF OBJECT_ID('tempdb.dbo.#ArbDates') IS NOT NULL DROP TABLE #ArbDates
DECLARE @Stopwatch DATETIME
----------------------------------
-- Build test data: 100000 rows
----------------------------------
;WITH Base10 (n) AS
(
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1
)
,Base100000 (n) AS
(
SELECT 1
FROM Base10 T1, Base10 T3, Base10 T4, Base10 T5, Base10 T6
)
SELECT MyDate = CAST(RAND(CHECKSUM(NEWID()))*3653.0+36524.0 AS DATETIME)
INTO #ArbDates
FROM Base100000
----------------------------------
-- Monitor time differences
----------------------------------
SET @Stopwatch = GETDATE()
-- NOT SARGABLE
SELECT *
FROM #ArbDates
WHERE DATEDIFF(DAY, MyDate, '2010-01-01') < 365
PRINT DATEDIFF(MS, @Stopwatch, GETDATE())
SET @Stopwatch = GETDATE()
-- SARGABLE
SELECT *
FROM #ArbDates
WHERE MyDate > DATEADD(DAY, -364, '2010-01-01')
PRINT DATEDIFF(MS, @Stopwatch, GETDATE())
View
<input type="text" name="name"/>
<input type="text" name="class"/>
Controller
function __construct()
{
parent:: __construct();
$this->load->Model('Model');
}
function index()
{
$this->load->view('view');
}
function user(){
if (isset($_POST['submit'])){
$data = array('name'=>$_POST['name'],
'class'=>$_POST['class']);
$this->Model->insert($data);
}
}
Model
function insert($data)
{
$this->db->insert('table_name',$data);
return true;
}
$(document).ready(function () {
$('#allot').click(function () {
if ($(this).is(':checked')) {
alert("Allot Thai Gayo Bhai");
}
});
$('#transfer').click(function () {
if ($(this).is(':checked')) {
alert("Transfer Thai Gayo");
}
});
});
You have correctly used "CURLOPT_COOKIEJAR" (writing) but you also need to set "CURLOPT_COOKIEFILE" (reading)
curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE);
curl_setopt ($ch, CURLOPT_COOKIEFILE, COOKIE_FILE);
Using @fireant's idea, I wrote up a function to handle overlays. This works well for any position argument (including negative positions).
def overlay_image_alpha(img, img_overlay, pos, alpha_mask):
"""Overlay img_overlay on top of img at the position specified by
pos and blend using alpha_mask.
Alpha mask must contain values within the range [0, 1] and be the
same size as img_overlay.
"""
x, y = pos
# Image ranges
y1, y2 = max(0, y), min(img.shape[0], y + img_overlay.shape[0])
x1, x2 = max(0, x), min(img.shape[1], x + img_overlay.shape[1])
# Overlay ranges
y1o, y2o = max(0, -y), min(img_overlay.shape[0], img.shape[0] - y)
x1o, x2o = max(0, -x), min(img_overlay.shape[1], img.shape[1] - x)
# Exit if nothing to do
if y1 >= y2 or x1 >= x2 or y1o >= y2o or x1o >= x2o:
return
channels = img.shape[2]
alpha = alpha_mask[y1o:y2o, x1o:x2o]
alpha_inv = 1.0 - alpha
for c in range(channels):
img[y1:y2, x1:x2, c] = (alpha * img_overlay[y1o:y2o, x1o:x2o, c] +
alpha_inv * img[y1:y2, x1:x2, c])
Usage is:
overlay_image_alpha(img_large,
img_small[:, :, 0:3],
(x, y),
img_small[:, :, 3] / 255.0)
Try this code snippet
BufferedImage image = ImageIO.read(new File("filename.jpg"));
// Process image
ImageIO.write(image, "jpg", new File("output.jpg"));
Kruskal can have better performance if the edges can be sorted in linear time, or are already sorted.
Prim's better if the number of edges to vertices is high.
Here change n
value according your requirement:
SELECT top 1 amount
FROM (
SELECT DISTINCT top n amount
FROM payment
ORDER BY amount DESC ) AS temp
ORDER BY amount
For Laravel 4 & 5:
server.php
in your Laravel root folder to index.php
.htaccess
file from /public
directory to your Laravel root folder.That's it !! :)
Try this:
HTML:
<table width="200" border="1" class="table">
<tr>
<td><a href="#"> </a></td>
<td> </td>
<td> </td>
</tr>
</table>
CSS:
.table a
{
display:block;
text-decoration:none;
}
I hope it will work fine.
You should remove the &
(ampersand) symbol, so that line 4 will look like this:
$conn = ADONewConnection($config['db_type']);
This is because ADONewConnection already returns an object by reference. As per documentation, assigning the result of a reference to object by reference results in an E_DEPRECATED message as of PHP 5.3.0
//loop it until number occurrences comes to 0. OR simply copy/paste
function replaceAll(find, replace, str)
{
while( str.indexOf(find) > -1)
{
str = str.replace(find, replace);
}
return str;
}
I couldn't find solution for other browsers. When I posted this question, IE was on the higher priority and gladly I found one for it. If you have a solution for other browsers (firefox, safari, opera) please do share here. Thanks.
VBSCRIPT is much more convenient than creating an ActiveX on VB6 or C#/VB.NET:
<script language='VBScript'>
Sub Print()
OLECMDID_PRINT = 6
OLECMDEXECOPT_DONTPROMPTUSER = 2
OLECMDEXECOPT_PROMPTUSER = 1
call WB.ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER,1)
End Sub
document.write "<object ID='WB' WIDTH=0 HEIGHT=0 CLASSID='CLSID:8856F961-340A-11D0-A96B-00C04FD705A2'></object>"
</script>
Now, calling:
<a href="javascript:window.print();">Print</a>
will send print without popup print window.
Appending to and copying slices
The variadic function
append
appends zero or more valuesx
tos
of typeS
, which must be a slice type, and returns the resulting slice, also of typeS
. The valuesx
are passed to a parameter of type...T
whereT
is the element type ofS
and the respective parameter passing rules apply. As a special case, append also accepts a first argument assignable to type[]byte
with a second argument ofstring
type followed by...
. This form appends the bytes of the string.append(s S, x ...T) S // T is the element type of S s0 := []int{0, 0} s1 := append(s0, 2) // append a single element s1 == []int{0, 0, 2} s2 := append(s1, 3, 5, 7) // append multiple elements s2 == []int{0, 0, 2, 3, 5, 7} s3 := append(s2, s0...) // append a slice s3 == []int{0, 0, 2, 3, 5, 7, 0, 0}
Passing arguments to ... parameters
If
f
is variadic with final parameter type...T
, then within the function the argument is equivalent to a parameter of type[]T
. At each call off
, the argument passed to the final parameter is a new slice of type[]T
whose successive elements are the actual arguments, which all must be assignable to the typeT
. The length of the slice is therefore the number of arguments bound to the final parameter and may differ for each call site.
The answer to your question is example s3 := append(s2, s0...)
in the Go Programming Language Specification. For example,
s := append([]int{1, 2}, []int{3, 4}...)
redirect statement is legacy
use http-request redirect instead
acl http ssl_fc,not
http-request redirect scheme https if http
For anyone who, like me, just wants to sync up your local branch name with the remote branch name, here's a handy command:
git branch -u origin/$(git rev-parse --abbrev-ref HEAD)
You can use local redirect. Following codes are jumping the HomeController's Index page:
public class SharedController : Controller
{
// GET: /<controller>/
public IActionResult _Layout(string btnLogout)
{
if (btnLogout != null)
{
return LocalRedirect("~/Index");
}
return View();
}
}
HTML:
First, we will need to add a class to your text container so that we can access and style it accordingly.
<div class="col-xs-5 textContainer">
<h3 class="text-left">Link up with other gamers all over the world who share the same tastes in games.</h3>
</div>
CSS:
Next, we will apply the following styles to align it vertically, according to the size of the image div next to it.
.textContainer {
height: 345px;
line-height: 340px;
}
.textContainer h3 {
vertical-align: middle;
display: inline-block;
}
All Done! Adjust the line-height and height on the styles above if you believe that it is still slightly out of align.
call EnumProcesses()
and check if the PID is in the list.
http://msdn.microsoft.com/en-us/library/ms682629%28VS.85%29.aspx
find /home/www \( -type d -name .git -prune \) -o -type f -print0 | xargs -0 sed -i 's/subdomainA\.example\.com/subdomainB.example.com/g'
-print0
tells find
to print each of the results separated by a null character, rather than a new line. In the unlikely event that your directory has files with newlines in the names, this still lets xargs
work on the correct filenames.
\( -type d -name .git -prune \)
is an expression which completely skips over all directories named .git
. You could easily expand it, if you use SVN or have other folders you want to preserve -- just match against more names. It's roughly equivalent to -not -path .git
, but more efficient, because rather than checking every file in the directory, it skips it entirely. The -o
after it is required because of how -prune
actually works.
For more information, see man find
.
Java doesn't parse ISO dates correctly.
Similar to McKenzie's answer.
Just fix the Z
before parsing.
Code
String string = "2013-03-05T18:05:05.000Z";
String defaultTimezone = TimeZone.getDefault().getID();
Date date = (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")).parse(string.replaceAll("Z$", "+0000"));
System.out.println("string: " + string);
System.out.println("defaultTimezone: " + defaultTimezone);
System.out.println("date: " + (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")).format(date));
Result
string: 2013-03-05T18:05:05.000Z
defaultTimezone: America/New_York
date: 2013-03-05T13:05:05.000-0500
Why not use the function reverse on the shift input, and and join the plain_text with the shift, and input it as the cipher text:
Plain = int(input("enter a number "))
Rev = plain[::-1]
Cipher = " ".join(for cipher_text in Rev)
You want:
document.cookie = cookieName +"=" + cookieValue + ";domain=.example.com;path=/;expires=" + myDate;
As per the RFC 2109, to have a cookie available to all subdomains, you must put a .
in front of your domain.
Setting the path=/ will have the cookie be available within the entire specified domain(aka .example.com
).
Try This
File file=new File("Your File");
boolean renameResult = file.renameTo(new File("New Name"));
// todo: check renameResult
Note : We should always check the renameTo return value to make sure rename file is successful because it’s platform dependent(different Operating system, different file system) and it doesn’t throw IO exception if rename fails.
If you know the data and the action the installed package react on, you simply should add these information to your intent instance before starting it.
If you have access to the AndroidManifest of the other app, you can see all needed information there.
If you need an ordered dictionary, you can use odict.
Another very simple yet noobish mistake of mine: I simply forgot to add a message -m
modifier in my commit. So I wrote:
git commit 'My message'
Instead of correct:
git commit -m 'My message'
NOTE: It does NOT throw any errors! But you will not be able to push your commits and always get Everything up to date
instead
Here's a simple example using urllib2 that does a basic authentication against GitHub's API.
import urllib2
u='username'
p='userpass'
url='https://api.github.com/users/username'
# simple wrapper function to encode the username & pass
def encodeUserData(user, password):
return "Basic " + (user + ":" + password).encode("base64").rstrip()
# create the request object and set some headers
req = urllib2.Request(url)
req.add_header('Accept', 'application/json')
req.add_header("Content-type", "application/x-www-form-urlencoded")
req.add_header('Authorization', encodeUserData(u, p))
# make the request and print the results
res = urllib2.urlopen(req)
print res.read()
Furthermore if you wrap this in a script and run it from a terminal you can pipe the response string to 'mjson.tool' to enable pretty printing.
>> basicAuth.py | python -mjson.tool
One last thing to note, urllib2 only supports GET & POST requests.
If you need to use other HTTP verbs like DELETE, PUT, etc you'll probably want to take a look at PYCURL
Be aware, IBOutletCollection
should be @property (strong, nonatomic)
.
You need to run following command to kill the process. Find out the id of the process which you wanted to kill by
> show processlist;
Take the value from id column and fire below command
kill query <processId>;
Query parameter specifies that we need to kill query command process.
The syntax for kill process as follows
KILL [CONNECTION | QUERY] processlist_id
Please refer this link for more information.
If your OS is Windows, then it is very simple. When you install Android Studio, adb.exe is located in the following folder:
C:\Users\**your-user-name**\AppData\Local\Android\Sdk\platform-tools
Copy the path and paste in your environment variables.
Open your terminal and type: adb
it's done!
This should solve your problem: FB Share button/dialog documentation Genereally speaking you can use either normal HTML code and style it with CSS, or you can use Javascript.
Here is an example:
<a href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fparse.com" target="_blank" rel="noopener">
<img class="YOUR_FB_CSS_STYLING_CLASS" src="img/YOUR_FB_ICON_IMAGE.png" width="22px" height="22px" alt="Share on Facebook">
</a>
Replace https%3A%2F%2Fparse.com, YOUR_FB_CSS_STYLING_CLASS and YOUR_FB_ICON_IMAGE.png with your own choices and you should be ok.
Note: For the sake of your users' security use the HTTPS link to FB, like in the a's href attribute.
The advantage of the session storage over local storage, in my opinion, is that it has unlimited capacity in Firefox, and won't persist longer than the session. (Of course it depends on what your goal is.)
You need to add a reference to System.Web.Extensions.dll
in project for System.Web.Script.Serialization error.
using ByteArrayOutputStream and System.setXXX is simple:
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
private final PrintStream originalErr = System.err;
@Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
}
@After
public void restoreStreams() {
System.setOut(originalOut);
System.setErr(originalErr);
}
sample test cases:
@Test
public void out() {
System.out.print("hello");
assertEquals("hello", outContent.toString());
}
@Test
public void err() {
System.err.print("hello again");
assertEquals("hello again", errContent.toString());
}
I used this code to test the command line option (asserting that -version outputs the version string, etc etc)
Edit:
Prior versions of this answer called System.setOut(null)
after the tests; This is the cause of NullPointerExceptions commenters refer to.
The best answer is the one above about default arguments, but I had fun writing this, and it certainly does fit the bill for "multiple constructors". Use at your own risk.
What about the new method.
"Typical implementations create a new instance of the class by invoking the superclass’s new() method using super(currentclass, cls).new(cls[, ...]) with appropriate arguments and then modifying the newly-created instance as necessary before returning it."
So you can have the new method modify your class definition by attaching the appropriate constructor method.
class Cheese(object):
def __new__(cls, *args, **kwargs):
obj = super(Cheese, cls).__new__(cls)
num_holes = kwargs.get('num_holes', random_holes())
if num_holes == 0:
cls.__init__ = cls.foomethod
else:
cls.__init__ = cls.barmethod
return obj
def foomethod(self, *args, **kwargs):
print "foomethod called as __init__ for Cheese"
def barmethod(self, *args, **kwargs):
print "barmethod called as __init__ for Cheese"
if __name__ == "__main__":
parm = Cheese(num_holes=5)
Use below method,
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
If you want to use regular expression you can use as below,
public static boolean isNumeric(String str)
{
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
I agree with @adietisheim and the rest of people that suggest HttpClient.
I spent time trying to make a simple call to rest service with HttpURLConnection and it hadn't convinced me and after that I tried with HttpClient and it was really more easy, understandable and nice.
An example of code to make a put http call is as follows:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPut putRequest = new HttpPut(URI);
StringEntity input = new StringEntity(XML);
input.setContentType(CONTENT_TYPE);
putRequest.setEntity(input);
HttpResponse response = httpClient.execute(putRequest);
Edit: use
<=
or>=
to count today's date.
This is the right answer for your code. Just use the strtotime() php function.
$paymentDate = date('Y-m-d');
$paymentDate=date('Y-m-d', strtotime($paymentDate));
//echo $paymentDate; // echos today!
$contractDateBegin = date('Y-m-d', strtotime("01/01/2001"));
$contractDateEnd = date('Y-m-d', strtotime("01/01/2012"));
if (($paymentDate >= $contractDateBegin) && ($paymentDate <= $contractDateEnd)){
echo "is between";
}else{
echo "NO GO!";
}
Try wrapping the spans in an anchor tag and apply the background image to that.
HTML:
<div class="header">
<a href="/">
<span class="header-title">My gray sea design</span><br />
<span class="header-title-two">A beautiful design</span>
</a>
</div>
CSS:
.header {
border-bottom:1px solid #eaeaea;
}
.header a {
display: block;
background-image: url("./images/embouchure.jpg");
background-repeat: no-repeat;
height:160px;
padding-left:280px;
padding-top:50px;
width:470px;
color: #eaeaea;
}
The max length of a varchar is subject to the max row size in MySQL, which is 64KB (not counting BLOBs):
VARCHAR(65535)
However, note that the limit is lower if you use a multi-byte character set:
VARCHAR(21844) CHARACTER SET utf8
Here are some examples:
The maximum row size is 65535, but a varchar also includes a byte or two to encode the length of a given string. So you actually can't declare a varchar of the maximum row size, even if it's the only column in the table.
mysql> CREATE TABLE foo ( v VARCHAR(65534) );
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs
But if we try decreasing lengths, we find the greatest length that works:
mysql> CREATE TABLE foo ( v VARCHAR(65532) );
Query OK, 0 rows affected (0.01 sec)
Now if we try to use a multibyte charset at the table level, we find that it counts each character as multiple bytes. UTF8 strings don't necessarily use multiple bytes per string, but MySQL can't assume you'll restrict all your future inserts to single-byte characters.
mysql> CREATE TABLE foo ( v VARCHAR(65532) ) CHARSET=utf8;
ERROR 1074 (42000): Column length too big for column 'v' (max = 21845); use BLOB or TEXT instead
In spite of what the last error told us, InnoDB still doesn't like a length of 21845.
mysql> CREATE TABLE foo ( v VARCHAR(21845) ) CHARSET=utf8;
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs
This makes perfect sense, if you calculate that 21845*3 = 65535, which wouldn't have worked anyway. Whereas 21844*3 = 65532, which does work.
mysql> CREATE TABLE foo ( v VARCHAR(21844) ) CHARSET=utf8;
Query OK, 0 rows affected (0.32 sec)
Just revisiting an old solution, I thought I'd give it a facelift for it's ~5 year anniversary!
click
event to all header (th
) cells...
table
, find all rows (except the first)... const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent;_x000D_
_x000D_
const comparer = (idx, asc) => (a, b) => ((v1, v2) => _x000D_
v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)_x000D_
)(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));_x000D_
_x000D_
// do the work..._x000D_
document.querySelectorAll('th').forEach(th => th.addEventListener('click', (() => {_x000D_
const table = th.closest('table');_x000D_
Array.from(table.querySelectorAll('tr:nth-child(n+2)'))_x000D_
.sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc))_x000D_
.forEach(tr => table.appendChild(tr) );_x000D_
})));
_x000D_
table, th, td {_x000D_
border: 1px solid black;_x000D_
}_x000D_
th {_x000D_
cursor: pointer;_x000D_
}
_x000D_
<table>_x000D_
<tr><th>Country</th><th>Date</th><th>Size</th></tr>_x000D_
<tr><td>France</td><td>2001-01-01</td><td><i>25</i></td></tr>_x000D_
<tr><td><a href=#>spain</a></td><td><i>2005-05-05</i></td><td></td></tr>_x000D_
<tr><td><b>Lebanon</b></td><td><a href=#>2002-02-02</a></td><td><b>-17</b></td></tr>_x000D_
<tr><td><i>Argentina</i></td><td>2005-04-04</td><td><a href=#>100</a></td></tr>_x000D_
<tr><td>USA</td><td></td><td>-6</td></tr>_x000D_
</table>
_x000D_
If you want to support IE11, you'll need to ditch the ES6 syntax and use alternatives to Array.from
and Element.closest
.
var getCellValue = function(tr, idx){ return tr.children[idx].innerText || tr.children[idx].textContent; }
var comparer = function(idx, asc) { return function(a, b) { return function(v1, v2) {
return v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2);
}(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
}};
// do the work...
Array.prototype.slice.call(document.querySelectorAll('th')).forEach(function(th) { th.addEventListener('click', function() {
var table = th.parentNode
while(table.tagName.toUpperCase() != 'TABLE') table = table.parentNode;
Array.prototype.slice.call(table.querySelectorAll('tr:nth-child(n+2)'))
.sort(comparer(Array.prototype.slice.call(th.parentNode.children).indexOf(th), this.asc = !this.asc))
.forEach(function(tr) { table.appendChild(tr) });
})
});
If you want new columns showing year and month separately you can do this:
df['year'] = pd.DatetimeIndex(df['ArrivalDate']).year
df['month'] = pd.DatetimeIndex(df['ArrivalDate']).month
or...
df['year'] = df['ArrivalDate'].dt.year
df['month'] = df['ArrivalDate'].dt.month
Then you can combine them or work with them just as they are.
Just do select date(timestamp_column)
and you would get the only the date part.
Sometimes doing select timestamp_column::date
may return date 00:00:00
where it doesn't remove the 00:00:00
part. But I have seen date(timestamp_column)
to work perfectly in all the cases. Hope this helps.
Here you can find a complete guide for MySQL case statements in SQL.
CASE
WHEN some_condition THEN return_some_value
ELSE return_some_other_value
END
See the above definition where it states that a callback function is passed off to some other function and at some point it is called.
In C++ it is desirable to have callback functions call a classes method. When you do this you have access to the member data. If you use the C way of defining a callback you will have to point it to a static member function. This is not very desirable.
Here is how you can use callbacks in C++. Assume 4 files. A pair of .CPP/.H files for each class. Class C1 is the class with a method we want to callback. C2 calls back to C1's method. In this example the callback function takes 1 parameter which I added for the readers sake. The example doesn't show any objects being instantiated and used. One use case for this implementation is when you have one class that reads and stores data into temporary space and another that post processes the data. With a callback function, for every row of data read the callback can then process it. This technique cuts outs the overhead of the temporary space required. It is particularly useful for SQL queries that return a large amount of data which then has to be post-processed.
/////////////////////////////////////////////////////////////////////
// C1 H file
class C1
{
public:
C1() {};
~C1() {};
void CALLBACK F1(int i);
};
/////////////////////////////////////////////////////////////////////
// C1 CPP file
void CALLBACK C1::F1(int i)
{
// Do stuff with C1, its methods and data, and even do stuff with the passed in parameter
}
/////////////////////////////////////////////////////////////////////
// C2 H File
class C1; // Forward declaration
class C2
{
typedef void (CALLBACK C1::* pfnCallBack)(int i);
public:
C2() {};
~C2() {};
void Fn(C1 * pThat,pfnCallBack pFn);
};
/////////////////////////////////////////////////////////////////////
// C2 CPP File
void C2::Fn(C1 * pThat,pfnCallBack pFn)
{
// Call a non-static method in C1
int i = 1;
(pThat->*pFn)(i);
}
Use direct URL of whatsapp
String url = "https://api.whatsapp.com/send?phone="+number;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
Solution without charts
Function SelectionToPicture(nome)
'save location ( change if you want )
FName = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\" & nome & ".jpg"
'copy selection and get size
Selection.CopyPicture xlScreen, xlBitmap
w = Selection.Width
h = Selection.Height
With ThisWorkbook.ActiveSheet
.Activate
Dim chtObj As ChartObject
Set chtObj = .ChartObjects.Add(100, 30, 400, 250)
chtObj.Name = "TemporaryPictureChart"
'resize obj to picture size
chtObj.Width = w
chtObj.Height = h
ActiveSheet.ChartObjects("TemporaryPictureChart").Activate
ActiveChart.Paste
ActiveChart.Export FileName:=FName, FilterName:="jpg"
chtObj.Delete
End With
End Function
You can also use this convoluted command, which does not trigger a warning about terminating its own process:
osascript -e "do shell script \"osascript -e \\\"tell application \\\\\\\"Terminal\\\\\\\" to quit\\\" &> /dev/null &\""; exit
This command is quite long, so you could define an alias (such as quit
) in your bash profile:
alias quit='osascript -e "do shell script \"osascript -e \\\"tell application \\\\\\\"Terminal\\\\\\\" to quit\\\" &> /dev/null &\""; exit'
This would allow you to simply type quit
into terminal without having to fiddle with any other settings.
<!DOCTYPE html
PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en-US">
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon"
type="image/png"
href="http://example.com/myicon.png">
</head>
<body>
...
</body>
</html>
rel="shortcut icon"
should be rel="icon"
Source: W3C
lambda
is an anonymous function, not an arbitrary function. The parameter being accepted would be the variable you're working with, and the column in which you're sorting it on.
I don't think you can use fractional seconds with to_date or the DATE type in Oracle. I think you need to_timestamp which returns a TIMESTAMP type.
An even simpler way to do this is to use jQuery's toggleClass() method
CSS
.newClass{visibility: hidden}
HTML
<a href="#" class=trigger>Trigger Element </a>
<div class="hidden_element">Some Content</div>
JS
$(document).ready(function(){
$(".trigger").click(function(){
$(".hidden_element").toggleClass("newClass");
});
});
The previous answers have covered the traditional menu used in android. Their is another option you can use if you are looking for an alternative
https://github.com/AnshulBansal/Android-Pulley-Menu
Pulley menu is an alternate to the traditional Menu which allows user to select any option for an activity intuitively. The menu is revealed by dragging the screen downwards and in that gesture user can also select any of the options.
Installing using apt-get
installs a system wide pip
, not just a local one for your user. Try this command to get pip running on your system ...
$ sudo apt-get install python-pip python-dev build-essential
Then pip will be installed without any issues and you will be able to use "sudo pip...".
If you use mod_rewrite to hide the extension of your scripts, or if you just like pretty URLs that end in /, then you might want to approach this from the other direction. Tell nginx to let anything with a non-static extension to go through to apache. For example:
location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$
{
root /path/to/static-content;
}
location ~* ^!.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$ {
if (!-f $request_filename) {
return 404;
}
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
I found the first part of this snippet over at: http://code.google.com/p/scalr/wiki/NginxStatic
You can do these conversions also with the .NET Framework:
JSON to XML: by using System.Runtime.Serialization.Json
var xml = XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(
Encoding.ASCII.GetBytes(jsonString), new XmlDictionaryReaderQuotas()));
XML to JSON: by using System.Web.Script.Serialization
var json = new JavaScriptSerializer().Serialize(GetXmlData(XElement.Parse(xmlString)));
private static Dictionary<string, object> GetXmlData(XElement xml)
{
var attr = xml.Attributes().ToDictionary(d => d.Name.LocalName, d => (object)d.Value);
if (xml.HasElements) attr.Add("_value", xml.Elements().Select(e => GetXmlData(e)));
else if (!xml.IsEmpty) attr.Add("_value", xml.Value);
return new Dictionary<string, object> { { xml.Name.LocalName, attr } };
}
All of the answers posted so far are correct, an endpoint is simply one end of a communication channel. In the case of OAuth, there are three endpoints you need to be concerned with:
Hope that helps clear things up. Have fun learning about OAuth! Post more questions if you run into any difficulties implementing an OAuth client.
This might be a little off topic, but you can pretty easily download a file using Powershell. Powershell comes with modern versions of Windows so you don't have to install any extra stuff on the computer. I learned how to do it by reading this page:
http://teusje.wordpress.com/2011/02/19/download-file-with-powershell/
The code was:
$webclient = New-Object System.Net.WebClient
$url = "http://www.example.com/file.txt"
$file = "$pwd\file.txt"
$webclient.DownloadFile($url,$file)
You could just divide your two numbers and multiply by 100. Note that this will throw an error if "whole" is 0, as asking what percentage of 0 a number is does not make sense:
def percentage(part, whole):
return 100 * float(part)/float(whole)
Or with a % at the end:
def percentage(part, whole):
Percentage = 100 * float(part)/float(whole)
return str(Percentage) + “%”
Or if the question you wanted it to answer was "what is 5% of 20", rather than "what percentage is 5 of 20" (a different interpretation of the question inspired by Carl Smith's answer), you would write:
def percentage(percent, whole):
return (percent * whole) / 100.0
Insert some vertical space
blah blah blah \\
\vspace{1cm}
to scale to the font, use ex
(the height of a lowercase "x") as the unit, and there are various predefined lengths related to the line spacing available, you might be particularly interested in baselineskip
.
var app = angular.module('myapp', []);
app.filter('htmlToPlaintext', function()
{
return function(text)
{
return text ? String(text).replace(/<[^>]+>/gm, '') : '';
};
});
<p>{{DetailblogList.description | htmlToPlaintext}}</p>
To produce key events without Windows Forms Context, We can use the following method,
[DllImport("user32.dll")]
public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
sample code is given below:
const int VK_UP = 0x26; //up key
const int VK_DOWN = 0x28; //down key
const int VK_LEFT = 0x25;
const int VK_RIGHT = 0x27;
const uint KEYEVENTF_KEYUP = 0x0002;
const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
int press()
{
//Press the key
keybd_event((byte)VK_UP, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
return 0;
}
List of Virtual Keys are defined here.
To get the complete picture, please use the below link, http://tksinghal.blogspot.in/2011/04/how-to-press-and-hold-keyboard-key.html
If an immutable map fits your needs then there is a library by google called guava (see also guava questions)
Guava provides an ImmutableMap with reliable user-specified iteration order. This ImmutableMap has O(1) performance for containsKey, get. Obviously put and remove are not supported.
ImmutableMap objects are constructed by using either the elegant static convenience methods of() and copyOf() or a Builder object.
In the model, write the below code;
public $timestamps = false;
This would work.
Explanation : By default laravel will expect created_at & updated_at column in your table. By making it to false it will override the default setting.
Let's say for example in one case, if you want to locked cells from range A1 to I50 then below is the code:
Worksheets("Enter your sheet name").Range("A1:I50").Locked = True
ActiveSheet.Protect Password:="Enter your Password"
In another case if you already have a protected sheet then follow below code:
ActiveSheet.Unprotect Password:="Enter your Password"
Worksheets("Enter your sheet name").Range("A1:I50").Locked = True
ActiveSheet.Protect Password:="Enter your Password"
val array2 = array :+ 4
//Array(1, 2, 3, 4)
Works also "reversed":
val array2 = 4 +: array
Array(4, 1, 2, 3)
There is also an "in-place" version:
var array = Array( 1, 2, 3 )
array +:= 4
//Array(4, 1, 2, 3)
array :+= 0
//Array(4, 1, 2, 3, 0)
Just is case somebody asks (like I did), this is also possible when one uses subplot2grid. For example:
import matplotlib.pyplot as plt
plt.subplot2grid((3,2), (0,1), rowspan=3)
plt.plot([2,3,4,5])
plt.tick_params(axis='y', which='both', labelleft='off', labelright='on')
plt.show()
It will show this:
I'm using Laravel 5.7 and tried all of the above answers but nothing seemed to be hitting the spot.
For me, it was a rather simple fix by removing the cache files created by Laravel.
It seemed that my changes were not being reflected, and therefore my application wasn't seeing the routes.
A bit overkill, but I decided to reset all my cache at the same time using the following commands:
php artisan route:clear
php artisan view:clear
php artisan cache:clear
The main one here is the first command which will delete the bootstrap/cache/routes.php
file.
The second command will remove the cached files for the views that are stored in the storage/framework/cache
folder.
Finally, the last command will clear the application cache.
You can use the familiar Matplotlib style calling a figure
and subplot
, but you simply need to specify the current axis using plt.gca()
. An example:
plt.figure(1)
plt.subplot(2,2,1)
df.A.plot() #no need to specify for first axis
plt.subplot(2,2,2)
df.B.plot(ax=plt.gca())
plt.subplot(2,2,3)
df.C.plot(ax=plt.gca())
etc...
Try to encode the XML using Apache XML serializer
//Serialize DOM
OutputFormat format = new OutputFormat (doc);
// as a String
StringWriter stringOut = new StringWriter ();
XMLSerializer serial = new XMLSerializer (stringOut,
format);
serial.serialize(doc);
// Display the XML
System.out.println(stringOut.toString());
Update t
SET
t.Column1=100
FROM
myTableA t
LEFT JOIN
myTableB t2
ON
t2.ID=t.ID
Replace myTableA
with your table name and replace Column1
with your column name.
After this simply LEFT JOIN to tableB. t
in this case is just an alias for myTableA
. t2
is an alias for your joined table, in my example that is myTableB
. If you don't like using t
or t2
use any alias name you prefer - it doesn't matter - I just happen to like using those.
The toString
is supposed to return a String
.
public String toString() {
return "Name: '" + this.name + "', Height: '" + this.height + "', Birthday: '" + this.bDay + "'";
}
I suggest you make use of your IDE's features to generate the toString
method. Don't hand-code it.
For instance, Eclipse can do so if you simply right-click on the source code and select Source > Generate toString
It depends on whether you are using JPA or Hibernate.
From the JPA 2.0 spec, the defaults are:
OneToMany: LAZY
ManyToOne: EAGER
ManyToMany: LAZY
OneToOne: EAGER
And in hibernate, all is Lazy
UPDATE:
The latest version of Hibernate aligns with the above JPA defaults.
You can achieve this with a conditional in an angular expression, such as:
<a href="#" class="{{ condition ? 'active' : '' }}">link</a>
That being said, I do find an angular directive to be the more "proper" way of doing it, even though outsourcing a lot of this mini-logic can somewhat pollute your code base.
I use conditionals for GUI styling every once in a while during development, because it's a little quicker than creating directives. I couldn't tell you an instance though in which they actually remained in the code base for long. In the end I either turn it into a directive or find a better way to solve the problem.
This program will open 26 sockets where you would be able to connect a lot of TCP clients to it.
#!usr/bin/python
from thread import *
import socket
import sys
def clientthread(conn):
buffer=""
while True:
data = conn.recv(8192)
buffer+=data
print buffer
#conn.sendall(reply)
conn.close()
def main():
try:
host = '192.168.1.3'
port = 6666
tot_socket = 26
list_sock = []
for i in range(tot_socket):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((host, port+i))
s.listen(10)
list_sock.append(s)
print "[*] Server listening on %s %d" %(host, (port+i))
while 1:
for j in range(len(list_sock)):
conn, addr = list_sock[j].accept()
print '[*] Connected with ' + addr[0] + ':' + str(addr[1])
start_new_thread(clientthread ,(conn,))
s.close()
except KeyboardInterrupt as msg:
sys.exit(0)
if __name__ == "__main__":
main()
Use composition not extends (yes I mean extends, as in a reference to the extends keyword in java and yes this is inheritance). Composition is superier because it completely shields your implementation, allowing you to change the implementation without impacting the users of your class.
I recommend trying something like this (I'm typing directly into this window, so buyer beware of syntax errors):
public LimitedSizeQueue implements Queue
{
private int maxSize;
private LinkedList storageArea;
public LimitedSizeQueue(final int maxSize)
{
this.maxSize = maxSize;
storageArea = new LinkedList();
}
public boolean offer(ElementType element)
{
if (storageArea.size() < maxSize)
{
storageArea.addFirst(element);
}
else
{
... remove last element;
storageArea.addFirst(element);
}
}
... the rest of this class
A better option (based on the answer by Asaf) might be to wrap the Apache Collections CircularFifoBuffer with a generic class. For example:
public LimitedSizeQueue<ElementType> implements Queue<ElementType>
{
private int maxSize;
private CircularFifoBuffer storageArea;
public LimitedSizeQueue(final int maxSize)
{
if (maxSize > 0)
{
this.maxSize = maxSize;
storateArea = new CircularFifoBuffer(maxSize);
}
else
{
throw new IllegalArgumentException("blah blah blah");
}
}
... implement the Queue interface using the CircularFifoBuffer class
}
Since value is the last entry, you can do:
metrics.sort_by(&:last)
You can use fetch optionally with await-try-catch
let photo = document.getElementById("image-file").files[0];
let formData = new FormData();
formData.append("photo", photo);
fetch('/upload/image', {method: "POST", body: formData});
async function SavePhoto(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
const ctrl = new AbortController() // timeout
setTimeout(() => ctrl.abort(), 5000);
try {
let r = await fetch('/upload/image',
{method: "POST", body: formData, signal: ctrl.signal});
console.log('HTTP response code:',r.status);
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Before selecting the file open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
<br><br>
(in stack overflow snippets there is problem with error handling, however in <a href="https://jsfiddle.net/Lamik/b8ed5x3y/5/">jsfiddle version</a> for 404 errors 4xx/5xx are <a href="https://stackoverflow.com/a/33355142/860099">not throwing</a> at all but we can read response status which contains code)
_x000D_
Old school approach - xhr
let photo = document.getElementById("image-file").files[0]; // file from input
let req = new XMLHttpRequest();
let formData = new FormData();
formData.append("photo", photo);
req.open("POST", '/upload/image');
req.send(formData);
function SavePhoto(e)
{
let user = { name:'john', age:34 };
let xhr = new XMLHttpRequest();
let formData = new FormData();
let photo = e.files[0];
formData.append("user", JSON.stringify(user));
formData.append("photo", photo);
xhr.onreadystatechange = state => { console.log(xhr.status); } // err handling
xhr.timeout = 5000;
xhr.open("POST", '/upload/image');
xhr.send(formData);
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Choose file and open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
<br><br>
(the stack overflow snippets, has some problem with error handling - the xhr.status is zero (instead of 404) which is similar to situation when we run script from file on <a href="https://stackoverflow.com/a/10173639/860099">local disc</a> - so I provide also js fiddle version which shows proper http error code <a href="https://jsfiddle.net/Lamik/k6jtq3uh/2/">here</a>)
_x000D_
SUMMARY
filename
formData parameter.Content-Type
to multipart/form-data
- this will be set automatically by browser./upload/image
you can use full address like http://.../upload/image
.multiple
attribute: <input multiple type=... />
, and attach all chosen files to formData in similar way (e.g. photo2=...files[2];
... formData.append("photo2", photo2);
)let user = {name:'john', age:34}
in this way: formData.append("user", JSON.stringify(user));
fetch
using AbortController
, for old approach by xhr.timeout= milisec
pmg is spot on about encapsulation; beyond hiding the function from other translation units (or rather, because of it), making functions static
can also confer performance benefits in the presence of compiler optimizations.
Because a static
function cannot be called from anywhere outside of the current translation unit (unless the code takes a pointer to its address), the compiler controls all the call points into it.
This means that it is free to use a non-standard ABI, inline it entirely, or perform any number of other optimizations that might not be possible for a function with external linkage.
Map<String, String> d = new HashMap<>();
void input(String u, String p, String e) {
read();
if (e.equals("login")) login(u, p);
else if (e.equals("register")) register(u, p);
write();
}
void read() {
d = new HashMap<>();
String s = "";
try {
s = new String(Files.readAllBytes(Paths.get("data.txt")));
}catch(IOException e) {
e.printStackTrace();
}
String [] pairs = s.split("\n");
for (int i = 0; i < pairs.length; i++) {
d.put(pairs[i].split(",")[0], pairs[i].split(",")[1]);
}
}
void write() {
try (FileWriter m = new FileWriter("data.txt")) {
for (Map.Entry<String, String> entry : d.entrySet()) {
m.write(entry.getKey() + "," + entry.getValue() + "\n");
}
m.close();
}catch (IOException e) {
e.printStackTrace();
}
}
boolean login(String u, String p) {
return (d.get(u).equals(p)) ? true : false;
}
boolean register(String u, String p) {
if (d.containsKey(u)) return false;
d.put(u, p);
return true;
}
Having the ability to add small animations to a PDF (portable document format, independent of application software, hardware, and operating systems) would make it the perfect solution for making extremely useful user guides. Some text, some images, and some animations/videos, all in one file that can be read by anybody on any computer.
As of acrobat pro version x, a gif can be added under Tools > Insert from File. But the gif wont play, it only shows the first image.
I'm not sure if this is frowned upon or not, but this is how I do it...
Step 1 - I usually have a class that contains methods and variables that I want to access globally. In this example I'll call it the "App" class. Create a static Activity variable inside the class for each activity that your app has. Then create a static method called "close" that will run the finish()
method on each of those Activity variables if they are NOT null. If you have a main/parent activity, close it last:
public class App
{
////////////////////////////////////////////////////////////////
// INSTANTIATED ACTIVITY VARIABLES
////////////////////////////////////////////////////////////////
public static Activity activity1;
public static Activity activity2;
public static Activity activity3;
////////////////////////////////////////////////////////////////
// CLOSE APP METHOD
////////////////////////////////////////////////////////////////
public static void close()
{
if (App.activity3 != null) {App.activity3.finish();}
if (App.activity2 != null) {App.activity2.finish();}
if (App.activity1 != null) {App.activity1.finish();}
}
}
Step 2 - in each of your activities, override the onStart()
and onDestroy()
methods. In onStart()
, set the static variable in your App class equal to "this
". In onDestroy()
, set it equal to null
. For example, in the "Activity1" class:
@Override
public void onStart()
{
// RUN SUPER | REGISTER ACTIVITY AS INSTANTIATED IN APP CLASS
super.onStart();
App.activity1 = this;
}
@Override
public void onDestroy()
{
// RUN SUPER | REGISTER ACTIVITY AS NULL IN APP CLASS
super.onDestroy();
App.activity1 = null;
}
Step 3 - When you want to close your app, simply call App.close()
from anywhere. All instantiated activities will close! Since you are only closing activities and not killing the app itself (as in your examples), Android is free to take over from there and do any necessary cleanup.
Again, I don't know if this would be frowned upon for any reason. If so, I'd love to read comments on why it is and how it can be improved!
If your table t1 and it's backup t2 have many columns, here's a compact way to do it.
In addition, my related problem was that only some of the columns were modified and many rows had no edits to these columns, so I wanted to leave those alone - basically restore a subset of columns from a backup of the entire table. If you want to just restore all rows, skip the where clause.
Of course the simpler way would be to delete and insert as select, but in my case I needed a solution with just updates.
The trick is that when you do select * from a pair of tables with duplicate column names, the 2nd one will get named _1. So here's what I came up with:
update (
select * from t1 join t2 on t2.id = t1.id
where id in (
select id from (
select id, col1, col2, ... from t2
minus select id, col1, col2, ... from t1
)
)
) set col1=col1_1, col2=col2_1, ...
Try this:
npm install -g gulp-sass
or
npm install --save gulp-sass
I don't know how it crazy it looks but it does the job really well
ascii2hex(){ a="$@";s=0000000;printf "$a" | hexdump | grep "^$s"| sed s/' '//g| sed s/^$s//;}
Created this when I was trying to see my name in HEX ;) use how can you use it :)
try this
input[type='text']
{
background:red !important;
}
The best way is to simply extract the date part using the SQL DATE() Function:
SELECT *
FROM table1
WHERE DATE(column_datetime) = @p_date;
I've just solved these exact errors myself. The key it seems is that your project.properties
file in your appcompat library project should use whatever the highest version of the API that your particular appcompat project has been written for (in your case it looks like v21). Easiest way I've found to tell is to look for the highest 'values-v**' folder inside the res folder (eg. values-v21
).
To clarify, in addition to the instructions at Support Library Setup, your appcompat/project.properties
file should have in it: target=android-21
(mine came with 19 instead).
Also ensure that you have the 'SDK Platform' to match that version installed (eg for v21 install Android 5.0 SDK Platform).
Alternatively if you don't want to use the appcompat at all, (I think) all you need to do is right click your project > Properties > Android > Library > Remove the reference to the appcompat. The errors will still show up for the appcompat project, but shouldn't affect your project after that.
You can use six and abc to construct a class for both python2 and python3 efficiently as follows:
import six
import abc
@six.add_metaclass(abc.ABCMeta)
class MyClass(object):
"""
documentation
"""
@abc.abstractmethod
def initialize(self, para=None):
"""
documentation
"""
raise NotImplementedError
Or you could figure out the exacting amount of hours and minutes and have that displayed by puttin it into the timer app that already exist in every iphone :)
The current object is explicitly passed to the method as the first parameter. self
is the conventional name. You can call it anything you want but it is strongly advised that you stick with this convention to avoid confusion.
You could achieve this with the use of anchors. Or more precisely the non use of them.
Controls are anchored by default to the top left of the form which means when the form size will be changed, their distance from the top left side of the form will remain constant. If you change the control anchor to bottom left, then the control will keep the same distance from the bottom and left sides of the form when the form if resized.
Turning off the anchor in a direction will keep the control centered in that direction when resizing.
NOTE: Turning off anchoring via the properties window in VS2015 may require entering None, None (instead of default Top,Left)
Using AspNetCore 2.x, you have to go a little different way:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class AuthorizeRoleAttribute : AuthorizeAttribute
{
public AuthorizeRoleAttribute(params YourEnum[] roles)
{
Policy = string.Join(",", roles.Select(r => r.GetDescription()));
}
}
just use it like this:
[Authorize(YourEnum.Role1, YourEnum.Role2)]
If you want to put a .gitignore file at the top level and make it work for any folder below it use /**/
.
E.g. to ignore all *.map
files in a /src/main/
folder and sub-folders use:
/src/main/**/*.map
Use D. See docs for further information.
It can be accomplished like this docs
$('input').trigger("keydown", {which: 50});
Use Shift+Del.
More info: Shift+Del combination key set a field to null when you filled a field by a value and you changed your decision and you want to make it null. It is useful and I amazed from the other answers that give strange solutions.
"npm install" replaces all dependencies in your node_modules installed with "npm link" with versions from npmjs (specified in your package.json)
VLookup
You can do it with a simple VLOOKUP formula. I've put the data in the same sheet, but you can also reference a different worksheet. For the price column just change the last value from 2 to 3, as you are referencing the third column of the matrix "A2:C4".
External Reference
To reference a cell of the same Workbook use the following pattern:
<Sheetname>!<Cell>
Example:
Table1!A1
To reference a cell of a different Workbook use this pattern:
[<Workbook_name>]<Sheetname>!<Cell>
Example:
[MyWorkbook]Table1!A1
I too faced the same issue. I had installed Oracle Express edition 10g in Windows XP OS using VMware and it was working fine. Since it was very awkward typing SQL queries in the SQL utility provided by 10g and since I was used to working with SQL developer, I installed 32 bit SQL developer in XP and tried connecting to my DB SID "XE". But the connection failed with error-ORA-12505 TNS listener doesn't currently know of SID given in connect descriptor. I was at sea as to how this problem occurred since it was working fine with the SQL utility and I had also created few Informatica mappings using the same. I did browse a lot on this stuff hither thither and applied the suggestions offered to me after pinging the status of "lsnrctl" on public forums but to no avail. However, this morning I tried creating a new connection again, and Voila, it worked with no issues. I am guessing after reading in few posts that sometimes listener listens before the DB connects or something(pardon me for my crude reference as I am a newbie here) but I suggest to just restart the machine and check again.
ALTER TABLE <tablename> CHANGE COLUMN <colname> <colname> VARCHAR(65536);
You have to list the column name twice, even if you aren't changing its name.
Note that after you make this change, the data type of the column will be MEDIUMTEXT
.
Miky D is correct, the MODIFY
command can do this more concisely.
Re the MEDIUMTEXT
thing: a MySQL row can be only 65535 bytes (not counting BLOB/TEXT columns). If you try to change a column to be too large, making the total size of the row 65536 or greater, you may get an error. If you try to declare a column of VARCHAR(65536)
then it's too large even if it's the only column in that table, so MySQL automatically converts it to a MEDIUMTEXT
data type.
mysql> create table foo (str varchar(300));
mysql> alter table foo modify str varchar(65536);
mysql> show create table foo;
CREATE TABLE `foo` (
`str` mediumtext
) ENGINE=MyISAM DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
I misread your original question, you want VARCHAR(65353)
, which MySQL can do, as long as that column size summed with the other columns in the table doesn't exceed 65535.
mysql> create table foo (str1 varchar(300), str2 varchar(300));
mysql> alter table foo modify str2 varchar(65353);
ERROR 1118 (42000): Row size too large.
The maximum row size for the used table type, not counting BLOBs, is 65535.
You have to change some columns to TEXT or BLOBs
An optional prefix
!
which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.
http://schacon.github.com/git/gitignore.html
*.json
!spec/*.json
From Start | Run open a command window. Assuming your environmental variables are set correctly start with the following:
C:\>sqlplus /nolog
SQL*Plus: Release 10.2.0.1.0 - Production on Tue Aug 26 10:40:44 2008
Copyright (c) 1982, 2005, Oracle. All rights reserved.
SQL> connect
Enter user-name: system
Enter password: <enter password if will not be visible>
Connected.
SQL> Exec DBMS_XDB.SETHTTPPORT(3010); [Assuming you want to have HTTP going to this port]
PL/SQL procedure successfully completed.
SQL>quit
then open browser and use 3010 port.
Try Visual Studio ? menu Tools ? Options ? ReSharper, Suspend button and Resume again (no need to close the window). This works in my case.