A UIImage
has a property imageOrientation
, which instructs the UIImageView
and other UIImage
consumers to rotate the raw image data. There's a good chance that this flag is being saved to the exif data in the uploaded jpeg image, but the program you use to view it is not honoring that flag.
To rotate the UIImage
to display properly when uploaded, you can use a category like this:
UIImage+fixOrientation.h
@interface UIImage (fixOrientation)
- (UIImage *)fixOrientation;
@end
UIImage+fixOrientation.m
@implementation UIImage (fixOrientation)
- (UIImage *)fixOrientation {
// No-op if the orientation is already correct
if (self.imageOrientation == UIImageOrientationUp) return self;
// We need to calculate the proper transformation to make the image upright.
// We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
CGAffineTransform transform = CGAffineTransformIdentity;
switch (self.imageOrientation) {
case UIImageOrientationDown:
case UIImageOrientationDownMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height);
transform = CGAffineTransformRotate(transform, M_PI);
break;
case UIImageOrientationLeft:
case UIImageOrientationLeftMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, 0);
transform = CGAffineTransformRotate(transform, M_PI_2);
break;
case UIImageOrientationRight:
case UIImageOrientationRightMirrored:
transform = CGAffineTransformTranslate(transform, 0, self.size.height);
transform = CGAffineTransformRotate(transform, -M_PI_2);
break;
case UIImageOrientationUp:
case UIImageOrientationUpMirrored:
break;
}
switch (self.imageOrientation) {
case UIImageOrientationUpMirrored:
case UIImageOrientationDownMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, 0);
transform = CGAffineTransformScale(transform, -1, 1);
break;
case UIImageOrientationLeftMirrored:
case UIImageOrientationRightMirrored:
transform = CGAffineTransformTranslate(transform, self.size.height, 0);
transform = CGAffineTransformScale(transform, -1, 1);
break;
case UIImageOrientationUp:
case UIImageOrientationDown:
case UIImageOrientationLeft:
case UIImageOrientationRight:
break;
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
CGContextRef ctx = CGBitmapContextCreate(NULL, self.size.width, self.size.height,
CGImageGetBitsPerComponent(self.CGImage), 0,
CGImageGetColorSpace(self.CGImage),
CGImageGetBitmapInfo(self.CGImage));
CGContextConcatCTM(ctx, transform);
switch (self.imageOrientation) {
case UIImageOrientationLeft:
case UIImageOrientationLeftMirrored:
case UIImageOrientationRight:
case UIImageOrientationRightMirrored:
// Grr...
CGContextDrawImage(ctx, CGRectMake(0,0,self.size.height,self.size.width), self.CGImage);
break;
default:
CGContextDrawImage(ctx, CGRectMake(0,0,self.size.width,self.size.height), self.CGImage);
break;
}
// And now we just create a new UIImage from the drawing context
CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
UIImage *img = [UIImage imageWithCGImage:cgimg];
CGContextRelease(ctx);
CGImageRelease(cgimg);
return img;
}
@end
use this artisan command for create shortcut in public folder
php artisan storage:link
Than you will able to access posted img or file
I'm using virtualenvwrapper and don't want to modify $PATH, here's how:
$ which python3
/usr/local/bin/python3
$ mkvirtualenv --python=/usr/local/bin/python3 env_name
check fast buttons and chost clicks from google https://developers.google.com/mobile/articles/fast_buttons
By default, Valgrind writes its output to stderr. So you need to do something like:
valgrind a.out > log.txt 2>&1
Alternatively, you can tell Valgrind to write somewhere else; see http://valgrind.org/docs/manual/manual-core.html#manual-core.comment (but I've never tried this).
The difference in whether you have to instantiate your @InjectMocks
annotated field is in the version of Mockito, not in whether you use the MockitoJunitRunner or MockitoAnnotations.initMocks
. In 1.9, which will also handle some constructor injection of your @Mock
fields, it will do the instantiation for you. In earlier versions, you have to instantiate it yourself.
This is how I do unit testing of my Spring beans. There is no problem. People run into confusion when they want to use Spring configuration files to actually do the injection of the mocks, which is crossing up the point of unit tests and integration tests.
And of course the unit under test is an Impl. You need to test a real concrete thing, right? Even if you declared it as an interface you would have to instantiate the real thing to test it. Now, you could get into spies, which are stub/mock wrappers around real objects, but that should be for corner cases.
create below stored procedure in your db(from which db u want to delete sp's)
then right click on that procedure - click on Execute Stored Procedure..
then click ok.
create Procedure [dbo].[DeleteAllProcedures]
As
declare @schemaName varchar(500)
declare @procName varchar(500)
declare cur cursor
for select s.Name, p.Name from sys.procedures p
INNER JOIN sys.schemas s ON p.schema_id = s.schema_id
WHERE p.type = 'P' and is_ms_shipped = 0 and p.name not like 'sp[_]%diagram%'
ORDER BY s.Name, p.Name
open cur
fetch next from cur into @schemaName,@procName
while @@fetch_status = 0
begin
if @procName <> 'DeleteAllProcedures'
exec('drop procedure ' + @schemaName + '.' + @procName)
fetch next from cur into @schemaName,@procName
end
close cur
deallocate cur
It seems that the most accurate (and seamless) method of adding the padding for iPhone X/8 using env()...
padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);
Here's a link describing this:
Relatively straightforward solution:
From the first character you want to copy, hold Shift down and go all the way to the end.
Press Ctrl+K, which cuts the text from the file.
Press Ctrl+X, and then N to not save any changes.
Paste the cut text anywhere you want.
Alternatively, if your text fits into the screen, you can simply use mouse to select and it automatically copies it to clipboard.
Several answers here use range
. xrange
is generally better as it returns a generator, rather than a fully-instantiated list. Where memory and or iterables of widely-varying lengths can be an issue, xrange
is superior.
Through discourse it's clear that the problem lies in using VS2010 to write the query, as it uses the canonical CONCAT()
function which is limited to 2 parameters. There's probably a way to change that, but I'm not aware of it.
An alternative:
SELECT '1'+'2'+'3'
This approach requires non-string values to be cast/converted to strings, as well as NULL
handling via ISNULL()
or COALESCE()
:
SELECT ISNULL(CAST(Col1 AS VARCHAR(50)),'')
+ COALESCE(CONVERT(VARCHAR(50),Col2),'')
Because it will iterate over properties belonging to objects up the prototype chain if you're not careful.
You can use for.. in
, just be sure to check each property with hasOwnProperty.
Make sure to have your apache SSH dlls loading correctly. On a fresh install I had to download and load into my apache bin directory the following dll "libssh2.dll"
After ssl dll was loaded cURL was able to load with no issues.
You can download it from the link below:
Seems -C
option upto tar v2.8.3 does not work consistently on all the platforms (OSes). -C
option is said to add directory to the archive but on Mac and Ubuntu it adds absolute path prefix inside generated tar.gz file.
tar target_path/file.tar.gz -C source_path/source_dir
Therefore the consistent and robust solution is to cd
in to source_path (parent directory of source_dir) and run
tar target_path/file.tar.gz source_dir
or
tar -cf target_path/file.tar.gz source_dir
in your script. This will remove absolute path prefix in your generated tar.gz file's directory structure.
It took me a while to locate why the sample application works but mine don't.
The library (Foundation.Framework) that the author refer to is the system library (from OS) where the iphone sdk (I am using 3.0) is not support any more.
Therefore the sample application (from about.com, http://www.appsamuck.com/day1.html) works but ours don't.
Not 100%; however, it sounds like the heap is an object or set of allocated space (on RAM) that is built into the functionality of the code either Java itself or more likely functionality from ehcache itself, and the off-heap Ram is there own system as well; however, it sounds like this is one magnitude slower as it is not as organized, meaning it may not use a heap (meaning one long set of space of ram), and instead uses different address spaces likely making it slightly less efficient.
Then of course the next tier lower is hard-drive space itself.
I don't use ehcache, so you may not want to trust me, but that what is what I gathered from their documentation.
For the asynchronous dispatch case you describe above, you shouldn't need to check if you're on the main thread. As Bavarious indicates, this will simply be queued up to be run on the main thread.
However, if you attempt to do the above using a dispatch_sync()
and your callback is on the main thread, your application will deadlock at that point. I describe this in my answer here, because this behavior surprised me when moving some code from -performSelectorOnMainThread:
. As I mention there, I created a helper function:
void runOnMainQueueWithoutDeadlocking(void (^block)(void))
{
if ([NSThread isMainThread])
{
block();
}
else
{
dispatch_sync(dispatch_get_main_queue(), block);
}
}
which will run a block synchronously on the main thread if the method you're in isn't currently on the main thread, and just executes the block inline if it is. You can employ syntax like the following to use this:
runOnMainQueueWithoutDeadlocking(^{
//Do stuff
});
I solved by deleting the derived data and this time it worked correctly. Tried with Xcode 7.3.1GM
If you are trying to return back the ID within the scope, using the SCOPE_IDENTITY()
would be a better approach. I would not advice to use @@IDENTITY
, as this can return any ID.
CREATE PROC [dbo].[sp_Test] (
@myID int output,
@myFirstName nvarchar(50),
@myLastName nvarchar(50),
@myAddress nvarchar(50),
@myPort int
) AS
BEGIN
INSERT INTO Dvds (myFirstName, myLastName, myAddress, myPort)
VALUES (@myFirstName, @myLastName, @myAddress, @myPort);
SET @myID = SCOPE_IDENTITY();
END
GO
Like many others here, I had the same error. In my case it was because the execute permission was denied on a stored procedure it used. It was resolved when the user associated with the data source was given that permission.
.zip application/zip, application/octet-stream
In your invocation, the two functions are the same.
average
can compute a weighted average though.
There is an alternate form of Throwable.printStackTrace() that takes a print stream as an argument. http://download.oracle.com/javase/6/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)
E.g.
catch(Exception e) {
e.printStackTrace(System.out);
}
This will print the stack trace to std out instead of std error.
I believe telnet 74.255.12.25 8089
. Why don't u try both
Simply change body height < 300px (height of mobile viewport on landspace is around 300px to 500px)
JS
$( '.offcanvas-toggle' ).on( 'click', function() {
$( 'body' ).toggleClass( 'offcanvas-expanded' );
});
CSS
.offcanvas-expended { /* this is class added to body on click */
height: 200px;
}
.offcanvas {
height: 100%;
}
The chart control in the WPF Toolkit has a horrible bug: it never forgets any of the data points. So if you try to implement a floating chart you will get out of memory after round about 3000 DataPoint-objects. This bug has been reported to MS over a year ago but nobody seems to care...
pip list -v
can be used to list packages' install locations, introduced in https://pip.pypa.io/en/stable/news/#b1-2018-03-31
Show install locations when list command ran with “-v” option. (#979)
>pip list -v
Package Version Location Installer
------------------------ --------- -------------------------------------------------------------------- ---------
alabaster 0.7.12 c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
apipkg 1.5 c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
argcomplete 1.10.3 c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
astroid 2.3.3 c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
...
This feature is introduced in pip
10.0.0b1. On Ubuntu 18.04 (Bionic Beaver), pip
or pip3
installed with sudo apt install python-pip
or sudo apt install python3-pip
is 9.0.1 which doesn't have this feature.
Check https://github.com/pypa/pip/issues/5599 for suitable ways of upgrading pip
or pip3
.
const preloadImage = src =>
new Promise(r => {
const image = new Image()
image.onload = r
image.onerror = r
image.src = src
})
// Preload an image
await preloadImage('https://picsum.photos/100/100')
// Preload a bunch of images in parallel
await Promise.all(images.map(x => preloadImage(x.src)))
The below code will help you to auto open the .exe file from excel...
Sub Auto_Open()
Dim x As Variant
Dim Path As String
' Set the Path variable equal to the path of your program's installation
Path = "C:\Program Files\GameTop.com\Alien Shooter\game.exe"
x = Shell(Path, vbNormalFocus)
End Sub
Looking into this, it seems like the LibMan approach works best for my needs with adding Bootstrap. I like it because it is now built into Visual Studio 2017(15.8 or later) and has its own dialog boxes.
Update 6/11/2020: bootstrap 4.1.3 is now added by default with VS-2019.5 (Thanks to Harald S. Hanssen for noticing.)
The default method VS adds to projects uses Bower but it looks like it is on the way out. In the header of Microsofts bower page they write:
Following a couple links lead to Use LibMan with ASP.NET Core in Visual Studio where it shows how libs can be added using a built-in Dialog:
In Solution Explorer, right-click the project folder in which the files should be added. Choose Add > Client-Side Library. The Add Client-Side Library dialog appears: [source: Scott Addie 2018]
Then for bootstrap just (1) select the unpkg, (2) type in "bootstrap@.." (3) Install. After this, you would just want to verify all the includes in the _Layout.cshtml or other places are correct. They should be something like href="~/lib/bootstrap/dist/js/bootstrap...")
You can easily do this
const shopId = new URLSearchParams(window.location.search).get('shop_id');
console.log(shopId);
For the default scenarios I would suggest Pattern.split() as well but if you need maximum performance (especially on Android all solutions I tested are quite slow) and you only need to split by a single char, I now use my own method:
public static ArrayList<String> splitBySingleChar(final char[] s,
final char splitChar) {
final ArrayList<String> result = new ArrayList<String>();
final int length = s.length;
int offset = 0;
int count = 0;
for (int i = 0; i < length; i++) {
if (s[i] == splitChar) {
if (count > 0) {
result.add(new String(s, offset, count));
}
offset = i + 1;
count = 0;
} else {
count++;
}
}
if (count > 0) {
result.add(new String(s, offset, count));
}
return result;
}
Use "abc".toCharArray() to get the char array for a String. For example:
String s = " a bb ccc dddd eeeee ffffff ggggggg ";
ArrayList<String> result = splitBySingleChar(s.toCharArray(), ' ');
Thanks to Chris for his awesome answer, I took it one step further and automated the process of running those statements (my table had over 8,000 permissions)
if object_id('dbo.tempPermissions') is not null
Drop table dbo.tempPermissions
Create table tempPermissions(ID int identity , Queries Varchar(255))
Insert into tempPermissions(Queries)
select 'GRANT ' + dp.permission_name collate latin1_general_cs_as
+ ' ON ' + s.name + '.' + o.name + ' TO ' + dpr.name
FROM sys.database_permissions AS dp
INNER JOIN sys.objects AS o ON dp.major_id=o.object_id
INNER JOIN sys.schemas AS s ON o.schema_id = s.schema_id
INNER JOIN sys.database_principals AS dpr ON dp.grantee_principal_id=dpr.principal_id
WHERE dpr.name NOT IN ('public','guest')
declare @count int, @max int, @query Varchar(255)
set @count =1
set @max = (Select max(ID) from tempPermissions)
set @query = (Select Queries from tempPermissions where ID = @count)
while(@count < @max)
begin
exec(@query)
set @count += 1
set @query = (Select Queries from tempPermissions where ID = @count)
end
select * from tempPermissions
drop table tempPermissions
additionally to restrict it to a single table add:
and o.name = 'tablename'
after the WHERE dpr.name NOT IN ('public','guest') and remember to edit the select statement so that it generates statements for the table you want to grant permissions 'TO' Not the table the permissions are coming 'FROM' (which is what the script does).
Check <mvc:annotation-driven />
in dispatcherservlet.xml , if not add it.
And add
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
these dependencies in your pom.xml
Here's a basic one-liner based on the C-v
followed by I
method outlined above.
This command (:Comment
) adds a chosen string to the beginning of any selected lines.
command! -range -nargs=1 Comment :execute "'<,'>normal! <C-v>0I" . <f-args> . "<Esc><Esc>"
Add this line to your .vimrc
to create a command that accepts a single argument and places the argument at the beginning of every line in the current selection.
E.g. if the following text is selected:
1
2
and you run this: :Comment //
, the result will be:
//1
//2
For new Qt users this is a little more confusing than it seems if you are using QT Designer and .ui
files.
Initially I tried to use ui->setWindowTitle
, but that doesn't exist. ui
is not a QDialog
or a QMainWindow
.
The owner of the ui
is the QDialog
or QMainWindow
, the .ui
just describes how to lay it out. In that case, you would use:
this->setWindowTitle("New Title");
I hope this helps someone else.
We should first read the documentation on proxy_pass carefully and fully.
The URI passed to upstream server is determined based on whether "proxy_pass" directive is used with URI or not. Trailing slash in proxy_pass directive means that URI is present and equal to /
. Absense of trailing slash means hat URI is absent.
Proxy_pass with URI:
location /some_dir/ {
proxy_pass http://some_server/;
}
With the above, there's the following proxy:
http:// your_server/some_dir/ some_subdir/some_file ->
http:// some_server/ some_subdir/some_file
Basically, /some_dir/
gets replaced by /
to change the request path from /some_dir/some_subdir/some_file
to /some_subdir/some_file
.
Proxy_pass without URI:
location /some_dir/ {
proxy_pass http://some_server;
}
With the second (no trailing slash): the proxy goes like this:
http:// your_server /some_dir/some_subdir/some_file ->
http:// some_server /some_dir/some_subdir/some_file
Basically, the full original request path gets passed on without changes.
So, in your case, it seems you should just drop the trailing slash to get what you want.
Caveat
Note that automatic rewrite only works if you don't use variables in proxy_pass. If you use variables, you should do rewrite yourself:
location /some_dir/ {
rewrite /some_dir/(.*) /$1 break;
proxy_pass $upstream_server;
}
There are other cases where rewrite wouldn't work, that's why reading documentation is a must.
Reading your question again, it seems I may have missed that you just want to edit the html output.
For that, you can use the sub_filter directive. Something like ...
location /admin/ {
proxy_pass http://localhost:8080/;
sub_filter "http://your_server/" "http://your_server/admin/";
sub_filter_once off;
}
Basically, the string you want to replace and the replacement string
That will return an item. Simply change to:
if (ddlCustomerNumber.Items.FindByText( GetCustomerNumberCookie().ToString()) != null)
ddlCustomerNumber.SelectedIndex = 0;
Try this
body {
max-width: max-content;
margin: auto;
}
Using vlines
:
import numpy as np
np.random.seed(5)
x = arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
p = plot(x, y, "o")
vlines(70,100,250)
The basic call signatures are:
vlines(x, ymin, ymax)
hlines(y, xmin, xmax)
Xampp has the php application under: C:\xampp\php file directory ... if you input C:\xampp\php\php in CMD it should enter the php application.
For anyone else that may encounter this problem and it is not solved by either of the options above, this is what worked for me.
1. Click on the website in IIS
2. Double Click on Authentication under IIS
3. Enable Anonymous Authentication
I had disabled this because we were using our own Auth, but that lead to this same problem and the accepted answer did not help in any way.
I found a very simple solution that seems to be working :
s3 = boto3.client("s3")
s3.put_object(
Body=open("filename.csv").read(),
Bucket="your-bucket",
Key="your-key"
)
Hope that helps !
The line should read either:
0 0-23/2 * * * /home/username/test.sh
or
0 0,2,4,6,8,10,12,14,16,18,20,22 * * * /home/username/test.sh
The problem you have is related to TCP streaming nature.
The fact that you sent 100 Bytes (for example) from the server doesn't mean you will read 100 Bytes in the client the first time you read. Maybe the bytes sent from the server arrive in several TCP segments to the client.
You need to implement a loop in which you read until the whole message was received.
Let me provide an example with DataInputStream
instead of BufferedinputStream
. Something very simple to give you just an example.
Let's suppose you know beforehand the server is to send 100 Bytes of data.
In client you need to write:
byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";
try
{
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
while(!end)
{
int bytesRead = in.read(messageByte);
dataString += new String(messageByte, 0, bytesRead);
if (dataString.length == 100)
{
end = true;
}
}
System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
e.printStackTrace();
}
Now, typically the data size sent by one node (the server here) is not known beforehand. Then you need to define your own small protocol for the communication between server and client (or any two nodes) communicating with TCP.
The most common and simple is to define TLV: Type, Length, Value. So you define that every message sent form server to client comes with:
So you know you have to receive a minimum of 2 Bytes and with the second Byte you know how many following Bytes you need to read.
This is just a suggestion of a possible protocol. You could also get rid of "Type".
So it would be something like:
byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";
try
{
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
int bytesRead = 0;
messageByte[0] = in.readByte();
messageByte[1] = in.readByte();
int bytesToRead = messageByte[1];
while(!end)
{
bytesRead = in.read(messageByte);
dataString += new String(messageByte, 0, bytesRead);
if (dataString.length == bytesToRead )
{
end = true;
}
}
System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
e.printStackTrace();
}
The following code compiles and looks better. It assumes the first two bytes providing the length arrive in binary format, in network endianship (big endian). No focus on different encoding types for the rest of the message.
import java.nio.ByteBuffer;
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;
class Test
{
public static void main(String[] args)
{
byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";
try
{
Socket clientSocket;
ServerSocket server;
server = new ServerSocket(30501, 100);
clientSocket = server.accept();
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
int bytesRead = 0;
messageByte[0] = in.readByte();
messageByte[1] = in.readByte();
ByteBuffer byteBuffer = ByteBuffer.wrap(messageByte, 0, 2);
int bytesToRead = byteBuffer.getShort();
System.out.println("About to read " + bytesToRead + " octets");
//The following code shows in detail how to read from a TCP socket
while(!end)
{
bytesRead = in.read(messageByte);
dataString += new String(messageByte, 0, bytesRead);
if (dataString.length() == bytesToRead )
{
end = true;
}
}
//All the code in the loop can be replaced by these two lines
//in.readFully(messageByte, 0, bytesToRead);
//dataString = new String(messageByte, 0, bytesToRead);
System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
In Swift
To trim space & newline from both side of the String:
var url: String = "\n http://example.com/xyz.mp4 "
var trimmedUrl: String = url.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
You can import the css file on App.vue, inside the style tag.
<style>
@import './assets/styles/yourstyles.css';
</style>
Also, make sure you have the right loaders installed, if you need any.
With rabbitmqadmin
you can remove them with this one-liner:
rabbitmqadmin -f tsv -q list queues name | while read queue; do rabbitmqadmin -q delete queue name=${queue}; done
I just wanted to know if the dictionary i was going to try to pull data from had data in it in the first place, this seems to be simplest way.
d = {}
bool(d)
#should return
False
d = {'hello':'world'}
bool(d)
#should return
True
My Issue: The 'onbeforeunload' event would only be triggered if there were odd number of submits(clicks). I had a combination of solutions from similar threads in SO to have my solution work. well my code will speak.
<!--The definition of event and initializing the trigger flag--->
$(document).ready(function() {
updatefgallowPrompt(true);
window.onbeforeunload = WarnUser;
}
function WarnUser() {
var allowPrompt = getfgallowPrompt();
if(allowPrompt) {
saveIndexedDataAlert();
return null;
} else {
updatefgallowPrompt(true);
event.stopPropagation
}
}
<!--The method responsible for deciding weather the unload event is triggered from submit or not--->
function saveIndexedDataAlert() {
var allowPrompt = getfgallowPrompt();
var lenIndexedDocs = parseInt($('#sortable3 > li').size()) + parseInt($('#sortable3 > ul').size());
if(allowPrompt && $.trim(lenIndexedDocs) > 0) {
event.returnValue = "Your message";
} else {
event.returnValue = " ";
updatefgallowPrompt(true);
}
}
<!---Function responsible to reset the trigger flag---->
$(document).click(function(event) {
$('a').live('click', function() { updatefgallowPrompt(false); });
});
<!--getter and setter for the flag---->
function updatefgallowPrompt (allowPrompt){ //exit msg dfds
$('body').data('allowPrompt', allowPrompt);
}
function getfgallowPrompt(){
return $('body').data('allowPrompt');
}
If you are happy to use a 3rd party library, you can do this with Pandas. The benefits include seamless access to specialized methods and row / column labeling:
import pandas as pd
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
df = pd.DataFrame(list(zip(*[list1, list2, list3]))).add_prefix('Col')
df.to_csv('file.csv', index=False)
print(df)
Col0 Col1 Col2
0 1 4 7
1 2 5 8
2 3 6 9
If you're OK with viewing it as XML:
DECLARE @xmltmp xml = (SELECT * FROM table FOR XML AUTO)
PRINT CONVERT(NVARCHAR(MAX), @xmltmp)
While the OP's question as asked doesn't necessarily require this, it's useful if you got here looking to print multiple rows/columns (within reason).
Some responses focus on refactoring, rather than naming conventions, as the way to improve readability. I don't feel that one can replace the other.
I've known programmers who are uncomfortable with using local declarations; they prefer to place all the declarations at the top of a block (as in C), so they know where to find them. I've found that, where scoping allows for it, declaring variables where they're first used decreases the time that I spend glancing backwards to find the declarations. (This is true for me even for small functions.) That makes it easier for me to understand the code I'm looking at.
I hope it's clear enough how this relates to member naming conventions: When members are uniformly prefixed, I never have to look back at all; I know the declaration won't even be found in the source file.
I'm sure that I didn't start out preferring these styles. Yet over time, working in environments where they were used consistently, I optimized my thinking to take advantage of them. I think it's possible that many folks who currently feel uncomfortable with them would also come to prefer them, given consistent usage.
The standard function atoi()
will likely do what you want.
A simple example using "atoi":
#include <unistd.h>
int main(int argc, char *argv[])
{
int useconds = atoi(argv[1]);
usleep(useconds);
}
I presume you want to copy C:\OtherFolder\fileToCheck.bat to C:\MyFolder if the existing file in C:\MyFolder is either missing entirely, or if it is missing "stringToCheck".
FINDSTR sets ERRORLEVEL to 0 if the string is found, to 1 if it is not. It also sets errorlevel to 1 if the file is missing. It also prints out each line that matches. Since you are trying to use it as a condition, I presume you don't need or want to see any of the output. The 1st thing I would suggest is to redirect both the normal and error output to nul using >nul 2>&1
.
Solution 1 (mostly the same as previous answers)
You can use IF ERRORRLEVEL N
to check if the errorlevel is >= N. Or you can use IF NOT ERRORLEVEL N
to check if errorlevel is < N. In your case you want the former.
findstr /c:"stringToCheck" "c:\MyFolder\fileToCheck.bat" >nul 2>&1
if errorlevel 1 xcopy "C:\OtherFolder\fileToCheck.bat" "c:\MyFolder"
Solution 2
You can test for a specific value of errorlevel by using %ERRORLEVEL%. You can probably check if the value is equal to 1, but it might be safer to check if the value is not equal to 0, since it is only set to 0 if the file exists and it contains the string.
findstr /c:"stringToCheck" "c:\MyFolder\fileToCheck.bat" >nul 2>&1
if not %errorlevel% == 0 xcopy "C:\OtherFolder\fileToCheck.bat" "c:\MyFolder"
or
findstr /c:"stringToCheck" "c:\MyFolder\fileToCheck.bat" >nul 2>&1
if %errorlevel% neq 0 xcopy "C:\OtherFolder\fileToCheck.bat" "c:\MyFolder"
Solution 3
There is a very compact syntax to conditionally execute a command based on the success or failure of the previous command: cmd1 && cmd2 || cmd3
which means execute cmd2 if cmd1 was successful (errorlevel=0), else execute cmd3 if cmd1 failed (errorlevel<>0). You can use && alone, or || alone. All the commands need to be on the same line. If you need to conditionally execute multiple commands you can use multiple lines by adding parentheses
cmd1 && (
cmd2
cmd3
) || (
cmd4
cmd5
)
So for your case, all you need is
findstr /c:"stringToCheck" "c:\MyFolder\fileToCheck.bat" >nul 2>&1 || xcopy "C:\OtherFolder\fileToCheck.bat" "c:\MyFolder"
But beware - the ||
will respond to the return code of the last command executed. In my earlier pseudo code the ||
will obviously fire if cmd1 fails, but it will also fire if cmd1 succeeds but then cmd3 fails.
So if your success block ends with a command that may fail, then you should append a harmless command that is guaranteed to succeed. I like to use (CALL )
, which is harmless, and always succeeds. It also is handy that it sets the ERRORLEVEL to 0. There is a corollary (CALL)
that always fails and sets ERRORLEVEL to 1.
On Unix systems, for several projects, I added these lines into the CMakeLists.txt and it was compiling successfully because base (/usr/include) and local includes (/usr/local/include) go into separated directories:
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -I/usr/local/include -L/usr/local/lib")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/usr/local/include")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -L/usr/local/lib")
It appends the correct directory, including paths for the C and C++ compiler flags and the correct directory path for the linker flags.
Note: C++ compiler (c++) doesn't support -L, so we have to use CMAKE_EXE_LINKER_FLAGS
In this case you use -1.
Can you just just some
?
<div style="text-align: center">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="89px" OnClick="btnSubmit_Click" />
<asp:Button ID="btnClear" runat="server" Text="Clear" Width="89px" OnClick="btnClear_Click" />
</div>
Removed NOT operation in alpha-numeric validation. Moved variables to block level scope. Some comments here and there. Derived from the best Micheal
function isAlphaNumeric ( str ) {
/* Iterating character by character to get ASCII code for each character */
for ( let i = 0, len = str.length, code = 0; i < len; ++i ) {
/* Collecting charCode from i index value in a string */
code = str.charCodeAt( i );
/* Validating charCode falls into anyone category */
if (
( code > 47 && code < 58) // numeric (0-9)
|| ( code > 64 && code < 91) // upper alpha (A-Z)
|| ( code > 96 && code < 123 ) // lower alpha (a-z)
) {
continue;
}
/* If nothing satisfies then returning false */
return false
}
/* After validating all the characters and we returning success message*/
return true;
};
console.log(isAlphaNumeric("oye"));
console.log(isAlphaNumeric("oye123"));
console.log(isAlphaNumeric("oye%123"));
_x000D_
You want reorder()
. Here is an example with dummy data
set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))
require("ggplot2")
p1 <- ggplot(df, aes(x = Category, y = Count)) +
geom_bar(stat = "identity")
p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
geom_bar(stat = "identity")
require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))
Giving:
Use reorder(Category, Count)
to have Category
ordered from low-high.
Contributed by Stephane CHAZELAS on c.u.s. Assuming POSIX shell:
prg=$0
if [ ! -e "$prg" ]; then
case $prg in
(*/*) exit 1;;
(*) prg=$(command -v -- "$prg") || exit;;
esac
fi
dir=$(
cd -P -- "$(dirname -- "$prg")" && pwd -P
) || exit
prg=$dir/$(basename -- "$prg") || exit
printf '%s\n' "$prg"
You should be able to do this via the command line arguments, assuming these are Sun VMs installed using the usual Windows InstallShield mechanisms with the JVM finder EXE in system32.
Type java -help for the options. In particular, see:
-version:<value>
require the specified version to run
-jre-restrict-search | -jre-no-restrict-search
include/exclude user private JREs in the version search
Above things didn't work for me. Below solutions finally worked. Debug Configurations -> Classpath -> User Entries -> (Add src folder of the project you want to debug.)
The difference between getHeight()
and getMeasuredHeight()
is that first method will return actual height of the View
, the second one will return summary height of View
's children. In ohter words, getHeight()
returns view height, getMeasuredHeight()
returns height which this view needs to show all it's elements
There is a workaround in Java for the reference. Let me explain by this example:
public class Yo {
public static void foo(int x){
System.out.println(x); //out 2
x = x+2;
System.out.println(x); // out 4
}
public static void foo(int[] x){
System.out.println(x[0]); //1
x[0] = x[0]+2;
System.out.println(x[0]); //3
}
public static void main(String[] args) {
int t = 2;
foo(t);
System.out.println(t); // out 2 (t did not change in foo)
int[] tab = new int[]{1};
foo(tab);
System.out.println(tab[0]); // out 3 (tab[0] did change in foo)
}}
I hope this helps!
When you write "tests defined as class methods", do you really mean class methods (methods which receive its class as first parameter) or just regular methods (methods which receive an instance as first parameter)?
Since your example uses self
for the test methods I'm assuming the latter, so you just need to use setup_method
instead:
class Test:
def setup_method(self, test_method):
# configure self.attribute
def teardown_method(self, test_method):
# tear down self.attribute
def test_buttons(self):
# use self.attribute for test
The test method instance is passed to setup_method
and teardown_method
, but can be ignored if your setup/teardown code doesn't need to know the testing context. More information can be found here.
I also recommend that you familiarize yourself with py.test's fixtures, as they are a more powerful concept.
Ensure compiled dll of your project placed in proper bin folder.
In my case, when i have changed the compiled directory of our subproject to bin folder of our main project, it worked.
As matt burns says in his answer, you may need to enable CORS on the server where the problem images are hosted.
If the server is Apache, this can be done by adding the following snippet (from here) to either your VirtualHost config or an .htaccess
file:
<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
<FilesMatch "\.(cur|gif|ico|jpe?g|png|svgz?|webp)$">
SetEnvIf Origin ":" IS_CORS
Header set Access-Control-Allow-Origin "*" env=IS_CORS
</FilesMatch>
</IfModule>
</IfModule>
...if adding it to a VirtualHost, you'll probably need to reload Apache's config too (eg. sudo service apache2 reload
if Apache's running on a Linux server)
How to import CSV file data into a PostgreSQL table?
steps:
Need to connect postgresql database in terminal
psql -U postgres -h localhost
Need to create database
create database mydb;
Need to create user
create user siva with password 'mypass';
Connect with database
\c mydb;
Need to create schema
create schema trip;
Need to create table
create table trip.test(VendorID int,passenger_count int,trip_distance decimal,RatecodeID int,store_and_fwd_flag varchar,PULocationID int,DOLocationID int,payment_type decimal,fare_amount decimal,extra decimal,mta_tax decimal,tip_amount decimal,tolls_amount int,improvement_surcharge decimal,total_amount
);
Import csv file data to postgresql
COPY trip.test(VendorID int,passenger_count int,trip_distance decimal,RatecodeID int,store_and_fwd_flag varchar,PULocationID int,DOLocationID int,payment_type decimal,fare_amount decimal,extra decimal,mta_tax decimal,tip_amount decimal,tolls_amount int,improvement_surcharge decimal,total_amount) FROM '/home/Documents/trip.csv' DELIMITER ',' CSV HEADER;
Find the given table data
select * from trip.test;
Dockerfiles are to build an image for example from a bare bone Ubuntu, you can add mysql
called mySQL
on one image and mywordpress
on a second image called mywordpress
.
Compose YAML files are to take these images and run them cohesively.
For example, if you have in your docker-compose.yml
file a service called db
:
services:
db:
image: mySQL --- image that you built.
and a service called wordpress such as:
wordpress:
image: mywordpress
then inside the mywordpress container you can use db
to connect to your mySQL container. This magic is possible because your docker host create a network bridge (network overlay).
In Eclipse:
Window -> Preferences -> Android -> Lint Error Checking.
In the list find an entry with ID = ProtectedPermission
. Set the Severity to something lower than Error. This way you can still compile the project using Eclipse.
In Android Studio:
File -> Settings -> Editor -> Inspections
Under Android Lint
, locate Using system app permission
. Either uncheck the checkbox or choose a Severity lower than Error.
But you all forgot to mention, that if a variable table is used within a loop it will need emptying (delete @table) prior to loading with data again within a loop.
When doing recursive replacement, the path and filename need to be included:
Get-ChildItem -Recurse | ForEach { (Get-Content $_.PSPath |
ForEach {$ -creplace "old", "new"}) | Set-Content $_.PSPath }
This wil replace all "old" with "new" case-sensitive in all the files of your folders of your current directory.
Parent table data missing causes the problem. In your problem non availability of data in "dbo.Sup_Item_Cat" causes the problem
A callback function, also known as a higher-order function, is a function that is passed to another function as a parameter, and the callback function is called (or executed) inside the parent function.
$("#button_1").click(function() {
alert("button 1 Clicked");
});
Here we have pass a function as a parameter to the click method. And the click method will call (or execute) the callback function we passed to it.
Use a CSS style on the text box. Your CSS should be something like this:
.uppercase
{
text-transform: uppercase;
}
<asp:TextBox ID="TextBox1" runat="server" Text="" CssClass="uppercase"></asp:TextBox>;
A more modern version:
function arraysEqual(a, b) {
a = Array.isArray(a) ? a : [];
b = Array.isArray(b) ? b : [];
return a.length === b.length && a.every((el, ix) => el === b[ix]);
}
Coercing non-array arguments to empty arrays stops a.every()
from exploding.
If you just want to see if the arrays have the same set of elements then you can use Array.includes()
:
function arraysContainSame(a, b) {
a = Array.isArray(a) ? a : [];
b = Array.isArray(b) ? b : [];
return a.length === b.length && a.every(el => b.includes(el));
}
You don't need to use regex, LIKE
is sufficient:
WHERE my_field LIKE '[a-zA-Z][a-zA-Z]%'
Assuming that by "alphabetical" you mean only latin characters, not anything classified as alphabetical in Unicode.
Note - if your collation is case sensitive, it's important to specify the range as [a-zA-Z]
. [a-z]
may exclude A
or Z
. [A-Z]
may exclude a
or z
.
Repeat >> reads in loop.
#include <iostream>
#include <fstream>
int main(int argc, char * argv[])
{
std::fstream myfile("D:\\data.txt", std::ios_base::in);
float a;
while (myfile >> a)
{
printf("%f ", a);
}
getchar();
return 0;
}
Result:
45.779999 67.900002 87.000000 34.889999 346.000000 0.980000
If you know exactly, how many elements there are in a file, you can chain >> operator:
int main(int argc, char * argv[])
{
std::fstream myfile("D:\\data.txt", std::ios_base::in);
float a, b, c, d, e, f;
myfile >> a >> b >> c >> d >> e >> f;
printf("%f\t%f\t%f\t%f\t%f\t%f\n", a, b, c, d, e, f);
getchar();
return 0;
}
Edit: In response to your comments in main question.
You have two options.
Edit: How to skip values in file
To choose the 1234th value, use the following code:
int skipped = 1233;
for (int i = 0; i < skipped; i++)
{
float tmp;
myfile >> tmp;
}
myfile >> value;
ok. I solved it
SELECT `smart_projects`.project_id, `smart_projects`.business_id, `smart_projects`.title,
`page_pages`.`funnel_id` as `funnel_id`, count(distinct(page_pages.page_id) )as page_count, count(distinct (CASE WHEN page_pages.funnel_id != 0 then page_pages.funnel_id ELSE NULL END ) ) as funnel_count
FROM `smart_projects`
LEFT JOIN `page_pages` ON `smart_projects`.`project_id` = `page_pages`.`project_id`
WHERE smart_projects.status != 0
AND `smart_projects`.`business_id` = 'cd9412774edb11e9'
GROUP BY `smart_projects`.`project_id`
ORDER BY `title` DESC
The original question hinted that it would be nice to be able to filter all the properties based on a prefix. I have just confirmed that this works as of Spring Boot 2.1.1.RELEASE, for Properties
or Map<String,String>
. I'm sure it's worked for while now. Interestingly, it does not work without the prefix =
qualification, i.e. I do not know how to get the entire environment loaded into a map. As I said, this might actually be what OP wanted to begin with. The prefix and the following '.' will be stripped off, which might or might not be what one wants:
@ConfigurationProperties(prefix = "abc")
@Bean
public Properties getAsProperties() {
return new Properties();
}
@Bean
public MyService createService() {
Properties properties = getAsProperties();
return new MyService(properties);
}
Postscript: It is indeed possible, and shamefully easy, to get the entire environment. I don't know how this escaped me:
@ConfigurationProperties
@Bean
public Properties getProperties() {
return new Properties();
}
Use the ToString() method - standard and custom numeric format strings. Have a look at the MSDN article How to: Pad a Number with Leading Zeros.
string text = no.ToString("0000");
This method works on Mac OS X v10.7.5 (Lion):
find . | grep FooBar | xargs -I{} cp {} ~/foo/bar
I also tested the exact syntax you posted. That also worked fine on 10.7.5.
Yes, you are synchronizing correctly. I will explain this in more detail. You must synchronize two or more method calls on the synchronizedMap object only in a case you have to rely on results of previous method call(s) in the subsequent method call in the sequence of method calls on the synchronizedMap object. Let’s take a look at this code:
synchronized (synchronizedMap) {
if (synchronizedMap.containsKey(key)) {
synchronizedMap.get(key).add(value);
}
else {
List<String> valuesList = new ArrayList<String>();
valuesList.add(value);
synchronizedMap.put(key, valuesList);
}
}
In this code
synchronizedMap.get(key).add(value);
and
synchronizedMap.put(key, valuesList);
method calls are relied on the result of the previous
synchronizedMap.containsKey(key)
method call.
If the sequence of method calls were not synchronized the result might be wrong.
For example thread 1
is executing the method addToMap()
and thread 2
is executing the method doWork()
The sequence of method calls on the synchronizedMap
object might be as follows:
Thread 1
has executed the method
synchronizedMap.containsKey(key)
and the result is "true
".
After that operating system has switched execution control to thread 2
and it has executed
synchronizedMap.remove(key)
After that execution control has been switched back to the thread 1
and it has executed for example
synchronizedMap.get(key).add(value);
believing the synchronizedMap
object contains the key
and NullPointerException
will be thrown because synchronizedMap.get(key)
will return null
.
If the sequence of method calls on the synchronizedMap
object is not dependent on the results of each other then you don't need to synchronize the sequence.
For example you don't need to synchronize this sequence:
synchronizedMap.put(key1, valuesList1);
synchronizedMap.put(key2, valuesList2);
Here
synchronizedMap.put(key2, valuesList2);
method call does not rely on the results of the previous
synchronizedMap.put(key1, valuesList1);
method call (it does not care if some thread has interfered in between the two method calls and for example has removed the key1
).
I ran into a similar problem on a Linux server, where two versions of Boost have been installed. One is the precompiled 1.53.0 version which counts as old in 2018; it's in /usr/include
and /usr/lib64
. The version I want to use is 1.67.0, as a minimum version of 1.65.1 is required for another C++ library I'm installing; it's in /opt/boost
, which has include
and lib
subdirectories. As suggested in previous answers, I set variables in CMakeLists.txt
to specify where to look for Boost 1.67.0 as follows
include_directories(/opt/boost/include/)
include_directories(/opt/boost/lib/)
set(BOOST_ROOT /opt/boost/)
set(BOOST_INCLUDEDIR /opt/boost/include/)
set(BOOST_LIBRARYDIR /opt/boost/lib)
set(Boost_NO_SYSTEM_PATHS TRUE)
set(Boost_NO_BOOST_CMAKE TRUE)
But CMake doesn't honor those changes. Then I found an article online: CMake can use a local Boost, and realized that I need to change the variables in CMakeCache.txt
. There I found that the Boost-related variables are still pointing to the default Boost 1.53.0, so no wonder CMake doesn't honor my changes in CMakeLists.txt
. Then I set the Boost-related variables in CMakeCache.txt
Boost_DIR:PATH=Boost_DIR-NOTFOUND
Boost_INCLUDE_DIR:PATH=/opt/boost/include/
Boost_LIBRARY_DIR_DEBUG:PATH=/opt/boost/lib
Boost_LIBRARY_DIR_RELEASE:PATH=/opt/boost/lib
I also changed the variables pointing to the non-header, compiled parts of the Boost library to point to the version I want. Then CMake successfully built the library that depends on a recent version of Boost.
In Visual Studio 2008 + , go to the
Tools menu --> select Options
In Options Window --> expand Source Control --> Select Subversion User Tools --> Select Beyond Compare
and click OK button..
#!/usr/bin/env python
"""Print a field specified by row, column numbers from given csv file.
USAGE:
%prog csv_filename row_number column_number
"""
import csv
import sys
filename = sys.argv[1]
row_number, column_number = [int(arg, 10)-1 for arg in sys.argv[2:])]
with open(filename, 'rb') as f:
rows = list(csv.reader(f))
print rows[row_number][column_number]
$ python print-csv-field.py input.csv 2 2
ddddd
Note: list(csv.reader(f))
loads the whole file in memory. To avoid that you could use itertools
:
import itertools
# ...
with open(filename, 'rb') as f:
row = next(itertools.islice(csv.reader(f), row_number, row_number+1))
print row[column_number]
The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*
. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*
.
So if you want to remove all the privileges and start totally from scratch do the following:
Revoke all privileges on database level:
REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';
Drop the user 'phpmyadmin'@'localhost'
DROP USER 'phpmyadmin'@'localhost';
Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.
To give you a bit background on what described above: as soon as you create a user the mysql.user
table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'
. If you do a show grants for 'phpmyadmin'@'localhost';
you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL
to this user on database level, this will be stored in the table mysql.db
. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb';
you will see a 'Y'
on every priv.
Above described shows the scenario you have on your db at the present. So having a user that only has USAGE
privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS;
he has no other privileges.
The answer is nice, but it introduces one problem. Whenever you assign onload
or onerror
directly, it may replace the callback that was assigned earlier. That is why there's a nice method that "registers the specified listener on the EventTarget it's called on" as they say on MDN. You can register as many listeners as you want on the same event.
Let me rewrite the answer a little bit.
function testImage(url) {
var tester = new Image();
tester.addEventListener('load', imageFound);
tester.addEventListener('error', imageNotFound);
tester.src = url;
}
function imageFound() {
alert('That image is found and loaded');
}
function imageNotFound() {
alert('That image was not found.');
}
testImage("http://foo.com/bar.jpg");
Because the external resource loading process is asynchronous, it would be even nicer to use modern JavaScript with promises, such as the following.
function testImage(url) {
// Define the promise
const imgPromise = new Promise(function imgPromise(resolve, reject) {
// Create the image
const imgElement = new Image();
// When image is loaded, resolve the promise
imgElement.addEventListener('load', function imgOnLoad() {
resolve(this);
});
// When there's an error during load, reject the promise
imgElement.addEventListener('error', function imgOnError() {
reject();
})
// Assign URL
imgElement.src = url;
});
return imgPromise;
}
testImage("http://foo.com/bar.jpg").then(
function fulfilled(img) {
console.log('That image is found and loaded', img);
},
function rejected() {
console.log('That image was not found');
}
);
How about using an expression which evaluates to TRUE (or FALSE)?
select get_something('NAME', 1 = 1) from dual
2A. As far as last seven days have much less rows than whole table an index can help
2B. If you are interested only in Created_Date you can try using some group by and count, it should help with the result set size
You're passing link=$a
and link=$b
in the hrefs for A and B, respectively. They are treated as strings, not variables. The following should fix that for you:
echo '<a href="pass.php?link=' . $a . '">Link 1</a>';
// and
echo '<a href="pass.php?link=' . $b . '">Link 2</a>';
The value of $a
also isn't included on pass.php
. I would suggest making a common variable file and include it on all necessary pages.
Expanding on Adis H's example to include the null case (got bit on this one)
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings["HostName"] != null)
config.AppSettings.Settings["HostName"].Value = hostName;
else
config.AppSettings.Settings.Add("HostName", hostName);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
//do processing
$(this).attr("label", $(this).text()).text("loading ....").animate({ disabled: true }, 1000, function () {
//original event call
$.when($(elm).delay(1000).one("click")).done(function () {//processing finalized
$(this).text($(this).attr("label")).animate({ disabled: false }, 1000, function () {
})
});
});
With recent browser support of "Clear-Site-Data" headers, you can clear different types of data: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data
header('Clear-Site-Data: "cache", "cookies", "storage", "executionContexts"');
There is another way of enabling this,
use hadoop hdfs -copyFromLocal to copy the .csv data file from your local computer to somewhere in HDFS, say '/path/filename'
enter Hive console, run the following script to load from the file to make it as a Hive table. Note that '\054' is the ascii code of 'comma' in octal number, representing fields delimiter.
CREATE EXTERNAL TABLE table name (foo INT, bar STRING)
COMMENT 'from csv file'
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\054'
STORED AS TEXTFILE
LOCATION '/path/filename';
<button class="btn btn-default glyphicon glyphicon-plus fa-2x" type="button">_x000D_
</button>_x000D_
_x000D_
<!--fa-2x , fa-3x , fa-4x ... -->_x000D_
<button class="btn btn-default glyphicon glyphicon-plus fa-3x" type="button">_x000D_
</button>
_x000D_
To make use of the Room without abuse of the @Query
annotation first use @Query
to select all rows and put them in a list, for example:
@Query("SELECT * FROM your_class_table")
List`<`your_class`>` load_all_your_class();
Put his list into the delete annotation, for example:
@Delete
void deleteAllOfYourTable(List`<`your_class`>` your_class_list);
Use command
google-chrome-stable
We can also use command
google-chrome
To open terminal but in my case when I make an interrupt ctrl + c
then it get closed so I would recommend to use google-chrome-stable
instead of google-chrome
If you write down a fractional value like 1 / 7
as decimal value you get
1/7 = 0.142857142857142857142857142857142857142857...
with an infinite sequence of 142857
. Since you can only write a finite number of digits you will inevitably introduce a rounding (or truncation) error.
Numbers like 1/10
or 1/100
expressed as binary numbers with a fractional part also have an infinite number of digits after the decimal point:
1/10 = binary 0.0001100110011001100110011001100110...
Doubles
store values as binary and therefore might introduce an error solely by converting a decimal number to a binary number, without even doing any arithmetic.
Decimal numbers (like BigDecimal
), on the other hand, store each decimal digit as is (binary coded, but each decimal on its own). This means that a decimal type is not more precise than a binary floating point or fixed point type in a general sense (i.e. it cannot store 1/7
without loss of precision), but it is more accurate for numbers that have a finite number of decimal digits as is often the case for money calculations.
Java's BigDecimal
has the additional advantage that it can have an arbitrary (but finite) number of digits on both sides of the decimal point, limited only by the available memory.
On Windows when you are using PowerShell you have to enclose all parameters with quotes.
So if you want to create a maven webapp archetype you would do as follows:
Prerequisites:
Howto:
Note: This is tested only on windows 10 powershell
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'student'
Ends an iterator block (e.g. says there are no more elements in the IEnumerable).
Change the content-type to "application/x-www-form-urlencoded", i solved the problem.
Please note that CSS3 viewport units (vh,vw) wouldn't play well on iOS When you scroll the page, viewport size is somehow recalculated and your size of element which uses viewport units also increases. So, actually some javascript is required.
The @Query annotation allows to execute native queries by setting the nativeQuery flag to true.
Quote from Spring Data JPA reference docs.
Also, see this section on how to do it with a named native query.
Another pure css based solution that is based on two clipped rounded elements that i rotate to get to the right angle:
http://jsfiddle.net/maayan/byT76/
That's the basic css that enables it:
.clip1 {
position:absolute;
top:0;left:0;
width:200px;
height:200px;
clip:rect(0px,200px,200px,100px);
}
.slice1 {
position:absolute;
width:200px;
height:200px;
clip:rect(0px,100px,200px,0px);
-moz-border-radius:100px;
-webkit-border-radius:100px;
border-radius:100px;
background-color:#f7e5e1;
border-color:#f7e5e1;
-moz-transform:rotate(0);
-webkit-transform:rotate(0);
-o-transform:rotate(0);
transform:rotate(0);
}
.clip2
{
position:absolute;
top:0;left:0;
width:200px;
height:200px;
clip:rect(0,100px,200px,0px);
}
.slice2
{
position:absolute;
width:200px;
height:200px;
clip:rect(0px,200px,200px,100px);
-moz-border-radius:100px;
-webkit-border-radius:100px;
border-radius:100px;
background-color:#f7e5e1;
border-color:#f7e5e1;
-moz-transform:rotate(0);
-webkit-transform:rotate(0);
-o-transform:rotate(0);
transform:rotate(0);
}
and the js rotates it as required.
quite easy to understand..
Hope it helps, Maayan
the easiest way is to use position:absolute
on both elements. You can absolutely position relative to the page, or you can absolutely position relative to a container div by setting the container div to position:relative
<div id="container" style="position:relative;">
<div id="div1" style="position:absolute; top:0; left:0;"></div>
<div id="div2" style="position:absolute; top:0; left:0;"></div>
</div>
Use PHP Document Object Model:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
$DOM = new DOMDocument;
$DOM->loadHTML($str);
//get all H1
$items = $DOM->getElementsByTagName('h1');
//display all H1 text
for ($i = 0; $i < $items->length; $i++)
echo $items->item($i)->nodeValue . "<br/>";
?>
This outputs as:
T1
T2
T3
[EDIT]: After OP Clarification:
If you want the content like Lorem ipsum. etc, you can directly use this regex:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>
this outputs:
Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG
You need to do two things:
The code:
dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))
library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha = 0.35, linetype=0)+
geom_line(aes(linetype=model), size = 1) +
geom_point(aes(shape=model), size=4) +
theme(legend.position=c(.6,0.8)) +
theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
scale_linetype_discrete("Model 1") +
scale_shape_discrete("Model 1") +
scale_colour_discrete("Model 1")
However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha=0.2, colour=NA)+
geom_line() +
geom_point() +
facet_wrap(~model)
Asking for the difference /between/ two commits without including the commits in-between makes little sense. Commits are just snapshots of the contents of the repository; asking for the difference between two necessarily includes them. So the question then is, what are you really looking for?
As William suggested, cherry-picking can give you the delta of a single commit rebased on top of another. That is:
$ git checkout 012345
$ git cherry-pick -n abcdef
$ git diff --cached
This takes commit 'abcdef', compares it to its immediate ancestor, then applies that difference on top of '012345'. This new difference is then shown - the only change is the context comes from '012345' rather than 'abcdef's immediate ancestor. Of course, you may get conflicts and etc, so it's not a very useful process in most cases.
If you're just interested in abcdef itself, you can do:
$ git log -u -1 abcdef
This compares abcdef to its immediate ancestor, alone, and is usually what you want.
And of course
$ git diff 012345..abcdef
gives you all differences between those two commits.
It would help to get a better idea of what you're trying to achieve - as I mentioned, asking for the difference between two commits without what's in between doesn't actually make sense.
Credit to @rominator007
I wrapped it into a function (because you may want to use it again)
function Replace-AllStringsInFile($SearchString,$ReplaceString,$FullPathToFile)
{
$content = [System.IO.File]::ReadAllText("$FullPathToFile").Replace("$SearchString","$ReplaceString")
[System.IO.File]::WriteAllText("$FullPathToFile", $content)
}
NOTE: This is NOT case sensitive!!!!!
See this post: String.Replace ignoring case
or with sed:
test -z $(echo "2000" | sed s/[0-9]//g) && echo "integer" || echo "no integer"
# integer
test -z $(echo "ab12" | sed s/[0-9]//g) && echo "integer" || echo "no integer"
# no integer
Encode string as unicode.
>>> special = u"\u2022"
>>> abc = u'ABC•def'
>>> abc.replace(special,'X')
u'ABCXdef'
Another alternative can be to execute the Keydown or KeyUp in the tag of the Form
<form name="nameForm" [formGroup]="groupForm" (keydown.enter)="executeFunction()" >
There are some misconceptions here.
Frequencies above 500 can be represented in an FFT result of length 1000. Unfortunately these frequencies are all folded together and mixed into the first 500 FFT result bins. So normally you don't want to feed an FFT a signal containing any frequencies at or above half the sampling rate, as the FFT won't care and will just mix the high frequencies together with the low ones (aliasing) making the result pretty much useless. That's why data should be low-pass filtered before being sampled and fed to an FFT.
The FFT returns amplitudes without frequencies because the frequencies depend, not just on the length of the FFT, but also on the sample rate of the data, which isn't part of the FFT itself or it's input. You can feed the same length FFT data at any sample rate, as thus get any range of frequencies out of it.
The reason the result plots ends at 500 is that, for any real data input, the frequencies above half the length of the FFT are just mirrored repeats (complex conjugated) of the data in the first half. Since they are duplicates, most people just ignore them. Why plot duplicates? The FFT calculates the other half of the result for people who feed the FFT complex data (with both real and imaginary components), which does create two different halves.
git clone
means you are making a copy of the repository in your system.
git fork
means you are copying the repository to your Github account.
git pull
means you are fetching the last modified repository.
git push
means you are returning the repository after modifying it.
In layman's term:
git clone
is downloading and git pull
is refreshing.
File file = new File("path");
OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.close();
Below Kotlin code can help to you
Create Marker
for (i in arrayList.indices) {
val marker = googleMap!!.addMarker(
MarkerOptions().position(
LatLng(
arrayList[i].location_latitude!!.toDoubleOrNull()!!,
arrayList[i].location_latitude!!.toDoubleOrNull()!!
)
).title(arrayList[i].business_name)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_marker))
)
marker.tag = i
}
Marker Click
googleMap!!.setOnMarkerClickListener { marker ->
Log.d(TAG, "Clicked on ${marker.tag}")
true
}
I would use specific user (and NOT Application user). Then I will enable impersonation in the application. Once you do that whatever account is set as the specific user, those credentials would used to access local resources on that server (Not for external resources).
Specific User setting is specifically meant for accessing local resources.
Where the usage of a regex can be helpful to determine if the character sequence of a date is correct, it cannot be used easily to determine if the date is valid. The following examples will pass the regular expression, but are all invalid dates: 20180231, 20190229, 20190431
So if you want to validate if your date string (let's call it datestr
) is in the correct format, it is best to parse it with date
and ask date
to convert the string to the correct format. If both strings are identical, you have a valid format and valid date.
if [[ "$datestr" == $(date -d "$datestr" "+%Y%m%d" 2>/dev/null) ]]; then
echo "Valid date"
else
echo "Invalid date"
fi
I had success using .on() like so:
$('.leadtoscore').on('click', {event_type: 'shot'}, add_event);
Then inside the add_event
function you get access to 'shot' like this:
event.data.event_type
See the .on() documentation for more info, where they provide the following example:
function myHandler( event ) {
alert( event.data.foo );
}
$( "p" ).on( "click", { foo: "bar" }, myHandler );
To add yonix’s comment as an answer, the old fb://page/…
URL no longer works. Apparently it was replaced by fb://profile/…
, even though a page is not a profile.
Let's see how to get and print day,month,year in python from current time:
import datetime
now = datetime.datetime.now()
year = '{:02d}'.format(now.year)
month = '{:02d}'.format(now.month)
day = '{:02d}'.format(now.day)
hour = '{:02d}'.format(now.hour)
minute = '{:02d}'.format(now.minute)
day_month_year = '{}-{}-{}'.format(year, month, day)
print('day_month_year: ' + day_month_year)
result:
day_month_year: 2019-03-26
I think you can't. The SELECT element is rendered at a point beyond the reach of CSS and HTML. Is it grayed out?
But you can try to add a "size" atribute.
It depends on the size of the file! The solutions above tend to use convenient shorthands to copy the entire file into memory, which will work in many cases.
For very large files you may need to use a streaming design where read the file by line or in chucks, process the chunks, then discard them from memory.
See the answer on reading line by line with perl if that's what you need.
OWASP discusses this:
What's the difference between the cache-control directives: no-cache, and no-store?
The no-cache directive in a response indicates that the response must not be used to serve a subsequent request i.e. the cache must not display a response that has this directive set in the header but must let the server serve the request. The no-cache directive can include some field names; in which case the response can be shown from the cache except for the field names specified which should be served from the server. The no-store directive applies to the entire message and indicates that the cache must not store any part of the response or any request that asked for it.
Am I totally safe with these directives?
No. But generally, use both Cache-Control: no-cache, no-store and Pragma: no-cache, in addition to Expires: 0 (or a sufficiently backdated GMT date such as the UNIX epoch). Non-html content types like pdf, word documents, excel spreadsheets, etc often get cached even when the above cache control directives are set (although this varies by version and additional use of must-revalidate, pre-check=0, post-check=0, max-age=0, and s-maxage=0 in practice can sometimes result at least in file deletion upon browser closure in some cases due to browser quirks and HTTP implementations). Also, 'Autocomplete' feature allows a browser to cache whatever the user types in an input field of a form. To check this, the form tag or the individual input tags should include 'Autocomplete="Off" ' attribute. However, it should be noted that this attribute is non-standard (although it is supported by the major browsers) so it will break XHTML validation.
Source here.
Differences between abstract class and interface on behalf of real implementation.
Interface: It is a keyword and it is used to define the template or blue print of an object and it forces all the sub classes would follow the same prototype,as for as implementation, all the sub classes are free to implement the functionality as per it's requirement.
Some of other use cases where we should use interface.
Communication between two external objects(Third party integration in our application) done through Interface here Interface works as Contract.
Abstract Class: Abstract,it is a keyword and when we use this keyword before any class then it becomes abstract class.It is mainly used when we need to define the template as well as some default functionality of an object that is followed by all the sub classes and this way it removes the redundant code and one more use cases where we can use abstract class, such as we want no other classes can directly instantiate an object of the class, only derived classes can use the functionality.
Example of Abstract Class:
public abstract class DesireCar
{
//It is an abstract method that defines the prototype.
public abstract void Color();
// It is a default implementation of a Wheel method as all the desire cars have the same no. of wheels.
// and hence no need to define this in all the sub classes in this way it saves the code duplicasy
public void Wheel() {
Console.WriteLine("Car has four wheel");
}
}
**Here is the sub classes:**
public class DesireCar1 : DesireCar
{
public override void Color()
{
Console.WriteLine("This is a red color Desire car");
}
}
public class DesireCar2 : DesireCar
{
public override void Color()
{
Console.WriteLine("This is a red white Desire car");
}
}
Example Of Interface:
public interface IShape
{
// Defines the prototype(template)
void Draw();
}
// All the sub classes follow the same template but implementation can be different.
public class Circle : IShape
{
public void Draw()
{
Console.WriteLine("This is a Circle");
}
}
public class Rectangle : IShape
{
public void Draw()
{
Console.WriteLine("This is a Rectangle");
}
}
The way you use the csv
module changed in Python 3 in several respects (docs), at least with respect to how you need to open the file. Anyway, something like
import csv
with open('test.csv', 'w', newline='') as fp:
a = csv.writer(fp, delimiter=',')
data = [['Me', 'You'],
['293', '219'],
['54', '13']]
a.writerows(data)
should work.
In most cases, traceroute command works fine. nslookup and host commands may fail.
You need to store the first run time of the program in order to do this. How I'd probably do it is using the built in application settings in visual studio. Make one called InstallDate which is a User Setting and defaults to DateTime.MinValue or something like that (e.g. 1/1/1900).
Then when the program is run the check is simple:
if (appmode == "trial")
{
// If the FirstRunDate is MinValue, it's the first run, so set this value up
if (Properties.Settings.Default.FirstRunDate == DateTime.MinValue)
{
Properties.Settings.Default.FirstRunDate = DateTime.Now;
Properties.Settings.Default.Save();
}
// Now check whether 30 days have passed since the first run date
if (Properties.Settings.Default.FirstRunDate.AddMonths(1) < DateTime.Now)
{
// Do whatever you want to do on expiry (exception message/shut down/etc.)
}
}
User settings are stored in a pretty weird location (something like C:\Documents and Settings\YourName\Local Settings\Application Data) so it will be pretty hard for average joe to find it anyway. If you want to be paranoid, just encrypt the date before saving it to settings.
EDIT: Sigh, misread the question, not as complex as I thought >.>
See if you want to use Google Map
at that time you need MD5
fingerprint for generating api kay
for using google map in your android application.
Keytool command generated MD5
fingerprint if you use JDK 1.6
and it generates SHA1
fingerprint if you use JDK 1.7
.
So the thing is that if you want to sign your application for publishing then read this.
And if you want to use google-map
read this.
Be sure that android:debuggable="true"
is set in the application
tag of your manifest file, and then:
You can try this script out since you do not want to target the Xoom only. I don't have a Xoom, but should work.
function mobile_detect(mobile,tablet,mobile_redirect,tablet_redirect,debug) {
var ismobile = (/iphone|ipod|android|blackberry|opera|mini|windows\sce|palm|smartphone|iemobile/i.test(navigator.userAgent.toLowerCase()));
var istablet = (/ipad|android|android 3.0|xoom|sch-i800|playbook|tablet|kindle/i.test(navigator.userAgent.toLowerCase()));
if (debug == true) {
alert(navigator.userAgent);
}
if (ismobile && mobile==true) {
if (debug == true) {
alert("Mobile Browser");
}
window.location = mobile_redirect;
} else if (istablet && tablet==true) {
if (debug == true) {
alert("Tablet Browser");
}
window.location = tablet_redirect;
}
}
I created a project on github. Check it out - https://github.com/codefuze/js-mobile-tablet-redirect. Feel free to submit issues if there is anything wrong!
There are couple of ways this can be done.
First, is converting to list and then to array again:
List<int> tmpList = intArry.ToList();
tmpList.Add(anyInt);
intArry = tmpList.ToArray();
Now this is not recommended as you convert to list and back again to array. If you do not want to use a list, you can use the second way which is assigning values directly into the array:
int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
This is the direct approach and if you do not want to tangle with lists and conversions, this is recommended for you.
To also get things outside the <html>...</html>
, most importantly the <!DOCTYPE ...>
declaration, you could walk through document.childNodes, turning each into a string:
const html = [...document.childNodes]
.map(node => nodeToString(node))
.join('\n') // could use '' instead, but whitespace should not matter.
function nodeToString(node) {
switch (node.nodeType) {
case node.ELEMENT_NODE:
return node.outerHTML
case node.TEXT_NODE:
// Text nodes should probably never be encountered, but handling them anyway.
return node.textContent
case node.COMMENT_NODE:
return `<!--${node.textContent}-->`
case node.DOCUMENT_TYPE_NODE:
return doctypeToString(node)
default:
throw new TypeError(`Unexpected node type: ${node.nodeType}`)
}
}
I published this code as document-outerhtml on npm.
edit Note the code above depends on a function doctypeToString
; its implementation could be as follows (code below is published on npm as doctype-to-string):
function doctypeToString(doctype) {
if (doctype === null) {
return ''
}
// Checking with instanceof DocumentType might be neater, but how to get a
// reference to DocumentType without assuming it to be available globally?
// To play nice with custom DOM implementations, we resort to duck-typing.
if (!doctype
|| doctype.nodeType !== doctype.DOCUMENT_TYPE_NODE
|| typeof doctype.name !== 'string'
|| typeof doctype.publicId !== 'string'
|| typeof doctype.systemId !== 'string'
) {
throw new TypeError('Expected a DocumentType')
}
const doctypeString = `<!DOCTYPE ${doctype.name}`
+ (doctype.publicId ? ` PUBLIC "${doctype.publicId}"` : '')
+ (doctype.systemId
? (doctype.publicId ? `` : ` SYSTEM`) + ` "${doctype.systemId}"`
: ``)
+ `>`
return doctypeString
}
Using variable notation, you can do it without a temporary file:
${C:\file.txt} = ${C:\file.txt} | select -skip 1
function Remove-Topline ( [string[]]$path, [int]$skip=1 ) {
if ( -not (Test-Path $path -PathType Leaf) ) {
throw "invalid filename"
}
ls $path |
% { iex "`${$($_.fullname)} = `${$($_.fullname)} | select -skip $skip" }
}
Do you have control over running the transformation? If so, you could pass in the current date to the XSL and use $current-date from inside your XSL. Below is how you declare the incoming parameter, but with knowing how you are running the transformation, I can't tell you how to pass in the value.
<xsl:param name="current-date" />
For example, from the bash script, use:
xsltproc --stringparam current-date `date +%Y-%m-%d` -o output.html path-to.xsl path-to.xml
Then, in the xsl you can use:
<xsl:value-of select="$current-date"/>
Just to add to CKoenig's response. His answer will work as long as the class you're dealing with is a reference type (like a class). If the custom object were a struct, this is a value type, and the results of .FirstOrDefault
will give you a local copy of that, which will mean it won't persist back to the collection, as this example shows:
struct MyStruct
{
public int TheValue { get; set; }
}
Test code:
List<MyStruct> coll = new List<MyStruct> {
new MyStruct {TheValue = 10},
new MyStruct {TheValue = 1},
new MyStruct {TheValue = 145},
};
var found = coll.FirstOrDefault(c => c.TheValue == 1);
found.TheValue = 12;
foreach (var myStruct in coll)
{
Console.WriteLine(myStruct.TheValue);
}
Console.ReadLine();
The output is 10,1,145
Change the struct to a class and the output is 10,12,145
HTH
With custom colours (for example, dark red, dark green and dark blue):
import random
COLORS = [(139, 0, 0),
(0, 100, 0),
(0, 0, 139)]
def random_color():
return random.choice(COLORS)
Actually, I'm pretty sure Reflector is considered a disassembler with some decompiler functionality. Disassembler because it reads the bytes out of an assembly's file and converts it to an assembly language (ILasm in this case). The Decompiler functionality it provides by parsing the IL into well known patterns (like expressions and statements) which then get translated into higher level languages like C#, VB.Net, etc. The addin api for Reflector allows you to write your own language translator if you wish ... however the magic of how it parses the IL into the expression trees is a closely guarded secret.
I would recommend looking at any of the three things mentioned above if you want to understand how IL disassemblers work: Dile, CCI and Mono are all good sources for this stuff.
I also highly recommend getting the Ecma 335 spec and Serge Lidin's book too.
select regexp_replace(field, E'[\\n\\r\\u2028]+', ' ', 'g' )
I had the same problem in my postgres d/b, but the newline in question wasn't the traditional ascii CRLF, it was a unicode line separator, character U2028. The above code snippet will capture that unicode variation as well.
Update... although I've only ever encountered the aforementioned characters "in the wild", to follow lmichelbacher's advice to translate even more unicode newline-like characters, use this:
select regexp_replace(field, E'[\\n\\r\\f\\u000B\\u0085\\u2028\\u2029]+', ' ', 'g' )
except:
accepts all exceptions, whereas
except Exception as e:
only accepts exceptions that you're meant to catch.
Here's an example of one that you're not meant to catch:
>>> try:
... input()
... except:
... pass
...
>>> try:
... input()
... except Exception as e:
... pass
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
The first one silenced the KeyboardInterrupt
!
Here's a quick list:
issubclass(BaseException, BaseException)
#>>> True
issubclass(BaseException, Exception)
#>>> False
issubclass(KeyboardInterrupt, BaseException)
#>>> True
issubclass(KeyboardInterrupt, Exception)
#>>> False
issubclass(SystemExit, BaseException)
#>>> True
issubclass(SystemExit, Exception)
#>>> False
If you want to catch any of those, it's best to do
except BaseException:
to point out that you know what you're doing.
All exceptions stem from BaseException
, and those you're meant to catch day-to-day (those that'll be thrown for the programmer) inherit too from Exception
.
This code will extract the content between square brackets and parentheses
(?:(?<=\().+?(?=\))|(?<=\[).+?(?=\]))
(?: non capturing group
(?<=\().+?(?=\)) positive lookbehind and lookahead to extract the text between parentheses
| or
(?<=\[).+?(?=\]) positive lookbehind and lookahead to extract the text between square brackets
the only solution worked for me was using java keytool and generating a .keystore
file the command line and then use that .keystore
file to sign my app
you can find the java keytool at this directory C:\Program Files\Java\jre7\bin
open a command window and switch to that directory and enter a command like this
keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000
Keytool prompts you to provide passwords for the keystore, your name , company etc . note that at the last prompt you need to enter yes.
It then generates the keystore as a file called my-release-key.keystore in the directory you're in. The keystore and key are protected by the passwords you entered. The keystore contains a single key, valid for 10000 days. The alias is a name that you — will use later, to refer to this keystore when signing your application.
For more information about Keytool, see the documentation at: http://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html
and for more information on signing Android apps go here: http://developer.android.com/tools/publishing/app-signing.html
If you are using React, make sure autoplay is set to,
autoPlay
React wants it to be camelcase!
If order is not the matter:
>>> foo='mppmt'
>>> ''.join(set(foo))
'pmt'
To keep the order:
>>> foo='mppmt'
>>> ''.join([j for i,j in enumerate(foo) if j not in foo[:i]])
'mpt'
To remove all child elements from your div:
$('#mysweetdiv').empty();
.removeData()
and the corresponding .data()
function are used to attach data behind an element, say if you wanted to note that a specific list element referred to user ID 25 in your database:
var $li = $('<li>Joe</li>').data('id', 25);
:) Your using the thread in a wrong way. Just do the following:
private void runthread()
{
splashTread = new Thread() {
@Override
public void run() {
try {
synchronized(this){
//wait 5 sec
wait(_splashTime);
}
} catch(InterruptedException e) {}
finally {
//call the handler to set the text
}
}
};
splashTread.start();
}
That's it.
No, but you can use the DescriptionAttribute to accomplish what you're looking for.
The question asks which characters are allowed in GET parameters without encoding or escaping them.
According to RFC3986 (general URL syntax) and RFC7230, section 2.7.1 (HTTP/S URL syntax) the only characters you need to percent-encode are those outside of the query set, see the definition below.
However, there are additional specifications like HTML5, Web forms, and the obsolete Indexed search, W3C recommendation. Those documents add a special meaning to some characters notably, to symbols like = & + ;.
Other answers here suggest that most of the reserved characters should be encoded, including "/" "?". That's not correct. In fact, RFC3986, section 3.4 advises against percent-encoding "/" "?" characters.
it is sometimes better for usability to avoid percent- encoding those characters.
RFC3986 defines query component as:
query = *( pchar / "/" / "?" )
pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
pct-encoded = "%" HEXDIG HEXDIG
sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
A percent-encoding mechanism is used to represent a data octet in a component when that octet's corresponding character is outside the allowed set or is being used as a delimiter of, or within, the component.
The conclusion is that XYZ part should encode:
special: # % = & ;
Space
sub-delims
out of query set: [ ]
non ASCII encodable characters
Unless special symbols = & ; are key=value separators.
Encoding other characters is allowed but not necessary.
You can do that in following way :
arr2 = arr1.map(x => Object.assign({}, x));
use the latest one for bootstrap 4 and above, this won't affect your UI
Use any()
.
if any(t < 0 for t in x):
# do something
Jquery.ajax does not encode POST data for you automatically the way that it does for GET data. Jquery expects your data to be pre-formated to append to the request body to be sent directly across the wire.
A solution is to use the jQuery.param function to build a query string that most scripts that process POST requests expect.
$.ajax({
url: 'superman',
type: 'POST',
data: jQuery.param({ field1: "hello", field2 : "hello2"}) ,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
In this case the param
method formats the data to:
field1=hello&field2=hello2
The Jquery.ajax documentation says that there is a flag called processData
that controls whether this encoding is done automatically or not. The documentation says that it defaults to true
, but that is not the behavior I observe when POST
is used.
I think the right way to find the internal Java used by the Android Studio is to
This will not require memorising the folder or searching for java and also these steps wil take of any future changes to the java location by the Android Studio team changes I suppose
This way you don't need to add the CSS outside of the component:
@Component({
selector: 'body',
template: 'app-element',
// prefer decorators (see below)
// host: {'[class.someClass]':'someField'}
})
export class App implements OnInit {
constructor(private cdRef:ChangeDetectorRef) {}
someField: boolean = false;
// alternatively also the host parameter in the @Component()` decorator can be used
@HostBinding('class.someClass') someField: boolean = false;
ngOnInit() {
this.someField = true; // set class `someClass` on `<body>`
//this.cdRef.detectChanges();
}
}
This CSS is defined inside the component and the selector is only applied if the class someClass
is set on the host element (from outside):
:host(.someClass) {
background-color: red;
}
strace lists all system calls done by the process it's applied to. If you don't know what system calls mean, you won't be able to get much mileage from it.
Nevertheless, if your problem involves files or paths or environment values, running strace on the problematic program and redirecting the output to a file and then grepping that file for your path/file/env string may help you see what your program is actually attempting to do, as distinct from what you expected it to.
I was struggling to get this right using the scripts provided above and some other scripts especially when files and folder names had newline or spaces.
Finally stumbled on tmpreaper and it has been worked pretty well for us so far.
tmpreaper -t 5d ~/Downloads
tmpreaper --protect '*.c' -t 5h ~/my_prg
Original Source link
Has features like test, which checks the directories recursively and lists them. Ability to delete symlinks, files or directories and also the protection mode for a certain pattern while deleting
public static URL getFinalURL(URL url) {
try {
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setInstanceFollowRedirects(false);
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
con.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
con.addRequestProperty("Referer", "https://www.google.com/");
con.connect();
//con.getInputStream();
int resCode = con.getResponseCode();
if (resCode == HttpURLConnection.HTTP_SEE_OTHER
|| resCode == HttpURLConnection.HTTP_MOVED_PERM
|| resCode == HttpURLConnection.HTTP_MOVED_TEMP) {
String Location = con.getHeaderField("Location");
if (Location.startsWith("/")) {
Location = url.getProtocol() + "://" + url.getHost() + Location;
}
return getFinalURL(new URL(Location));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return url;
}
To get "User-Agent" and "Referer" by yourself, just go to developer mode of one of your installed browser (E.g. press F12 on Google Chrome). Then go to tab 'Network' and then click on one of the requests. You should see it's details. Just press 'Headers' sub tab (the image below)
The above methods are useful but they are not full-proof because it will give error if time is between 12:00 AM/PM and 01:00 AM/PM . It will return the "No Go" in-spite of being in between the timing . Here is the code for the same:
$time = '2019-03-27 12:00 PM';
$date_one = $time;
$date_one = strtotime($date_one);
$date_one = strtotime("+60 minutes", $date_one);
$date_one = date('Y-m-d h:i A', $date_one);
$date_ten = strtotime($time);
$date_ten = strtotime("-12 minutes", $date_ten);
$date_ten = date('Y-m-d h:i A', $date_ten);
$paymentDate='2019-03-27 12:45 AM';
$contractDateBegin = date('Y-m-d h:i A', strtotime($date_ten));
$contractDateEnd = date('Y-m-d h:i A', strtotime($date_one));
echo $paymentDate;
echo "---------------";
echo $contractDateBegin;
echo "---------------";
echo $contractDateEnd;
echo "---------------";
$contractDateEnd='2019-03-27 01:45 AM';
if($paymentDate > $contractDateBegin && $paymentDate < $contractDateEnd)
{
echo "is between";
}
else
{
echo "NO GO!";
}
Here you will get output "NO Go"
because 12:45 > 01:45
.
To get proper output date in between, make sure that for "AM"
values from 01:00 AM
to 12:00 AM
will get converted to the 24-hour format. This little trick helped me.
In MySQL, It should be like this
INSERT INTO this_table_archive (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00';
for i in range(len(list)): list[i]=float(list[i])
In addition to the other options, if you want a dateformat ISO, you get can get it directly
console.log(new Date().toISOString());
_x000D_
If you are not so keen on having to decorate code with Attributes as I am, esp when you cant tell at compile time what will happen here is my solution.
Using the Javascript Serializer
public static class JsonSerializerExtensions
{
public static string ToJsonString(this object target,bool ignoreNulls = true)
{
var javaScriptSerializer = new JavaScriptSerializer();
if(ignoreNulls)
{
javaScriptSerializer.RegisterConverters(new[] { new PropertyExclusionConverter(target.GetType(), true) });
}
return javaScriptSerializer.Serialize(target);
}
public static string ToJsonString(this object target, Dictionary<Type, List<string>> ignore, bool ignoreNulls = true)
{
var javaScriptSerializer = new JavaScriptSerializer();
foreach (var key in ignore.Keys)
{
javaScriptSerializer.RegisterConverters(new[] { new PropertyExclusionConverter(key, ignore[key], ignoreNulls) });
}
return javaScriptSerializer.Serialize(target);
}
}
public class PropertyExclusionConverter : JavaScriptConverter
{
private readonly List<string> propertiesToIgnore;
private readonly Type type;
private readonly bool ignoreNulls;
public PropertyExclusionConverter(Type type, List<string> propertiesToIgnore, bool ignoreNulls)
{
this.ignoreNulls = ignoreNulls;
this.type = type;
this.propertiesToIgnore = propertiesToIgnore ?? new List<string>();
}
public PropertyExclusionConverter(Type type, bool ignoreNulls)
: this(type, null, ignoreNulls){}
public override IEnumerable<Type> SupportedTypes
{
get { return new ReadOnlyCollection<Type>(new List<Type>(new[] { this.type })); }
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
var result = new Dictionary<string, object>();
if (obj == null)
{
return result;
}
var properties = obj.GetType().GetProperties();
foreach (var propertyInfo in properties)
{
if (!this.propertiesToIgnore.Contains(propertyInfo.Name))
{
if(this.ignoreNulls && propertyInfo.GetValue(obj, null) == null)
{
continue;
}
result.Add(propertyInfo.Name, propertyInfo.GetValue(obj, null));
}
}
return result;
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
throw new NotImplementedException(); //Converter is currently only used for ignoring properties on serialization
}
}
Use HashBytes
SELECT HashBytes('MD5', '[email protected]')
That will give you 0xF53BD08920E5D25809DF2563EF9C52B6
-
SELECT CONVERT(NVARCHAR(32),HashBytes('MD5', '[email protected]'),2)
That will give you F53BD08920E5D25809DF2563EF9C52B6
db2 connect to MY_INSTACE_DB with myuser -- connect to db2
db2 "select TABNAME from syscat.tables where tabschema = 'mySchema' with ur"
db2 terminate -- end connection
ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));
why do u want to write a code like this? If you have a class 'ReportClass' is available, you can instantiate it directly as shown below.
ReportClass report = new ReportClass();
The code ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));
is used when you dont have the necessary class available, but you want to instantiate and or or invoke a method dynamically.
I mean it is useful when u know the assembly but while writing the code you dont have the class ReportClass
available.
I had this problem and did not find any solution which I liked, so I created a python wrapper for mpg321: mpyg321.
You would need to have mpg321 installed on your computer, and then do pip install mpyg321
.
The usage is pretty simple:
from mpyg321.mpyg321 import MPyg321Player
from time import sleep
player = MPyg321Player() # instanciate the player
player.play_song("sample.mp3") # play a song
sleep(5)
player.pause() # pause playing
sleep(3)
player.resume() # resume playing
sleep(5)
player.stop() # stop playing
player.quit() # quit the player
You can also define callbacks for several events (music paused by user, end of song...).
A reliable way to address this is
from six.moves import input
six is a module which patches over many of the 2/3 common code base pain points.
It looks like the answer is at least 12 million if you have a beefy server, your server software is optimized for it, you have enough clients. If you test from one client to one server, the number of port numbers on the client will be one of the obvious resource limits (Each TCP connection is defined by the unique combination of IP and port number at the source and destination).
(You need to run multiple clients as otherwise you hit the 64K limit on port numbers first)
When it comes down to it, this is a classic example of the witticism that "the difference between theory and practise is much larger in practise than in theory" - in practise achieving the higher numbers seems to be a cycle of a. propose specific configuration/architecture/code changes, b. test it till you hit a limit, c. Have I finished? If not then d. work out what was the limiting factor, e. go back to step a (rinse and repeat).
Here is an example with 2 million TCP connections onto a beefy box (128GB RAM and 40 cores) running Phoenix http://www.phoenixframework.org/blog/the-road-to-2-million-websocket-connections - they ended up needing 50 or so reasonably significant servers just to provide the client load (their initial smaller clients maxed out to early, eg "maxed our 4core/15gb box @ 450k clients").
Here is another reference for go this time at 10 million: http://goroutines.com/10m.
This appears to be java based and 12 million connections: https://mrotaru.wordpress.com/2013/06/20/12-million-concurrent-connections-with-migratorydata-websocket-server/
From the manual entry for PDOStatement::bindParam
:
[With
bindParam
] UnlikePDOStatement::bindValue()
, the variable is bound as a reference and will only be evaluated at the time thatPDOStatement::execute()
is called.
So, for example:
$sex = 'male';
$s = $dbh->prepare('SELECT name FROM students WHERE sex = :sex');
$s->bindParam(':sex', $sex); // use bindParam to bind the variable
$sex = 'female';
$s->execute(); // executed with WHERE sex = 'female'
or
$sex = 'male';
$s = $dbh->prepare('SELECT name FROM students WHERE sex = :sex');
$s->bindValue(':sex', $sex); // use bindValue to bind the variable's value
$sex = 'female';
$s->execute(); // executed with WHERE sex = 'male'
I wrote this for Outlook at first. Modified it a little for Word, but it will not work on a standalone install because that key does not show the bitness, only Outlook does.
Also, I wrote it to only support current versions of Office, =>2010
I stripped all the setup and post processing...
:checkarch
IF NOT "%PROCESSOR_ARCHITECTURE%"=="x86" SET InstallArch=64bit
IF "%PROCESSOR_ARCHITEW6432%"=="AMD64" SET InstallArch=64bit
IF "%InstallArch%"=="64bit" SET Wow6432Node=\Wow6432Node
GOTO :beginscript
:beginscript
SET _cmdDetectedOfficeVersion=reg query "HKEY_CLASSES_ROOT\Word.Application\CurVer"
@FOR /F "tokens=* USEBACKQ" %%F IN (`!_cmdDetectedOfficeVersion! 2^>NUL `) DO (
SET _intDetectedOfficeVersion=%%F
)
set _intDetectedOfficeVersion=%_intDetectedOfficeVersion:~-2%
:switchCase
:: Call and mask out invalid call targets
goto :case!_intDetectedOfficeVersion! 2>nul || (
:: Default case
ECHO Not installed/Supported
)
goto :case-install
:case14
Set _strOutlookVer= Word 2010 (!_intDetectedOfficeVersion!)
CALL :GetBitness !_intDetectedOfficeVersion!
GOTO :case-install
:case15
Set _strOutlookVer= Word 2013 (!_intDetectedOfficeVersion!)
CALL :GetBitness !_intDetectedOfficeVersion!
GOTO :case-install
:case16
Set _strOutlookVer= Word 2016 (!_intDetectedOfficeVersion!)
CALL :GetBitness !_intDetectedOfficeVersion!
goto :case-install
:case-install
CALL :output_text !_strOutlookVer! !_strBitness! is installed
GOTO :endscript
:GetBitness
FOR /F "tokens=3*" %%a in ('reg query "HKLM\Software%Wow6432Node%\Microsoft\Office\%1.0\Outlook" /v Bitness 2^>NUL') DO Set _strBitness=%%a
GOTO :EOF
GitHub is the entire site. Gists are a particular service offered on that site, namely code snippets akin to pastebin. However, everything is driven by git revision control, so gists also have complete revision histories.
The existing answers are a little too verbose so I created this smaller, auto-matching version.
function prefered_language(array $available_languages, $http_accept_language) {
$available_languages = array_flip($available_languages);
$langs;
preg_match_all('~([\w-]+)(?:[^,\d]+([\d.]+))?~', strtolower($http_accept_language), $matches, PREG_SET_ORDER);
foreach($matches as $match) {
list($a, $b) = explode('-', $match[1]) + array('', '');
$value = isset($match[2]) ? (float) $match[2] : 1.0;
if(isset($available_languages[$match[1]])) {
$langs[$match[1]] = $value;
continue;
}
if(isset($available_languages[$a])) {
$langs[$a] = $value - 0.1;
}
}
arsort($langs);
return $langs;
}
And the sample usage:
//$_SERVER["HTTP_ACCEPT_LANGUAGE"] = 'en-us,en;q=0.8,es-cl;q=0.5,zh-cn;q=0.3';
// Languages we support
$available_languages = array("en", "zh-cn", "es");
$langs = prefered_language($available_languages, $_SERVER["HTTP_ACCEPT_LANGUAGE"]);
/* Result
Array
(
[en] => 0.8
[es] => 0.4
[zh-cn] => 0.3
)*/
Select Distinct CAST(FLOOR( CAST(start_date AS FLOAT ) )AS DATETIME) from Table
Please run below code may it helps you :)
var str = "this,is,an,example";_x000D_
var strArr = str.split(',');_x000D_
var data = "";_x000D_
for(var i=0; i<strArr.length; i++){_x000D_
data += "Index : "+i+" value : "+strArr[i]+"<br/>";_x000D_
}_x000D_
document.getElementById('print').innerHTML = data;
_x000D_
<div id="print">_x000D_
</div>
_x000D_
Do a str.replace('; ', ', ')
and then a str.split(', ')
You have a couple of basic misconceptions about Java:
I want it to return the array without having to explicitly tell the console to print.
1) Java does not work that way. Nothing ever gets printed implicitly. (Java does not support an interactive interpreter with a "repl" loop ... like Python, Ruby, etc.)
2) The "main" doesn't "return" anything. The method signature is:
public static void main(String[] args)
and the void
means "no value is returned". (And, sorry, no you can't replace the void
with something else. If you do then the java
command won't recognize the "main" method.)
3) If (hypothetically) you did want your "main" method to return something, and you altered the declaration to allow that, then you still would need to use a return
statement to tell it what value to return. Unlike some language, Java does not treat the value of the last statement of a method as the return value for the method. You have to use a return
statement ...
There are four steps to solve a sudoku puzzle:
If still not solved then do it for next possible value and run it in recursion.
import math
import sys
def is_solved(l):
for x, i in enumerate(l):
for y, j in enumerate(i):
if j == 0:
# Incomplete
return None
for p in range(9):
if p != x and j == l[p][y]:
# Error
print('horizontal issue detected!', (x, y))
return False
if p != y and j == l[x][p]:
# Error
print('vertical issue detected!', (x, y))
return False
i_n, j_n = get_box_start_coordinate(x, y)
for (i, j) in [(i, j) for p in range(i_n, i_n + 3) for q in range(j_n, j_n + 3)
if (p, q) != (x, y) and j == l[p][q]]:
# Error
print('box issue detected!', (x, y))
return False
# Solved
return True
def is_valid(l):
for x, i in enumerate(l):
for y, j in enumerate(i):
if j != 0:
for p in range(9):
if p != x and j == l[p][y]:
# Error
print('horizontal issue detected!', (x, y))
return False
if p != y and j == l[x][p]:
# Error
print('vertical issue detected!', (x, y))
return False
i_n, j_n = get_box_start_coordinate(x, y)
for (i, j) in [(i, j) for p in range(i_n, i_n + 3) for q in range(j_n, j_n + 3)
if (p, q) != (x, y) and j == l[p][q]]:
# Error
print('box issue detected!', (x, y))
return False
# Solved
return True
def get_box_start_coordinate(x, y):
return 3 * int(math.floor(x/3)), 3 * int(math.floor(y/3))
def get_horizontal(x, y, l):
return [l[x][i] for i in range(9) if l[x][i] > 0]
def get_vertical(x, y, l):
return [l[i][y] for i in range(9) if l[i][y] > 0]
def get_box(x, y, l):
existing = []
i_n, j_n = get_box_start_coordinate(x, y)
for (i, j) in [(i, j) for i in range(i_n, i_n + 3) for j in range(j_n, j_n + 3)]:
existing.append(l[i][j]) if l[i][j] > 0 else None
return existing
def detect_and_simplify_double_pairs(l, pl):
for (i, j) in [(i, j) for i in range(9) for j in range(9) if len(pl[i][j]) == 2]:
temp_pair = pl[i][j]
for p in (p for p in range(j+1, 9) if len(pl[i][p]) == 2 and len(set(pl[i][p]) & set(temp_pair)) == 2):
for q in (q for q in range(9) if q != j and q != p):
pl[i][q] = list(set(pl[i][q]) - set(temp_pair))
if len(pl[i][q]) == 1:
l[i][q] = pl[i][q].pop()
return True
for p in (p for p in range(i+1, 9) if len(pl[p][j]) == 2 and len(set(pl[p][j]) & set(temp_pair)) == 2):
for q in (q for q in range(9) if q != i and p != q):
pl[q][j] = list(set(pl[q][j]) - set(temp_pair))
if len(pl[q][j]) == 1:
l[q][j] = pl[q][j].pop()
return True
i_n, j_n = get_box_start_coordinate(i, j)
for (a, b) in [(a, b) for a in range(i_n, i_n+3) for b in range(j_n, j_n+3)
if (a, b) != (i, j) and len(pl[a][b]) == 2 and len(set(pl[a][b]) & set(temp_pair)) == 2]:
for (c, d) in [(c, d) for c in range(i_n, i_n+3) for d in range(j_n, j_n+3)
if (c, d) != (a, b) and (c, d) != (i, j)]:
pl[c][d] = list(set(pl[c][d]) - set(temp_pair))
if len(pl[c][d]) == 1:
l[c][d] = pl[c][d].pop()
return True
return False
def update_unique_horizontal(x, y, l, pl):
tl = pl[x][y]
for i in (i for i in range(9) if i != y):
tl = list(set(tl) - set(pl[x][i]))
if len(tl) == 1:
l[x][y] = tl.pop()
return True
return False
def update_unique_vertical(x, y, l, pl):
tl = pl[x][y]
for i in (i for i in range(9) if i != x):
tl = list(set(tl) - set(pl[i][y]))
if len(tl) == 1:
l[x][y] = tl.pop()
return True
return False
def update_unique_box(x, y, l, pl):
tl = pl[x][y]
i_n, j_n = get_box_start_coordinate(x, y)
for (i, j) in [(i, j) for i in range(i_n, i_n+3) for j in range(j_n, j_n+3) if (i, j) != (x, y)]:
tl = list(set(tl) - set(pl[i][j]))
if len(tl) == 1:
l[x][y] = tl.pop()
return True
return False
def find_and_place_possibles(l):
while True:
pl = populate_possibles(l)
if pl != False:
return pl
def populate_possibles(l):
pl = [[[]for j in i] for i in l]
for (i, j) in [(i, j) for i in range(9) for j in range(9) if l[i][j] == 0]:
p = list(set(range(1, 10)) - set(get_horizontal(i, j, l) +
get_vertical(i, j, l) + get_box(i, j, l)))
if len(p) == 1:
l[i][j] = p.pop()
return False
else:
pl[i][j] = p
return pl
def find_and_remove_uniques(l, pl):
for (i, j) in [(i, j) for i in range(9) for j in range(9) if l[i][j] == 0]:
if update_unique_horizontal(i, j, l, pl) == True:
return True
if update_unique_vertical(i, j, l, pl) == True:
return True
if update_unique_box(i, j, l, pl) == True:
return True
return False
def try_with_possibilities(l):
while True:
improv = False
pl = find_and_place_possibles(l)
if detect_and_simplify_double_pairs(
l, pl) == True:
continue
if find_and_remove_uniques(
l, pl) == True:
continue
if improv == False:
break
return pl
def get_first_conflict(pl):
for (x, y) in [(x, y) for x, i in enumerate(pl) for y, j in enumerate(i) if len(j) > 0]:
return (x, y)
def get_deep_copy(l):
new_list = [i[:] for i in l]
return new_list
def run_assumption(l, pl):
try:
c = get_first_conflict(pl)
fl = pl[c[0]
][c[1]]
# print('Assumption Index : ', c)
# print('Assumption List: ', fl)
except:
return False
for i in fl:
new_list = get_deep_copy(l)
new_list[c[0]][c[1]] = i
new_pl = try_with_possibilities(new_list)
is_done = is_solved(new_list)
if is_done == True:
l = new_list
return new_list
else:
new_list = run_assumption(new_list, new_pl)
if new_list != False and is_solved(new_list) == True:
return new_list
return False
if __name__ == "__main__":
l = [
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 8, 0, 0, 0, 0, 4, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 6, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[2, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]
]
# This puzzle copied from Hacked rank test case
if is_valid(l) == False:
print("Sorry! Invalid.")
sys.exit()
pl = try_with_possibilities(l)
is_done = is_solved(l)
if is_done == True:
for i in l:
print(i)
print("Solved!!!")
sys.exit()
print("Unable to solve by traditional ways")
print("Starting assumption based solving")
new_list = run_assumption(l, pl)
if new_list != False:
is_done = is_solved(new_list)
print('is solved ? - ', is_done)
for i in new_list:
print(i)
if is_done == True:
print("Solved!!! with assumptions.")
sys.exit()
print(l)
print("Sorry! No Solution. Need to fix the valid function :(")
sys.exit()
ob_start();
include "yourfile.php";
$myvar = ob_get_clean();
First save your program as program.c
.
Now you need the compiler, so you need to go to App Store and install Xcode which is Apple's compiler and development tools. How to find App Store? Do a "Spotlight Search" by typing ⌘Space and start typing App Store
and hit Enter when it guesses correctly.
App Store looks like this:
Xcode looks like this on App Store:
Then you need to install the command-line tools in Terminal. How to start Terminal? You need to do another "Spotlight Search", which means you type ⌘Space and start typing Terminal
and hit Enter when it guesses Terminal
.
Now install the command-line tools like this:
xcode-select --install
Then you can compile your code with by simply running gcc
as in the next line without having to fire up the big, ugly software development GUI called Xcode
:
gcc -Wall -o program program.c
Note: On newer versions of OS X, you would use clang
instead of gcc
, like this:
clang program.c -o program
Then you can run it with:
./program
Hello, world!
If your program is C++, you'll probably want to use one of these commands:
clang++ -o program program.cpp
g++ -std=c++11 -o program program.cpp
g++-7 -std=c++11 -o program program.cpp
Adding to Tim's answer:
#search:placeholder-shown {
// show background image, I like svg
// when using svg, do not use HEX for colour; you can use rbg/a instead
// also notice the single quotes
background-image url('data:image/svg+xml; utf8, <svg>... <g fill="grey"...</svg>')
// other background props
}
#search:not(:placeholder-shown) { background-image: none;}
Introduce a new variable that you'll use as a 'loop breaker'. First assign something to it(False,0, etc.), and then, inside the outer loop, before you break from it, change the value to something else(True,1,...). Once the loop exits make the 'parent' loop check for that value. Let me demonstrate:
breaker = False #our mighty loop exiter!
while True:
while True:
if conditionMet:
#insert code here...
breaker = True
break
if breaker: # the interesting part!
break # <--- !
If you have an infinite loop, this is the only way out; for other loops execution is really a lot faster. This also works if you have many nested loops. You can exit all, or just a few. Endless possibilities! Hope this helped!
I’ve been struggling with this for a while now. Dycey’s solution is correct in that specifying the src
multiple times outputs the same thing in your css file. However, this seems to break in OSX Firefox 23 (probably other versions too, but I don’t have time to test).
The cross-browser @font-face
solution from Font Squirrel looks like this:
@font-face {
font-family: 'fontname';
src: url('fontname.eot');
src: url('fontname.eot?#iefix') format('embedded-opentype'),
url('fontname.woff') format('woff'),
url('fontname.ttf') format('truetype'),
url('fontname.svg#fontname') format('svg');
font-weight: normal;
font-style: normal;
}
To produce the src
property with the comma-separated values, you need to write all of the values on one line, since line-breaks are not supported in Sass. To produce the above declaration, you would write the following Sass:
@font-face
font-family: 'fontname'
src: url('fontname.eot')
src: url('fontname.eot?#iefix') format('embedded-opentype'), url('fontname.woff') format('woff'), url('fontname.ttf') format('truetype'), url('fontname.svg#fontname') format('svg')
font-weight: normal
font-style: normal
I think it seems silly to write out the path a bunch of times, and I don’t like overly long lines in my code, so I worked around it by writing this mixin:
=font-face($family, $path, $svg, $weight: normal, $style: normal)
@font-face
font-family: $family
src: url('#{$path}.eot')
src: url('#{$path}.eot?#iefix') format('embedded-opentype'), url('#{$path}.woff') format('woff'), url('#{$path}.ttf') format('truetype'), url('#{$path}.svg##{$svg}') format('svg')
font-weight: $weight
font-style: $style
Usage: For example, I can use the previous mixin to setup up the Frutiger Light font like this:
+font-face('frutigerlight', '../fonts/frutilig-webfont', 'frutigerlight')
For a google maps integration I was looking for a way to detect when a div has changed in size. Since google maps always require proper dimensions e.g. width and height in order to render properly.
The solution I came up with is a delegation of an event, in my case a tab click. This could be a window resize of course, the idea remains the same:
if (parent.is(':visible')) {
w = parent.outerWidth(false);
h = w * mapRatio /*9/16*/;
this.map.css({ width: w, height: h });
} else {
this.map.closest('.tab').one('click', function() {
this.activate();
}.bind(this));
}
this.map
in this case is my map div.
Since my parent is invisible on load, the computed width and height are 0 or don't match.
By using .bind(this)
I can delegate the script execution (this.activate
) to an event (click
).
Now I'm confident the same applies for resize events.
$(window).one('resize', function() {
this.div.css({ /*whatever*/ });
}.bind(this));
Hope it helps anyone!
To run a java file in Android ensure your class has the main method. In Android Studio 3.5 just right click inside the file and select "Run 'Filename.main()'" or click on "Run" on the menu and select "Run Filename" from the resulting drop-down menu.
You could also just call to_a after each_byte or even better String#bytes
=> 'hello world'.each_byte.to_a
=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
=> 'hello world'.bytes
=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
You can construct a pivot table for each distinct value of X
. In this case,
for xval, xgroup in g:
ptable = pd.pivot_table(xgroup, rows='Y', cols='Z',
margins=False, aggfunc=numpy.size)
will construct a pivot table for each value of X
. You may want to index ptable
using the xvalue
. With this code, I get (for X1
)
X
Z Z1 Z2 Z3
Y
Y1 2 1 NaN
Y2 NaN NaN 1
>>> from datetime import date, timedelta
>>> yesterday = date.today() - timedelta(days=1)
>>> yesterday.strftime('%m%d%y')
'110909'
The first parameter is the number of arguments provided and the second parameter is a list of strings representing those arguments.
Just change your syntax ever so slightly:
CASE WHEN STATE = 2 AND RetailerProcessType = 1 THEN '"AUTHORISED"'
WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
WHEN STATE = 2 AND RetailerProcessType = 2 THEN '"AUTHORISED"'
ELSE '"DECLINED"'
END
If you don't put the field expression before the CASE
statement, you can put pretty much any fields and comparisons in there that you want. It's a more flexible method but has slightly more verbose syntax.
You can't have duplicate keys in a Map
. You can rather create a Map<Key, List<Value>>
, or if you can, use Guava's Multimap
.
Multimap<Integer, String> multimap = ArrayListMultimap.create();
multimap.put(1, "rohit");
multimap.put(1, "jain");
System.out.println(multimap.get(1)); // Prints - [rohit, jain]
And then you can get the java.util.Map
using the Multimap#asMap()
method.
Compare value of phone2
with empty string:
select phone, phone2
from jewishyellow.users
where phone like '813%' and phone2<>''
Note that NULL
value is interpreted as false
.
If you do not want to the text twice as column heading as well as value, use the following stmt!
SELECT 'some text' as '';Example:
mysql>SELECT 'some text' as ''; +-----------+ | | +-----------+ | some text | +-----------+ 1 row in set (0.00 sec)
If you look at the source code for a StringBuilder or StringBuffer the setLength() call just resets an index value for the character array. IMHO using the setLength method will always be faster than a new allocation. They should have named the method 'clear' or 'reset' so it would be clearer.
Here is code for image encoding and image decoding.
In an XML file
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yyuyuyuuyuyuyu"
android:id="@+id/tv5"
/>
In a Java file:
TextView textView5;
Bitmap bitmap;
textView5 = (TextView) findViewById(R.id.tv5);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... voids) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
byte[] byteFormat = stream.toByteArray();
// Get the Base64 string
String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);
return imgString;
}
@Override
protected void onPostExecute(String s) {
textView5.setText(s);
}
}.execute();
jQuery has two methods
// First. Get content as HTML
$("#my_div_id").html();
// Second. Get content as text
$("#my_div_id").text();