Works fine for me, the code needed around the getResource() thing is as follows:
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> spinner, View v,
int arg2, long arg3) {
String selectedVal = getResources().getStringArray(R.array.compass_rate_values)[spinner.getSelectedItemPosition()];
//Do something with the value
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Just need to make sure (by yourself) the values in the two arrays are aligned properly!
If you do not want to include that your code script (as advised by others above), then simply you may do the following after generating the figure window:
Go to "Edit" in the figure window
Go to "Figure Properties"
At the bottom, you can type the name you want in "Figure Name" field. You can uncheck "Show Figure Number".
That's all.
Good luck.
Just for anyone else landing on this page from Google or elsewhere, this answer is probably the best answer out of all of them.
To summarize, simply hit:
CTRL + ,
And then start typing the file name.
Can be done using numpy where() function:
import pandas as pd
import numpy as np
In [716]: df = pd.DataFrame({"gene_name": ['SLC45A1', 'NECAP2', 'CLIC4', 'ADC', 'AGBL4'] , "BoolCol": [False, True, False, True, True] },
index=list("abcde"))
In [717]: df
Out[717]:
BoolCol gene_name
a False SLC45A1
b True NECAP2
c False CLIC4
d True ADC
e True AGBL4
In [718]: np.where(df["BoolCol"] == True)
Out[718]: (array([1, 3, 4]),)
In [719]: select_indices = list(np.where(df["BoolCol"] == True)[0])
In [720]: df.iloc[select_indices]
Out[720]:
BoolCol gene_name
b True NECAP2
d True ADC
e True AGBL4
Though you don't always need index for a match, but incase if you need:
In [796]: df.iloc[select_indices].index
Out[796]: Index([u'b', u'd', u'e'], dtype='object')
In [797]: df.iloc[select_indices].index.tolist()
Out[797]: ['b', 'd', 'e']
You don't have to use the message passing to obtain or modify DOM. I used chrome.tabs.executeScript
instead. In my example I am using only activeTab permission, therefore the script is executed only on the active tab.
part of manifest.json
"browser_action": {
"default_title": "Test",
"default_popup": "index.html"
},
"permissions": [
"activeTab",
"<all_urls>"
]
index.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<button id="test">TEST!</button>
<script src="test.js"></script>
</body>
</html>
test.js
document.getElementById("test").addEventListener('click', () => {
console.log("Popup DOM fully loaded and parsed");
function modifyDOM() {
//You can play with your DOM here or check URL against your regex
console.log('Tab script:');
console.log(document.body);
return document.body.innerHTML;
}
//We have permission to access the activeTab, so we can call chrome.tabs.executeScript:
chrome.tabs.executeScript({
code: '(' + modifyDOM + ')();' //argument here is a string but function.toString() returns function's code
}, (results) => {
//Here we have just the innerHTML and not DOM structure
console.log('Popup script:')
console.log(results[0]);
});
});
You don't need to have static
in function definition
Look for any module that uses buffering, and selectively disable it.
I'm running PHP 5.3.5 on CentOS 4.8, and after doing this I found eaccelerator needed an upgrade.
As Cody and Brett mentioned, you could reduce VBA slowdown with sensible use of Redim Preserve
. Brett suggested Mod
to do this.
You can also use a user defined Type
and Sub
to do this. Consider my code below:
Public Type dsIntArrayType
eElems() As Integer
eSize As Integer
End Type
Public Sub PushBackIntArray( _
ByRef dsIntArray As dsIntArrayType, _
ByVal intValue As Integer)
With dsIntArray
If UBound(.eElems) < (.eSize + 1) Then
ReDim Preserve .eElems(.eSize * 2 + 1)
End If
.eSize = .eSize + 1
.eElems(.eSize) = intValue
End With
End Sub
This calls ReDim Preserve
only when the size has doubled. The member variable eSize
keeps track of the actual data size of eElems
. This approach has helped me improve performance when final array length is not known until run time.
Hope this helps others too.
Batch files have really very limited logic powers so the best you can hope to come up with is a good workaround that indirectly achieves what you want. That's not to say that you should feel they are inferior to a real language - they still demand the same attention to detail and manual debugging as a real application. It's just that you'll need to work a lot harder to make them do what you want in a robust manner.
For the OP's question it sounds like you require two specific files to exist. Just use a tally:
IF EXIST somefile.txt (
set /a file1_status=1
)
IF EXIST someotehrfile.txt (
set /a file2_status=1
)
set /a file_status_result=file1_status + file2_status
if %file_status_result% equ 2 (
goto somefileexists
)
goto exit
:somefileexists
IF EXIST someotherfile.txt SET var=...
:exit
My example uses 3 variables, but you could just add 1 to file_result_status if the file exists. But if you want more granular control later in your batch file you can record the result for each file as I have done so you don't have to keep checking if a file exists later on.
Jquery like any other good JavaScript frameworks supplies you with functionality independent of browser platform wrapping all the intricacies, which you may not care about or don't want to care about.
I think using a framework is better instead of using pure JavaScript and doing all the stuff from scratch, unless you usage is very limited.
I definitely recommend JQuery!
Thanks
You can specify a default value for the optional argument with something that would never passed to the function and check it with the is
operator:
class _NO_DEFAULT:
def __repr__(self):return "<no default>"
_NO_DEFAULT = _NO_DEFAULT()
def func(optional= _NO_DEFAULT):
if optional is _NO_DEFAULT:
print("the optional argument was not passed")
else:
print("the optional argument was:",optional)
then as long as you do not do func(_NO_DEFAULT)
you can be accurately detect whether the argument was passed or not, and unlike the accepted answer you don't have to worry about side effects of ** notation:
# these two work the same as using **
func()
func(optional=1)
# the optional argument can be positional or keyword unlike using **
func(1)
#this correctly raises an error where as it would need to be explicitly checked when using **
func(invalid_arg=7)
create directive with this code:
$scope.$watch($http.pendingRequests, toggleLoader);
function toggleLoader(status){
if(status.length){
element.addClass('active');
} else {
element.removeClass('active');
}
}
Try:
"${str:$((${#str}-1)):1}"
For e.g.:
someone@mypc:~$ str="A random string*"; echo "$str"
A random string*
someone@mypc:~$ echo "${str:$((${#str}-1)):1}"
*
someone@mypc:~$ echo "${str:$((${#str}-2)):1}"
g
By far, the easiest one I've used is: http://datatables.net/
Amazingly simple...just make sure if you go the DOM replacement route (IE, building a table and letting DataTables reformat it) then make sure to format your table with <thead>
and <tbody>
or it won't work. That's about the only gotcha.
There's also support for AJAX, etc. As with all really good pieces of code, it's also VERY easy to turn it all off. You'd be suprised what you might use, though. I started with a "bare" DataTable that only sorted one field and then realized that some of the features were really relevant to what I'm doing. Clients LOVE the new features.
Bonus points to DataTables for full ThemeRoller support....
I've also had ok luck with tablesorter, but it's not nearly as easy, not quite as well documented, and has only ok features.
if you want to set the home or back icon (not logo or static icon) so you can use
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator( getResources().getDrawable(R.drawable.home) );
If you're recompiling a disassembled APK
with APK tool:
Just Set Memory Allocation a little bigger
set switch -Xmx1024m
to -Xmx2048m
java -Xmx2048m -jar signapk.jar -w testkey.x509.pem testkey.pk8 "%APKOUT%" "%SIGNED%"
you're good to go.. :)
I just wanted to add :--
Popping out from backstack using following
fragmentManager.popBackStack()
is just about removing the fragments from the transaction, no way it is going to remove the fragment from the screen. So ideally, it may not be visible to you but there may be two or three fragments stacked over each other, and on back key press the UI may look cluttered,stacked.
Just taking a simple example:-
Suppose you have a fragmentA which loads Fragmnet B using fragmentmanager.replace() and then we do addToBackStack, to save this transaction. So the flow is :--
STEP 1 -> FragmentA->FragmentB (we moved to FragmentB, but Fragment A is in background, not visible).
Now You do some work in fragmentB and press the Save button—which after saving should go back to fragmentA.
STEP 2-> On save of FragmentB, we go back to FragmentA.
STEP 3 ->So common mistake would be... in Fragment B,we will do fragment Manager.replace() fragmentB with fragmentA.
But what actually is happenening, we are loading Fragment A again, replacing FragmentB . So now there are two FragmentA (one from STEP-1, and one from this STEP-3).
Two instances of FragmentsA are stacked over each other, which may not be visible , but it is there.
So even if we do clear the backstack by above methods, the transaction is cleared but not the actual fragments. So ideally in such a particular case, on press of save button you simply need to go back to fragmentA by simply doing fm.popBackStack() or fm.popBackImmediate().
So correct Step3-> fm.popBackStack() go back to fragmentA, which is already in memory.
Although many correct answers have already been given, the classical (read non-DOM) approach would be like this:
document.forms['yourform']['yourtextarea'].value = 'yourvalue';
where in the HTML your textarea is nested somewhere in a form like this:
<form name="yourform">
<textarea name="yourtextarea" rows="10" cols="60"></textarea>
</form>
And as it happens, that would work with Netscape Navigator 4 and Internet Explorer 3 too. And, not unimportant, Internet Explorer on mobile devices.
The basic difference between Linear Regression and Logistic Regression is : Linear Regression is used to predict a continuous or numerical value but when we are looking for predicting a value that is categorical Logistic Regression come into picture.
Logistic Regression is used for binary classification.
You must initialize your List seeAlso :
List<String> seeAlso = new Vector<String>();
or
List<String> seeAlso = new ArrayList<String>();
you can use rindex()
function to get the last occurrence of a character in string
s="hellloooloo"
b='l'
print(s.rindex(b))
if you are using MySQL 5.7.*, then you can use st_distance_sphere(POINT, POINT).
Select st_distance_sphere(POINT(-2.997065, 53.404146 ), POINT(58.615349, 23.56676 ))/1000 as distcance
I came here looking for how to delete empty __init__.py
files as they are implicit in Python 3.3+ and ended up using:
find -depth '(' -type f -name __init__.py ')' -print0 |
while IFS= read -d '' -r file; do if [[ ! -s $file ]]; then rm $file; fi; done
Also (at least in zsh) using $path as the variable also breaks your $PATH env and so it'll break your open shell. Anyway, thought I'd share!
double myNum = .912385;
int precision = 10000; //keep 4 digits
myNum= Math.floor(myNum * precision +.5)/precision;
Mark color: #005580;
as color: #005580 !important;
.
It will override default bootstrap hover.
Use:
awk -v FS='\t' -v OFS='\t' ...
Example from one of my scripts.
I use the FS
and OFS
variables to manipulate BIND zone files, which are tab delimited:
awk -v FS='\t' -v OFS='\t' \
-v record_type=$record_type \
-v hostname=$hostname \
-v ip_address=$ip_address '
$1==hostname && $3==record_type {$4=ip_address}
{print}
' $zone_file > $temp
This is a clean and easy to read way to do this.
To a first approximation, 0 is success, non-zero is failure, with 1 being general failure, and anything larger than one being a specific failure. Aside from the trivial exceptions of false and test, which are both designed to give 1 for success, there's a few other exceptions I found.
More realistically, 0 means success or maybe failure, 1 means general failure or maybe success, 2 means general failure if 1 and 0 are both used for success, but maybe sucess as well.
The diff command gives 0 if files compared are identical, 1 if they differ, and 2 if binaries are different. 2 also means failure. The less command gives 1 for failure unless you fail to supply an argument, in which case, it exits 0 despite failing.
The more command and the spell command give 1 for failure, unless the failure is a result of permission denied, nonexistent file, or attempt to read a directory. In any of these cases, they exit 0 despite failing.
Then the expr command gives 1 for success unless the output is the empty string or zero, in which case, 0 is success. 2 and 3 are failure.
Then there's cases where success or failure is ambiguous. When grep fails to find a pattern, it exits 1, but it exits 2 for a genuine failure (like permission denied). Klist also exits 1 when it fails to find a ticket, although this isn't really any more of a failure than when grep doesn't find a pattern, or when you ls an empty directory.
So, unfortunately, the unix powers that be don't seem to enforce any logical set of rules, even on very commonly used executables.
The error is:
Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])
In JSON, platforms
look like this:
"platforms": [
{
"platform": "iphone"
},
{
"platform": "ipad"
},
{
"platform": "android_phone"
},
{
"platform": "android_tablet"
}
]
So try change your pojo to something like this:
private List platforms;
public List getPlatforms(){
return this.platforms;
}
public void setPlatforms(List platforms){
this.platforms = platforms;
}
EDIT: you will need change mobile_networks
too. Will look like this:
private List mobile_networks;
public List getMobile_networks() {
return mobile_networks;
}
public void setMobile_networks(List mobile_networks) {
this.mobile_networks = mobile_networks;
}
$result= mysql_query("SELECT * FROM MY_TABLE");
while($row = mysql_fetch_array($result)){
echo $row['whatEverColumnName'];
}
Another way to do this would be to add before adding lines in your output, the following line :
output.writerow(dict(zip(dr.fieldnames, dr.fieldnames)))
The zip would return a list of doublet containing the same value. This list could be used to initiate a dictionary.
add ExcelUtility class to your project and enjoy it.
ExcelUtility.cs File content:
using System;
using Microsoft.Office.Interop.Excel;
static class ExcelUtility
{
public static void WriteArray<T>(this _Worksheet sheet, int startRow, int startColumn, T[,] array)
{
var row = array.GetLength(0);
var col = array.GetLength(1);
Range c1 = (Range) sheet.Cells[startRow, startColumn];
Range c2 = (Range) sheet.Cells[startRow + row - 1, startColumn + col - 1];
Range range = sheet.Range[c1, c2];
range.Value = array;
}
public static bool SaveToExcel<T>(T[,] data, string path)
{
try
{
//Start Excel and get Application object.
var oXl = new Application {Visible = false};
//Get a new workbook.
var oWb = (_Workbook) (oXl.Workbooks.Add(""));
var oSheet = (_Worksheet) oWb.ActiveSheet;
//oSheet.WriteArray(1, 1, bufferData1);
oSheet.WriteArray(1, 1, data);
oXl.Visible = false;
oXl.UserControl = false;
oWb.SaveAs(path, XlFileFormat.xlWorkbookDefault, Type.Missing,
Type.Missing, false, false, XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
oWb.Close(false);
oXl.Quit();
}
catch (Exception e)
{
return false;
}
return true;
}
}
usage :
var data = new[,]
{
{11, 12, 13, 14, 15, 16, 17, 18, 19, 20},
{21, 22, 23, 24, 25, 26, 27, 28, 29, 30},
{31, 32, 33, 34, 35, 36, 37, 38, 39, 40}
};
ExcelUtility.SaveToExcel(data, "test.xlsx");
Best Regards!
The first case will fail when JS is off. It's also a little bit slower since JS must be parsed first (DOM must be loaded). However JS is safer since the destination doesn't know the referer and your redirect might be tracked (referers aren't reliable in general yet this is something).
You can also use meta refresh tag. It also requires DOM to be loaded.
// Make option have a "selected" attribute using jQuery
var yourValue = "Gateway 2";
$("#gate").find('option').each(function( i, opt ) {
if( opt.value === yourValue )
$(opt).attr('selected', 'selected');
});
below example with target="_blank"
works for Safari and Mozilla
<a href="http://www.starfall.com" `target="_blank"`>
Using target="new"
worked for Chrome
<a href="http://www.starfall.com" `target="new"`>
First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="file" name="file">
<input type="submit" value="Submit">
</form>
Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:
const http = require("http");
const path = require("path");
const fs = require("fs");
const express = require("express");
const app = express();
const httpServer = http.createServer(app);
const PORT = process.env.PORT || 3000;
httpServer.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));
Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).
In Express 3.x you could use express.bodyParser
middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:
You need to define a route to handle form posts:
const multer = require("multer");
const handleError = (err, res) => {
res
.status(500)
.contentType("text/plain")
.end("Oops! Something went wrong!");
};
const upload = multer({
dest: "/path/to/temporary/directory/to/store/uploaded/files"
// you might also want to set some limits: https://github.com/expressjs/multer#limits
});
app.post(
"/upload",
upload.single("file" /* name attribute of <file> element in your form */),
(req, res) => {
const tempPath = req.file.path;
const targetPath = path.join(__dirname, "./uploads/image.png");
if (path.extname(req.file.originalname).toLowerCase() === ".png") {
fs.rename(tempPath, targetPath, err => {
if (err) return handleError(err, res);
res
.status(200)
.contentType("text/plain")
.end("File uploaded!");
});
} else {
fs.unlink(tempPath, err => {
if (err) return handleError(err, res);
res
.status(403)
.contentType("text/plain")
.end("Only .png files are allowed!");
});
}
}
);
In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.
In order to show the uploaded image, assuming you already have an HTML page containing an img element:
<img src="/image.png" />
you can define another route in your express app and use res.sendFile
to serve the stored image:
app.get("/image.png", (req, res) => {
res.sendFile(path.join(__dirname, "./uploads/image.png"));
});
TypeError: Converting circular structure to JSON in nodejs:
This error can be seen on Arangodb when using it with Node.js, because storage is missing in your database. If the archive is created under your database, check in the Aurangobi web interface.
The new standard, as used by Inuit.css and Bourbon - two very widely used and well-maintained CSS/Sass frameworks:
.btcf:after {
content:"";
display:block;
clear:both;
}
Keep in mind that clearfixes are essentially a hack for what flexbox layouts can now provide in a much smarter way. CSS floats were originally designed for inline content to flow around - like images in a long textual article - and not for grid layouts and the like. If your target browsers support flexbox, it's worth looking into.
This doesn't support IE7. You shouldn't be supporting IE7. Doing so continues to expose users to unfixed security exploits and makes life harder for all other web developers, as it reduces the pressure on users and organisations to switch to modern browsers.
This clearfix was announced and explained by Thierry Koblentz in July 2012. It sheds unnecessary weight from Nicolas Gallagher's 2011 micro-clearfix. In the process, it frees a pseudo-element for your own use. This has been updated to use display: block
rather than display: table
(again, credit to Thierry Koblentz).
The exclusion pattern should be case-insensitive, so you shouldn't have to specify every case for the exclusion.
That said, the -Exclude
parameter accepts an array of strings, so as long as you define $archive
as such, you should be set.
$archive = ("*archive*","*Archive*","*ARCHIVE*");
You also should drop the trailing asterisk from $folder
- since you're specifying -recurse
, you should only need to give the top-level folder.
$folder = "T:\Drawings\Design\"
Fully revised script. This also changes how you detect whether you've found a directory, and skips the Foreach-Object
because you can just pull the property directly & dump it all to the file.
$folder = "T:\Drawings\Design\";
$raw_txt = "T:\Design Projects\Design_Admin\PowerShell\raw.txt";
$search_pro = "T:\Design Projects\Design_Admin\PowerShell\search.pro";
$archive = ("*archive*","*Archive*","*ARCHIVE*");
Get-ChildItem -Path $folder -Exclude $archive -Recurse | where {$_.PSIsContainer} | select-Object -expandproperty FullName |out-file $search_pro
Apache Commons Lang 3 contais the class EnumUtils. If you aren't using Apache Commons in your projects, you're doing it wrong. You are reinventing the wheel!
There's a dozen of cool methods that we could use without throws an Exception. For example:
Gets the enum for the class, returning null if not found.
This method differs from Enum.valueOf in that it does not throw an exceptionfor an invalid enum name and performs case insensitive matching of the name.
EnumUtils.getEnumIgnoreCase(SeasonEnum.class, season);
Use anchors instead:
aa=re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$",ip)
These make sure that the start and end of the string are matched at the start and end of the regex. (well, technically, you don't need the starting ^
anchor because it's implicit in the .match()
method).
Then, check if the regex did in fact match before trying to access its results:
if aa:
ip = aa.group()
Of course, this is not a good approach for validating IP addresses (check out gnibbler's answer for a proper method). However, regexes can be useful for detecting IP addresses in a larger string:
ip_candidates = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", ip)
Here, the \b
word boundary anchors make sure that the digits don't exceed 3 for each segment.
<div style="width:1px;background-color:red;height:30px;float:right;"></div>
Easily can be done using a div like this
Here's the link I used as a guide. Hope this helps!
Converting HTML to PDF using ITextSharp
protected void Page_Load(object sender, EventArgs e)
{
try
{
string strHtml = string.Empty;
//HTML File path -http://aspnettutorialonline.blogspot.com/
string htmlFileName = Server.MapPath("~") + "\\files\\" + "ConvertHTMLToPDF.htm";
//pdf file path. -http://aspnettutorialonline.blogspot.com/
string pdfFileName = Request.PhysicalApplicationPath + "\\files\\" + "ConvertHTMLToPDF.pdf";
//reading html code from html file
FileStream fsHTMLDocument = new FileStream(htmlFileName, FileMode.Open, FileAccess.Read);
StreamReader srHTMLDocument = new StreamReader(fsHTMLDocument);
strHtml = srHTMLDocument.ReadToEnd();
srHTMLDocument.Close();
strHtml = strHtml.Replace("\r\n", "");
strHtml = strHtml.Replace("\0", "");
CreatePDFFromHTMLFile(strHtml, pdfFileName);
Response.Write("pdf creation successfully with password -http://aspnettutorialonline.blogspot.com/");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
public void CreatePDFFromHTMLFile(string HtmlStream, string FileName)
{
try
{
object TargetFile = FileName;
string ModifiedFileName = string.Empty;
string FinalFileName = string.Empty;
/* To add a Password to PDF -http://aspnettutorialonline.blogspot.com/ */
TestPDF.HtmlToPdfBuilder builder = new TestPDF.HtmlToPdfBuilder(iTextSharp.text.PageSize.A4);
TestPDF.HtmlPdfPage first = builder.AddPage();
first.AppendHtml(HtmlStream);
byte[] file = builder.RenderPdf();
File.WriteAllBytes(TargetFile.ToString(), file);
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(TargetFile.ToString());
ModifiedFileName = TargetFile.ToString();
ModifiedFileName = ModifiedFileName.Insert(ModifiedFileName.Length - 4, "1");
string password = "password";
iTextSharp.text.pdf.PdfEncryptor.Encrypt(reader, new FileStream(ModifiedFileName, FileMode.Append), iTextSharp.text.pdf.PdfWriter.STRENGTH128BITS, password, "", iTextSharp.text.pdf.PdfWriter.AllowPrinting);
//http://aspnettutorialonline.blogspot.com/
reader.Close();
if (File.Exists(TargetFile.ToString()))
File.Delete(TargetFile.ToString());
FinalFileName = ModifiedFileName.Remove(ModifiedFileName.Length - 5, 1);
File.Copy(ModifiedFileName, FinalFileName);
if (File.Exists(ModifiedFileName))
File.Delete(ModifiedFileName);
}
catch (Exception ex)
{
throw ex;
}
}
You can download the sample file. Just place the html
you want to convert in the files
folder and run. It will automatically generate the pdf file and place it in the same folder. But in your case, you can specify your html path in the htmlFileName
variable.
Quoting from Wikipedia:
Thus, anyone can create a UUID and use it to identify something with reasonable confidence that the identifier will never be unintentionally used by anyone for anything else
It goes on to explain in pretty good detail on how safe it actually is. So to answer your question: Yes, it's safe enough.
The best superuser role would be the root.The Syntax is:
use admin
db.createUser(
{
user: "root",
pwd: "password",
roles: [ "root" ]
})
For more details look at built-in roles.
Hope this helps !!!
window.open
will open a new browser with the specified URL.
window.location.href
will open the URL in the window in which the code is called.
Note also that window.open()
is a function on the window object itself whereas window.location
is an object that exposes a variety of other methods and properties.
Whatever way you try above you need to test it by upload it to app connect like me to make sure it works and save your valuable time
You can skip the complex Canvas manipulation and do this entirely with Drawables, using LayerDrawable
. You have one of two choices: You can either define it in XML then simply set the image, or you can configure a LayerDrawable
dynamically in code.
Solution #1 (via XML):
Create a new Drawable XML file, let's call it layer.xml
:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/t" />
<item android:drawable="@drawable/tt" />
</layer-list>
Now set the image using that Drawable:
testimage.setImageDrawable(getResources().getDrawable(R.layout.layer));
Solution #2 (dynamic):
Resources r = getResources();
Drawable[] layers = new Drawable[2];
layers[0] = r.getDrawable(R.drawable.t);
layers[1] = r.getDrawable(R.drawable.tt);
LayerDrawable layerDrawable = new LayerDrawable(layers);
testimage.setImageDrawable(layerDrawable);
(I haven't tested this code so there may be a mistake, but this general outline should work.)
$ rails g model Item name:string description:text product:references
I too found the guides difficult to use. Easy to understand, but hard to find what I am looking for.
Also, I have temp projects that I run the rails generate
commands on. Then once I get them working I run it on my real project.
Reference for the above code: http://guides.rubyonrails.org/getting_started.html#associating-models
You can use this one it's for YYYY-MM-DD. It checks if it's a valid date and that the value is not NULL. It returns TRUE
if everythings check out to be correct or FALSE
if anything is invalid. It doesn't get easier then this!
function validateDate(date) {
var matches = /^(\d{4})[-\/](\d{2})[-\/](\d{2})$/.exec(date);
if (matches == null) return false;
var d = matches[3];
var m = matches[2] - 1;
var y = matches[1] ;
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d &&
composedDate.getMonth() == m &&
composedDate.getFullYear() == y;
}
Be aware that months need to be subtracted like this: var m = matches[2] - 1;
else the new Date()
instance won't be properly made.
I know this is old, but I was having trouble too. For Spring 3 using Maven and Eclipse, I needed to put the log4j.xml in src/test/resources for the Unit test to log properly. Placing in in the root of the test did not work for me. Hopefully this helps others.
It only opens the first (bookmarked) page full screen. Any next page will be opened WITH the address bar visible again. Whatever meta tag you put into your page header...
I strongly recommend the use of getopt.
If you want help to print out for your options then take a look at GetOptionKit.
Changing the format but not changing the type:
df['date'] = pd.to_datetime(df["date"].dt.strftime('%Y-%m'))
Probable cause that remount
fails is you are not running adb
as root
.
Shell Script should be as follow.
# Script to mount Android Device as read/write.
# List the Devices.
adb devices;
# Run adb as root (Needs root access).
adb root;
# Since you're running as root su is not required
adb shell mount -o rw,remount /;
If this fails, you could try the below:
# List the Devices.
adb devices;
# Run adb as root
adb root;
adb remount;
adb shell su -c "mount -o rw,remount /";
To find which user
you are:
$ adb shell whoami
I got this to work. My big issue was my json was a string (in my database...and not a specific/known Type).
Ok, I finally got this to work.
////[Route("api/[controller]")]
////[ApiController]
////public class MyController: Microsoft.AspNetCore.Mvc.ControllerBase
////{
//// public IActionResult MyMethod(string myParam) {
string hardCodedJson = "{}";
int hardCodedStatusCode = 200;
Newtonsoft.Json.Linq.JObject job = Newtonsoft.Json.Linq.JObject.Parse(hardCodedJson);
/* "this" comes from your class being a subclass of Microsoft.AspNetCore.Mvc.ControllerBase */
Microsoft.AspNetCore.Mvc.ContentResult contRes = this.Content(job.ToString());
contRes.StatusCode = hardCodedStatusCode;
return contRes;
//// } ////end MyMethod
//// } ////end class
I happen to be on asp.net core 3.1
#region Assembly Microsoft.AspNetCore.Mvc.Core, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
//C:\Program Files\dotnet\packs\Microsoft.AspNetCore.App.Ref\3.1.0\ref\netcoreapp3.1\Microsoft.AspNetCore.Mvc.Core.dll
I got the hint from here :: https://www.jianshu.com/p/7b3e92c42b61
just export the table with data .. then copy its sql like
CREATE TABLE IF NOT EXISTS `employees` (
`emp_badgenumber` int(20) NOT NULL AUTO_INCREMENT,
`emp_fullname` varchar(100) NOT NULL,
`emp_father_name` varchar(30) NOT NULL,
`emp_mobile` varchar(20) DEFAULT NULL,
`emp_cnic` varchar(20) DEFAULT NULL,
`emp_gender` varchar(10) NOT NULL,
`emp_is_deleted` tinyint(4) DEFAULT '0',
`emp_registration_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`emp_overtime_allowed` tinyint(4) DEFAULT '1',
PRIMARY KEY (`emp_badgenumber`),
UNIQUE KEY `bagdenumber` (`emp_badgenumber`),
KEY `emp_badgenumber` (`emp_badgenumber`),
KEY `emp_badgenumber_2` (`emp_badgenumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=111121326 ;
now change auto increment value and execute sql.
Yes with Virtual Host you can have as many parallel programs as you want:
Open
/etc/httpd/conf/httpd.conf
Listen 81
Listen 82
Listen 83
<VirtualHost *:81>
ServerAdmin [email protected]
DocumentRoot /var/www/site1/html
ServerName site1.com
ErrorLog logs/site1-error_log
CustomLog logs/site1-access_log common
ScriptAlias /cgi-bin/ "/var/www/site1/cgi-bin/"
</VirtualHost>
<VirtualHost *:82>
ServerAdmin [email protected]
DocumentRoot /var/www/site2/html
ServerName site2.com
ErrorLog logs/site2-error_log
CustomLog logs/site2-access_log common
ScriptAlias /cgi-bin/ "/var/www/site2/cgi-bin/"
</VirtualHost>
<VirtualHost *:83>
ServerAdmin [email protected]
DocumentRoot /var/www/site3/html
ServerName site3.com
ErrorLog logs/site3-error_log
CustomLog logs/site3-access_log common
ScriptAlias /cgi-bin/ "/var/www/site3/cgi-bin/"
</VirtualHost>
Restart apache
service httpd restart
You can now refer Site1 :
http://<ip-address>:81/
http://<ip-address>:81/cgi-bin/
Site2 :
http://<ip-address>:82/
http://<ip-address>:82/cgi-bin/
Site3 :
http://<ip-address>:83/
http://<ip-address>:83/cgi-bin/
If path is not hardcoded in any script then your websites should work seamlessly.
In my case the problem was I was trying to add same view multiple times to linear layout
View childView = LayoutInflater.from(context).inflate(R.layout.lay_progressheader, parentLayout,false);
for (int i = 1; i <= totalCount; i++) {
parentLayout.addView(childView);
}
just initialize view every time to fix the issue
for (int i = 1; i <= totalCount; i++) {
View childView = LayoutInflater.from(context).inflate(R.layout.lay_progressheader, parentLayout,false);
parentLayout.addView(childView);
}
I know this is too late but for those who are coming here for the first time, I'd like to post a solution. I have a float value index
and a string imgfile
and I had the same problem as you. This is how I fixed the issue
index = 1.0
imgfile = 'data/2.jpg'
out = '%.1f,%s' % (index,imgfile)
print out
The output is
1.0,data/2.jpg
You may modify this formatting example as per your convenience.
A simple formula to use is
=COUNTIF($B:$B,A1)
Formula specified is for cell A1. Simply copy and paste special - format to the whole of column A
You probably need to use reflection to get the types of them to check. To get the type of the List: Get generic type of java.util.List
You can also use Js2Py which is written in pure python and is able to both execute and translate javascript to python. Supports virtually whole JavaScript even labels, getters, setters and other rarely used features.
import js2py
js = """
function escramble_758(){
var a,b,c
a='+1 '
b='84-'
a+='425-'
b+='7450'
c='9'
document.write(a+c+b)
}
escramble_758()
""".replace("document.write", "return ")
result = js2py.eval_js(js) # executing JavaScript and converting the result to python string
Advantages of Js2Py include portability and extremely easy integration with python (since basically JavaScript is being translated to python).
To install:
pip install js2py
Talk is cheap, show you the code:
>>> tup = (10, 20, 30)
>>> i = 50
>>> print '%d %s'%(i,tup)
50 (10, 20, 30)
>>> print '%s'%(tup,)
(10, 20, 30)
>>>
What worked for me was to:
..\packages
to ..\..\..\packages
since I moved the project to a deeper folder.You should use hasOwnProperty
. For example:
myObj.hasOwnProperty('myKey');
Note: If you are using ESLint, the above may give you an error for violating the no-prototype-builtins rule, in that case the workaround is as below:
Object.prototype.hasOwnProperty.call(myObj, 'myKey');
This solution works without using bash specific features or temporary files. Bonus: in the end the exit status is actually an exit status and not some string in a file.
Situation:
someprog | filter
you want the exit status from someprog
and the output from filter
.
Here is my solution:
((((someprog; echo $? >&3) | filter >&4) 3>&1) | (read xs; exit $xs)) 4>&1
echo $?
See my answer for the same question on unix.stackexchange.com for a detailed explanation and an alternative without subshells and some caveats.
Currently from the onAttach
Fragment code, it is not clear if the Context
is the current activity: Source Code
public void onAttach(Context context) {
mCalled = true;
final Activity hostActivity = mHost == null ? null : mHost.getActivity();
if (hostActivity != null) {
mCalled = false;
onAttach(hostActivity);
}
}
If you will take a look at getActivity
you will see the same call
/**
* Return the Activity this fragment is currently associated with.
*/
final public Activity getActivity() {
return mHost == null ? null : mHost.getActivity();
}
So If you want to be sure that you are getting the Activity then use getActivity()
(in onAttach
in your Fragment
) but don't forget to check for null
because if mHost
is null
your activity will be null
You need debounce!
Here is a jQuery plugin, and here is all you need to know about debounce. If you are coming here from Google and Underscore has found its way into the JSoup of your app, it has debounce baked right in!
How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:
Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.
ANTLR mega tutorial by Gabriele Tomassetti is very helpful
It has grammar examples, examples of visitors in different languages (Java, JavaScript, C# and Python) and many other things. Highly recommended.
EDIT: other useful articles by Gabriele Tomassetti on ANTLR
You can use sticky
position.
Here is a sample code. This is HTML/CSS solution. No js is required.
.view {
margin: auto;
width: 600px;
}
.wrapper {
position: relative;
overflow: auto;
border: 1px solid black;
white-space: nowrap;
}
.sticky-col {
position: -webkit-sticky;
position: sticky;
background-color: white;
}
.first-col {
width: 100px;
min-width: 100px;
max-width: 100px;
left: 0px;
}
.second-col {
width: 150px;
min-width: 150px;
max-width: 150px;
left: 100px;
}
_x000D_
<div class="view">
<div class="wrapper">
<table class="table">
<thead>
<tr>
<th class="sticky-col first-col">Number</th>
<th class="sticky-col second-col">First Name</th>
<th>Last Name</th>
<th>Employer</th>
</tr>
</thead>
<tbody>
<tr>
<td class="sticky-col first-col">1</td>
<td class="sticky-col second-col">Mark</td>
<td>Ham</td>
<td>Micro</td>
</tr>
<tr>
<td class="sticky-col first-col">2</td>
<td class="sticky-col second-col">Jacob</td>
<td>Smith</td>
<td>Adob Adob Adob AdobAdob Adob Adob Adob Adob</td>
</tr>
<tr>
<td class="sticky-col first-col">3</td>
<td class="sticky-col second-col">Larry</td>
<td>Wen</td>
<td>Goog Goog Goog GoogGoog Goog Goog Goog Goog Goog</td>
</tr>
</tbody>
</table>
</div>
</div>
_x000D_
Bootply code: https://www.bootply.com/g8pfBXOcY9
Here is a link from developer.nokia.com wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator
And another link here
AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).
The command (or the URL in it) to add the github repository as a remote isn't quite correct. If I understand your repository name correctly, it should be;
git remote add demo_app '[email protected]:levelone/demo_app.git'
you have error in your sql syntax.
please use this query and checkout.
$query = mysql_query("UPDATE `anstalld` SET mandag = '$mandag', tisdag = '$tisdag', onsdag = '$onsdag', torsdag = '$torsdag', fredag = '$fredag' WHERE namn = '$namn' ");
If your application only works in portrait orientation, this is enough:
[[[UIApplication sharedApplication] keyWindow] addSubview:yourView]
And your view will not be shown over keyboard and status bar.
If you want to get a topmost view that over keyboard or status bar, or you want the topmost view can rotate correctly with devices, please try this framework:
https://github.com/HarrisonXi/TopmostView
It supports iOS7/8/9.
def apprentice():
read(diveintopython)
experiment(interpreter)
read(python_tutorial)
experiment(interpreter, modules/files)
watch(pycon)
def master():
refer(python-essential-reference)
refer(PEPs/language reference)
experiment()
read(good_python_code) # Eg. twisted, other libraries
write(basic_library) # reinvent wheel and compare to existing wheels
if have_interesting_ideas:
give_talk(pycon)
def guru():
pass # Not qualified to comment. Fix the GIL perhaps?
Perhaps it is late for the party. But there is an alternative solution for this is to use ApiMultipartFormFormatter plugin.
This plugin helps you to receive the multipart/formdata content as ASP.NET Core does.
In the github page, demo is already provided.
HashMap
is a Map
implementation, allowing duplicate values but not duplicate keys.. For adding an object a Key/Value pair is required. Null Keys and Null values are allowed. eg:
{The->3,world->5,is->2,nice->4}
HashSet
is a Set
implementation,which does not allow duplicates.If you tried to add a duplicate object, a call to public boolean add(Object o)
method, then the set remains unchanged and returns false
. eg:
[The,world,is,nice]
here's the trick (works everywhere):
r(function(){
alert('DOM Ready!');
});
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
Procedural programming divides sequences of statements and conditional constructs into separate blocks called procedures that are parameterized over arguments that are (non-functional) values.
Functional programming is the same except that functions are first-class values, so they can be passed as arguments to other functions and returned as results from function calls.
Note that functional programming is a generalization of procedural programming in this interpretation. However, a minority interpret "functional programming" to mean side-effect-free which is quite different but irrelevant for all major functional languages except Haskell.
As ping
works, but telnet
to port 80
does not, the HTTP port 80
is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?).
You need to add some code to your python program, that handles the proxy, like described here:
I am going to be general and not specific to Java as DAO and ORM are used in all languages.
To understand DAO you first need to understand ORM (Object Relational Mapping). This means that if you have a table called "person" with columns "name" and "age", then you would create object-template for that table:
type Person {
name
age
}
Now with help of DAO instead of writing some specific queries, to fetch all persons, for what ever type of db you are using (which can be error-prone) instead you do:
list persons = DAO.getPersons();
...
person = DAO.getPersonWithName("John");
age = person.age;
You do not write the DAO abstraction yourself, instead it is usually part of some opensource project, depending on what language and framework you are using.
Now to the main question here. "..where it is used..". Well usually if you are writing complex business and domain specific code your life will be very difficult without DAO. Of course you do not need to use ORM and DAO provided, instead you can write your own abstraction and native queries. I have done that in the past and almost always regretted it later.
On my Ubuntu LAMP installation, I solved this problem with the following 2 changes.
sudo a2enmod rewrite
.AllowOverride All
Then restart the Apache server: service apache2 restart
COMBOBOXID.DropDownStyle = ComboBoxStyle.DropDownList;
Use a subquery in the where clause. For a delete query requirig a join, this example will delete rows that are unmatched in the joined table "docx_document" and that have a create date > 120 days in the "docs_documents" table.
delete from docs_documents d
where d.id in (
select a.id from docs_documents a
left join docx_document b on b.id = a.document_id
where b.id is null
and floor(sysdate - a.create_date) > 120
);
When you subtract two variables of type TIMESTAMP
, you get an INTERVAL DAY TO SECOND
which includes a number of milliseconds and/or microseconds depending on the platform. If the database is running on Windows, systimestamp
will generally have milliseconds. If the database is running on Unix, systimestamp
will generally have microseconds.
1 select systimestamp - to_timestamp( '2012-07-23', 'yyyy-mm-dd' )
2* from dual
SQL> /
SYSTIMESTAMP-TO_TIMESTAMP('2012-07-23','YYYY-MM-DD')
---------------------------------------------------------------------------
+000000000 14:51:04.339000000
You can use the EXTRACT
function to extract the individual elements of an INTERVAL DAY TO SECOND
SQL> ed
Wrote file afiedt.buf
1 select extract( day from diff ) days,
2 extract( hour from diff ) hours,
3 extract( minute from diff ) minutes,
4 extract( second from diff ) seconds
5 from (select systimestamp - to_timestamp( '2012-07-23', 'yyyy-mm-dd' ) diff
6* from dual)
SQL> /
DAYS HOURS MINUTES SECONDS
---------- ---------- ---------- ----------
0 14 55 37.936
You can then convert each of those components into milliseconds and add them up
SQL> ed
Wrote file afiedt.buf
1 select extract( day from diff )*24*60*60*1000 +
2 extract( hour from diff )*60*60*1000 +
3 extract( minute from diff )*60*1000 +
4 round(extract( second from diff )*1000) total_milliseconds
5 from (select systimestamp - to_timestamp( '2012-07-23', 'yyyy-mm-dd' ) diff
6* from dual)
SQL> /
TOTAL_MILLISECONDS
------------------
53831842
Normally, however, it is more useful to have either the INTERVAL DAY TO SECOND
representation or to have separate columns for hours, minutes, seconds, etc. rather than computing the total number of milliseconds between two TIMESTAMP
values.
Might also be interesting for you to know that you can use:
{r echo=FALSE, results='hide',message=FALSE}
a<-as.numeric(rnorm(100))
hist(a, breaks=24)
to exclude all the commands you give, all the results it spits out and all message info being spit out by R (eg. after library(ggplot) or something)
public class UserNotFoundException extends Exception {
public UserNotFoundException(String message) {
super(message)
From http://msdn.microsoft.com/en-us/library/ms176089.aspx
varchar [ ( n | max ) ] Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The ISO synonyms for varchar are char varying or character varying.
1 character = 1 byte. And don't forget 2 bytes for the termination. So, 2^31-3 characters.
When signing into the server to execute the code use this instead:
ssh -X username@servername
the -X
will get rid of the no display name and no $DISPLAY environment variable
error
:)
Besides all above solutions, check if you have the "id
" or any custom defined parameter in the DELETE
method is matching the route config.
public void Delete(int id)
{
//some code here
}
If you hit with repeated 405 errors better reset the method signature to default as above and try.
The route config by default will look for id
in the URL. So the parameter name id
is important here unless you change the route config under the App_Start
folder.
You may change the data type of the id
though.
For example the method below should work just fine:
public void Delete(string id)
{
//some code here
}
Note: Also ensure that you pass the data over the url not the data method that will carry the payload as body content.
DELETE http://{url}/{action}/{id}
Example:
DELETE http://localhost/item/1
Hope it helps.
I know, that's a 8 years old question, but that can still happen today.
Powershell ca be used for that. An example is shown here. The shortest command for the cmd is:
powershell -command "&{(get-host).ui.rawui.windowsize=@{width=100;height=55};}"
Set your wanted window size to the width and hight vars. However, this short line has two limitations:
To avoid that, in the command below the buffer size is defined. In addition, the process runs parallel to the other following cmd commands:
start /b powershell -command "&{$w=(get-host).ui.rawui;$w.buffersize=@{width=177;height=999};$w.windowsize=@{width=155;height=55};}"
The width and height values to the buffersize object, here 177 and 999, must be bigger or equal to the window size values.
You could try something like:
WebElement rxBtn = driver.findElement(By.className("icon-rx"));
WebElement otcBtn = driver.findElement(By.className("icon-otc"));
WebElement herbBtn = driver.findElement(By.className("icon-herb"));
Assert.assertEquals(true, rxBtn.isDisplayed());
Assert.assertEquals(true, otcBtn.isDisplayed());
Assert.assertEquals(true, herbBtn.isDisplayed());
This is just an example. Basically you declare and define the WebElement variables you wish to use and then Assert
whether or not they are displayed. This is using TestNG Assertions.
Type IF /? to get help about if, it clearly explains how to use IF EXIST.
To delete a complete tree except some folders, see the answer of this question: Windows batch script to delete everything in a folder except one
Finally copying just means calling COPY and calling another bat file can be done like this:
MYOTHERBATFILE.BAT sync.bat myprogram.ini
if you are ubuntu user than try this:
sudo apt-get remove jenkins
sudo apt-get remove --auto-remove jenkins
'apt-get remove' command is use to remove package.
If the to-be-updated component is not inside the same NamingContainer
component (ui:repeat
, h:form
, h:dataTable
, etc), then you need to specify the "absolute" client ID. Prefix with :
(the default NamingContainer
separator character) to start from root.
<p:ajax process="@this" update="count :subTotal"/>
To be sure, check the client ID of the subTotal
component in the generated HTML for the actual value. If it's inside for example a h:form
as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.
<p:ajax process="@this" update="count :formId:subTotal"/>
Space separation of IDs is more recommended as <f:ajax>
doesn't support comma separation and starters would otherwise get confused.
Use attribute binding syntax instead
<ol class="viewer-nav"><li *ngFor="let section of sections"
[attr.data-sectionvalue]="section.value">{{ section.text }}</li>
</ol>
or
<ol class="viewer-nav"><li *ngFor="let section of sections"
attr.data-sectionvalue="{{section.value}}">{{ section.text }}</li>
</ol>
Yes,
with open('filename.txt') as fp:
for line in fp:
print line
is the way to go.
It is not more verbose. It is more safe.
With ES6 arrow functions it will be like this:
//Let's say we have these cars
let cars = [ { brand: 'Porsche', top_speed: 260 },
{ brand: 'Benz', top_speed: 110 },
{ brand: 'Fiat', top_speed: 90 },
{ brand: 'Aston Martin', top_speed: 70 } ]
Array.prototype.sort()
can accept a comparator function (here I used arrow notation, but ordinary functions work the same):
let sortedByBrand = [...cars].sort((first, second) => first.brand > second.brand)
// [ { brand: 'Aston Martin', top_speed: 70 },
// { brand: 'Benz', top_speed: 110 },
// { brand: 'Fiat', top_speed: 90 },
// { brand: 'Porsche', top_speed: 260 } ]
The above approach copies the contents of cars array into a new one and sorts it alphabetically based on brand names. Similarly, you can pass a different function:
let sortedBySpeed =[...cars].sort((first, second) => first.top_speed > second.top_speed)
//[ { brand: 'Aston Martin', top_speed: 70 },
// { brand: 'Fiat', top_speed: 90 },
// { brand: 'Benz', top_speed: 110 },
// { brand: 'Porsche', top_speed: 260 } ]
If you don't mind mutating the orginal array cars.sort(comparatorFunction)
will do the trick.
Just open your setting->compiler and click on the reset defaults and it will start work.
For the string data
output = []
def uniq(input):
if input not in output:
output.append(input)
print output
You can use the inbuilt function max()
with multiple arguments:
print max(1, 2, 3)
or a list:
list = [1, 2, 3]
print max(list)
or in fact anything iterable.
In MySQL InnoDB, there are two types of index.
Primary key which is called clustered index. Index key words are stored with real record data in the B+Tree leaf node.
Secondary key which is non clustered index. These index only store primary key's key words along with their own index key words in the B+Tree leaf node. So when searching from secondary index, it will first find its primary key index key words and scan the primary key B+Tree to find the real data records. This will make secondary index slower compared to primary index search. However, if the select
columns are all in the secondary index, then no need to look up primary index B+Tree again. This is called covering index.
Try to use:
pattern="(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/\d{4}"
Without the need to edit any registry keys, the Productivity Power Tools extension (available for all versions of visual studio) provides guideline functionality.
Once installed just right click while in the editor window and choose the add guide line option. Note that the guideline will always be placed on the column where your editing cursor is currently at, regardless of where you right click in the editor window.
To turn off go to options and find Productivity Power Tools
and in that section turn off Column Guides
. A reboot will be necessary.
You also encounter this if you run an Application on a Scheduled Task in Non-Interactive mode.
As soon as you show a Dialog it throws the error:
Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.
You can see its a MessageBox causing the problem in the stack trace:
at System.Windows.Forms.MessageBox.ShowCore(IWin32Window owner, String text, String caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, Boolean showHelp)
If you're running your app on a Scheduled Task send an email instead of showing a Dialog.
Depending on your rights, you need sudo at beginning.
Use display:table-cell;
for removing space between .Left and .Right
div.left {_x000D_
background:blue;_x000D_
height:200px;_x000D_
width:300px;_x000D_
}_x000D_
_x000D_
div.right{_x000D_
background:green;_x000D_
height:300px;_x000D_
width:100px;_x000D_
}_x000D_
_x000D_
.container{_x000D_
background:black;_x000D_
height:400px;_x000D_
width:450px;_x000D_
}_x000D_
_x000D_
.container > div {_x000D_
display: table-cell;_x000D_
}
_x000D_
<div class="container">_x000D_
<div>_x000D_
<div class="left">_x000D_
LEFT_x000D_
</div>_x000D_
</div>_x000D_
<div>_x000D_
<div class="right">_x000D_
RIGHT_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
None of these worked for me.. they return as true, even when they aren't. The problem is, you have to test the available permission against the current process user rights, this tests for file creation rights, just change the FileSystemRights clause to 'Write' to test write access..
/// <summary>
/// Test a directory for create file access permissions
/// </summary>
/// <param name="DirectoryPath">Full directory path</param>
/// <returns>State [bool]</returns>
public static bool DirectoryCanCreate(string DirectoryPath)
{
if (string.IsNullOrEmpty(DirectoryPath)) return false;
try
{
AuthorizationRuleCollection rules = Directory.GetAccessControl(DirectoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
WindowsIdentity identity = WindowsIdentity.GetCurrent();
foreach (FileSystemAccessRule rule in rules)
{
if (identity.Groups.Contains(rule.IdentityReference))
{
if ((FileSystemRights.CreateFiles & rule.FileSystemRights) == FileSystemRights.CreateFiles)
{
if (rule.AccessControlType == AccessControlType.Allow)
return true;
}
}
}
}
catch {}
return false;
}
var Klass = function Klass() {
var thus = this;
var somePublicVariable = x
, somePublicVariable2 = x
;
var somePrivateVariable = x
, somePrivateVariable2 = x
;
var privateMethod = (function p() {...}).bind(this);
function publicMethod() {...}
// export precepts
this.var1 = somePublicVariable;
this.method = publicMethod;
return this;
};
First, you may change your preference of adding methods to the instance instead of the constructor's prototype
object. I almost always declare methods inside of the constructor because I use Constructor Hijacking very often for purposes regarding Inheritance & Decorators.
Here's how I decide where which declarations are writ:
this
)var
declarations take precedence over function
declarations{}
and []
)public
declarations take precedence over private
declarationsFunction.prototype.bind
over thus
, self
, vm
, etc
this
from within the Lexical Scope of the Closure Space.Here's why these help:
Constructor Hijackingvar Super = function Super() {
...
this.inherited = true;
...
};
var Klass = function Klass() {
...
// export precepts
Super.apply(this); // extends this with property `inherited`
...
};
Model Design
var Model = function Model(options) {
var options = options || {};
this.id = options.id || this.id || -1;
this.string = options.string || this.string || "";
// ...
return this;
};
var model = new Model({...});
var updated = Model.call(model, { string: 'modified' });
(model === updated === true); // > true
Design Patterns
var Singleton = new (function Singleton() {
var INSTANCE = null;
return function Klass() {
...
// export precepts
...
if (!INSTANCE) INSTANCE = this;
return INSTANCE;
};
})();
var a = new Singleton();
var b = new Singleton();
(a === b === true); // > true
As you can see, I really have no need for thus
since I prefer Function.prototype.bind
(or .call
or .apply
) over thus
. In our Singleton
class, we don't even name it thus
because INSTANCE
conveys more information. For Model
, we return this
so that we can invoke the Constructor using .call
to return the instance we passed into it. Redundantly, we assigned it to the variable updated
, though it is useful in other scenarios.
Alongside, I prefer constructing object-literals using the new
keyword over {brackets}:
var klass = new (function Klass(Base) {
...
// export precepts
Base.apply(this); //
this.override = x;
...
})(Super);
Not Preferred
var klass = Super.apply({
override: x
});
As you can see, the latter has no ability to override its Superclass's "override" property.
If I do add methods to the Class's prototype
object, I prefer an object literal -- with or without using the new
keyword:
Klass.prototype = new Super();
// OR
Klass.prototype = new (function Base() {
...
// export precepts
Base.apply(this);
...
})(Super);
// OR
Klass.prototype = Super.apply({...});
// OR
Klass.prototype = {
method: function m() {...}
};
Not Preferred
Klass.prototype.method = function m() {...};
You have to reference System.Configuration
via explorer (not only append using System.Configuration
). Then you can write:
string xmlDataDirectory =
System.Configuration.ConfigurationManager.AppSettings.Get("xmlDataDirectory");
Tested with VS2010 (thanks to www.developpez.net). Hope this helps.
I noticed that the answers here are using: device-width
, device-height
, min-device-width
, min-device-height
, max-device-width
, max-device-height
.
Please refrain from using them since they are deprecated. see MDN for reference. Instead use the regular min-width
, max-width
and so on. For extra assurance, you can set the min and max to the same px amount.
For example:
iPhone X
@media only screen
and (width : 375px)
and (height : 635px)
and (orientation : portrait)
and (-webkit-device-pixel-ratio : 3) { }
You may also notice that I am using 635px for height. Try it yourself the window height is actually 635px. run iOS simulator for iPhone X and in Safari Web inspector do window.innerHeight
. Here are a few useful links on this subject:
When you create a new File
, you are supposed to provide the file name, not only the directory you want to put your file in.
Try with something like
File file = new File("D:/Data/" + item.getFileName());
You ultimately have to decide what the null bool will represent. If null
should be false
, you can do this:
bool newBool = x.HasValue ? x.Value : false;
Or:
bool newBool = x.HasValue && x.Value;
Or:
bool newBool = x ?? false;
Remove the \s
from your new regex and it should work - whitespace is already included in "anything but alphanumerics".
Note that you may want to add a +
after the ]
so you don't get sequences of more than one underscore. You can also chain onto .replace(/^_+|_+$/g,'')
to trim off underscores at the start or end of the string.
You need to specify which object you're calling getElementById from. In this case you can use document. You also can't just call .value on any element directly. For example if the element is textbox .value will return the value, but if it's a div it will not have a value.
You also have a wrong condition, you're checking
if (myEle == null)
which you should change to
if (myEle != null)
var myEle = document.getElementById("myElement");
if(myEle != null) {
var myEleValue= myEle.value;
}
Form controls are notoriously difficult to style cross-platform/browser. Some browsers will honor a CSS height
rule, some won't.
You can try line-height
(may need display:block;
or display:inline-block;
) or top
and bottom padding
also. If none of those work, that's pretty much it - use a graphic, position the input
in the center and set border:none;
so it looks like the form control is big but it actually isn't...
Ensure your encoding is correct for all of your files, this can sometimes happen if you have the encoding wrong for your file or the wrong encoding in your XML header.
So, if I have the following NewFile.xml:
<?xml version="1.0" encoding="UTF-16"?>
<bar foo="foiré" />
And the eclipse encoding is UTF-8:
The encoding of your file, the defined encoding in Eclipse (through Properties->Resource) and the declared encoding in the XML document all need to agree.
The validator is attempting to read the file, expecting <?xml ... but because the encoding is different from that expected, it's not finding it. Hence the error: Content is not allowed in prolog. The prolog is the bit before the <?xml declaration.
EDIT: Sorry, didn't realise that the .xml files were generated and actually contain javascript.
When you suspend the validators, the error messages that you've generated don't go away. To get them to go away, you have to manually delete them.
I think that because you've suspended the validators, Eclipse doesn't realise it has to delete the old error messages which came from the validators.
Considering this issue again: there is a very popular solution that is referenced within this thread that has its origin here:
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
I have stayed away from this solution because of the use of dirname - it can present cross-platform difficulties, particularly if a script needs to be locked down for security reasons. But as a pure Bash alternative, how about using:
DIR="$( cd "$( echo "${BASH_SOURCE[0]%/*}" )" && pwd )"
Would this be an option?
It's a kludge, but assuming there's a minimum length for SEARCHSTRING
, for example 2 characters, substring
the SEARCHSTRING
parameter at the second character and pass it as two parameters instead: SEARCHSTRING1 ("Nu")
and SEARCHSTRING2 ("ll").
Concatenate
them back together when executing the query to the database.
Since Symfony 3.1 you can use JSON Helper http://symfony.com/doc/current/book/controller.html#json-helper
public function indexAction()
{
// returns '{"username":"jane.doe"}' and sets the proper Content-Type header
return $this->json(array('username' => 'jane.doe'));
// the shortcut defines three optional arguments
// return $this->json($data, $status = 200, $headers = array(), $context = array());
}
Another method that may work for you (it's how I do it) is registering a class.
Assume you create a custom tableView like the following:
class UICustomTableViewCell: UITableViewCell {...}
You can then register this cell in whatever UITableViewController you will be displaying it in with "registerClass":
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(UICustomTableViewCell.self, forCellReuseIdentifier: "UICustomTableViewCellIdentifier")
}
And you can call it as you would expect in the cell for row method:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UICustomTableViewCellIdentifier", forIndexPath: indexPath) as! UICustomTableViewCell
return cell
}
mysql> CREATE TABLE tin3(id int PRIMARY KEY,val TINYINT(10) ZEROFILL);
Query OK, 0 rows affected (0.04 sec)
mysql> INSERT INTO tin3 VALUES(1,12),(2,7),(4,101);
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM tin3;
+----+------------+
| id | val |
+----+------------+
| 1 | 0000000012 |
| 2 | 0000000007 |
| 4 | 0000000101 |
+----+------------+
3 rows in set (0.00 sec)
mysql>
mysql> SELECT LENGTH(val) FROM tin3 WHERE id=2;
+-------------+
| LENGTH(val) |
+-------------+
| 10 |
+-------------+
1 row in set (0.01 sec)
mysql> SELECT val+1 FROM tin3 WHERE id=2;
+-------+
| val+1 |
+-------+
| 8 |
+-------+
1 row in set (0.00 sec)
The easiest way to do this is to click on the Terminate button(red square) in the console:
for me the clearest way is this:
doubleList.stream().reduce((a,b)->a+b).get();
or
doubleList.parallelStream().reduce((a,b)->a+b).get();
It also use internal loops, but it is not possible without loops.
Suppose you want to see the difference between commits 012345 and abcdef. The following should do what you want:
$ git checkout 012345 $ git cherry-pick -n abcdef $ git diff --cached
If using Zend Studio, same arrow, go to RSE view, click on the downward facing arrow, hit preferences, and then check show hidden files.
That did the trick for me.
This is simpler in my head than anywhere here, so:
401: You need HTTP basic auth to see this.
403: You can't see this, and HTTP basic auth won't help.
If the user just needs to log in using you site's standard HTML login form, 401 would not be appropriate because it is specific to HTTP basic auth.
I don't recommend using 403 to deny access to things like /includes
, because as far as the web is concerned, those resources don't exist at all and should therefore 404.
This leaves 403 as "you need to be logged in".
In other words, 403 means "this resource requires some form of auth other than HTTP basic auth".
https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2
With LINQ:
List<string> l = new List<string> { "1", "2", "3" ,"4","5"};
List<string> l2 = l.Skip(1).Take(2).ToList();
If you need foreach, then no need for ToList:
foreach (string s in l.Skip(1).Take(2)){}
Advantage of LINQ is that if you want to just skip some leading element,you can :
List<string> l2 = l.Skip(1).ToList();
foreach (string s in l.Skip(1)){}
i.e. no need to take care of count/length, etc.
Try this:
printf '\n%s\n' 'I want this on a new line!'
That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.
quantity=38; price=142.15; description='advanced widget'
$ printf '%8d%10.2f %s\n' "$quantity" "$price" "$description"
38 142.15 advanced widget
ViewResult is a subclass of ActionResult. The View method returns a ViewResult. So really these two code snippets do the exact same thing. The only difference is that with the ActionResult one, your controller isn't promising to return a view - you could change the method body to conditionally return a RedirectResult or something else without changing the method definition.
Also, please make sure you installed the correct version of apache on your computer. For example, not install a x86 on a 64bit system. Vice versa.
Using simply tr :
$ tr ':' $'\n' <<< string1:string2:string3:string4:string5
string1
string2
string3
string4
string5
If you really need sed :
$ sed 's/:/\n/g' <<< string1:string2:string3:string4:string5
string1
string2
string3
string4
string5
You need sp_addlinkedserver()
http://msdn.microsoft.com/en-us/library/ms190479.aspx
Example:
exec sp_addlinkedserver @server = 'test'
then
select * from [server].[database].[schema].[table]
In your example:
select * from [test].[testdb].[dbo].[table]
Try using white-space: nowrap;
in the container style (instead of overflow: hidden;
)
You can use the NotMapped
attribute data annotation to instruct Code-First to exclude a particular property
public class Customer
{
public int CustomerID { set; get; }
public string FirstName { set; get; }
public string LastName{ set; get; }
[NotMapped]
public int Age { set; get; }
}
[NotMapped]
attribute is included in the System.ComponentModel.DataAnnotations
namespace.
You can alternatively do this with Fluent API
overriding OnModelCreating
function in your DBContext
class:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Ignore(t => t.LastName);
base.OnModelCreating(modelBuilder);
}
http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx
The version I checked is EF 4.3
, which is the latest stable version available when you use NuGet.
Edit : SEP 2017
Data annotation
If you are using asp.net core (2.0 at the time of this writing), The [NotMapped]
attribute can be used on the property level.
public class Customer
{
public int Id { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
[NotMapped]
public int FullName { set; get; }
}
Fluent API
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
base.OnModelCreating(modelBuilder);
}
public DbSet<Customer> Customers { get; set; }
}
I would look into any number of online sitemap generation tools. Personally, I've used this one (java based)in the past, but if you do a google search for "sitemap builder" I'm sure you'll find lots of different options.
Using next
or readlines
etc, is not necessary. As the documentation says: "For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code".
Here's an example:
with open('/path/to/file') as myfile:
for line in myfile:
print(line)
This might be another option. The trick is in the wrapper
function that returns another function which is passed in to pool.map
. The code below reads an input array and for each (unique) element in it, returns how many times (ie counts) that element appears in the array, For example if the input is
np.eye(3) = [ [1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
then zero appears 6 times and one 3 times
import numpy as np
from multiprocessing.dummy import Pool as ThreadPool
from multiprocessing import cpu_count
def extract_counts(label_array):
labels = np.unique(label_array)
out = extract_counts_helper([label_array], labels)
return out
def extract_counts_helper(args, labels):
n = max(1, cpu_count() - 1)
pool = ThreadPool(n)
results = {}
pool.map(wrapper(args, results), labels)
pool.close()
pool.join()
return results
def wrapper(argsin, results):
def inner_fun(label):
label_array = argsin[0]
counts = get_label_counts(label_array, label)
results[label] = counts
return inner_fun
def get_label_counts(label_array, label):
return sum(label_array.flatten() == label)
if __name__ == "__main__":
img = np.ones([2,2])
out = extract_counts(img)
print('input array: \n', img)
print('label counts: ', out)
print("========")
img = np.eye(3)
out = extract_counts(img)
print('input array: \n', img)
print('label counts: ', out)
print("========")
img = np.random.randint(5, size=(3, 3))
out = extract_counts(img)
print('input array: \n', img)
print('label counts: ', out)
print("========")
You should get:
input array:
[[1. 1.]
[1. 1.]]
label counts: {1.0: 4}
========
input array:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
label counts: {0.0: 6, 1.0: 3}
========
input array:
[[4 4 0]
[2 4 3]
[2 3 1]]
label counts: {0: 1, 1: 1, 2: 2, 3: 2, 4: 3}
========
Use time.sleep
or Event().wait
like this:
from threading import Event
from time import sleep
delay_in_sec = 2
# Use time.sleep like this
sleep(delay_in_sec) # Returns None
print(f'slept for {delay_in_sec} seconds')
# Or use Event().wait like this
Event().wait(delay_in_sec) # Returns False
print(f'waited for {delay_in_sec} seconds')
Use threading.Timer
like this:
from threading import Timer
delay_in_sec = 2
def hello(delay_in_sec):
print(f'function called after {delay_in_sec} seconds')
t = Timer(delay_in_sec, hello, [delay_in_sec]) # Hello function will be called 2 seconds later with [delay_in_sec] as the *args parameter
t.start() # Returns None
print("Started")
Outputs:
Started
function called after 2 seconds
timer_obj.cancel()
.There is a trick you can use with templates to provide H file only constants.
(note, this is an ugly example, but works verbatim in at least in g++ 4.6.1.)
(values.hpp file)
#include <string>
template<int dummy>
class tValues
{
public:
static const char* myValue;
};
template <int dummy> const char* tValues<dummy>::myValue = "This is a value";
typedef tValues<0> Values;
std::string otherCompUnit(); // test from other compilation unit
(main.cpp)
#include <iostream>
#include "values.hpp"
int main()
{
std::cout << "from main: " << Values::myValue << std::endl;
std::cout << "from other: " << otherCompUnit() << std::endl;
}
(other.cpp)
#include "values.hpp"
std::string otherCompUnit () {
return std::string(Values::myValue);
}
Compile (e.g. g++ -o main main.cpp other.cpp && ./main) and see two compilation units referencing the same constant declared in a header:
from main: This is a value
from other: This is a value
In MSVC, you may instead be able to use __declspec(selectany)
For example:
__declspec(selectany) const char* data = "My data";
Julian's solution is tested working with some minor corrections. The following is an example that also used https://sourceforge.net/projects/bat-to-exe/ GenericConsole.cs and https://www.codeproject.com/Articles/19225/Bat-file-compiler program.txt for args part:
using System;
using System.Text; //StringBuilder
using System.Diagnostics;
using System.IO;
class Program
{
private static bool redirectStandardOutput = true;
private static string buildargument(string[] args)
{
StringBuilder arg = new StringBuilder();
for (int i = 0; i < args.Length; i++)
{
arg.Append("\"" + args[i] + "\" ");
}
return arg.ToString();
}
static void Main(string[] args)
{
Process prc = new Process();
prc.StartInfo = //new ProcessStartInfo("cmd.exe", String.Format("/c \"\"{0}\" {1}", Path.Combine(Environment.CurrentDirectory, "mapTargetIDToTargetNameA3.bat"), buildargument(args)));
//new ProcessStartInfo(Path.Combine(Environment.CurrentDirectory, "mapTargetIDToTargetNameA3.bat"), buildargument(args));
new ProcessStartInfo("mapTargetIDToTargetNameA3.bat");
prc.StartInfo.Arguments = buildargument(args);
prc.EnableRaisingEvents = true;
if (redirectStandardOutput == true)
{
prc.StartInfo.UseShellExecute = false;
}
else
{
prc.StartInfo.UseShellExecute = true;
}
prc.StartInfo.CreateNoWindow = true;
prc.OutputDataReceived += OnOutputDataRecived;
prc.ErrorDataReceived += OnErrorDataReceived;
//prc.Exited += OnExited;
prc.StartInfo.RedirectStandardOutput = redirectStandardOutput;
prc.StartInfo.RedirectStandardError = redirectStandardOutput;
try
{
prc.Start();
prc.BeginOutputReadLine();
prc.BeginErrorReadLine();
prc.WaitForExit();
}
catch (Exception e)
{
Console.WriteLine("OS error: " + e.Message);
}
prc.Close();
}
// Handle the dataevent
private static void OnOutputDataRecived(object sender, DataReceivedEventArgs e)
{
//do something with your data
Console.WriteLine(e.Data);
}
//Handle the error
private static void OnErrorDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
// Handle Exited event and display process information.
//private static void OnExited(object sender, System.EventArgs e)
//{
// var process = sender as Process;
// if (process != null)
// {
// Console.WriteLine("ExitCode: " + process.ExitCode);
// }
// else
// {
// Console.WriteLine("Process exited");
// }
//}
}
The code need to compile inside VS2007, using commandline csc.exe generated executable will not show console output correctly, or even crash with CLR20r3 error. Comment out the OnExited event process, the console output of the bat to exe will be more like the original bat console output.
From the git-branch manual page:
git branch --contains <commit>
Only list branches which contain the specified commit (HEAD if not specified). Implies
--list
.
git branch -r --contains <commit>
Lists remote tracking branches as well (as mentioned in user3941992's answer below) that is "local branches that have a direct relationship to a remote branch".
As noted by Carl Walsh, this applies only to the default refspec
fetch = +refs/heads/*:refs/remotes/origin/*
If you need to include other ref namespace (pull request, Gerrit, ...), you need to add that new refspec, and fetch again:
git config --add remote.origin.fetch "+refs/pull/*/head:refs/remotes/origin/pr/*"
git fetch
git branch -r --contains <commit>
See also this git ready article.
The
--contains
tag will figure out if a certain commit has been brought in yet into your branch. Perhaps you’ve got a commit SHA from a patch you thought you had applied, or you just want to check if commit for your favorite open source project that reduces memory usage by 75% is in yet.
$ git log -1 tests
commit d590f2ac0635ec0053c4a7377bd929943d475297
Author: Nick Quaranto <[email protected]>
Date: Wed Apr 1 20:38:59 2009 -0400
Green all around, finally.
$ git branch --contains d590f2
tests
* master
Note: if the commit is on a remote tracking branch, add the -a
option.
(as MichielB comments below)
git branch -a --contains <commit>
MatrixFrog comments that it only shows which branches contain that exact commit.
If you want to know which branches contain an "equivalent" commit (i.e. which branches have cherry-picked that commit) that's git cherry
:
Because
git cherry
compares the changeset rather than the commit id (sha1), you can usegit cherry
to find out if a commit you made locally has been applied<upstream>
under a different commit id.
For example, this will happen if you’re feeding patches<upstream>
via email rather than pushing or pulling commits directly.
__*__*__*__*__> <upstream>
/
fork-point
\__+__+__-__+__+__-__+__> <head>
(Here, the commits marked '-
' wouldn't show up with git cherry
, meaning they are already present in <upstream>
.)
Sometimes you can play with padding and margin top, add line-height, etc.
See fiddle.
Style and text forked from @aspirinemaga
.parent
{
width:300px;
line-height:30px;
border:1px solid red;
padding-top:20px;
}
way of getting home directory of current user is
String currentUsersHomeDir = System.getProperty("user.home");
and to append path separator
String otherFolder = currentUsersHomeDir + File.separator + "other";
The system-dependent default name-separator character, represented as a string for convenience. This string contains a single character, namely separatorChar.
How about a very simple method
+call your while loop in a function
- set your value inside (nonsense, but shows the example)
- return your value inside
+capture your value outside
+set outside
+display outside
#!/bin/bash
# set -e
# set -u
# No idea why you need this, not using here
foo=0
bar="hello"
if [[ "$bar" == "hello" ]]
then
foo=1
echo "Setting \$foo to $foo"
fi
echo "Variable \$foo after if statement: $foo"
lines="first line\nsecond line\nthird line"
function my_while_loop
{
echo -e $lines | while read line
do
if [[ "$line" == "second line" ]]
then
foo=2; return 2;
echo "Variable \$foo updated to $foo inside if inside while loop"
fi
echo -e $lines | while read line
do
if [[ "$line" == "second line" ]]
then
foo=2;
echo "Variable \$foo updated to $foo inside if inside while loop"
return 2;
fi
# Code below won't be executed since we returned from function in 'if' statement
# We aready reported the $foo var beint set to 2 anyway
echo "Value of \$foo in while loop body: $foo"
done
}
my_while_loop; foo="$?"
echo "Variable \$foo after while loop: $foo"
Output:
Setting $foo 1
Variable $foo after if statement: 1
Value of $foo in while loop body: 1
Variable $foo after while loop: 2
bash --version
GNU bash, version 3.2.51(1)-release (x86_64-apple-darwin13)
Copyright (C) 2007 Free Software Foundation, Inc.
select to_timestamp(cast(epoch_ms/1000 as bigint))::date
worked for me
You should always use audio/mpeg, because firefox cannot play audio/mpeg3 files
I hope it will help, it did the trick for me,
first, after connected my device to the computer I switch the paramater above to "camera device (PTP)";
then, I install PdaNet on my computer, finally all the usb driver were installed, and it works.
My smartphone is a samsung GS2, Android 4.4.2.
The commands are adduser
and addgroup
.
Here's a template for Docker you can use in busybox environments (alpine) as well as Debian-based environments (Ubuntu, etc.):
ENV USER=docker
ENV UID=12345
ENV GID=23456
RUN adduser \
--disabled-password \
--gecos "" \
--home "$(pwd)" \
--ingroup "$USER" \
--no-create-home \
--uid "$UID" \
"$USER"
Note the following:
--disabled-password
prevents prompt for a password--gecos ""
circumvents the prompt for "Full Name" etc. on Debian-based systems--home "$(pwd)"
sets the user's home to the WORKDIR. You may not want this.--no-create-home
prevents cruft getting copied into the directory from /etc/skel
The usage description for these applications is missing the long flags present in the code for adduser and addgroup.
The following long-form flags should work both in alpine as well as debian-derivatives:
BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.
Usage: adduser [OPTIONS] USER [GROUP]
Create new user, or add USER to GROUP
--home DIR Home directory
--gecos GECOS GECOS field
--shell SHELL Login shell
--ingroup GRP Group (by name)
--system Create a system user
--disabled-password Don't assign a password
--no-create-home Don't create home directory
--uid UID User id
One thing to note is that if --ingroup
isn't set then the GID is assigned to match the UID. If the GID corresponding to the provided UID already exists adduser will fail.
BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.
Usage: addgroup [-g GID] [-S] [USER] GROUP
Add a group or add a user to a group
--gid GID Group id
--system Create a system group
I discovered all of this while trying to write my own alternative to the fixuid project for running containers as the hosts UID/GID.
My entrypoint helper script can be found on GitHub.
The intent is to prepend that script as the first argument to ENTRYPOINT
which should cause Docker to infer UID and GID from a relevant bind mount.
An environment variable "TEMPLATE" may be required to determine where the permissions should be inferred from.
(At the time of writing I don't have documentation for my script. It's still on the todo list!!)
Your code works fine.
def list = [["c":"d"], ["e":"f"], ["g":"h"]]
Map tmpHM = [1:"second (e:f)", 0:"first (c:d)", 2:"third (g:h)"]
for (objKey in tmpHM.keySet()) {
HashMap objHM = (HashMap) list.get(objKey);
print("objHM: ${objHM} , ")
}
prints objHM: [e:f] , objHM: [c:d] , objHM: [g:h] ,
See https://groovyconsole.appspot.com/script/5135817529884672
Then click "edit in console", "execute script"
In Java 8 you can use the Stream interface:
return dvdList.stream().anyMatch(d -> d.getTitle().equalsIgnoreCase("SomeTitle"));
You can also delete cookies without using jquery.cookie plugin:
document.cookie = 'NAMEOFYOURCOOKIE' + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
Put the APK file into the tools folder in the Android SDK and give the path to tools in the command prompt and use the command:
adb install "name".apk file
Debug Diagnostics Tool (DebugDiag) can be a lifesaver. It creates and analyze IIS crash dumps. I figured out my crash in minutes once I saw the call stack. https://support.microsoft.com/en-us/kb/919789
If you want a robust library, Text_Diff (a PEAR package) looks to be pretty good. It has some pretty cool features.
For the new PHP programmer might confuse why there are lot of method for to get current date and time and which one to use in their project.
1. date
method (PHP 4, PHP 5, PHP 7)
This is the very common and very easiest way to get the date and time in php.
// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');
// Prints something like: Monday
echo date("l");
// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));
/* use the constants in the format parameter */
// prints something like: Wed, 25 Sep 2013 15:28:57 -0700
echo date(DATE_RFC2822);
// prints something like: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
You can learn more about it in here
2. DateTime
class (PHP 5 >= 5.2.0, PHP 7)
when you want to use PHP with OOP, this is the best way to get date and time.
<?php
// Specified date/time in your computer's time zone.
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:sP') . "\n";
// Specified date/time in the specified time zone.
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
// Current date/time in your computer's time zone.
$date = new DateTime();
echo $date->format('Y-m-d H:i:sP') . "\n";
// Current date/time in the specified time zone.
$date = new DateTime(null, new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
// Using a UNIX timestamp. Notice the result is in the UTC time zone.
$date = new DateTime('@946684800');
echo $date->format('Y-m-d H:i:sP') . "\n";
// Non-existent values roll over.
$date = new DateTime('2000-02-30');
echo $date->format('Y-m-d H:i:sP') . "\n";
?>
You can learn more about it in here
3. Carbon Date time package
if you are using Composer, Laravel, Symfony or any kinda framework this is the best way to get the date and time. Also this package extends DateTime class in php so you use all the method in Datetime class. This in-built in frameworks like laravel so you don't have to install it separately.
printf("Right now is %s", Carbon::now()->toDateTimeString());
printf("Right now in Vancouver is %s", Carbon::now('America/Vancouver')); // automatically converted to string
$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();
// Carbon embed 823 languages:
echo $tomorrow->locale('fr')->isoFormat('dddd, MMMM Do YYYY, h:mm');
echo $tomorrow->locale('ar')->isoFormat('dddd, MMMM Do YYYY, h:mm');
$officialDate = Carbon::now()->toRfc2822String();
$howOldAmI = Carbon::createFromDate(1975, 5, 21)->age;
$noonTodayLondonTime = Carbon::createFromTime(12, 0, 0, 'Europe/London');
$internetWillBlowUpOn = Carbon::create(2038, 01, 19, 3, 14, 7, 'GMT');
if (Carbon::now()->isWeekend()) {
echo 'Party!';
}
echo Carbon::now()->subMinutes(2)->diffForHumans(); // '2 minutes ago'
You can learn more about it in here
Hope this helps and if you know any other way to get the date and time feel free to edit the answer.
Match the .env file and the config.php file with your username and password and your hostname in the database settings.if they are not equal,relation will not connect.
functools.cache
is released in Python 3.9 (docs):
from functools import cache
@cache
def factorial(n):
return n * factorial(n-1) if n else 1
In previous versions, one of the early answers is still a valid solution using lru_cache
as an ordinary cache without limit and lru feature. (docs)
If maxsize is set to None, the LRU feature is disabled and the cache can grow without bound.
Here is a prettier version of it:
cache = lru_cache(maxsize=None)
@cache
def func(param1):
pass
This solution sort by Col1 and group by Col2. Then extract value of Col2 and display it in a mbox.
var grouped = from DataRow dr in dt.Rows orderby dr["Col1"] group dr by dr["Col2"];
string x = "";
foreach (var k in grouped) x += (string)(k.ElementAt(0)["Col2"]) + Environment.NewLine;
MessageBox.Show(x);
Perhaps you don't have to include the single quotes:
curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/&fileName=1.doc"
Update: Reading curl's manual, you could actually separate both fields with two --data:
curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/" --data "fileName=1.doc"
You could also try --data-binary:
curl --request POST 'http://localhost/Service' --data-binary "path=/xyz/pqr/test/" --data-binary "fileName=1.doc"
And --data-urlencode:
curl --request POST 'http://localhost/Service' --data-urlencode "path=/xyz/pqr/test/" --data-urlencode "fileName=1.doc"
The solutions so far are all quite complicated. The idiomatic solution should doubtless be:
String.Join(",", x.Cast(Of String)().ToArray())
There's no need for fancy acrobatics in new framework versions. Supposing a not-so-modern version, the following would be easiest:
Console.WriteLine(String.Join(",", CType(x.ToArray(GetType(String)), String())))
mspmsp's second solution is a nice approach as well but it's not working because it misses the AddressOf
keyword. Also, Convert.ToString
is rather inefficient (lots of unnecessary internal evaluations) and the Convert
class is generally not very cleanly designed. I tend to avoid it, especially since it's completely redundant.
We can concat Like this :
<h5 th:text ="${currentItem.first_name}+ ' ' + ${currentItem.last_name}"></h5>
@OMG Ponies - One of my reasons of not using the following code
SELECT t.col1 as a,
CASE WHEN t.col1 = 'test' THEN 'yes' END as value
FROM TABLE t;
can be that the t.col1 is not an actual column in the table. For example, it can be a value from a XML column like
Select XMLColumnName.value('(XMLPathOfTag)[1]', 'varchar(max)')
as XMLTagAlias from Table
I solved the issue by Changing the port no. in adrs-instances.xml file:
\JDEV_USER_HOME\system11.1.1.3.37.56.60\o.j2ee\adrs-instances.xml
NOTE: Solution below does not work on Windows. On linux exec a "which ping" command from the console, and set command path (of the suggested exec call) accordingly
I think you want to check the exit status of the command, whereas shell_exec gives you full output (might be dangerous shall command output change from command version to version. for some reason). Moreover your variable $ip is not interpreted within single quotes. You'd have to use double ones "". That might be the only thing you need to fix in order to make it work.
But I think following code can be more "portable". IMHO it is in fact better to catch the exit status, rather than trying to parse result string. IMHO it's also better to specify full path to ping command.
<?php
function pingAddress($ip) {
$pingresult = exec("/bin/ping -n 3 $ip", $outcome, $status);
if (0 == $status) {
$status = "alive";
} else {
$status = "dead";
}
echo "The IP address, $ip, is ".$status;
}
pingAddress("127.0.0.1");
SELECT DATEDIFF (MyUnits, '2010-01-22 15:29:55.090', '2010-01-22 15:30:09.153')
Substitute "MyUnits" based on DATEDIFF on MSDN
Use your console:
console.log(object);
Or if you are inspecting html dom elements use console.dir(object). Example:
let element = document.getElementById('alertBoxContainer');
console.dir(element);
Or if you have an array of js objects you could use:
console.table(objectArr);
If you are outputting a lot of console.log(objects) you can also write
console.log({ objectName1 });
console.log({ objectName2 });
This will help you label the objects written to console.
run compaudit
and it will give you a list of directories it thinks are insecure
sudo chown -R username:root target_directory
sudo chmod -R 755 target_directory
Swift 3 & Xcode 8.3.2
This code will help you, i add an explanation too
// Create custom class, this will make your life easier
class CustomDelay {
static let cd = CustomDelay()
// This is your custom delay function
func runAfterDelay(_ delay:Double, closure:@escaping ()->()) {
let when = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}
}
// here how to use it (Example 1)
class YourViewController: UIViewController {
// example delay time 2 second
let delayTime = 2.0
override func viewDidLoad() {
super.viewDidLoad()
CustomDelay.cd.runAfterDelay(delayTime) {
// This func will run after 2 second
// Update your UI here, u don't need to worry to bring this to the main thread because your CustomDelay already make this to main thread automatically :)
self.runFunc()
}
}
// example function 1
func runFunc() {
// do your method 1 here
}
}
// here how to use it (Example 2)
class YourSecondViewController: UIViewController {
// let say you want to user run function shoot after 3 second they tap a button
// Create a button (This is programatically, you can create with storyboard too)
let shootButton: UIButton = {
let button = UIButton(type: .system)
button.frame = CGRect(x: 15, y: 15, width: 40, height: 40) // Customize where do you want to put your button inside your ui
button.setTitle("Shoot", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
// create an action selector when user tap shoot button
shootButton.addTarget(self, action: #selector(shoot), for: .touchUpInside)
}
// example shoot function
func shoot() {
// example delay time 3 second then shoot
let delayTime = 3.0
// delay a shoot after 3 second
CustomDelay.cd.runAfterDelay(delayTime) {
// your shoot method here
// Update your UI here, u don't need to worry to bring this to the main thread because your CustomDelay already make this to main thread automatically :)
}
}
}
The Algorithm for given flow chart :
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Step :01
Step :02 [Variable initialization]
Step :03[Condition Check]
Step:04
If you look at the Object class (Parent class of all classes in Java) the toString() method implementation is
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
whenever you print any object in Java then toString() will be call. Now it's up to you if you override toString() then your method will call other Object class method call.
I am doing something similar but in C++. What you need to do is read the lines in one at a time and parse them (go over the words one by one). I have an outter loop that goes over all the lines and inside that is another loop that goes over all the words. Once the word you need is found, just exit the loop and return a counter or whatever you want.
This is my code. It basically parses out all the words and adds them to the "index". The line that word was in is then added to a vector and used to reference the line (contains the name of the file, the entire line and the line number) from the indexed words.
ifstream txtFile;
txtFile.open(path, ifstream::in);
char line[200];
//if path is valid AND is not already in the list then add it
if(txtFile.is_open() && (find(textFilePaths.begin(), textFilePaths.end(), path) == textFilePaths.end())) //the path is valid
{
//Add the path to the list of file paths
textFilePaths.push_back(path);
int lineNumber = 1;
while(!txtFile.eof())
{
txtFile.getline(line, 200);
Line * ln = new Line(line, path, lineNumber);
lineNumber++;
myList.push_back(ln);
vector<string> words = lineParser(ln);
for(unsigned int i = 0; i < words.size(); i++)
{
index->addWord(words[i], ln);
}
}
result = true;
}
This should help you.
* {
margin: 0;
}
html, body {
height: 100%;
}
.wrapper {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto -155px; /* the bottom margin is the negative value of the footer's height */
}
.footer {
height: 155px;
}
You can use the TypeDescriptor class to do this:
foreach(PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
{
string name=descriptor.Name;
object value=descriptor.GetValue(obj);
Console.WriteLine("{0}={1}",name,value);
}
TypeDescriptor lives in the System.ComponentModel namespace and is the API that Visual Studio uses to display your object in its property browser. It's ultimately based on reflection (as any solution would be), but it provides a pretty good level of abstraction from the reflection API.
Also you can pipe the answers to the script:
printf "y\npassword\n" | sh test.sh
where \n
is escape-sequence
You can do this replacing position:absolute;
by position:fixed;
.
You can use the below code in the parent page.
<script>
window.onunload = refreshParent;
function refreshParent() {
window.opener.location.reload();
}
</script>
You can find more info about what limitations browsers will likely add to mitigate this and what IETF is doing about it as well as why this is needed at IETF SPEC on IP handling
I recommend use /(?=.*...)/g
Example
const text1 = 'I am using regex';
/(?=.*regex)/g.test(text1) // true
const text2 = 'regex is awesome';
/(?=.*regex)/g.test(text2) // true
const text3 = 'regex is util';
/(?=.*util)(?=.*regex)/g.test(text3) // true
const text4 = 'util is necessary';
/(?=.*util)(?=.*regex)/g.test(text4) // false because need regex in text
Use regex101 to test
There's another, more accessible solution: Don't put the action on your buttons. There's a lot of functionality built into forms already. Instead of handling button presses, handle form submissions and resets. Simply add onSubmit={handleSubmit}
and onReset={handleReset}
to your form
elements.
To stop the actual submission just include event
in your function and an event.preventDefault();
to stop the default submission behavior. Now your form behaves correctly from an accessibility standpoint and you're handling any form of submission the user might take.
There are already a bunch of great answers here that use Newtonsoft.JSON, but here's one more that uses JObject.Parse
in combination with ToString()
, since that hasn't been mentioned yet:
var jObj = Newtonsoft.Json.Linq.JObject.Parse(json);
var formatted = jObj.ToString(Newtonsoft.Json.Formatting.Indented);
Using dateadd to remove a week from the current date.
datex BETWEEN DATEADD(WEEK,-1,GETDATE()) AND GETDATE()
Did you try to configure the "Media Mode" in "Camera (PTP)" instead of "Media device (MTP)"? This is sometimes solving the issue. Its in the USB Computer Connection options of your Android device, you should see an "authorize" dialog then.
Update 04/2017: looks like it has been fixed in Android 7.1.2
Not a big deal, but most regex engines support the POSIX character classes, and there's [:xdigit:]
for matching hex characters, which is simpler than the common 0-9a-fA-F
stuff.
So, the regex as requested (ie. with optional 0x
) is: /(0x)?[[:xdigit:]]+/
Procedure successful but any outpout
Error line1: Unexpected identifier
Here is the code:
SET SERVEROUTPUT ON
DECLARE
-- Curseurs
CURSOR c1 IS
SELECT RWID FROM J_EVT
WHERE DT_SYST < TO_DATE(TO_CHAR(SYSDATE,'DD/MM') || '/' || TO_CHAR(TO_NUMBER(TO_CHAR(SYSDATE, 'YYYY')) - 3));
-- Collections
TYPE tc1 IS TABLE OF c1%RWTYPE;
-- Variables de type record
rtc1 tc1;
vCpt NUMBER:=0;
BEGIN
OPEN c1;
LOOP
FETCH c1 BULK COLLECT INTO rtc1 LIMIT 5000;
FORALL i IN 1..rtc1.COUNT
DELETE FROM J_EVT
WHERE RWID = rtc1(i).RWID;
COMMIT;
-- Nombres lus : 5025651
FOR i IN 1..rtc1.COUNT LOOP
vCpt := vCpt + SQL%BULK_RWCOUNT(i);
END LOOP;
EXIT WHEN c1%NOTFOUND;
END LOOP;
CLOSE c1;
COMMIT;
DBMS_OUTPUT.PUT_LINE ('Nombres supprimes : ' || TO_CHAR(vCpt));
END;
/
exit
For variable argument functions like printf
and scanf
, the arguments are promoted, for example, any smaller integer types are promoted to int
, float
is promoted to double
.
scanf
takes parameters of pointers, so the promotion rule takes no effect. It must use %f
for float*
and %lf
for double*
.
printf
will never see a float
argument, float
is always promoted to double
. The format specifier is %f
. But C99 also says %lf
is the same as %f
in printf
:
C99 §7.19.6.1 The
fprintf
function
l
(ell) Specifies that a followingd
,i
,o
,u
,x
, orX
conversion specifier applies to along int
orunsigned long int
argument; that a followingn
conversion specifier applies to a pointer to along int
argument; that a followingc
conversion specifier applies to awint_t
argument; that a followings
conversion specifier applies to a pointer to awchar_t
argument; or has no effect on a followinga
,A
,e
,E
,f
,F
,g
, orG
conversion specifier.
More cross-platform implementation will be:
import pathlib
two_up = (pathlib.Path(__file__) / ".." / "..").resolve()
Using parent
is not supported on Windows. Also need to add .resolve()
, to:
Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows)
To find all socket files on your system run:
sudo find / -type s
My Mysql server system had the socket open at /var/lib/mysql/mysql.sock
Once you find where the socket is being opened, add or edit the line to your /etc/my.cnf file with the path to the socket file:
socket=/var/lib/mysql/mysql.sock
Sometimes the system startup script that launched the command line executable specifies a flag --socket=path
. This flag could override the my.cnf location, and that would result in a socket not being found where the my.cnf file indicates it should be. Then when you try to run the mysql command line client, it will read my.cnf to find the socket, but it will not find it since it deviates from where the server created one. So, Unless you care where the socket resides, just changing the my.cnf to match should work.
Then, stop the mysqld process. How you do this will vary by system.
If you're super user in the linux system, try one of the following if you don't know the specific method your Mysql setup uses:
service mysqld stop
/etc/init.d/mysqld stop
mysqladmin -u root -p shutdown
pkill -9 mysqld
pgrep mysql
or ps aux | grep mysql | grep -v grep
4969
terminate with kill -9 4969
After you do this you might want to look for a pid file in /var/run/mysqld/
and delete it
Make sure the permissions on your socket is such that whatever user mysqld is running as can read/write to it. An easy test is to open it up to full read/write and see if it still works:
chmod 777 /var/run/mysqld/mysqld.sock
If that fixes the issue, you can tailor the permissions and ownership of the socket as needed based on your security settings.
Also, the directory the socket resides in has to be reachable by the user running the mysqld process.
Use a Java 8 Stream
.
myString.chars().mapToObj(i -> (char) i).collect(Collectors.toList());
Breakdown:
myString
.chars() // Convert to an IntStream
.mapToObj(i -> (char) i) // Convert int to char, which gets boxed to Character
.collect(Collectors.toList()); // Collect in a List<Character>
(I have absolutely no idea why String#chars()
returns an IntStream
.)
You may also need to make database containing table active
use [dbname]
otherwise you may get error (even if you specify database i.e. dbname.table )
FAILED Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. Unable to alter partition. Unable to alter partitions because table or database does not exist.
DIR="/some/dir"
if [ "$(ls -A $DIR)" ]; then
echo 'There is something alive in here'
fi
Right-click on an aspx file and choose 'browse with'. I think there's an option there to set as default.
You could use this function:
function RefreshTable(tableId, urlData)
{
//Retrieve the new data with $.getJSON. You could use it ajax too
$.getJSON(urlData, null, function( json )
{
table = $(tableId).dataTable();
oSettings = table.fnSettings();
table.fnClearTable(this);
for (var i=0; i<json.aaData.length; i++)
{
table.oApi._fnAddData(oSettings, json.aaData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
table.fnDraw();
});
}
Dont' forget to call it after your delete function has succeded.
With Visual Studio 2019 I had a similar issue when I wanted to run tests (MSTest directly from VS). In my case I only had an x64 native DLL and I received this error message. First, I thought it is because Visual Studio runs as x86 but this page helped me to solve the issue:
Run unit test as a 64-bit process
It says
I did both (I explicitly set x64) and then my tests started to work.