On ubuntu, you also have to install imagemagick
and libmagickcore-dev
like this :
sudo apt-get install imagemagick libmagickcore-dev libmagickwand-dev
Everything is written in the doc.
This would require knowledge of a backend website language.
Fortunately, Python's Flask Library is a suitable backend language for the project at hand.
Check out this answer from another thread.
You can always take the CTE, (Common Tabular Expression), approach.
;WITH updateCTE AS
(
SELECT ID, TITLE
FROM HOLD_TABLE
WHERE ID = 101
)
UPDATE updateCTE
SET TITLE = 'TEST';
This could be the issue with the Java Build path. Try below steps :
This should resolve the issue.
Just a thought but what if you worked this problem from the opposite direction? Rather than determining which browsers are mobile why not determine which browsers are not? Then code your site to default to the mobile version and redirect to the standard version. There are two basic possibilities when looking at a mobile browser. Either it has javascript support or it doesn't. So if the browser does not have javascript support it will default to the mobile version. If it does have JavaScript support, check the screen size. Anything below a certain size will likely also be a mobile browser. Anything larger will get redirected to your standard layout. Then all you need to do is determine if the user with JavaScript disabled is mobile or not.
According to the W3C the number of users with JavaScript disabled was about 5% and of those users most have turned it off which implies that they actually know what they are doing with a browser. Are they a large part of your audience? If not then don't worry about them. If so, whats the worst case scenario? You have those users browsing the mobile version of your site, and that's a good thing.
Funny, I was just researching this yesterday!
I personally use Monaco 10 or 11 for the Mac, but a good cross platform font would have to be Droid Sans Mono: http://damieng.com/blog/2007/11/14/droid-sans-mono-great-coding-font Or DejaVu sans mono is another great one (goes under a lot of different names, will be Menlo on SNow leopard and is really just a repackaged Prima/Vera) check it out here: Prima/Vera... Check it out here: http://dejavu-fonts.org/wiki/index.php?title=Download
I had faced the same issue. I changed the return type of one method and ran the test code of that one class. That is when I faced this NoSuchMethodError
. As a solution, I ran the maven builds on the entire repository once, before running the test code again. The issue got resolved in the next single test run.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.YEAR, 2012);
cal.add(Calendar.DAY_OF_MONTH, 5);
You can also substract days like Calendar.add(Calendar.DAY_OF_MONTH, -5);
Async:
fs.readFile('test.txt', 'utf8', callback);
Sync:
var content = fs.readFileSync('test.txt', 'utf8');
This is really weird, why nobody is mentioning the /IM switch ?! I've been using it for a long time in backup jobs. But I tried googling just now and I couldn't land on a single web page that says anything about it even on MS website !!! Also found so many user posts complaining about the same issue!!
Anyway.. to use Robocopy to overwrite EVERYTHING what ever size or time in source or distination you must include these three switches in your command (/IS /IT /IM)
/IS :: Include Same files. (Includes same size files)
/IT :: Include Tweaked files. (Includes same files with different Attributes)
/IM :: Include Modified files (Includes same files with different times).
This is the exact command I use to transfer few TeraBytes of mostly 1GB+ files (ISOs - Disk Images - 4K Videos):
robocopy B:\Source D:\Destination /E /J /COPYALL /MT:1 /DCOPY:DATE /IS /IT /IM /X /V /NP /LOG:A:\ROBOCOPY.LOG
I did a small test for you .. and here is the result:
Total Copied Skipped Mismatch FAILED Extras
Dirs : 1028 1028 0 0 0 169
Files : 8053 8053 0 0 0 1
Bytes : 649.666 g 649.666 g 0 0 0 1.707 g
Times : 2:46:53 0:41:43 0:00:00 0:41:44
Speed : 278653398 Bytes/sec.
Speed : 15944.675 MegaBytes/min.
Ended : Friday, August 21, 2020 7:34:33 AM
Dest, Disk: WD Gold 6TB (Compare the write speed with my result)
Even with those "Extras", that's for reporting only because of the "/X" switch. As you can see nothing was Skipped and Total number and size of all files are equal to the Copied. Sometimes It will show small number of skipped files when I abuse it and cancel it multiple times during operation but even with that the values in the first 2 columns are always Equal. I also confirmed that once before by running a PowerShell script that scans all files in destination and generate a report of all time-stamps.
Some performance tips from my history with it and so many tests & troubles!:
. Despite of what most users online advise to use maximum threads "/MT:128" like it's a general trick to get the best performance ... PLEASE DON'T USE "/MT:128" WITH VERY LARGE FILES ... that's a big mistake and it will decrease your drive performance dramatically after several runs .. it will create very high fragmentation or even cause the files system to fail in some cases and you end up spending valuable time trying to recover a RAW partition and all that nonsense. And above all that, It will perform 4-6 times slower!!
benweet's solution, but also checking the visibility of the file before copy:
function copy(from, to) {
return new Promise(function (resolve, reject) {
fs.access(from, fs.F_OK, function (error) {
if (error) {
reject(error);
} else {
var inputStream = fs.createReadStream(from);
var outputStream = fs.createWriteStream(to);
function rejectCleanup(error) {
inputStream.destroy();
outputStream.end();
reject(error);
}
inputStream.on('error', rejectCleanup);
outputStream.on('error', rejectCleanup);
outputStream.on('finish', resolve);
inputStream.pipe(outputStream);
}
});
});
}
This should give you the required layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="@+id/flag"
android:layout_width="fill_parent"
android:layout_height="250dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:scaleType="fitXY"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Play with the android:layout_marginTop="20dp"
to see which one suits you better. Use the id textview
to dynamically set the android:text
value.
Since a RelativeLayout stacks its children, defining the TextView after ImageView puts it 'over' the ImageView.
NOTE: Similar results can be obtained using a FrameLayout
as the parent, along with the efficiency gain over using any other android container. Thanks to Igor Ganapolsky
(see comment below) for pointing out that this answer needs an update.
jQuery's each
is one option:
<div id="test">
<img src="testing.png"/>
<img src="testing1.png"/>
</div>
$('#test img').each(function(){
console.log($(this).attr('src'));
});
You can add Blank Line throw PdfContentByte
class in itextPdf
. As shown below:
package com.pdf.test;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class Ranvijay {
public static final String RESULT = "d:/printReport.pdf";
public void createPdf(String filename) throws Exception {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(filename));
document.open();
Font bold = new Font(Font.FontFamily.HELVETICA, 8f, Font.BOLD);
Font normal = new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL);
PdfPTable tabletmp = new PdfPTable(1);
tabletmp.getDefaultCell().setBorder(Rectangle.NO_BORDER);
tabletmp.setWidthPercentage(100);
PdfPTable table = new PdfPTable(2);
float[] colWidths = { 45, 55 };
table.setWidths(colWidths);
String imageUrl = "http://ssl.gstatic.com/s2/oz/images/logo/2x/googleplus_color_33-99ce54a16a32f6edc61a3e709eb61d31.png";
Image image2 = Image.getInstance(new URL(imageUrl));
image2.setWidthPercentage(60);
table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);
PdfPCell cell = new PdfPCell();
cell.setBorder(Rectangle.NO_BORDER);
cell.addElement(image2);
table.addCell(cell);
String email = "[email protected]";
String collectionDate = "09/09/09";
Chunk chunk1 = new Chunk("Date: ", normal);
Phrase ph1 = new Phrase(chunk1);
Chunk chunk2 = new Chunk(collectionDate, bold);
Phrase ph2 = new Phrase(chunk2);
Chunk chunk3 = new Chunk("\nEmail: ", normal);
Phrase ph3 = new Phrase(chunk3);
Chunk chunk4 = new Chunk(email, bold);
Phrase ph4 = new Phrase(chunk4);
Paragraph ph = new Paragraph();
ph.add(ph1);
ph.add(ph2);
ph.add(ph3);
ph.add(ph4);
table.addCell(ph);
tabletmp.addCell(table);
PdfContentByte canvas = writer.getDirectContent();
canvas.saveState();
canvas.setLineWidth((float) 10 / 10);
canvas.moveTo(40, 806 - (5 * 10));
canvas.lineTo(555, 806 - (5 * 10));
canvas.stroke();
document.add(tabletmp);
canvas.restoreState();
PdfPTable tabletmp1 = new PdfPTable(1);
tabletmp1.getDefaultCell().setBorder(Rectangle.NO_BORDER);
tabletmp1.setWidthPercentage(100);
document.add(tabletmp1);
document.close();
}
/**
* Main method.
*
* @param args
* no arguments needed
* @throws DocumentException
* @throws IOException
*/
public static void main(String[] args) throws Exception {
new Ranvijay().createPdf(RESULT);
System.out.println("Done Please check........");
}
}
net.exe stop "servicename" && net.exe start "servicename"
For an excellent resource on how bash invocation works, what dotfiles do what, and how you should use/configure them, read this:
Since I can not comment because of not having enough reward points I have to answer to correct answer given by @Burhan Khalid.
In very layman language Enter key press is combination of carriage return and line feed.
Carriage return points the cursor to the beginning of the line horizontly and Line feed shifts the cursor to the next line vertically.Combination of both gives you new line(\n) effect.
Reference - https://en.wikipedia.org/wiki/Carriage_return#Computers
I am a little late to the party but here is my part
$(document).on('keydown', function ( e ) {
// You may replace `c` with whatever key you want
if ((e.metaKey || e.ctrlKey) && ( String.fromCharCode(e.which).toLowerCase() === 'c') ) {
console.log( "You pressed CTRL + C" );
}
});
Note: in C# the term "function" is often replaced by the term "method". For the sake of this question there is no difference, so I'll just use the term "function".
The other answers have already given you a quick way to fix your problem (just make Add
a static
function), but I'd like to explain why.
C# has a fundamentally different design paradigm than C. That paradigm is called object-oriented programming (OOP). Explaining all the differences between OOP and functional programming is beyond the scope of this question, but here's the short version as it applies to you.
Writing your program in C, you would have created a function that adds two numbers, and that function would exist independently and be callable from anywhere. In C# most functions don't exist independently; instead, they exist in the context of an object. In your example code, only an instance (an object) of the class Program
knows how to perform Add
. Said another way, you have to create an instance of Program
, and then ask Program
to perform an Add
for you.
The solutions that people gave you, using the static
keyword, route around that design. Using the static
keyword is kind of like saying, "Hey, this function I'm defining doesn't need any context/state, it can just be called." Since your Add
function is very simple, this makes sense. As you start diving deeper into OOP, you're going to find that your functions get more complicated and rely on knowing their state/context.
My advice: Pick up an OOP book and get ready to switch your brain from functional programming to OOP programming. You're in for a ride.
If You want your upper axis to be a function of the lower axis tick-values you can do as below. Please note: sometimes get_xticks()
will have a ticks outside of the visible range, which you have to allow for when converting.
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
ax1 = fig.add_subplot(111)
ax1.plot(range(5), range(5))
ax1.grid(True)
ax2 = ax1.twiny()
ax2.set_xticks( ax1.get_xticks() )
ax2.set_xbound(ax1.get_xbound())
ax2.set_xticklabels([x * 2 for x in ax1.get_xticks()])
title = ax1.set_title("Upper x-axis ticks are lower x-axis ticks doubled!")
title.set_y(1.1)
fig.subplots_adjust(top=0.85)
fig.savefig("1.png")
Gives:
I noticed that Internet Explorer 11 gets incredibly slow when slicing the data like Jeremy suggested. This is true for Chrome, but Internet Explorer seems to have a problem when passing the sliced data to the Blob-Constructor. On my machine, passing 5 MB of data makes Internet Explorer crash and memory consumption is going through the roof. Chrome creates the blob in no time.
Run this code for a comparison:
var byteArrays = [],
megaBytes = 2,
byteArray = new Uint8Array(megaBytes*1024*1024),
block,
blobSlowOnIE, blobFastOnIE,
i;
for (i = 0; i < (megaBytes*1024); i++) {
block = new Uint8Array(1024);
byteArrays.push(block);
}
//debugger;
console.profile("No Slices");
blobSlowOnIE = new Blob(byteArrays, { type: 'text/plain'});
console.profileEnd();
console.profile("Slices");
blobFastOnIE = new Blob([byteArray], { type: 'text/plain'});
console.profileEnd();
So I decided to include both methods described by Jeremy in one function. Credits go to him for this.
function base64toBlob(base64Data, contentType, sliceSize) {
var byteCharacters,
byteArray,
byteNumbers,
blobData,
blob;
contentType = contentType || '';
byteCharacters = atob(base64Data);
// Get BLOB data sliced or not
blobData = sliceSize ? getBlobDataSliced() : getBlobDataAtOnce();
blob = new Blob(blobData, { type: contentType });
return blob;
/*
* Get BLOB data in one slice.
* => Fast in Internet Explorer on new Blob(...)
*/
function getBlobDataAtOnce() {
byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
byteArray = new Uint8Array(byteNumbers);
return [byteArray];
}
/*
* Get BLOB data in multiple slices.
* => Slow in Internet Explorer on new Blob(...)
*/
function getBlobDataSliced() {
var slice,
byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
slice = byteCharacters.slice(offset, offset + sliceSize);
byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
byteArray = new Uint8Array(byteNumbers);
// Add slice
byteArrays.push(byteArray);
}
return byteArrays;
}
}
FirefoxProfile profile = new FirefoxProfile();
String PROXY = "xx.xx.xx.xx:xx";
OpenQA.Selenium.Proxy proxy = new OpenQA.Selenium.Proxy();
proxy.HttpProxy=PROXY;
proxy.FtpProxy=PROXY;
proxy.SslProxy=PROXY;
profile.SetProxyPreferences(proxy);
FirefoxDriver driver = new FirefoxDriver(profile);
It is for C#
Integrated Security=true;
doesn't work in all SQL providers, it throws an exception when used with the OleDb
provider.
So basically Integrated Security=SSPI;
is preferred since works with both SQLClient
& OleDB
provider.
Here's the full set of syntaxes according to MSDN - Connection String Syntax (ADO.NET)
When you try to execute a program in unix (one with the executable bit set), the operating system will look at the first few bytes of the file. These form the so-called "magic number", which can be used to decide the format of the program and how to execute it.
#!
corresponds to the magic number 0x2321 (look it up in an ascii table). When the system sees that the magic number, it knows that it is dealing with a text script and reads until the next \n
(there is a limit, but it escapes me atm). Having identified the interpreter (the first argument after the shebang) it will call the interpreter.
Other files also have magic numbers. Try looking at a bitmap (.BMP) file via less
and you will see the first two characters are BM
. This magic number denotes that the file is indeed a bitmap.
Convert String to Hexadecimal:
public String hexToString(String hex) {
return Integer.toHexString(Integer.parseInt(hex));
}
definitely this is the easy way.
Not really, you have to assign a variable. So
var bar = Stuff.Elements.Foo;
bar.Name = "Bob Dylan";
bar.Age = 68;
bar.Location = "On Tour";
bar.IsCool = True;
Or in C# 3.0:
var bar = Stuff.Elements.Foo
{
Name = "Bob Dylan",
Age = 68,
Location = "On Tour",
IsCool = True
};
You can't unless you're using some kind of extended CSS such as SASS. However it is very reasonable to apply those two extra classes to .someDiv
.
If .someDiv
is unique I would also choose to give it an id and referencing it in css using the id.
The documentation on how to do this can be found on MSDN. The key extract is this:
To programmatically add or modify system environment variables, add them to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, then broadcast a
WM_SETTINGCHANGE
message with lParam set to the string "Environment". This allows applications, such as the shell, to pick up your updates.
Note that your application will need elevated admin rights in order to be able to modify this key.
You indicate in the comments that you would be happy to modify just the per-user environment. Do this by editing the values in HKEY_CURRENT_USER\Environment. As before, make sure that you broadcast a WM_SETTINGCHANGE
message.
You should be able to do this from your Java application easily enough using the JNI registry classes.
I write this Method to convert date time to our LocalTimeZone
-Here (NSString *)TimeZone parameter is a server timezone
-(NSString *)convertTimeIntoLocal:(NSString *)defaultTime :(NSString *)TimeZone
{
NSDateFormatter *serverFormatter = [[NSDateFormatter alloc] init];
[serverFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:TimeZone]];
[serverFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *theDate = [serverFormatter dateFromString:defaultTime];
NSDateFormatter *userFormatter = [[NSDateFormatter alloc] init];
[userFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[userFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *dateConverted = [userFormatter stringFromDate:theDate];
return dateConverted;
}
I had the same problem and couldn't find the right solution so I wrote a function called GetFiles:
/// <summary>
/// Get all files with a specific extension
/// </summary>
/// <param name="extensionsToCompare">string list of all the extensions</param>
/// <param name="Location">string of the location</param>
/// <returns>array of all the files with the specific extensions</returns>
public string[] GetFiles(List<string> extensionsToCompare, string Location)
{
List<string> files = new List<string>();
foreach (string file in Directory.GetFiles(Location))
{
if (extensionsToCompare.Contains(file.Substring(file.IndexOf('.')+1).ToLower())) files.Add(file);
}
files.Sort();
return files.ToArray();
}
This function will call Directory.Getfiles()
only one time.
For example call the function like this:
string[] images = GetFiles(new List<string>{"jpg", "png", "gif"}, "imageFolder");
EDIT: To get one file with multiple extensions use this one:
/// <summary>
/// Get the file with a specific name and extension
/// </summary>
/// <param name="filename">the name of the file to find</param>
/// <param name="extensionsToCompare">string list of all the extensions</param>
/// <param name="Location">string of the location</param>
/// <returns>file with the requested filename</returns>
public string GetFile( string filename, List<string> extensionsToCompare, string Location)
{
foreach (string file in Directory.GetFiles(Location))
{
if (extensionsToCompare.Contains(file.Substring(file.IndexOf('.') + 1).ToLower()) &&& file.Substring(Location.Length + 1, (file.IndexOf('.') - (Location.Length + 1))).ToLower() == filename)
return file;
}
return "";
}
For example call the function like this:
string image = GetFile("imagename", new List<string>{"jpg", "png", "gif"}, "imageFolder");
-webkit-padding-start: 0;
will remove padding added by webkit engine
You can use useValue
in providers
import { MyService } from './my.service';
@NgModule({
...
providers: [ { provide: MyService, useValue: new MyService() } ],
...
})
Any of the above answers are valid, or an alternative way is to expand the table name to include the database name as well - eg:
SELECT * from us_music, de_music where `us_music.genre` = 'punk' AND `de_music.genre` = 'punk'
If you wanna maintain the same order in your list, say: your Map looks like:
map.put(1, "msg1")
map.put(2, "msg2")
map.put(3, "msg3")
and you want your list looks like
["msg1", "msg2", "msg3"] // same order as the map
you will have to iterate through the Map:
// sort your map based on key, otherwise you will get IndexOutofBoundException
Map<String, String> treeMap = new TreeMap<String, String>(map)
List<String> list = new List<String>();
for (treeMap.Entry<Integer, String> entry : treeMap.entrySet()) {
list.add(entry.getKey(), entry.getValue());
}
payton109’s answer is correct if you’re in the default US-EAST-1 region. If your bucket is in a different region, use a slightly different URL:
https://s3-<region>.amazonaws.com/your.domain.com/some/asset
Where <region>
is the bucket location name. For example, if your bucket is in the us-west-2
(Oregon) region, you can do this:
https://s3-us-west-2.amazonaws.com/your.domain.com/some/asset
For restarting the animation of a gif image, you can use the code:
$('#img_gif').attr('src','file.gif?' + Math.random());
Personally I'm doing this using ngx-material-file-input for the front-end, and Firebase for the back-end. More precisely Cloud Storage for Firebase for the back-end combined with Cloud Firestore. Below an example, which limits file to be not larger than 20 MB, and accepts only certain file extensions. I'm also using Cloud Firestore for storing links to the uploaded files, but you can skip this.
contact.component.html
<mat-form-field>
<!--
Accept only files in the following format: .doc, .docx, .jpg, .jpeg, .pdf, .png, .xls, .xlsx. However, this is easy to bypass, Cloud Storage rules has been set up on the back-end side.
-->
<ngx-mat-file-input
[accept]="[
'.doc',
'.docx',
'.jpg',
'.jpeg',
'.pdf',
'.png',
'.xls',
'.xlsx'
]"
(change)="uploadFile($event)"
formControlName="fileUploader"
multiple
aria-label="Here you can add additional files about your project, which can be helpeful for us."
placeholder="Additional files"
title="Additional files"
type="file"
>
</ngx-mat-file-input>
<mat-icon matSuffix>folder</mat-icon>
<mat-hint
>Accepted formats: DOC, DOCX, JPG, JPEG, PDF, PNG, XLS and XLSX,
maximum files upload size: 20 MB.
</mat-hint>
<!--
Non-null assertion operators are required to let know the compiler that this value is not empty and exists.
-->
<mat-error
*ngIf="contactForm.get('fileUploader')!.hasError('maxContentSize')"
>
This size is too large,
<strong
>maximum acceptable upload size is
{{
contactForm.get('fileUploader')?.getError('maxContentSize')
.maxSize | byteFormat
}}</strong
>
(uploaded size:
{{
contactForm.get('fileUploader')?.getError('maxContentSize')
.actualSize | byteFormat
}}).
</mat-error>
</mat-form-field>
contact.component.ts (size validator part)
import { FileValidator } from 'ngx-material-file-input';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
/**
* @constructor
* @description Creates a new instance of this component.
* @param {formBuilder} - an abstraction class object to create a form group control for the contact form.
*/
constructor(
private angularFirestore: AngularFirestore,
private angularFireStorage: AngularFireStorage,
private formBuilder: FormBuilder
) {}
public maxFileSize = 20971520;
public contactForm: FormGroup = this.formBuilder.group({
fileUploader: [
'',
Validators.compose([
FileValidator.maxContentSize(this.maxFileSize),
Validators.maxLength(512),
Validators.minLength(2)
])
]
})
contact.component.ts (file uploader part)
import { AngularFirestore } from '@angular/fire/firestore';
import {
AngularFireStorage,
AngularFireStorageReference,
AngularFireUploadTask
} from '@angular/fire/storage';
import { catchError, finalize } from 'rxjs/operators';
import { throwError } from 'rxjs';
public downloadURL: string[] = [];
/**
* @description Upload additional files to Cloud Firestore and get URL to the files.
* @param {event} - object of sent files.
* @returns {void}
*/
public uploadFile(event: any): void {
// Iterate through all uploaded files.
for (let i = 0; i < event.target.files.length; i++) {
const randomId = Math.random()
.toString(36)
.substring(2); // Create random ID, so the same file names can be uploaded to Cloud Firestore.
const file = event.target.files[i]; // Get each uploaded file.
// Get file reference.
const fileRef: AngularFireStorageReference = this.angularFireStorage.ref(
randomId
);
// Create upload task.
const task: AngularFireUploadTask = this.angularFireStorage.upload(
randomId,
file
);
// Upload file to Cloud Firestore.
task
.snapshotChanges()
.pipe(
finalize(() => {
fileRef.getDownloadURL().subscribe((downloadURL: string) => {
this.angularFirestore
.collection(process.env.FIRESTORE_COLLECTION_FILES!) // Non-null assertion operator is required to let know the compiler that this value is not empty and exists.
.add({ downloadURL: downloadURL });
this.downloadURL.push(downloadURL);
});
}),
catchError((error: any) => {
return throwError(error);
})
)
.subscribe();
}
}
storage.rules
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read; // Required in order to send this as attachment.
// Allow write files Firebase Storage, only if:
// 1) File is no more than 20MB
// 2) Content type is in one of the following formats: .doc, .docx, .jpg, .jpeg, .pdf, .png, .xls, .xlsx.
allow write: if request.resource.size <= 20 * 1024 * 1024
&& (request.resource.contentType.matches('application/msword')
|| request.resource.contentType.matches('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
|| request.resource.contentType.matches('image/jpg')
|| request.resource.contentType.matches('image/jpeg')
|| request.resource.contentType.matches('application/pdf')
|| request.resource.contentType.matches('image/png')
|| request.resource.contentType.matches('application/vnd.ms-excel')
|| request.resource.contentType.matches('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'))
}
}
}
System.out.println("Link : " + s3Object.getObjectContent().getHttpRequest().getURI());
with this you can retrieve the link of already uploaded file to S3 bucket.
Try passing it directly to the ng-click function:
<div class="col-lg-1 text-center">
<span class="glyphicon glyphicon-trash" data="{{event.id}}"
ng-click="deleteEvent(event.id)"></span>
</div>
Then it should be available in your handler:
$scope.deleteEvent=function(idPassedFromNgClick){
console.log(idPassedFromNgClick);
}
Here's an example
Nowadays there IS support of Apache Commons Lang's StringUtils,
This is the primitive:
int org.apache.commons.lang.StringUtils.ordinalIndexOf(CharSequence str, CharSequence searchStr, int ordinal)
for your problem you can code the following: StringUtils.ordinalIndexOf(uri, "/", 3)
You can also find the last nth occurrence of a character in a string with the lastOrdinalIndexOf method.
Try reducing the range of the for loop to range(len(a)-1)
:
a = [0,1,2,3]
b = []
for i in range(len(a)-1):
b.append(a[i]+a[i+1])
print(b)
This can also be written as a list comprehension:
b = [a[i] + a[i+1] for i in range(len(a)-1)]
print(b)
I wrote a Higher-Order Component called withScrollToTop
. This HOC takes in two flags:
onComponentWillMount
- Whether to scroll to top upon navigation (componentWillMount
)onComponentDidUpdate
- Whether to scroll to top upon update (componentDidUpdate
). This flag is necessary in cases where the component is not unmounted but a navigation event occurs, for example, from /users/1
to /users/2
.// @flow
import type { Location } from 'react-router-dom';
import type { ComponentType } from 'react';
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
type Props = {
location: Location,
};
type Options = {
onComponentWillMount?: boolean,
onComponentDidUpdate?: boolean,
};
const defaultOptions: Options = {
onComponentWillMount: true,
onComponentDidUpdate: true,
};
function scrollToTop() {
window.scrollTo(0, 0);
}
const withScrollToTop = (WrappedComponent: ComponentType, options: Options = defaultOptions) => {
return class withScrollToTopComponent extends Component<Props> {
props: Props;
componentWillMount() {
if (options.onComponentWillMount) {
scrollToTop();
}
}
componentDidUpdate(prevProps: Props) {
if (options.onComponentDidUpdate &&
this.props.location.pathname !== prevProps.location.pathname) {
scrollToTop();
}
}
render() {
return <WrappedComponent {...this.props} />;
}
};
};
export default (WrappedComponent: ComponentType, options?: Options) => {
return withRouter(withScrollToTop(WrappedComponent, options));
};
To use it:
import withScrollToTop from './withScrollToTop';
function MyComponent() { ... }
export default withScrollToTop(MyComponent);
Try this way:
HashMap<String, Integer> hashMap = new HashMap();
for (int i=1; i<=3; i++) {
hashMap.put("n" + i, 5);
}
Be advised that if you're using nodejs there's (at the time of writing) a dependency on libssl 1.0.* - so installing an alternative SSL library will break your nodejs installation.
An alternative solution to installing a different SSL library is that posted in this answer here: https://stackoverflow.com/a/59927568/13564342 to instead install libcurl4-gnutls-dev
sudo apt install libcurl4-gnutls-dev
You need to use ScriptManager.RegisterStartupScript for Ajax.
protected void ButtonPP_Click(object sender, EventArgs e) { if (radioBtnACO.SelectedIndex < 0) { string csname1 = "PopupScript"; var cstext1 = new StringBuilder(); cstext1.Append("alert('Please Select Criteria!')"); ScriptManager.RegisterStartupScript(this, GetType(), csname1, cstext1.ToString(), true); } }
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast with the procedural programming style that emphasizes changes in state.
Doesn't look like you are using the correct overload of ActionLink. Try this:-
<%=Html.ActionLink("Modify Villa", "Modify", new {id = "1"})%>
This assumes your view is under the /Views/Villa folder. If not then I suspect you need:-
<%=Html.ActionLink("Modify Villa", "Modify", "Villa", new {id = "1"}, null)%>
The way I do this is to git add
this first then git stash apply <stash code>
. It's the most simple way.
You can use Len(StrFile) > 0
in loop check statement !
Sub openMyfile()
Dim Source As String
Dim StrFile As String
'do not forget last backslash in source directory.
Source = "E:\Planning\03\"
StrFile = Dir(Source)
Do While Len(StrFile) > 0
Workbooks.Open Filename:=Source & StrFile
StrFile = Dir()
Loop
End Sub
If it's not possible to start the main process again (for long enough), there is also the possibility to commit
the container to a new image and run a new container from this image. While this is not the usual best practice workflow, I find it really useful to debug a failing script once in a while.
docker exec -it 6198ef53d943 bash
Error response from daemon: Container 6198ef53d9431a3f38e8b38d7869940f7fb803afac4a2d599812b8e42419c574 is not running
docker commit 6198ef53d943
sha256:ace7ca65e6e3fdb678d9cdfb33a7a165c510e65c3bc28fecb960ac993c37ef33
docker run -it ace7ca65e6e bash
root@72d38a8c787d:/#
I found python in 1988 and fell in love with it. Our group at work had been dissolved and we were looking for other jobs on site, so I had a couple of months to play around doing whatever I wanted to. I spent the time profitably learning and using python. I suggest you spend time thinking up and writing utilities and various useful tools. I've got 200-300 in my python tools library now (can't even remember them all). I learned python from Guido's tutorial, which is a good place to start (a C programmer will feel right at home).
python is also a great tool for making models -- physical, math, stochastic, etc. Use numpy and scipy. It also wouldn't hurt to learn some GUI stuff -- I picked up wxPython and learned it, as I had some experience using wxWidgets in C++. wxPython has some impressive demo stuff!
This is how i solve this issue.
The answer of Jonathan Amend on this post helped me a lot.
The example below is simplified.
For more details, the above source code is able to download a file using a JQuery Ajax request (GET, POST, PUT etc). It, also, helps to upload parameters as JSON and to change the content type to application/json (my default).
The html source:
<form method="POST">
<input type="text" name="startDate"/>
<input type="text" name="endDate"/>
<input type="text" name="startDate"/>
<select name="reportTimeDetail">
<option value="1">1</option>
</select>
<button type="submit"> Submit</button>
</form>
A simple form with two input text, one select and a button element.
The javascript page source:
<script type="text/javascript" src="JQuery 1.11.0 link"></script>
<script type="text/javascript">
// File Download on form submition.
$(document).on("ready", function(){
$("form button").on("click", function (event) {
event.stopPropagation(); // Do not propagate the event.
// Create an object that will manage to download the file.
new AjaxDownloadFile({
url: "url that returns a file",
data: JSON.stringify($("form").serializeObject())
});
return false; // Do not submit the form.
});
});
</script>
A simple event on button click. It creates an AjaxDownloadFile object. The AjaxDownloadFile class source is below.
The AjaxDownloadFile class source:
var AjaxDownloadFile = function (configurationSettings) {
// Standard settings.
this.settings = {
// JQuery AJAX default attributes.
url: "",
type: "POST",
headers: {
"Content-Type": "application/json; charset=UTF-8"
},
data: {},
// Custom events.
onSuccessStart: function (response, status, xhr, self) {
},
onSuccessFinish: function (response, status, xhr, self, filename) {
},
onErrorOccured: function (response, status, xhr, self) {
}
};
this.download = function () {
var self = this;
$.ajax({
type: this.settings.type,
url: this.settings.url,
headers: this.settings.headers,
data: this.settings.data,
success: function (response, status, xhr) {
// Start custom event.
self.settings.onSuccessStart(response, status, xhr, self);
// Check if a filename is existing on the response headers.
var filename = "";
var disposition = xhr.getResponseHeader("Content-Disposition");
if (disposition && disposition.indexOf("attachment") !== -1) {
var filenameRegex = /filename[^;=\n]*=(([""]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1])
filename = matches[1].replace(/[""]/g, "");
}
var type = xhr.getResponseHeader("Content-Type");
var blob = new Blob([response], {type: type});
if (typeof window.navigator.msSaveBlob !== "undefined") {
// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed.
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
// Use HTML5 a[download] attribute to specify filename.
var a = document.createElement("a");
// Safari doesn"t support this yet.
if (typeof a.download === "undefined") {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location = downloadUrl;
}
setTimeout(function () {
URL.revokeObjectURL(downloadUrl);
}, 100); // Cleanup
}
// Final custom event.
self.settings.onSuccessFinish(response, status, xhr, self, filename);
},
error: function (response, status, xhr) {
// Custom event to handle the error.
self.settings.onErrorOccured(response, status, xhr, self);
}
});
};
// Constructor.
{
// Merge settings.
$.extend(this.settings, configurationSettings);
// Make the request.
this.download();
}
};
I created this class to added to my JS library. It is reusable. Hope that helps.
Search for [ ]{2,}
. This will find two or more adjacent spaces anywhere within the line. It will also match leading and trailing spaces as well as lines that consist entirely of spaces. If you don't want that, check out Alexander's answer.
Actually, you can leave out the brackets, they are just for clarity (otherwise the space character that is being repeated isn't that well visible :)).
The problem with \s{2,}
is that it will also match newlines on Windows files (where newlines are denoted by CRLF
or \r\n
which is matched by \s{2}
.
If you also want to find multiple tabs and spaces, use [ \t]{2,}
.
Swift code can be deployed to OS X 10.9 and iOS 7.0. It will usually crash at launch on older OS versions.
HTTPS proxy doesn't make sense because you can't terminate your HTTP connection at the proxy for security reasons. With your trust policy, it might work if the proxy server has a HTTPS port. Your error is caused by connecting to HTTP proxy port with HTTPS.
You can connect through a proxy using SSL tunneling (many people call that proxy) using proxy CONNECT command. However, Java doesn't support newer version of proxy tunneling. In that case, you need to handle the tunneling yourself. You can find sample code here,
http://www.javaworld.com/javaworld/javatips/jw-javatip111.html
EDIT: If you want defeat all the security measures in JSSE, you still need your own TrustManager. Something like this,
public SSLTunnelSocketFactory(String proxyhost, String proxyport){
tunnelHost = proxyhost;
tunnelPort = Integer.parseInt(proxyport);
dfactory = (SSLSocketFactory)sslContext.getSocketFactory();
}
...
connection.setSSLSocketFactory( new SSLTunnelSocketFactory( proxyHost, proxyPort ) );
connection.setDefaultHostnameVerifier( new HostnameVerifier()
{
public boolean verify( String arg0, SSLSession arg1 )
{
return true;
}
} );
EDIT 2: I just tried my program I wrote a few years ago using SSLTunnelSocketFactory and it doesn't work either. Apparently, Sun introduced a new bug sometime in Java 5. See this bug report,
http://bugs.sun.com/view_bug.do?bug_id=6614957
The good news is that the SSL tunneling bug is fixed so you can just use the default factory. I just tried with a proxy and everything works as expected. See my code,
public class SSLContextTest {
public static void main(String[] args) {
System.setProperty("https.proxyHost", "proxy.xxx.com");
System.setProperty("https.proxyPort", "8888");
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
// set up a TrustManager that trusts everything
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
System.out.println("getAcceptedIssuers =============");
return null;
}
public void checkClientTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkClientTrusted =============");
}
public void checkServerTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkServerTrusted =============");
}
} }, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(
sslContext.getSocketFactory());
HttpsURLConnection
.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String arg0, SSLSession arg1) {
System.out.println("hostnameVerifier =============");
return true;
}
});
URL url = new URL("https://www.verisign.net");
URLConnection conn = url.openConnection();
BufferedReader reader =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is what I get when I run the program,
checkServerTrusted =============
hostnameVerifier =============
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
......
As you can see, both SSLContext and hostnameVerifier are getting called. HostnameVerifier is only involved when the hostname doesn't match the cert. I used "www.verisign.net" to trigger this.
You can use the struct's pack:
In [11]: struct.pack(">I", 1)
Out[11]: '\x00\x00\x00\x01'
The ">" is the byte-order (big-endian) and the "I" is the format character. So you can be specific if you want to do something else:
In [12]: struct.pack("<H", 1)
Out[12]: '\x01\x00'
In [13]: struct.pack("B", 1)
Out[13]: '\x01'
This works the same on both python 2 and python 3.
Note: the inverse operation (bytes to int) can be done with unpack.
The syntax for creating a new table is
CREATE TABLE new_table
AS
SELECT *
FROM old_table
This will create a new table named new_table
with whatever columns are in old_table
and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.
SELECT INTO
is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.
Maybe you could look at why they are complaining. If a php file has a newline after the ending ?>, php will output it as part of the page. This is not a problem unless you try to send headers after the file is included.
However, the ?> at the end of a php file is optional. No ending ?>, no problem with a newline at the end of the file.
I just learned something new thanks to Artiso. I gave each module a name in the properties box. These names were also what I declared in the module. When I tried to call my second module, I kept getting an error: Compile error: Expected variable or procedure, not module
After reading Artiso's comment above about not having the same names, I renamed my second module, called it from the first, and problem solved. Interesting stuff! Thanks for the info Artiso!
In case my experience is unclear:
Module Name: AllFSGroupsCY Public Sub AllFSGroupsCY()
Module Name: AllFSGroupsPY Public Sub AllFSGroupsPY()
From AllFSGroupsCY()
Public Sub FSGroupsCY()
AllFSGroupsPY 'will error each time until the properties name is changed
End Sub
This should help. How can I upload files asynchronously?
As the post suggest I recommend a plugin located here http://malsup.com/jquery/form/#code-samples
Check if the user has scrolled past the header ad, then display the footer ad.
if($(your header ad).position().top < 0) { $(your footer ad).show() }
Am I correct at what you are looking for?
Here:
http://jsbin.com/urize4/edit
Live Preview
http://jsbin.com/urize4/
You should use "readonly
" instead like:
$("input[type='text']").attr("readonly", "true");
In the interest of possibly saving someone a minute or two, here is the solution that was used in Objective-C instead of python. This version takes an NSArray of NSValues that contain MKMapCoordinates, which was called for in my implementation:
#import <MapKit/MKGeometry.h>
+ (CLLocationCoordinate2D)centerCoordinateForCoordinates:(NSArray *)coordinateArray {
double x = 0;
double y = 0;
double z = 0;
for(NSValue *coordinateValue in coordinateArray) {
CLLocationCoordinate2D coordinate = [coordinateValue MKCoordinateValue];
double lat = GLKMathDegreesToRadians(coordinate.latitude);
double lon = GLKMathDegreesToRadians(coordinate.longitude);
x += cos(lat) * cos(lon);
y += cos(lat) * sin(lon);
z += sin(lat);
}
x = x / (double)coordinateArray.count;
y = y / (double)coordinateArray.count;
z = z / (double)coordinateArray.count;
double resultLon = atan2(y, x);
double resultHyp = sqrt(x * x + y * y);
double resultLat = atan2(z, resultHyp);
CLLocationCoordinate2D result = CLLocationCoordinate2DMake(GLKMathRadiansToDegrees(resultLat), GLKMathRadiansToDegrees(resultLon));
return result;
}
I dislike having Docker environment variables when I do not expect user of a Docker image to change them.
Just put it somewhere in one RUN
. If you do not have UTF-8 locales generated, then you can do the following set of commands:
export DEBIAN_FRONTEND=noninteractive
apt-get update -q -q
apt-get install --yes locales
locale-gen --no-purge en_US.UTF-8
update-locale LANG=en_US.UTF-8
echo locales locales/locales_to_be_generated multiselect en_US.UTF-8 UTF-8 | debconf-set-selections
echo locales locales/default_environment_locale select en_US.UTF-8 | debconf-set-selections
dpkg-reconfigure locales
localhost is a special hostname that almost always resolves to 127.0.0.1. If you ask someone else to connect to http://localhost
they'll be connecting to their computer instead or yours.
To share your web server with someone else you'll need to find your IP address or your hostname and provide that to them instead. On windows you can find this with ipconfig /all
on a command line.
You'll also need to make sure any firewalls you may have configured allow traffic on port 80 to connect to the WAMP server.
you can use enumerate keeping the ind/index of the elements is in vm, if you make vm
a set you will also have 0(1)
lookups:
vm = {-1, -1, -1, -1}
print([ind if q in vm else 9999 for ind,ele in enumerate(vm) ])
I think the best way is to put your includes in your PHP include path. There are various ways to do this depending on your setup.
Then you can simply refer to
require_once 'inc1.php';
from inside any file regardless of where it is whether in your includes or in your web accessible files, or any level of nested subdirectories.
This allows you to have your include files outside the web server root, which is a best practice.
e.g.
site directory
html (web root)
your web-accessible files
includes
your include files
Also, check out __autoload for lazy loading of class files
h5py provides a model of datasets and groups. The former is basically arrays and the latter you can think of as directories. Each is named. You should look at the documentation for the API and examples:
http://docs.h5py.org/en/latest/quick.html
A simple example where you are creating all of the data upfront and just want to save it to an hdf5 file would look something like:
In [1]: import numpy as np
In [2]: import h5py
In [3]: a = np.random.random(size=(100,20))
In [4]: h5f = h5py.File('data.h5', 'w')
In [5]: h5f.create_dataset('dataset_1', data=a)
Out[5]: <HDF5 dataset "dataset_1": shape (100, 20), type "<f8">
In [6]: h5f.close()
You can then load that data back in using: '
In [10]: h5f = h5py.File('data.h5','r')
In [11]: b = h5f['dataset_1'][:]
In [12]: h5f.close()
In [13]: np.allclose(a,b)
Out[13]: True
Definitely check out the docs:
Writing to hdf5 file depends either on h5py or pytables (each has a different python API that sits on top of the hdf5 file specification). You should also take a look at other simple binary formats provided by numpy natively such as np.save
, np.savez
etc:
Lamp stack stands for Linux Apache Mysql PHP
there is also Mean Stack MongoDB ExpressJS AngularJS NodeJS
A project can be referenced by multiple solutions.
Put your library or core code into one project, then reference that project in both solutions.
You may be better off working out what value type your function or code accepts, and asking for that:
if (is.integer(aVariable))
{
do whatever
}
This may be an improvement over isnull, because it provides type checking. On the other hand, it may reduce the genericity of your code.
Alternatively, just make the function you want:
is.defined = function(x)!is.null(x)
Shift-Tab
Ctrl-Tab
< key
depends on your editor.
Visual Studio Community 2015 suffices to build extensions for Python 3.5. It's free but a 6 GB download (overkill). On my computer it installed vcvarsall at C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat
For Python 3.4 you'd need Visual Studio 2010. I don't think there's any free edition. See https://matthew-brett.github.io/pydagogue/python_msvc.html
This is one of the dumb mistakes I've done. I spent a lot of time trying to debug this problem and tried all the responses posted above, but in the end, it was one of my many dumb mistakes.
I was using org.apache.logging.log4j.Logger
(:fml:) whereas I should have used org.apache.log4j.Logger
. Using this correct logger saved my evening.
If you are willing to use std::array
instead of built-in arrays, you may use:
std::array<int, 5> iar1 = {1,2,3,4,5};
std::array<int, 5> iar2 = {1,2,3,4,5};
if (iar1 == iar2)
Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.
You've got:
//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]
Which translates into:
Get me all the elements that have an ID
that contains ctl00_btnAircraftMapCell
. Out of these elements, get any child elements that have a title
that contains Select Seat
.
What you actually want is:
//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]
Which translates into:
Get me all the anchor elements that have both: an id
that contains ctl00_btnAircraftMapCell
and a title
that contains Select Seat
.
Here is another method to add days on date using dateutil's relativedelta.
from datetime import datetime
from dateutil.relativedelta import relativedelta
print 'Today: ',datetime.now().strftime('%d/%m/%Y %H:%M:%S')
date_after_month = datetime.now()+ relativedelta(day=1)
print 'After a Days:', date_after_month.strftime('%d/%m/%Y %H:%M:%S')
Output:
Today: 25/06/2015 20:41:44
After a Days: 01/06/2015 20:41:44
777
!If you use nginx (like me), just change the ownership of the folders under /var/lib/php/
from apache
to nginx
:
[root@centos ~]# cd /var/lib/php/
[root@centos php]# ll
total 12
drwxrwx---. 2 root apache 4096 Jan 30 16:23 opcache
drwxrwx---. 2 root apache 4096 Feb 5 20:56 session
drwxrwx---. 2 root apache 4096 Jan 30 16:23 wsdlcache
[root@centos php]# chown -R :nginx opcache/
[root@centos php]# chown -R :nginx session/
[root@centos php]# chown -R :nginx wsdlcache/
[root@centos php]# ll
total 12
drwxrwx---. 2 root nginx 4096 Jan 30 16:23 opcache
drwxrwx---. 2 root nginx 4096 Feb 5 20:56 session
drwxrwx---. 2 root nginx 4096 Jan 30 16:23 wsdlcache
And also for the folders under /var/lib/phpMyAdmin/
:
[root@centos php]# cd /var/lib/phpMyAdmin
[root@centos phpMyAdmin]# ll
total 12
drwxr-x---. 2 apache apache 4096 Dec 23 20:29 config
drwxr-x---. 2 apache apache 4096 Dec 23 20:29 save
drwxr-x---. 2 apache apache 4096 Dec 23 20:29 upload
[root@centos phpMyAdmin]# chown -R nginx:nginx config/
[root@centos phpMyAdmin]# chown -R nginx:nginx save/
[root@centos phpMyAdmin]# chown -R nginx:nginx upload/
[root@centos phpMyAdmin]# ll
total 12
drwxr-x---. 2 nginx nginx 4096 Dec 23 20:29 config
drwxr-x---. 2 nginx nginx 4096 Dec 23 20:29 save
drwxr-x---. 2 nginx nginx 4096 Dec 23 20:29 upload
Based on your comments it sounds like you are doing something like this:
Thread thread = new Thread(new Runnable(){
public void run() { // do stuff }});
thread.start();
...
thread.wait();
There are three problems.
As others have said, obj.wait()
can only be called if the current thread holds the primitive lock / mutex for obj
. If the current thread does not hold the lock, you get the exception you are seeing.
The thread.wait()
call does not do what you seem to be expecting it to do. Specifically, thread.wait()
does not cause the nominated thread to wait. Rather it causes the current thread to wait until some other thread calls thread.notify()
or thread.notifyAll()
.
There is actually no safe way to force a Thread
instance to pause if it doesn't want to. (The nearest that Java has to this is the deprecated Thread.suspend()
method, but that method is inherently unsafe, as is explained in the Javadoc.)
If you want the newly started Thread
to pause, the best way to do it is to create a CountdownLatch
instance and have the thread call await()
on the latch to pause itself. The main thread would then call countDown()
on the latch to let the paused thread continue.
Orthogonal to the previous points, using a Thread
object as a lock / mutex may cause problems. For example, the javadoc for Thread::join
says:
This implementation uses a loop of
this.wait
calls conditioned onthis.isAlive
. As a thread terminates thethis.notifyAll
method is invoked. It is recommended that applications not usewait
,notify
, ornotifyAll
onThread
instances.
delete your local branch by following command
git branch -d branch_name
you could also do
git branch -D branch_name
which basically force a delete (even if local not merged to source)
SHOULD be unique does not mean MUST be unique. However, as stated, some parsers would fail and others would just use the last value parsed. However, if the spec was cleaned up a little to allow for duplicates then I could see a use where you may have an event handler which is transforming the JSON to HTML or some other format... In such cases it would be perfectly valid to parse the JSON and create another document format...
[
"div":
{
"p": "hello",
"p": "universe"
},
"div":
{
"h1": "Heading 1",
"p": "another paragraph"
}
]
could then easily parse to html for example:
<body>
<div>
<p>hello</p>
<p>universe</p>
</div>
<div>
<h1>Heading 1</h1>
<p>another paragraph</p>
</div>
</body>
I can see the reasoning behind the question but as it stands... I wouldn't trust it.
You can use the base64
CLI tool to generate the base64 encoded version of your username + password like this:
$ echo -n "joeuser:secretpass" | base64
am9ldXNlcjpzZWNyZXRwYXNz
-or-
$ base64 <<<"joeuser:secretpass"
am9ldXNlcjpzZWNyZXRwYXNzCg==
Base64 is reversible so you can also decode it to confirm like this:
$ echo -n "joeuser:secretpass" | base64 | base64 -D
joeuser:secretpass
-or-
$ base64 <<<"joeuser:secretpass" | base64 -D
joeuser:secretpass
NOTE: username = joeuser, password = secretpass
You can put this together into curl
like this:
$ curl -H "Authorization: Basic $(base64 <<<"joeuser:secretpass")" http://example.com
Most will likely agree that if you're going to bother doing this, then you might as well just use curl
's -u
option.
$ curl --help |grep -- "--user " -u, --user USER[:PASSWORD] Server user and password
For example:
$ curl -u someuser:secretpass http://example.com
But you can do this in a semi-safer manner if you keep your credentials in a encrypted vault service such as LastPass or Pass.
For example, here I'm using the LastPass' CLI tool, lpass
, to retrieve my credentials:
$ curl -u $(lpass show --username example.com):$(lpass show --password example.com) \
http://example.com
There's an even safer way to hand your credentials off to curl
though. This method makes use of the -K
switch.
$ curl -X GET -K \
<(cat <<<"user = \"$(lpass show --username example.com):$(lpass show --password example.com)\"") \
http://example.com
When used, your details remain hidden, since they're passed to curl
via a temporary file descriptor, for example:
+ curl -skK /dev/fd/63 -XGET -H 'Content-Type: application/json' https://es-data-01a.example.com:9200/_cat/health
++ cat
+++ lpass show --username example.com
+++ lpass show --password example.com
1561075296 00:01:36 rdu-es-01 green 9 6 2171 1085 0 0 0 0 - 100.0%
NOTE: Above I'm communicating with one of our Elasticsearch nodes, inquiring about the cluster's health.
This method is dynamically creating a file with the contents user = "<username>:<password>"
and giving that to curl
.
The methods shown above are facilitating a feature known as Basic Authorization that's part of the HTTP standard.
When the user agent wants to send authentication credentials to the server, it may use the Authorization field.
The Authorization field is constructed as follows:
- The username and password are combined with a single colon (:). This means that the username itself cannot contain a colon.
- The resulting string is encoded into an octet sequence. The character set to use for this encoding is by default unspecified, as long as it is compatible with US-ASCII, but the server may suggest use of UTF-8 by sending the charset parameter.
- The resulting string is encoded using a variant of Base64.
- The authorization method and a space (e.g. "Basic ") is then prepended to the encoded string.
For example, if the browser uses Aladdin as the username and OpenSesame as the password, then the field's value is the base64-encoding of Aladdin:OpenSesame, or QWxhZGRpbjpPcGVuU2VzYW1l. Then the Authorization header will appear as:
Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l
Source: Basic access authentication
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$this = $('h1');
$this.css('color','#3498db');
$this.css('text-align','center');
$this.css('border','1px solid #ededed');
});
</script>
</head>
<body>
<h1>Title</h1>
</body>
</html>
Using river can present issues when your operation scales up. River will use a ton of memory when under heavy operation. I recommend implementing your own elasticsearch models, or if you're using mongoose you can build your elasticsearch models right into that or use mongoosastic which essentially does this for you.
Another disadvantage to Mongodb River is that you'll be stuck using mongodb 2.4.x branch, and ElasticSearch 0.90.x. You'll start to find that you're missing out on a lot of really nice features, and the mongodb river project just doesn't produce a usable product fast enough to keep stable. That said Mongodb River is definitely not something I'd go into production with. It's posed more problems than its worth. It will randomly drop write under heavy load, it will consume lots of memory, and there's no setting to cap that. Additionally, river doesn't update in realtime, it reads oplogs from mongodb, and this can delay updates for as long as 5 minutes in my experience.
We recently had to rewrite a large portion of our project, because its a weekly occurrence that something goes wrong with ElasticSearch. We had even gone as far as to hire a Dev Ops consultant, who also agrees that its best to move away from River.
UPDATE: Elasticsearch-mongodb-river now supports ES v1.4.0 and mongodb v2.6.x. However, you'll still likely run into performance problems on heavy insert/update operations as this plugin will try to read mongodb's oplogs to sync. If there are a lot of operations since the lock(or latch rather) unlocks, you'll notice extremely high memory usage on your elasticsearch server. If you plan on having a large operation, river is not a good option. The developers of ElasticSearch still recommend you to manage your own indexes by communicating directly with their API using the client library for your language, rather than using river. This isn't really the purpose of river. Twitter-river is a great example of how river should be used. Its essentially a great way to source data from outside sources, but not very reliable for high traffic or internal use.
Also consider that mongodb-river falls behind in version, as its not maintained by ElasticSearch Organization, its maintained by a thirdparty. Development was stuck on v0.90 branch for a long time after the release of v1.0, and when a version for v1.0 was released it wasn't stable until elasticsearch released v1.3.0. Mongodb versions also fall behind. You may find yourself in a tight spot when you're looking to move to a later version of each, especially with ElasticSearch under such heavy development, with many very anticipated features on the way. Staying up on the latest ElasticSearch has been very important as we rely heavily on constantly improving our search functionality as its a core part of our product.
All in all you'll likely get a better product if you do it yourself. Its not that difficult. Its just another database to manage in your code, and it can easily be dropped in to your existing models without major refactoring.
compileSDK should match appCompat version. TargetSDK can still be 22 (e.g. in case you didn't update to the new permission model yet)
The following will cover all browsers worth covering:
text-shadow: 0 0 2px #fff; /* Firefox 3.5+, Opera 9+, Safari 1+, Chrome, IE10 */
filter: progid:DXImageTransform.Microsoft.Glow(Color=#ffffff,Strength=1); /* IE<10 */
Note that the right format is ("dd/MM/yyyy") before the code works. "mm" means minuts !
String valid_until = "01/07/2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = null;
try {
strDate = sdf.parse(valid_until);
} catch (ParseException e) {
e.printStackTrace();
}
if (new Date().after(strDate)) {
catalog_outdated = 1;
}
Also Model::all(['id'])->toArray()
it will only fetch id as array.
From arrays
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.
So in the case of a String array, once you create it with some length, you can't modify it, but you can add elements until you fill it.
String[] arr = new String[10]; // 10 is the length of the array.
arr[0] = "kk";
arr[1] = "pp";
...
So if your requirement is to add many objects, it's recommended that you use Lists like:
List<String> a = new ArrayList<String>();
a.add("kk");
a.add("pp");
The documentation is misleading.
I have the following code running in production
DECLARE @table TABLE (UserID varchar(100))
DECLARE @sql varchar(1000)
SET @sql = 'spSelUserIDList'
/* Will also work
SET @sql = 'SELECT UserID FROM UserTable'
*/
INSERT INTO @table
EXEC(@sql)
SELECT * FROM @table
You can use URL Encoding Functions PHP has the
rawurlencode()
function
ASP has the
Server.URLEncode()
function
In JavaScript you can use the
encodeURIComponent()
function.
Your column is nullable
int maxAge = context.Persons.Select(p => p.Age).Max() ?? 0;
Your column is non-nullable
int maxAge = context.Persons.Select(p => p.Age).Cast<int?>().Max() ?? 0;
In both cases, you can use the second code. If you use DefaultIfEmpty
, you will do a bigger query on your server. For people who are interested, here are the EF6 equivalent:
Query without DefaultIfEmpty
SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
MAX([Extent1].[Age]) AS [A1]
FROM [dbo].[Persons] AS [Extent1]
) AS [GroupBy1]
Query with DefaultIfEmpty
SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
MAX([Join1].[A1]) AS [A1]
FROM ( SELECT
CASE WHEN ([Project1].[C1] IS NULL) THEN 0 ELSE [Project1].[Age] END AS [A1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable1]
LEFT OUTER JOIN (SELECT
[Extent1].[Age] AS [Age],
cast(1 as tinyint) AS [C1]
FROM [dbo].[Persons] AS [Extent1]) AS [Project1] ON 1 = 1
) AS [Join1]
) AS [GroupBy1]
From the AWS documentation:
Amazon SNS allows applications to send time-critical messages to multiple subscribers through a “push” mechanism, eliminating the need to periodically check or “poll” for updates.
Amazon SQS is a message queue service used by distributed applications to exchange messages through a polling model, and can be used to decouple sending and receiving components—without requiring each component to be concurrently available.
They changed print
in Python 3. In 2 it was a statement, now it is a function and requires parenthesis.
Here's the docs from Python 3.0.
First of all do not use list
as a variable name- that is a builtin function.
I'm not super clear of what you're asking (a little more context would help), but maybe this is helpful-
my_list = []
my_list.append(np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))
my_list.append(np.genfromtxt('temp2.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))
That will create a list (a type of mutable array in python) called my_list
with the output of the np.getfromtext()
method in the first 2 indexes.
The first can be referenced with my_list[0]
and the second with my_list[1]
If key is present table.put(key, val)
will just overwrite the value else it'll create a new entry. Poof! and you are done. :)
you can get the value from a map by using key is table.get(key);
That's about it
Use a white space to match all descendants of an element:
div.dropdown * {
color: red;
}
x y
matches every element y that is inside x, however deeply nested it may be - children, grandchildren and so on.
The asterisk *
matches any element.
Official Specification: CSS 2.1: Chapter 5.5: Descendant Selectors
You could try os.environ["MY_DATA"] instead.
The below example is self explainatory. where refs and events can be used to call function from and to parent and child.
// PARENT
<template>
<parent>
<child
@onChange="childCallBack"
ref="childRef"
:data="moduleData"
/>
<button @click="callChild">Call Method in child</button>
</parent>
</template>
<script>
export default {
methods: {
callChild() {
this.$refs.childRef.childMethod('Hi from parent');
},
childCallBack(message) {
console.log('message from child', message);
}
}
};
</script>
// CHILD
<template>
<child>
<button @click="callParent">Call Parent</button>
</child>
</template>
<script>
export default {
methods: {
callParent() {
this.$emit('onChange', 'hi from child');
},
childMethod(message) {
console.log('message from parent', message);
}
}
}
</script>
Maven acts as both a dependency management tool - it can be used to retrieve jars from a central repository or from a repository you set up - and as a declarative build tool. The difference between a "declarative" build tool and a more traditional one like ant or make is you configure what needs to get done, not how it gets done. For example, you can say in a maven script that a project should be packaged as a WAR file, and maven knows how to handle that.
Maven relies on conventions about how project directories are laid out in order to achieve its "declarativeness." For example, it has a convention for where to put your main code, where to put your web.xml, your unit tests, and so on, but also gives the ability to change them if you need to.
You should also keep in mind that there is a plugin for running ant commands from within maven:
http://maven.apache.org/plugins/maven-ant-plugin/
Also, maven's archetypes make getting started with a project really fast. For example, there is a Wicket archetype, which provides a maven command you run to get a whole, ready-to-run hello world-type project.
Replace [ with nothing, then ] with nothing.
I was able to figure out this using a PyCharm plugin called EnvFile. This plugin, basically allows setting environment variables to run configurations from one or multiple files.
The installation is pretty simple:
Preferences > Plugins > Browse repositories... > Search for "Env File" > Install Plugin.
Then, I created a file, in my project root, called environment.env
which contains:
DATABASE_URL=postgres://127.0.0.1:5432/my_db_name
DEBUG=1
Then I went to Run->Edit Configurations, and I followed the steps in the next image:
In 3, I chose the file environment.env
, and then I could just click the play button in PyCharm, and everything worked like a charm.
This is the right answer
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/favorites_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00ff00"
android:rowCount="2"
android:columnCount="2">
<Button
android:text="Cell 0"
android:layout_row="0"
android:layout_column="0"
android:layout_columnWeight="1"
android:layout_rowWeight="1"
android:textSize="14dip"
/>
<Button
android:text="Cell 1"
android:layout_row="0"
android:layout_column="1"
android:textSize="14dip"
android:layout_columnWeight="1"
android:layout_rowWeight="1"/>
<Button
android:text="Cell 2"
android:layout_row="1"
android:layout_column="0"
android:textSize="14dip"
android:layout_columnWeight="1"
android:layout_rowWeight="1"/>
<Button
android:text="Cell 3"
android:layout_row="1"
android:layout_column="1"
android:textSize="14dip"
android:layout_columnWeight="1"
android:layout_rowWeight="1"/>
</GridLayout>
Check permissions on templates and appname directories, either with ls -l or try doing an absolute path open() from django.
Do a describe on dba_arguments, dba_errors, dba_procedures, dba_objects, dba_source, dba_object_size. Each of these has part of the pictures for looking at the procedures and functions.
Also the object_type in dba_objects for packages is 'PACKAGE' for the definition and 'PACKAGE BODY" for the body.
If you are comparing schemas on the same database then try:
select * from dba_objects
where schema_name = 'ASCHEMA'
and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )
minus
select * from dba_objects
where schema_name = 'BSCHEMA'
and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )
and switch around the orders of ASCHEMA and BSCHEMA.
If you also need to look at triggers and comparing other stuff between the schemas you should take a look at the Article on Ask Tom about comparing schemas
W3C says:
<!DOCTYPE html
PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en-US">
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon"
type="image/png"
href="http://example.com/myicon.png">
[…]
</head>
[…]
</html>
See http://www.w3.org/2005/10/howto-favicon
But keep in mind: Some browser need a while to recognize that there is a favicon - try to delete the cookies and reopen your site! (And be sure the icon is at the path :) )
You could always write a simple program in Python or something to create an include file that has simple #define
statements with a build number, time, and date. You would then need to run this program before doing a build.
If you like I'll write one and post source here.
If you are lucky, your build tool (IDE or whatever) might have the ability to run an external command, and then you could have the external tool rewrite the include file automatically with each build.
EDIT: Here's a Python program. This writes a file called build_num.h
and has an integer build number that starts at 1 and increments each time this program is run; it also writes #define
values for the year, month, date, hours, minutes and seconds of the time this program is run. It also has a #define
for major and minor parts of the version number, plus the full VERSION
and COMPLETE_VERSION
that you wanted. (I wasn't sure what you wanted for the date and time numbers, so I went for just concatenated digits from the date and time. You can change this easily.)
Each time you run it, it reads in the build_num.h
file, and parses it for the build number; if the build_num.h
file does not exist, it starts the build number at 1. Likewise it parses out major and minor version numbers, and if the file does not exist defaults those to version 0.1.
import time
FNAME = "build_num.h"
build_num = None
version_major = None
version_minor = None
DEF_BUILD_NUM = "#define BUILD_NUM "
DEF_VERSION_MAJOR = "#define VERSION_MAJOR "
DEF_VERSION_MINOR = "#define VERSION_MINOR "
def get_int(s_marker, line):
_, _, s = line.partition(s_marker) # we want the part after the marker
return int(s)
try:
with open(FNAME) as f:
for line in f:
if DEF_BUILD_NUM in line:
build_num = get_int(DEF_BUILD_NUM, line)
build_num += 1
elif DEF_VERSION_MAJOR in line:
version_major = get_int(DEF_VERSION_MAJOR, line)
elif DEF_VERSION_MINOR in line:
version_minor = get_int(DEF_VERSION_MINOR, line)
except IOError:
build_num = 1
version_major = 0
version_minor = 1
assert None not in (build_num, version_major, version_minor)
with open(FNAME, 'w') as f:
f.write("#ifndef BUILD_NUM_H\n")
f.write("#define BUILD_NUM_H\n")
f.write("\n")
f.write(DEF_BUILD_NUM + "%d\n" % build_num)
f.write("\n")
t = time.localtime()
f.write("#define BUILD_YEAR %d\n" % t.tm_year)
f.write("#define BUILD_MONTH %d\n" % t.tm_mon)
f.write("#define BUILD_DATE %d\n" % t.tm_mday)
f.write("#define BUILD_HOUR %d\n" % t.tm_hour)
f.write("#define BUILD_MIN %d\n" % t.tm_min)
f.write("#define BUILD_SEC %d\n" % t.tm_sec)
f.write("\n")
f.write("#define VERSION_MAJOR %d\n" % version_major)
f.write("#define VERSION_MINOR %d\n" % version_minor)
f.write("\n")
f.write("#define VERSION \"%d.%d\"\n" % (version_major, version_minor))
s = "%d.%d.%04d%02d%02d.%02d%02d%02d" % (version_major, version_minor,
t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec)
f.write("#define COMPLETE_VERSION \"%s\"\n" % s)
f.write("\n")
f.write("#endif // BUILD_NUM_H\n")
I made all the defines just be integers, but since they are simple integers you can use the standard stringizing tricks to build a string out of them if you like. Also you can trivially extend it to build additional pre-defined strings.
This program should run fine under Python 2.6 or later, including any Python 3.x version. You could run it under an old Python with a few changes, like not using .partition()
to parse the string.
Beginning with C# 7.1, you can use default literal to produce the default value of a type when the compiler can infer the expression type.
Console.Writeline(default(Guid));
// ouptut: 00000000-0000-0000-0000-000000000000
Console.WriteLine(default(int)); // output: 0
Console.WriteLine(default(object) is null); // output: True
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/default
I really like cottsaks solution and think its very clearly explained. my only addition was to alter step 2 as follows
public abstract class MyController : Controller
{
#region Http404 handling
protected override void HandleUnknownAction(string actionName)
{
//if controller is ErrorController dont 'nest' exceptions
if(this.GetType() != typeof(ErrorController))
this.InvokeHttp404(HttpContext);
}
public ActionResult InvokeHttp404(HttpContextBase httpContext)
{
IController errorController = ObjectFactory.GetInstance<ErrorController>();
var errorRoute = new RouteData();
errorRoute.Values.Add("controller", "Error");
errorRoute.Values.Add("action", "Http404");
errorRoute.Values.Add("url", httpContext.Request.Url.OriginalString);
errorController.Execute(new RequestContext(
httpContext, errorRoute));
return new EmptyResult();
}
#endregion
}
Basically this stops urls containing invalid actions AND controllers from triggering the exception routine twice. eg for urls such as asdfsdf/dfgdfgd
**just copy paste this code and run you can see the textbox disabled **
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style>.container{float:left;width:200px;height:25px;position:relative;}
.container input{float:left;width:200px;height:25px;}
.overlay{display:block;width:208px;position:absolute;top:0px;left:0px;height:32px;}
</style>
</head>
<body>
<div class="container">
<input type="text" value="[email protected]" />
<div class="overlay">
</div>
</div>
</body>
</html>
Whereas @jbarrueta answer is perfect, in the 2.12 version of Jackson was introduced a new long-awaited type for the @JsonTypeInfo
annotation, DEDUCTION
.
It is useful for the cases when you have no way to change the incoming json or must not do so. I'd still recommend to use use = JsonTypeInfo.Id.NAME
, as the new way may throw an exception in complex cases when it has no way to determine which subtype to use.
Now you can simply write
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION)
@JsonSubTypes({
@JsonSubTypes.Type(Dog.class),
@JsonSubTypes.Type(Cat.class) }
)
public abstract class Animal {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And it will produce {"name":"ruffus", "breed":"english shepherd"}
and {"name":"goya", "favoriteToy":"mice"}
Once again, it's safer to use NAME
if some of the fields may be not present, like breed
or favoriteToy
.
To query a large set of text in efficient manner you can use the concept of Edit Distance/ Prefix Edit Distance.
Edit Distance ED(x,y): minimal number of transfroms to get from term x to term y
But computing ED between each term and query text is resource and time intensive. Therefore instead of calculating ED for each term first we can extract possible matching terms using a technique called Qgram Index. and then apply ED calculation on those selected terms.
An advantage of Qgram index technique is it supports for Fuzzy Search.
One possible approach to adapt QGram index is build an Inverted Index using Qgrams. In there we store all the words which consists with particular Qgram, under that Qgram.(Instead of storing full string you can use unique ID for each string). You can use Tree Map data structure in Java for this. Following is a small example on storing of terms
col : colmbia, colombo, gancola, tacolama
Then when querying, we calculate the number of common Qgrams between query text and available terms.
Example: x = HILLARY, y = HILARI(query term)
Qgrams
$$HILLARY$$ -> $$H, $HI, HIL, ILL, LLA, LAR, ARY, RY$, Y$$
$$HILARI$$ -> $$H, $HI, HIL, ILA, LAR, ARI, RI$, I$$
number of q-grams in common = 4
number of q-grams in common = 4.
For the terms with high number of common Qgrams, we calculate the ED/PED against the query term and then suggest the term to the end user.
you can find an implementation of this theory in following project(See "QGramIndex.java"). Feel free to ask any questions. https://github.com/Bhashitha-Gamage/City_Search
To study more about Edit Distance, Prefix Edit Distance Qgram index please watch the following video of Prof. Dr Hannah Bast https://www.youtube.com/embed/6pUg2wmGJRo (Lesson starts from 20:06)
Data transfer between two platform requires a common data format. JSON is a common global format to send cross platform data.
drawChart(600/50, JSON.parse('<?php echo json_encode($day); ?>'), JSON.parse('<?php echo json_encode($week); ?>'), JSON.parse('<?php echo json_encode($month); ?>'), JSON.parse('<?php echo json_encode(createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day'))))); ?>'))
This is the answer to your question. The answer may look very complex. You can see a simple example describing the communication between server side and client side here
$employee = array(
"employee_id" => 10011,
"Name" => "Nathan",
"Skills" =>
array(
"analyzing",
"documentation" =>
array(
"desktop",
"mobile"
)
)
);
Conversion to JSON format is required to send the data back to client application ie, JavaScript. PHP has a built in function json_encode(), which can convert any data to JSON format. The output of the json_encode function will be a string like this.
{
"employee_id": 10011,
"Name": "Nathan",
"Skills": {
"0": "analyzing",
"documentation": [
"desktop",
"mobile"
]
}
}
On the client side, success function will get the JSON string. Javascript also have JSON parsing function JSON.parse() which can convert the string back to JSON object.
$.ajax({
type: 'POST',
headers: {
"cache-control": "no-cache"
},
url: "employee.php",
async: false,
cache: false,
data: {
employee_id: 10011
},
success: function (jsonString) {
var employeeData = JSON.parse(jsonString); // employeeData variable contains employee array.
});
For >= 2nd row values insert into table-
$file = fopen($filename, "r");
//$sql_data = "SELECT * FROM prod_list_1 ";
$count = 0; // add this line
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
//print_r($emapData);
//exit();
$count++; // add this line
if($count>1){ // add this line
$sql = "INSERT into prod_list_1(p_bench,p_name,p_price,p_reason) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
mysql_query($sql);
} // add this line
}
Setting a reference to the Microsoft Access 12.0 Object Library allows us to test if a table exists using DCount.
Public Function ifTableExists(tblName As String) As Boolean
If DCount("[Name]", "MSysObjects", "[Name] = '" & tblName & "'") = 1 Then
ifTableExists = True
End If
End Function
You can write a generic function to do this...
var numberFormat = function(number, width) {
return new Array(+width + 1 - (number + '').length).join('0') + number;
}
That way, it's not a problem to deal with any arbitrarily width.
for frequency distribution of a variable with excessive values you can collapse down the values in classes,
Here I excessive values for employrate
variable, and there's no meaning of it's frequency distribution with direct values_count(normalize=True)
country employrate alcconsumption
0 Afghanistan 55.700001 .03
1 Albania 11.000000 7.29
2 Algeria 11.000000 .69
3 Andorra nan 10.17
4 Angola 75.699997 5.57
.. ... ... ...
208 Vietnam 71.000000 3.91
209 West Bank and Gaza 32.000000
210 Yemen, Rep. 39.000000 .2
211 Zambia 61.000000 3.56
212 Zimbabwe 66.800003 4.96
[213 rows x 3 columns]
frequency distribution with values_count(normalize=True)
with no classification,length of result here is 139 (seems meaningless as a frequency distribution):
print(gm["employrate"].value_counts(sort=False,normalize=True))
50.500000 0.005618
61.500000 0.016854
46.000000 0.011236
64.500000 0.005618
63.500000 0.005618
58.599998 0.005618
63.799999 0.011236
63.200001 0.005618
65.599998 0.005618
68.300003 0.005618
Name: employrate, Length: 139, dtype: float64
putting classification we put all values with a certain range ie.
0-10 as 1, 11-20 as 2 21-30 as 3, and so forth.
gm["employrate"]=gm["employrate"].str.strip().dropna()
gm["employrate"]=pd.to_numeric(gm["employrate"])
gm['employrate'] = np.where(
(gm['employrate'] <=10) & (gm['employrate'] > 0) , 1, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=20) & (gm['employrate'] > 10) , 1, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=30) & (gm['employrate'] > 20) , 2, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=40) & (gm['employrate'] > 30) , 3, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=50) & (gm['employrate'] > 40) , 4, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=60) & (gm['employrate'] > 50) , 5, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=70) & (gm['employrate'] > 60) , 6, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=80) & (gm['employrate'] > 70) , 7, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=90) & (gm['employrate'] > 80) , 8, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=100) & (gm['employrate'] > 90) , 9, gm['employrate']
)
print(gm["employrate"].value_counts(sort=False,normalize=True))
after classification we have a clear frequency distribution.
here we can easily see, that 37.64%
of countries have employ rate between 51-60%
and 11.79%
of countries have employ rate between 71-80%
5.000000 0.376404
7.000000 0.117978
4.000000 0.179775
6.000000 0.264045
8.000000 0.033708
3.000000 0.028090
Name: employrate, dtype: float64
I had the same problem, but the field used to default to null, and now I want to default it to 0. That required adding one more line after mdb's solution:
ALTER TABLE [Table] ADD CONSTRAINT [Constraint] DEFAULT 0 FOR [Column];
You should use List<Person>
or a HashSet<Person>
.
For a console application you can use System.Reflection.Assembly.GetExecutingAssembly().Location
as long as the call is made within the code of the console app itself, if you call this from within another dll or plugin this will return the location of that DLL and not the executable.
I am on Laravel 7.25 and I don't know if it supports on previous versions or not but Its pretty good.
public function joinSub($query, $as, $first, $operator = null, $second = null, $type = 'inner', $where = false)
Showing/Getting the user ID and the total number of posts by them left joining two tables users and posts.
return DB::table('users')
->joinSub('select user_id,count(id) noOfPosts from posts group by user_id', 'totalPosts', 'users.id', '=', 'totalPosts.user_id', 'left')
->select('users.name', 'totalPosts.noOfPosts')
->get();
If you don't wanna mention 'left' for leftjoin then you can use another prebuilt function
public function leftJoinSub($query, $as, $first, $operator = null, $second = null)
{
return $this->joinSub($query, $as, $first, $operator, $second, 'left');
}
And yeah, it actually calls the same function but it passes the join type itself. You can apply the same logic for other joins i.e. righJoinSub(...) etc.
Check eclipse.ini, there are two entries like:
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20120913-144807
For some twisted reason jars have version in their name - so if you upgrade/have two different version of eclipse( while eclipse.ini is either linked or provided as system wide conf file for eclipse ) it will cause above error.
This is the code which worked for me. My django version is 1.10.4 final
from django.conf.urls import url, include
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
# Examples:
# url(r'^$', 'blog.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
]
You can't do it as a simple single query, but this would do:
select title
from kmovies
where title in (
select title
from kmovies
group by title
order by cnt desc
having count(title) > 1
)
Using Guava (r07) you can do this:
for(char c : Lists.charactersOf(someString)) { ... }
This has the convenience of using foreach while not copying the string to a new array. Lists.charactersOf
returns a view of the string as a List
.
https://docs.python.org/3/library/pprint.html
If you need the text (for using with curses for example):
import pprint
myObject = []
myText = pprint.pformat(myObject)
Then myText
variable will something alike php var_dump
or print_r
. Check the documentation for more options, arguments.
I would rewrite your dequeue function as:
std::string FileQueue::dequeue(const std::chrono::milliseconds& timeout)
{
std::unique_lock<std::mutex> lock(qMutex);
while(q.empty()) {
if (populatedNotifier.wait_for(lock, timeout) == std::cv_status::timeout )
return std::string();
}
std::string ret = q.front();
q.pop();
return ret;
}
It is shorter and does not have duplicate code like your did. Only issue it may wait longer that timeout. To prevent that you would need to remember start time before loop, check for timeout and adjust wait time accordingly. Or specify absolute time on wait condition.
If you aren't actually restricted to keeping all of these elements as sibling nodes you can wrap the ones that go together in another default flex box, and have the container of both use space-between.
.space-between {_x000D_
border: 1px solid red;_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}_x000D_
.default-flex {_x000D_
border: 1px solid blue;_x000D_
display: flex;_x000D_
}_x000D_
.child {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
border: 1px solid;_x000D_
}
_x000D_
<div class="space-between">_x000D_
<div class="child">1</div>_x000D_
<div class="default-flex">_x000D_
<div class="child">2</div>_x000D_
<div class="child">3</div>_x000D_
<div class="child">4</div>_x000D_
<div class="child">5</div>_x000D_
</div>_x000D_
</div>
_x000D_
Or if you were doing the same thing with flex-start and flex-end reversed you just swap the order of the default-flex container and lone child.
You can only use
Object& return_Object();
if the object returned has a greater scope than the function. For example, you can use it if you have a class where it is encapsulated. If you create an object in your function, use pointers. If you want to modify an existing object, pass it as an argument.
class MyClass{
private:
Object myObj;
public:
Object& return_Object() {
return myObj;
}
Object* return_created_Object() {
return new Object();
}
bool modify_Object( Object& obj) {
// obj = myObj; return true; both possible
return obj.modifySomething() == true;
}
};
I haven't seen my own way of doing it before, so, try this out. It is way easier to follow and has a much smaller footprint:
if([bool]([Security.Principal.WindowsIdentity]::GetCurrent()).Groups -notcontains "S-1-5-32-544") {
Start Powershell -ArgumentList "& '$MyInvocation.MyCommand.Path'" -Verb runas
}
Very simply, if the current Powershell session was called with administrator privileges, the Administrator Group well-known SID will show up in the Groups when you grab the current identity. Even if the account is a member of that group, the SID won't show up unless the process was invoked with elevated credentials.
Nearly all of these answers are a variation on Microsoft's Ben Armstrong's immensely popular method of how to accomplish it while not really grasping what it is actually doing and how else to emulate the same routine.
Based on the @trashgod's comment, this is the simpliest way to calculate >distance:
double distance = Math.hypot(x1-x2, y1-y2);
From documentation of Math.hypot:Returns:
sqrt(x²+ y²)
without intermediate overflow or underflow.Bob
Below Bob's approved comment he said he couldn't explain what the
Math.hypot(x1-x2, y1-y2);
did. To explain a triangle has three sides. With two points you can find the length of those points based on the x,y
of each. Xa=0, Ya=0
If thinking in Cartesian coordinates that is (0,0)
and then Xb=5, Yb=9
Again, cartesian coordinates is (5,9)
. So if you were to plot those on a grid, the distance from from x to another x assuming they are on the same y axis is +5
. and the distance along the Y axis from one to another assuming they are on the same x-axis is +9
. (think number line) Thus one side of the triangle's length is 5, another side is 9. A hypotenuse is
(x^2) + (y^2) = Hypotenuse^2
which is the length of the remaining side of a triangle. Thus being quite the same as a standard distance formula where
Sqrt of (x1-x2)^2 + (y1-y2)^2 = distance
because if you do away with the sqrt on the lefthand side of the operation and instead make distance^2 then you still have to get the sqrt from the distance. So the distance formula is the Pythagorean theorem but in a way that teachers can call it something different to confuse people.
You can use Task Scheduler Managed Wrapper:
using System;
using Microsoft.Win32.TaskScheduler;
class Program
{
static void Main(string[] args)
{
// Get the service on the local machine
using (TaskService ts = new TaskService())
{
// Create a new task definition and assign properties
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Does something";
// Create a trigger that will fire the task at this time every other day
td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });
// Create an action that will launch Notepad whenever the trigger fires
td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));
// Register the task in the root folder
ts.RootFolder.RegisterTaskDefinition(@"Test", td);
// Remove the task we just created
ts.RootFolder.DeleteTask("Test");
}
}
}
Alternatively you can use native API or go for Quartz.NET. See this for details.
Ensure debug mode is on - either add APP_DEBUG=true
to .env file or set an environment variable
Log files are in storage/logs folder. laravel.log
is the default filename. If there is a permission issue with the log folder, Laravel just halts. So if your endpoint generally works - permissions are not an issue.
In case your calls don't even reach Laravel or aren't caused by code issues - check web server's log files (check your Apache/nginx config files to see the paths).
If you use PHP-FPM, check its log files as well (you can see the path to log file in PHP-FPM pool config).
this worked for me:
rsync /dev/null node:existing-dir/new-dir/
I do get this message :
skipping non-regular file "null"
but I don't have to worry about having an empty directory hanging around.
You can do by run a bat file:
@ECHO OFF
FOR /F "tokens=5" %%T IN ('netstat -a -n -o ^| findstr "9797" ') DO (
SET /A ProcessId=%%T) &GOTO SkipLine
:SkipLine
echo ProcessId to kill = %ProcessId%
taskkill /f /pid %ProcessId%
PAUSE
You can use the Text_Qualifier
field in your Flat file connection manager to as "
. This should wrap your data in quotes and only separate by commas which are outside the quotes.
There is no string split function in MySQL. so you have to create your own function. This will help you. More details at this link.
CREATE FUNCTION SPLIT_STR(
x VARCHAR(255),
delim VARCHAR(12),
pos INT
)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
delim, '');
SELECT SPLIT_STR(string, delimiter, position)
SELECT SPLIT_STR('a|bb|ccc|dd', '|', 3) as third;
+-------+
| third |
+-------+
| ccc |
+-------+
According to w3.org the value attribute of the number input is defined as a floating-point number. The syntax of the floating-point number seems to only accept dots as decimal separators.
I've listed a few options below that might be helpful to you:
With the pattern attribute you can specify the allowed format with a regular expression in a HTML5 compatible way. Here you could specify that the comma character is allowed and a helpful feedback message if the pattern fails.
<input type="number" pattern="[0-9]+([,\.][0-9]+)?" name="my-num"
title="The number input must start with a number and use either comma or a dot as a decimal character."/>
Note: Cross-browser support varies a lot. It may be complete, partial or non-existant..
You could try to bind a simple callback to for example the onchange (and/or blur) event that would either replace the comma or validate all together.
Thirdly you could try to use the formnovalidate attribute on the number inputs with the intention of disabling browser validation for that field all together.
<input type="number" formnovalidate />
<input type="number" pattern="[0-9]+([,\.][0-9]+)?"
name="my-num" formnovalidate
title="The number input must start with a number and use either comma or a dot as a decimal character."/>
EventHandler.GetInvocationList().Length > 0
With HTML5, you can do this natively with: <input name="first_name" placeholder="First Name">
This is not supported with all browsers though (IE)
This may work:
<input type="first_name" value="First Name" onfocus="this.value==this.defaultValue?this.value='':null">
Otherwise, if you are using jQuery, you can use .focus and .css to change the color.
// Checking the format
var urlString: NSString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)
// Convert your data and set your request's HTTPBody property
var stringData: NSString = NSString(string: "jsonRequest=\(urlString)")
var requestBodyData: NSData = stringData.dataUsingEncoding(NSUTF8StringEncoding)!
As well as the suggestions for \c
and ignorecase
, I find the smartcase
very useful. If you search for something containing uppercase characters, it will do a case sensitive search; if you search for something purely lowercase, it will do a case insensitive search. You can use \c
and \C
to override this:
:set ignorecase
:set smartcase
/copyright " Case insensitive
/Copyright " Case sensitive
/copyright\C " Case sensitive
/Copyright\c " Case insensitive
See:
:help /\c
:help /\C
:help 'smartcase'
You can also use,
parent.jQuery("#testdiv").attr("style", content from form);
Firstly — I don't think column1 is not NULL or column1 <> ''
makes very much sense. Maybe you meant to write column1 is not NULL and column1 <> ''
(AND
instead of OR
)?
Secondly — because of Hive's "schema on read" approach to table definitions, invalid values will be converted to NULL
when you read from them. So, for example, if table1.column1
is of type STRING
and table2.column1
is of type INT
, then I don't think that table1.column1 IS NOT NULL
is enough to guarantee that table2.column1 IS NOT NULL
. (I'm not sure about this, though.)
You have to put your script tag after the one that references Angular. Move it out of the head
:
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>
The way you've set it up now, your script runs before Angular is loaded on the page.
I first used the JavaScript code, it worked amazingly until a website did not click.
So I've found this solution:
First, import ActionChains for Python & active it:
from selenium.webdriver.common.action_chains import ActionChains
actions = ActionChains(driver)
To click on a specific point in your sessions use this:
actions.move_by_offset(X coordinates, Y coordinates).click().perform()
NOTE: The code above will only work if the mouse has not been touched, to reset the mouse coordinates use this:
actions.move_to_element_with_offset(driver.find_element_by_tag_name('body'), 0,0))
In Full:
actions.move_to_element_with_offset(driver.find_element_by_tag_name('body'), 0,0)
actions.move_by_offset(X coordinates, Y coordinates).click().perform()
Setting profilinglevel to 2 is another option to log all queries.
try the following code :
In your controller :
function myCtrl ($scope) {
$scope.units = [
{'id': 10, 'label': 'test1'},
{'id': 27, 'label': 'test2'},
{'id': 39, 'label': 'test3'},
];
$scope.data= $scope.units[0]; // Set by default the value "test1"
};
In your page :
<select ng-model="data" ng-options="opt as opt.label for opt in units ">
</select>
If you are using jQuery, you could scroll with an animation using the following:
$(MyContainerDiv).animate({scrollTop: $(MyContainerDiv).scrollTop() + ($('element_within_div').offset().top - $(MyContainerDiv).offset().top)});
The animation is optional: you could also take the scrollTop value calculated above and put it directly in the container's scrollTop property.
Here is a solution using only a custom adapter with a different view type for the empty situation.
public class EventAdapter extends
RecyclerView.Adapter<EventAdapter.ViewHolder> {
private static final int VIEW_TYPE_EVENT = 0;
private static final int VIEW_TYPE_DATE = 1;
private static final int VIEW_TYPE_EMPTY = 2;
private ArrayList items;
public EventAdapter(ArrayList items) {
this.items = items;
}
@Override
public int getItemCount() {
if(items.size() == 0){
return 1;
}else {
return items.size();
}
}
@Override
public int getItemViewType(int position) {
if (items.size() == 0) {
return VIEW_TYPE_EMPTY;
}else{
Object item = items.get(position);
if (item instanceof Event) {
return VIEW_TYPE_EVENT;
} else {
return VIEW_TYPE_DATE;
}
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
ViewHolder vh;
if (viewType == VIEW_TYPE_EVENT) {
v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_event, parent, false);
vh = new ViewHolderEvent(v);
} else if (viewType == VIEW_TYPE_DATE) {
v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_event_date, parent, false);
vh = new ViewHolderDate(v);
} else {
v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_event_empty, parent, false);
vh = new ViewHolder(v);
}
return vh;
}
@Override
public void onBindViewHolder(EventAdapter.ViewHolder viewHolder,
final int position) {
int viewType = getItemViewType(position);
if (viewType == VIEW_TYPE_EVENT) {
//...
} else if (viewType == VIEW_TYPE_DATE) {
//...
} else if (viewType == VIEW_TYPE_EMPTY) {
//...
}
}
public static class ViewHolder extends ParentViewHolder {
public ViewHolder(View v) {
super(v);
}
}
public static class ViewHolderDate extends ViewHolder {
public ViewHolderDate(View v) {
super(v);
}
}
public static class ViewHolderEvent extends ViewHolder {
public ViewHolderEvent(View v) {
super(v);
}
}
}
var el = document.getElementsByClassName('myclass')
el[0].classList.add('newclass');
el[0].classList.remove('newclass');
To find whether the class exists or not, use:
el[0].classList.contains('newclass'); // this will return true or false
Browser support IE8+
A simplest fix would be:
x = input("Give starting number: ")
y = input("Give ending number: ")
x = int(x) # parse string into an integer
y = int(y) # parse string into an integer
for i in range(x,y):
print(i)
input
returns you a string (raw_input
in Python 2). int
tries to parse it into an integer. This code will throw an exception if the string doesn't contain a valid integer string, so you'd probably want to refine it a bit using try
/except
statements.
In the SQL Server Management Studio, to find out details of the active transaction, execute following command
DBCC opentran()
You will get the detail of the active transaction, then from the SPID of the active transaction, get the detail about the SPID using following commands
exec sp_who2 <SPID>
exec sp_lock <SPID>
For example, if SPID is 69 then execute the command as
exec sp_who2 69
exec sp_lock 69
Now , you can kill that process using the following command
KILL 69
I hope this helps :)
OK, so looking at Comparison of file systems if you only care about the main players file systems:
NUL
, \
, /
, :
, *
, "
, <
, >
, |
. Also, no space character at the start or end, and no period at the end.:
or /
NUL
or /
so any byte except NUL
, \
, /
, :
, *
, "
, <
, >
, |
and you can't have files/folders call .
or ..
and no control characters (of course).
Very simple 2 string answer to your question:
$array_1 = array(
'0' => 'zero',
'1' => 'one',
'2' => 'two',
'3' => 'three',
);
At first you insert anything to your third element with array_splice and then assign a value to this element:
array_splice($array_1, 3, 0 , true);
$array_1[3] = array('sample_key' => 'sample_value');
The answer, u
, (and many others) is in $ vimtutor
.
Would you please try with below code block, which is exactly what you're looking for:
SqlConnection conn = new SqlConnection
{
ConnectionString = "Data Source=" + System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\Database.sdf"
};
Dependencies that are not referenced in an interfaces methods should be regarded as implementation details, not something that the interface enforces. Of course there can be exceptions, but as a rule, you should define your interface as what the behavior is expected to be. Internal state of a given implementation shouldn't be a design concern of the interface.
You must include jQuery in the project.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I didn't find any doc about this so I just opened a random code example from tutorialrepublic.com http://www.tutorialrepublic.com/twitter-bootstrap-tutorial/bootstrap-dropdowns.php
Hope this helps someone else.
String webviewurl = "http://test.com/testing.pdf";
webView.getSettings().setJavaScriptEnabled(true);
if(webviewurl.contains(".pdf")){
webviewurl = "http://docs.google.com/gview?embedded=true&url=" + webviewurl; }
webview.loadUrl(webviewurl);
string items = string.Empty;
foreach (ListItem i in CheckBoxList1.Items)
{
if (i.Selected == true)
{
items += i.Text + ",";
}
}
Response.Write("selected items"+ items);
If you need an easier way to do it, and don't want much fuss, a simple execution could be:
raise Exception.new('something bad happened!')
This will raise an exception, say e
with e.message = something bad happened!
and then you can rescue it as you are rescuing all other exceptions in general.
Are you using Google App Engine? You could use cookies (made with JavaScript) to maintain a relationship between filenames and the name received from the server.
On my Fedora 10 system, with findutils-4.4.0-1.fc10.i386
:
find <path> -daystart -ctime 0 -print
The -daystart
flag tells it to calculate from the start of today instead of from 24 hours ago.
Note however that this will actually list files created or modified in the last day. find
has no options that look at the true creation date of the file.
I recommend adding the following line after the export to PDF:
ThisWorkbook.Sheets("Sheet1").Select
(where eg. Sheet1
is the single sheet you want to be active afterwards)
Leaving multiple sheets in a selected state may cause problems executing some code. (eg. unprotect doesn't function properly when multiple sheets are actively selected.)
Found an XML transform stylesheet here (wayback machine link, site itself is in german)
The stylesheet added here could be helpful:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="iso-8859-1"/>
<xsl:strip-space elements="*" />
<xsl:template match="/*/child::*">
<xsl:for-each select="child::*">
<xsl:if test="position() != last()">"<xsl:value-of select="normalize-space(.)"/>", </xsl:if>
<xsl:if test="position() = last()">"<xsl:value-of select="normalize-space(.)"/>"<xsl:text>
</xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Perhaps you want to remove the quotes inside the xsl:if tags so it doesn't put your values into quotes, depending on where you want to use the CSV file.
What you want is a SQL case statement. The form of these is either:
select case [expression or column]
when [value] then [result]
when [value2] then [result2]
else [value3] end
or:
select case
when [expression or column] = [value] then [result]
when [expression or column] = [value2] then [result2]
else [value3] end
In your example you are after:
declare @temp as varchar(100)
set @temp='Measure'
select case @temp
when 'Measure' then Measure
else OtherMeasure end
from Measuretable
Using Hex
in Apache Commons:
String hexString = "fd00000aa8660b5b010006acdc0100000101000100010000";
byte[] bytes = Hex.decodeHex(hexString.toCharArray());
System.out.println(new String(bytes, "UTF-8"));
Basically, replace
replaces a character with another and ''
is not a character. What you're looking for is erase
.
See this question which answers the same problem. In your case:
#include <algorithm>
str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());
Or use boost
if that's an option for you, like:
#include <boost/algorithm/string.hpp>
boost::erase_all(str, "a");
All of this is well-documented on reference websites. But if you didn't know of these functions, you could easily do this kind of things by hand:
std::string output;
output.reserve(str.size()); // optional, avoids buffer reallocations in the loop
for(size_t i = 0; i < str.size(); ++i)
if(str[i] != 'a') output += str[i];
It's nuanced.
If you need to have other systems interface with your services, than a lot of clients will be happier with SOAP, due to the layers of "verification" you have with the contracts, WSDL, and the SOAP standard.
For day-to-day systems calling into systems, I think that SOAP is a lot of unnecessary overhead when a simple HTML call will do.
You can use the backtick operator:
& "C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe" `
-verb:sync `
-source:contentPath="c:\workspace\xxx\master\Build\_PublishedWebsites\xxx.Web" `
-dest:contentPath="c:\websites\xxx\wwwroot\,computerName=192.168.1.1,username=administrator,password=xxx"
That's still a little too long for my taste, so I'd use some well-named variables:
$msdeployPath = "C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe"
$verbArg = '-verb:sync'
$sourceArg = '-source:contentPath="c:\workspace\xxx\master\Build\_PublishedWebsites\xxx.Web"'
$destArg = '-dest:contentPath="c:\websites\xxx\wwwroot\,computerName=192.168.1.1,username=administrator,password=xxx"'
& $msdeployPath $verbArg $sourceArg $destArg
This simple in below solution worked for me. http://forums.codeblocks.org/index.php?topic=17336.0
I had a similar problem. Please note I'm a total n00b in C++ and IDE's but heres what I did (after some research) So of course I downloaded the version that came with the compiler and it didn't work. Heres what I did: 1) go to settings in the upper part 2) click compiler 3) choose reset to defaults.
Hopefully this works
ClassA a = <something>;
ClassB b = (ClassB) a;
The 2nd line will fail if ClassA is not a subclass of ClassB, and will throw a ClassCastException.
Add below in app gradle file implementation project(path: ':project name')
I like to do this witch i think is cleaner :
1 - Add the model to namespace:
use App\Employee;
2 - then you can do :
$employees = Employee::get();
or maybe somthing like this:
$employee = Employee::where('name', 'John')->first();
Suppose you want to give attributes to an instance which was previously not written in code.
The setattr()
does just that.
It takes the instance of the class self
and key and value to set.
class Example:
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
For people using Kotlin, inazaruk's answer will not work, the IDE will require the variable to be initialized, so instead of using the postDelayed
inside the Runnable
, we'll use it in an separate method.
Initialize your Runnable
like this :
private var myRunnable = Runnable {
//Do some work
//Magic happens here ?
runDelayedHandler(1000) }
Initialize your runDelayedHandler
method like this :
private fun runDelayedHandler(timeToWait : Long) {
if (!keepRunning) {
//Stop your handler
handler.removeCallbacksAndMessages(null)
//Do something here, this acts like onHandlerStop
}
else {
//Keep it running
handler.postDelayed(myRunnable, timeToWait)
}
}
As you can see, this approach will make you able to control the lifetime of the task, keeping track of keepRunning
and changing it during the lifetime of the application will do the job for you.
The first <img />
is invalid - src
is a required attribute. data-src
is an attribute than can be leveraged by, say, JavaScript, but has no presentational meaning.
string urlParameters = "param1=value1¶m2=value2";
string _endPointName = "your url post api";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(_endPointName);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
httpWebRequest.Headers["ContentType"] = "application/x-www-form-urlencoded";
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
(se, cert, chain, sslerror) =>
{
return true;
};
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(urlParameters);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
This should work :
str = str.replace(/[^a-z0-9-]/g, '');
Everything between the indicates what your are looking for
/
is here to delimit your pattern so you have one to start and one to end[]
indicates the pattern your are looking for on one specific character^
indicates that you want every character NOT corresponding to what followsa-z
matches any character between 'a' and 'z' included0-9
matches any digit between '0' and '9' included (meaning any digit)-
the '-' characterg
at the end is a special parameter saying that you do not want you regex to stop on the first character matching your pattern but to continue on the whole stringThen your expression is delimited by /
before and after.
So here you say "every character not being a letter, a digit or a '-' will be removed from the string".
The following doesn't work:
if (something)
doit();
else
var v = 1 + 2;
But this works:
if (something)
doit();
else {
var v = 1 + 2;
}
They key problem of any 'named output variable' scheme where the caller can pass in the variable name (whether using eval
or declare -n
) is inadvertent aliasing, i.e. name clashes: From an encapsulation point of view, it's awful to not be able to add or rename a local variable in a function without checking ALL the function's callers first to make sure they're not wanting to pass that same name as the output parameter. (Or in the other direction, I don't want to have to read the source of the function I'm calling just to make sure the output parameter I intend to use is not a local in that function.)
The only way around that is to use a single dedicated output variable like REPLY
(as suggested by Evi1M4chine) or a convention like the one suggested by Ron Burk.
However, it's possible to have functions use a fixed output variable internally, and then add some sugar over the top to hide this fact from the caller, as I've done with the call
function in the following example. Consider this a proof of concept, but the key points are
REPLY
, and can also return an exit code as usualREPLY
(see the wrapper
example). The exit code of the function is passed through, so using them in e.g. an if
or while
or similar constructs works as expected.The reason this works is because the call
function itself has no locals and uses no variables other than REPLY
, avoiding any potential for name clashes. At the point where the caller-defined output variable name is assigned, we're effectively in the caller's scope (technically in the identical scope of the call
function), rather than in the scope of the function being called.
#!/bin/bash
function call() { # var=func [args ...]
REPLY=; "${1#*=}" "${@:2}"; eval "${1%%=*}=\$REPLY; return $?"
}
function greet() {
case "$1" in
us) REPLY="hello";;
nz) REPLY="kia ora";;
*) return 123;;
esac
}
function wrapper() {
call REPLY=greet "$@"
}
function main() {
local a b c d
call a=greet us
echo "a='$a' ($?)"
call b=greet nz
echo "b='$b' ($?)"
call c=greet de
echo "c='$c' ($?)"
call d=wrapper us
echo "d='$d' ($?)"
}
main
Output:
a='hello' (0)
b='kia ora' (0)
c='' (123)
d='hello' (0)
Use Modernizr for detection of feature capabilities. In general jQuery offers to detect browser features: http://api.jquery.com/jQuery.support/. However, hashchange is not on the list.
The wiki of Modernizr offers a list of libraries to add HTML5 capabilities to old browsers. The list for hashchange includes a pointer to the project HTML5 History API, which seems to offer the functionality you would need if you wanted to emulate the behavior in old browsers.
best way is using reference, and not using unset (which make another step to clean memory)
$tab = ['two' => [] ];
solution:
$tab['newname'] = & $tab['two'];
you have one original and one reference with new name.
or if you don't want have two names in one value is good make another tab and foreach on reference
foreach($tab as $key=> & $value) {
if($key=='two') {
$newtab["newname"] = & $tab[$key];
} else {
$newtab[$key] = & $tab[$key];
}
}
Iterration is better on keys than clone all array, and cleaning old array if you have long data like 100 rows +++ etc..
As of Jquery 3.0 and above .bind has been deprecated and they prefer using .on instead. As @Blazemonger answered earlier that it may be removed and its for sure that it will be removed. For the older versions .bind would also call .on internally and there is no difference between them. Please also see the api for more detail.
strtol()
is your friend here. The third parameter is the numerical base that you are converting.
Example:
#include <stdio.h> /* printf */
#include <stdlib.h> /* strtol */
int main(int argc, char **argv)
{
long int num = 0;
long int num2 =0;
char * str. = "f00d";
char * str2 = "0xf00d";
num = strtol( str, 0, 16); //converts hexadecimal string to long.
num2 = strtol( str2, 0, 0); //conversion depends on the string passed in, 0x... Is hex, 0... Is octal and everything else is decimal.
printf( "%ld\n", num);
printf( "%ld\n", num);
}
Yes. Use WindowBuilder Pro (provided by Google). It supports SWT and Swing as well with multiple layouts (Group layout, MiGLayout etc.) It's integrated out of the box with Eclipse Indigo, but you can install plugin on previous versions (3.4/3.5/3.6):
For anyone reading the example in "A Swift Tour" chapter of "The Swift Programming Language" and looking for a way to simplify the simpleDescription() method, converting the enum itself to String by doing String(self)
will do it:
enum Rank: Int
{
case Ace = 1 //required otherwise Ace will be 0
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace, .Jack, .Queen, .King:
return String(self).lowercaseString
default:
return String(self.rawValue)
}
}
}
Although the accepted answer works fine, since v0.21.0rc1 it gives a warning
UserWarning: Pandas doesn't allow columns to be created via a new attribute name
Instead, one can do
df[["X", "A", "B", "C"]].plot(x="X", kind="bar")
Here is my solution. I first create random numbers with random.uniform, format them in to string with double precision and then convert them back to float. You can adjust the precision by changing '.2f' to '.3f' etc..
import random
from decimal import Decimal
GndSpeedHigh = float(format(Decimal(random.uniform(5, 25)), '.2f'))
GndSpeedLow = float(format(Decimal(random.uniform(2, GndSpeedHigh)), '.2f'))
GndSpeedMean = float(Decimal(format(GndSpeedHigh + GndSpeedLow) / 2, '.2f')))
print(GndSpeedMean)
Here 'AffiliateDueDate' and 'Title' are columns, both are sorted in ascending order.
array.sort(function(a, b) {
if (a.AffiliateDueDate > b.AffiliateDueDate ) return 1;
else if (a.AffiliateDueDate < b.AffiliateDueDate ) return -1;
else if (a.Title > b.Title ) return 1;
else if (a.Title < b.Title ) return -1;
else return 0;
})
This query should work for you:
SELECT *
FROM table
WHERE MONTH(columnName) = MONTH(CURRENT_DATE())
AND YEAR(columnName) = YEAR(CURRENT_DATE())
Simplest is actually just Age.Max()
, you don't need any more code.
In my case it wasn't changing the color because I was setting the color in my xml resource.
After delete the line that set the color it worked perfectly programmatically
This is an example I did in a RecyclerView
final Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.ic_icon).mutate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
holder.image.setBackground(drawable);
} else {
holder.image.setBackgroundDrawable(drawable);
}
I ran into this issue while trying to install a PySpark package. I got around the issue by changing the TLS version with an environment variable:
echo 'export JAVA_TOOL_OPTIONS="-Dhttps.protocols=TLSv1.2"' >> ~/.bashrc
source ~/.bashrc
Demo : http://jsfiddle.net/xavi3r/D3prt/
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
Original Answer: Resetting a multi-stage form with jQuery
Mike's suggestion (from the comments) to keep checkbox and selects intact!
Warning: If you're creating elements (so they're not in the dom), replace :hidden
with [type=hidden]
or all fields will be ignored!
$(':input','#myform')
.removeAttr('checked')
.removeAttr('selected')
.not(':button, :submit, :reset, :hidden, :radio, :checkbox')
.val('');
I agree with the existing answers that the second form is better because it does not have any side effects and is easier to parallelise (just use a parallel stream).
Performance wise, it appears they are equivalent until you start using parallel streams. In that case, map will perform really much better. See below the micro benchmark results:
Benchmark Mode Samples Score Error Units
SO28319064.forEach avgt 100 187.310 ± 1.768 ms/op
SO28319064.map avgt 100 189.180 ± 1.692 ms/op
SO28319064.mapWithParallelStream avgt 100 55,577 ± 0,782 ms/op
You can't boost the first example in the same manner because forEach is a terminal method - it returns void - so you are forced to use a stateful lambda. But that is really a bad idea if you are using parallel streams.
Finally note that your second snippet can be written in a sligthly more concise way with method references and static imports:
myFinalList = myListToParse.stream()
.filter(Objects::nonNull)
.map(this::doSomething)
.collect(toList());
i had the same problem and was already using the code in the selected answer. this link was the answer for me; maybe for others also.
I ran into this issue as well. I don't know the technical details of what was actually happening. However, in my situation, the root cause was that there was cascading deletes setup in the Oracle database and my JPA/Hibernate code was also trying to do the cascading delete calls. So my advice is to make sure that you know exactly what is happening.