Declare the parameter in test.ps1:
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$input_dir,
[Parameter(Mandatory=$True)]
[string]$output_dir,
[switch]$force = $false
)
Run the script from Run OR Windows Task Scheduler:
powershell.exe -command "& C:\FTP_DATA\test.ps1 -input_dir C:\FTP_DATA\IN -output_dir C:\FTP_DATA\OUT"
or,
powershell.exe -command "& 'C:\FTP DATA\test.ps1' -input_dir 'C:\FTP DATA\IN' -output_dir 'C:\FTP DATA\OUT'"
The almighty switch
works well here:
'one
two
three' > file
$regex = '^t'
switch -regex -file file {
$regex { "line is $_" }
}
Output:
line is two
line is three
From your situation it sounds like you need to create a "Revision#" folder once a day with a "Reports" folder in there. If that's the case, you just need to know what the next revision number is. Write a function that gets the next revision number, Get-NextRevisionNumber. Or you could do something like this:
foreach($Project in (Get-ChildItem "D:\TopDirec" -Directory)){
# Select all the Revision folders from the project folder.
$Revisions = Get-ChildItem "$($Project.Fullname)\Revision*" -Directory
# The next revision number is just going to be one more than the highest number.
# You need to cast the string in the first pipeline to an int so Sort-Object works.
# If you sort it descending the first number will be the biggest so you select that one.
# Once you have the highest revision number you just add one to it.
$NextRevision = ($Revisions.Name | Foreach-Object {[int]$_.Replace('Revision','')} | Sort-Object -Descending | Select-Object -First 1)+1
# Now in this we kill two birds with one stone.
# It will create the "Reports" folder but it also creates "Revision#" folder too.
New-Item -Path "$($Project.Fullname)\Revision$NextRevision\Reports" -Type Directory
# Move on to the next project folder.
# This untested example loop requires PowerShell version 3.0.
}
To remove newlines, use tr:
tr -d '\n'
If you want to replace each newline with a single space:
tr '\n' ' '
The error ba: Event not found
is coming from csh, and is due to csh trying to match !ba
in your history list. You can escape the !
and write the command:
sed ':a;N;$\!ba;s/\n/ /g' # Suitable for csh only!!
but sed is the wrong tool for this, and you would be better off using a shell that handles quoted strings more reasonably. That is, stop using csh and start using bash.
from here
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["BloggingDatabase"].ConnectionString);
}
note you may need to add Microsoft.EntityFrameworkCore.SqlServer
You can do this with a Correlated Subquery (That is a subquery wherein you reference a field in the main query). In this case:
SELECT *
FROM yourtable t1
WHERE date = (SELECT max(date) from yourtable WHERE id = t1.id)
Here we give the yourtable
table an alias of t1
and then use that alias in the subquery grabbing the max(date)
from the same table yourtable
for that id
.
Looks like your file contains ASCII characters, which are encoded in just 1 byte. If text file was containing non-ASCII character, e.g. 2-byte UTF-8, then you get just the first byte, not whole character.
In this case, to validate Date (DD-MM-YYYY) or (DD/MM/YYYY), with a year between 1900 and 2099,like this with month and Days validation
if (!Regex.Match(txtDob.Text, @"^(0[1-9]|1[0-9]|2[0-9]|3[0,1])([/+-])(0[1-9]|1[0-2])([/+-])(19|20)[0-9]{2}$").Success)
{
MessageBox.Show("InValid Date of Birth");
txtDob.Focus();
}
How about;
function keyValue(key, value){
this.Key = key;
this.Value = value;
};
keyValue.prototype.updateTo = function(newKey, newValue) {
this.Key = newKey;
this.Value = newValue;
};
array[1].updateTo("xxx", "999");
In fact return (i++)
will only return 10.
The ++ and -- operators can be placed before or after the variable, with different effects. If they are before, then they will be processed and returned and essentially treated just like (i-1) or (i+1), but if you place the ++ or -- after the i, then the return is essentailly
return i;
i + 1;
So it will return 10 and never increment it.
Use a for
loop and set each one in turn.
You can simply give it as:
System.out.println("Address:" +houseAddress);
Your output will look like [address1, address2, address3]
This is because the class ArrayList or its superclass would have a toString() function overridden.
Hope this helps.
Target build x64 Target Server Hosting IIS 64 Bit
If the application build is targeting 64-Bit OS then on the 64-Bit server hosting the IIS,Set the enable 32 bit application on the app pool running the website/web application to false.
You need to give your submit <input>
a name or it won't be available using $_POST['submit']
:
<p><input type="submit" value="Submit" name="submit" /></p>
There is simple answer in the official guide:
What does it not do?
It does not cause a full page reload when the browser URL is changed. To reload the page after changing the URL, use the lower-level API, $window.location.href.
You make a bog standard HTTP GET Request. You get a bog standard HTTP Response with an application/json content type and a JSON document as the body. You then parse this.
Since you have tagged this 'JavaScript' (I assume you mean "from a web page in a browser"), and I assume this is a third party service, you're stuck. You can't fetch data from remote URI in JavaScript unless explicit workarounds (such as JSONP) are put in place.
Oh wait, reading the documentation you linked to - JSONP is available, but you must say 'js' not 'json' and specify a callback: format=js&callback=foo
Then you can just define the callback function:
function foo(myData) {
// do stuff with myData
}
And then load the data:
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = theUrlForTheApi;
document.body.appendChild(script);
In addition to inconsistent and numbers, a missing item inside datatable scripts columns part can cause this too. Correcting that fixed my datatables search bar.
I'm talking about this part;
"columns": [
null,
.
.
.
null
],
I struggled with this error till I was pointed that this part had one less "null" than my total thead count.
Use the built-in function round()
:
In [23]: round(66.66666666666,4)
Out[23]: 66.6667
In [24]: round(1.29578293,6)
Out[24]: 1.295783
help on round()
:
round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0 digits). This always returns a floating point number. Precision may be negative.
I had a similar issue where visual studio keeps loading symbol and got stuck.
It turns out I added some "Command line arguments" in the Debug options, and one of the parameters is invalid(I am supposed to pass in some values).
After I remove the extra parameter, it starts working again.
Try this:
From this question.
After spending hours looking for the solution to this problem, I finally struck gold by making the changes mentioned on an Eclipse Forum.
Steps:
Prerequisites: mysysgit is installed with default configuration.
1.Create the file C:/Users/Username/.ssh/config (Replace "Username" with your Windows 7 user name. (e.g. C:/Users/John/.ssh/config)) and put this in it:
Host github.com
HostName github.com
User git
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa
2.Try setting up the remote repository now in Eclipse.
Cheers. It should work perfectly.
I had a same problem and I fix it with the following steps:
How about:
function changeText() {
$("#demoTable td").each(function () {
$(this).html().replace("8: Tap on APN and Enter <B>www</B>", "");
}
}
Set up a simple repository using a web server with its default configuration. The key is the directory structure. The documentation does not mention it explicitly, but it is the same structure as a local repository.
To set up an internal repository just requires that you have a place to put it, and then start copying required artifacts there using the same layout as in a remote repository such as repo.maven.apache.org. Source
Add a file to your repository like this:
mvn install:install-file \
-Dfile=YOUR_JAR.jar -DgroupId=YOUR_GROUP_ID
-DartifactId=YOUR_ARTIFACT_ID -Dversion=YOUR_VERSION \
-Dpackaging=jar \
-DlocalRepositoryPath=/var/www/html/mavenRepository
If your domain is example.com
and the root directory of the web server is located at /var/www/html/
, then maven can find "YOUR_JAR.jar" if configured with <url>http://example.com/mavenRepository</url>
.
Use localStorage for that. It's persistent over sessions.
Writing :
localStorage['myKey'] = 'somestring'; // only strings
Reading :
var myVar = localStorage['myKey'] || 'defaultValue';
If you need to store complex structures, you might serialize them in JSON. For example :
Reading :
var stored = localStorage['myKey'];
if (stored) myVar = JSON.parse(stored);
else myVar = {a:'test', b: [1, 2, 3]};
Writing :
localStorage['myKey'] = JSON.stringify(myVar);
Note that you may use more than one key. They'll all be retrieved by all pages on the same domain.
Unless you want to be compatible with IE7, you have no reason to use the obsolete and small cookies.
Install Java 7u21 from: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u21-oth-JPR
Set these variables:
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH
Run your app and have fun :)
The short answer is "yes". A sample ldapsearch
command to query an Active Directory server is:
ldapsearch \
-x -h ldapserver.mydomain.com \
-D "[email protected]" \
-W \
-b "cn=users,dc=mydomain,dc=com" \
-s sub "(cn=*)" cn mail sn
This would connect to an AD server at hostname ldapserver.mydomain.com
as user [email protected]
, prompt for the password on the command line and show name and email details for users in the cn=users,dc=mydomain,dc=com
subtree.
See Managing LDAP from the Command Line on Linux for more samples. See LDAP Query Basics for Microsoft Exchange documentation for samples using LDAP queries with Active Directory.
I got this error after deleting Xcode. I fixed it by resetting the command line tools path with sudo xcode-select -r
.
Before:
navin@Radiant ~$ /usr/bin/clang
xcrun: error: active developer path ("/Applications/Xcode.app/Contents/Developer") does not exist
Use `sudo xcode-select --switch path/to/Xcode.app` to specify the Xcode that you wish to use for command line developer tools, or use `xcode-select --install` to install the standalone command line developer tools.
See `man xcode-select` for more details.
navin@Radiant ~$ xcode-select --install
xcode-select: error: command line tools are already installed, use "Software Update" to install updates
After:
navin@Radiant ~$ /usr/bin/clang
clang: error: no input files
If you're writing C++, I can't recommend using the Boost libraries strongly enough.
The latest version (1.55) includes a new Predef library which covers exactly what you're looking for, along with dozens of other platform and architecture recognition macros.
#include <boost/predef.h>
// ...
#if BOOST_OS_WINDOWS
#elif BOOST_OS_LINUX
#elif BOOST_OS_MACOS
#endif
1.
if(1 == @$manta_option['iso_format_recent_works']){
$theme_img = 'recent_works_thumbnail';
} else {
$theme_img = 'recent_works_iso_thumbnail';
}
2.
if(isset($manta_option['iso_format_recent_works']) && 1 == $manta_option['iso_format_recent_works']){
$theme_img = 'recent_works_thumbnail';
} else {
$theme_img = 'recent_works_iso_thumbnail';
}
3.
if (!empty($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
}
else{
}
$pdf->Output( "myfile.pdf", "F");
TCPDF ERROR: Unable to create output file: myfile.pdf
In the include/tcpdf_static.php
file about 2435 line in the static function fopenLocal
if I delete the complete 'if statement' it works fine.
public static function fopenLocal($filename, $mode) {
/*if (strpos($filename, '://') === false) {
$filename = 'file://'.$filename;
} elseif (strpos($filename, 'file://') !== 0) {
return false;
}*/
return fopen($filename, $mode);
}
To pass info to a fragment , you setArguments when you create it, and you can retrieve this argument later on the method onCreate or onCreateView of your fragment.
On the newInstance function of your fragment you add the arguments you wanna send to it:
/**
* Create a new instance of DetailsFragment, initialized to
* show the text at 'index'.
*/
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
Then inside the fragment on the method onCreate
or onCreateView
you can retrieve the arguments like this:
Bundle args = getArguments();
int index = args.getInt("index", 0);
If you want now communicate from your fragment with your activity (sending or not data), you need to use interfaces. The way you can do this is explained really good in the documentation tutorial of communication between fragments. Because all fragments communicate between each other through the activity, in this tutorial you can see how you can send data from the actual fragment to his activity container to use this data on the activity or send it to another fragment that your activity contains.
Documentation tutorial:
http://developer.android.com/training/basics/fragments/communicating.html
This script below should put you on the right track perhaps?
You can keep this html the same (though I changed the method to POST):
<form method="POST" id="subscribeForm">
<fieldset id="cbgroup">
<div><input name="list" id="list0" type="checkbox" value="newsletter0" >zero</div>
<div><input name="list" id="list1" type="checkbox" value="newsletter1" >one</div>
<div><input name="list" id="list2" type="checkbox" value="newsletter2" >two</div>
</fieldset>
<input name="submit" type="submit" value="submit">
</form>
and this javascript validates
function onSubmit()
{
var fields = $("input[name='list']").serializeArray();
if (fields.length === 0)
{
alert('nothing selected');
// cancel submit
return false;
}
else
{
alert(fields.length + " items selected");
}
}
// register event on form, not submit button
$('#subscribeForm').submit(onSubmit)
and you can find a working example of it here
UPDATE (Oct 2012)
Additionally it should be noted that the checkboxes must have a "name" property, or else they will not be added to the array. Only having "id" will not work.
UPDATE (May 2013)
Moved the submit registration to javascript and registered the submit onto the form (as it should have been originally)
UPDATE (June 2016)
Changes == to ===
I know it's an old thread, but I landed here several times via Google and think no given answer is really satisfying yet. Try using one of the following functions:
EDIT: As I'm getting some likes on this old thread, I wanna share an updated solution as well (basically putting my two previous functions together and automatically deciding whether it's a bar or hbar plot):
def label_bars(ax, bars, text_format, **kwargs):
"""
Attaches a label on every bar of a regular or horizontal bar chart
"""
ys = [bar.get_y() for bar in bars]
y_is_constant = all(y == ys[0] for y in ys) # -> regular bar chart, since all all bars start on the same y level (0)
if y_is_constant:
_label_bar(ax, bars, text_format, **kwargs)
else:
_label_barh(ax, bars, text_format, **kwargs)
def _label_bar(ax, bars, text_format, **kwargs):
"""
Attach a text label to each bar displaying its y value
"""
max_y_value = ax.get_ylim()[1]
inside_distance = max_y_value * 0.05
outside_distance = max_y_value * 0.01
for bar in bars:
text = text_format.format(bar.get_height())
text_x = bar.get_x() + bar.get_width() / 2
is_inside = bar.get_height() >= max_y_value * 0.15
if is_inside:
color = "white"
text_y = bar.get_height() - inside_distance
else:
color = "black"
text_y = bar.get_height() + outside_distance
ax.text(text_x, text_y, text, ha='center', va='bottom', color=color, **kwargs)
def _label_barh(ax, bars, text_format, **kwargs):
"""
Attach a text label to each bar displaying its y value
Note: label always outside. otherwise it's too hard to control as numbers can be very long
"""
max_x_value = ax.get_xlim()[1]
distance = max_x_value * 0.0025
for bar in bars:
text = text_format.format(bar.get_width())
text_x = bar.get_width() + distance
text_y = bar.get_y() + bar.get_height() / 2
ax.text(text_x, text_y, text, va='center', **kwargs)
Now you can use them for regular bar plots:
fig, ax = plt.subplots((5, 5))
bars = ax.bar(x_pos, values, width=0.5, align="center")
value_format = "{:.1%}" # displaying values as percentage with one fractional digit
label_bars(ax, bars, value_format)
or for horizontal bar plots:
fig, ax = plt.subplots((5, 5))
horizontal_bars = ax.barh(y_pos, values, width=0.5, align="center")
value_format = "{:.1%}" # displaying values as percentage with one fractional digit
label_bars(ax, horizontal_bars, value_format)
In the case of stored procedure update, you should delete it from the .dbml file and reinsert it again. But if the stored procedure have two paths (ex: if something; display some columns; else display some other columns), make sure the two paths have the same columns aliases!!! Otherwise only the first path columns will exist.
The above answer for webkit appearance worked, but the button still looked kind pale/dull compared to the browser on other devices/desktop. I also had to set opacity to full (ranges from 0 to 1)
-webkit-appearance:none;
opacity: 1
After setting the opacity, the button looked the same on all the different devices/emulator/desktop.
x=[]
for i in range(0,5):
x.append(i)
print(x[i])
A nice way to access from dynamic string names that contain objects (for example object.subobject.property)
function ReadValue(varname)
{
var v=varname.split(".");
var o=window;
if(!v.length)
return undefined;
for(var i=0;i<v.length-1;i++)
o=o[v[i]];
return o[v[v.length-1]];
}
function AssignValue(varname,value)
{
var v=varname.split(".");
var o=window;
if(!v.length)
return;
for(var i=0;i<v.length-1;i++)
o=o[v[i]];
o[v[v.length-1]]=value;
}
Example:
ReadValue("object.subobject.property");
WriteValue("object.subobject.property",5);
eval works for read value, but write value is a bit harder.
A more advanced version (Create subclasses if they dont exists, and allows objects instead of global variables)
function ReadValue(varname,o=window)
{
if(typeof(varname)==="undefined" || typeof(o)==="undefined" || o===null)
return undefined;
var v=varname.split(".");
if(!v.length)
return undefined;
for(var i=0;i<v.length-1;i++)
{
if(o[v[i]]===null || typeof(o[v[i]])==="undefined")
o[v[i]]={};
o=o[v[i]];
}
if(typeof(o[v[v.length-1]])==="undefined")
return undefined;
else
return o[v[v.length-1]];
}
function AssignValue(varname,value,o=window)
{
if(typeof(varname)==="undefined" || typeof(o)==="undefined" || o===null)
return;
var v=varname.split(".");
if(!v.length)
return;
for(var i=0;i<v.length-1;i++)
{
if(o[v[i]]===null || typeof(o[v[i]])==="undefined")
o[v[i]]={};
o=o[v[i]];
}
o[v[v.length-1]]=value;
}
Example:
ReadValue("object.subobject.property",o);
WriteValue("object.subobject.property",5,o);
This is the same that o.object.subobject.property
After save new file press
Ctrl-6
This is shortcut to alternate file
Found this solution which is much cleaner in terms of getting a String representation back from an MD5 hash.
import java.security.*;
import java.math.*;
public class MD5 {
public static void main(String args[]) throws Exception{
String s="This is a test";
MessageDigest m=MessageDigest.getInstance("MD5");
m.update(s.getBytes(),0,s.length());
System.out.println("MD5: "+new BigInteger(1,m.digest()).toString(16));
}
}
The code was extracted from here.
Not accessible to any webpage (true) but is easily accessible and easily editible via dev tools, such as chrome (ctl-shift-J). Therefore, custom crypto required before storing the value.
But, if javascript needs to decrypt (to validate) then the decrypt algorithm is exposed and can be manipulated.
Javascript needs a fully secure container and the ability to properly implement private variables and functions that are available only to the js interpreter. But, this violates user security - since tracking data can be used with impunity.
Consequently, javascript will never be fully secure.
You can call andReturn()
and use the returned MvcResult
object to get the content as a String
.
See below:
MvcResult result = mockMvc.perform(post("/api/users").header("Authorization", base64ForTestUser).contentType(MediaType.APPLICATION_JSON)
.content("{\"userName\":\"testUserDetails\",\"firstName\":\"xxx\",\"lastName\":\"xxx\",\"password\":\"xxx\"}"))
.andDo(MockMvcResultHandlers.print())
.andExpect(status().isBadRequest())
.andReturn();
String content = result.getResponse().getContentAsString();
// do what you will
My approach to delete all rows from a table i DynamoDb is just to pull all rows out from the table, using DynamoDbs ScanAsync and then feed the result list to DynamoDbs AddDeleteItems. Below code in C# works fine for me.
public async Task DeleteAllReadModelEntitiesInTable()
{
List<ReadModelEntity> readModels;
var conditions = new List<ScanCondition>();
readModels = await _context.ScanAsync<ReadModelEntity>(conditions).GetRemainingAsync();
var batchWork = _context.CreateBatchWrite<ReadModelEntity>();
batchWork.AddDeleteItems(readModels);
await batchWork.ExecuteAsync();
}
Note: Deleting the table and then recreating it again from the web console may cause problems if using YAML/CloudFormation to create the table.
This should work, since your state will change after the Ajax call, and the parent component will re-render.
render : function () {
var item;
if (this.state.isRequired) {
item = <MyOwnInput attribute={'whatever'} />
} else {
item = <MyOwnInput />
}
return (
<div>
{item}
</div>
);
}
This simple example shows how to capture curl output, and use it in a bash script
function main
{
\curl -vs 'http://google.com' 2>&1
# note: add -o /tmp/ignore.png if you want to ignore binary output, by saving it to a file.
}
# capture output of curl to a variable
OUT=$(main)
# search output for something using grep.
echo
echo "$OUT" | grep 302
echo
echo "$OUT" | grep title
Two ways can store HQL query results:
INSERT OVERWRITE DIRECTORY "HDFS Path" ROW FORMAT DELIMITED FIELDS TERMINATED BY '|'
SELECT * FROM XXXX LIMIT 10;
$hive -e "select * from table_Name" > ~/sample_output.txt
$hive -e "select * from table where city = 'London' and id >=100" > /home/user/outputdirectory/city details.csv
In Spring STS, Right click the project & select "Open Project", This provision do the necessary action on the background & bring the project back to work space.
Thanks & Regards Vengat Maran
In addition to the generic device (or "Any iOS Device" in newer versions of Xcode) mentioned in the other answers, it is possible that the "Archive" action is not selected for the current target in the scheme.
To view and edit at the current scheme, select Product > Schemes > Edit Scheme...
(Cmd+<), then make sure that the "Archive" action is checked in the line corresponding to the desired target.
In the image below, Archive
is not checked and the Archive
action is greyed out in the Product
menu. Checking the indicated checkbox fixed the issue for me.
I use this.
var iframe = parent.document.getElementById("theiframe");
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var currentFrame = innerDoc.location.href;
Nowell pointed it out that this has been addressed as of August 6th, 2013. A working example using this form might be:
<form class="dropzone" id="my-awesome-dropzone"></form>
You could use this JavaScript:
Dropzone.options.myAwesomeDropzone = {
maxFiles: 1,
accept: function(file, done) {
console.log("uploaded");
done();
},
init: function() {
this.on("maxfilesexceeded", function(file){
alert("No more files please!");
});
}
};
The dropzone element even gets a special style, so you can do things like:
<style>
.dz-max-files-reached {background-color: red};
</style>
The cex
parameter will do that for you.
a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
col = 1:6, space = c(0, 2))
legend("topright",
legend = c("a", "b", "c", "d", "e", "f"),
fill = 1:6, ncol = 2,
cex = 0.75)
What you need to do is update the config.ini
file for the device and re-download the system image.
Update the following values in C:\Users\USER\.android\avd\DEVICE_ID\config.ini
(on Windows) or ~/.android/avd/DEVICE_ID/config.ini
(on Linux)
PlayStore.enabled = true
image.sysdir.1=system-images\android-27\google_apis_playstore\x86\
tag.display=Google Play
tag.id=google_apis_playstore
Then re-download the system image for the device from Android Studio > Tools > AVD Manager
That is all. Restart your device and you'll have the Play Store installed.
This has also been answered here: How to install Google Play app in Android Studio emulator?
This is a destructor. It's called when the object is destroyed (out of life scope or deleted).
To be clear, you have to use ~NameOfTheClass like for the constructor, other names are invalid.
class MaxHeap:
def __init__(self, items=[]):
self.heap = [0]
self.items = items
for item in items:
self.heap.append(item)
self.__floatUp(len(self.heap)-1)
"""
self.heap = [0] heap index stars form 1
self.heap.append(item) append items from list to heap
append items to it's proper place
"""
def push(self, data):
self.heap.append(data)
self.__floatUp(len(self.heap)-1)
"""
Append data to the end of the list the using float up put it to the proper place
"""
def peek(self):
if self.heap[1]:
return self.heap[1]
else:
return False
"""
To return the first element form list
"""
def pop(self):
if (len(self.heap)) > 2:
self.__swap(1,len(self.heap)-1)
max = self.heap.pop()
self.__bubbleDown(1)
elif (len(self.heap)) == 2:
max = self.heap.pop()
else:
return False
return max
"""
If length is greater than two then swap first and last value as only the last value can be removed from the tree
Place the new first item after removing of the item to its proper place using bubble down
"""
def __swap(self, i, j):
self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
"""
Swap is used in a bubble down and bubble up for proper placing of values is list
"""
def __floatUp(self, index):
parent = index // 2
if index <= 1:
return
elif self.heap[index] > self.heap[parent]:
self.__swap(index, parent)
self.__floatUp(parent)
"""
if value and parents , where parent < value , swap where parent, value = value,parent
After swap again check parent > value == True if false then again continue
"""
def __bubbleDown(self, index):
left = index * 2
right = index * 2 + 1
largest = index
if len(self.heap) > left and self.heap[largest] < self.heap[left]:
largest = left
if len(self.heap) > right and self.heap[largest] < self.heap[right]:
largest = right
if largest != index:
self.__swap(index, largest)
self.__bubbleDown(largest)
"""
self.heap[largest] < self.heap[left] : largest = left
current value and lower left value is bigger largest = left
self.heap[largest] > self.heap[right]
current value and lower value right value if lower right value is bigger than largest value
after getting the largest value we will swap larger value and smaller value and them again check that the current value is
bigger than is down value then again swap space and check again until every node is settled at its the correct place
"""
def __str__(self):
return str(self.heap)
"""
To str representation of the list
"""
m = MaxHeap([95, 3, 21])
m.push(10)
print(m)
print(m.pop())
print(m.peek())
Basic Difference
Function must return a value but in Stored Procedure it is optional( Procedure can return zero or n values).
Functions can have only input parameters for it whereas Procedures can have input/output parameters .
Function takes one input parameter it is mandatory but Stored Procedure may take o to n input parameters..
Functions can be called from Procedure whereas Procedures cannot be called from Function.
Advance Difference
Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function allows only SELECT statement in it.
Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement.
Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be.
Functions that return tables can be treated as another rowset. This can be used in JOINs with other tables.
Inline Function can be though of as views that take parameters and can be used in JOINs and other Rowset operations.
Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a Function.
We can go for Transaction Management in Procedure whereas we can't go in Function.
You can use Apphance. This is a cross-platform service (now mainly Android, iOS with other platforms on their way) which allows to debug remotely any mobile device (Android, iOS now - others under development). It's much more than just a crashlog, in fact it is much more: logging, reporting of problems by testers, crashlogs. It takes about 5 minutes to integrate. Currently you can request for access to closed beta.
Disclaimer: I am CTO of Polidea, a company behind Apphance and co-creator of it.
Update: Apphance is no longer closed beta! Update 2: Apphance is available as part of http://applause.com offering
I am not able to add a comment to M. Kiewisch since I do not have enough reputation points (only have 41 but need more than 50 to comment).
Anyway, just want to point out that M. Kiewisch solution does not work as is and may need more tweaking. Consider for example
>>> df = pd.DataFrame({'a': [1, 2, 3, 5], 'b': [4, np.NaN, 6, 4]})
>>> df
a b
0 1 4.0
1 2 NaN
2 3 6.0
3 5 4.0
>>> df.groupby(['b']).sum()
a
b
4.0 6
6.0 3
>>> df.astype(str).groupby(['b']).sum()
a
b
4.0 15
6.0 3
nan 2
which shows that for group b=4.0, the corresponding value is 15 instead of 6. Here it is just concatenating 1 and 5 as strings instead of adding it as numbers.
SELECT product FROM Your_table_name WHERE Product LIKE '%XYZ%';
The above statement will show result from a single table. If you want to add more tables then simply use the UNION statement.
SELECT product FROM Table_name_1
WHERE Product LIKE '%XYZ%'
UNION
SELECT product FROM Table_name_2
WHERE Product LIKE '%XYZ%'
UNION
SELECT product FROM Table_name_3
WHERE Product LIKE '%XYZ%'
... and so on
To expand on J.F. Sebastian's answer:
You can use git-rebase to easily make all kinds of changes to your commit history.
After running git rebase --interactive you get the following in your $EDITOR:
pick 366eca1 This has a huge file
pick d975b30 delete foo
pick 121802a delete bar
# Rebase 57d0b28..121802a onto 57d0b28
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
You can move lines to change the order of commits and delete lines to remove that commit. Or you can add a command to combine (squash) two commits into a single commit (previous commit is the above commit), edit commits (what was changed), or reword commit messages.
I think pick just means that you want to leave that commit alone.
(Example is from here)
Give this a go:
<form name="postcontent" id="postcontent">
<input name="postsubmit" type="submit" id="postsubmit" value="POST"/>
<textarea id="postdata" name="postdata" placeholder="What's Up ?"></textarea>
</form>
<script>
(function() {
$("#postcontent").on('submit', function(e) {
e.preventDefault();
$.ajax({
type:"POST",
url:"add_new_post.php",
data:$("#postcontent").serialize(),
beforeSend:function(){
$(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
},success:function(response){
//alert(response);
$("#return_update_msg").html(response);
$(".post_submitting").fadeOut(1000);
}
});
});
})();
</script>
I tend to just load the entire buffer as a raw memory chunk into memory and do the parsing on my own. That way I have best control over what the standard lib does on multiple platforms.
This is a stub I use for this. you may also want to check the error-codes for fseek, ftell and fread. (omitted for clarity).
char * buffer = 0;
long length;
FILE * f = fopen (filename, "rb");
if (f)
{
fseek (f, 0, SEEK_END);
length = ftell (f);
fseek (f, 0, SEEK_SET);
buffer = malloc (length);
if (buffer)
{
fread (buffer, 1, length, f);
}
fclose (f);
}
if (buffer)
{
// start to process your data / extract strings here...
}
For Visual Studio 2015 the MSBuild variables have changed a bit:
<Target Name="SpicNSpan" AfterTargets="Clean"> <!-- common vars https://msdn.microsoft.com/en-us/library/c02as0cs.aspx?f=255&MSPPError=-2147217396 -->
<RemoveDir Directories="$(TargetDir)" /> <!-- bin -->
<RemoveDir Directories="$(SolutionDir).vs" /> <!-- .vs -->
<RemoveDir Directories="$(ProjectDir)$(BaseIntermediateOutputPath)" /> <!-- obj -->
</Target>
Notice that this snippet also wipes out the .vs folder from the root directory of your solution. You may want to comment out the associated line if you feel that removing the .vs folder is an overkill. I have it enabled because I noticed that in some third party projects it causes issues when files ala application.config exist inside the .vs folder.
Addendum:
If you are into optimizing the maintainability of your solutions you might want to take things one step further and place the above snippet into a separate file like so:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="SpicNSpan" AfterTargets="Clean"> <!-- common vars https://msdn.microsoft.com/en-us/library/c02as0cs.aspx?f=255&MSPPError=-2147217396 -->
<RemoveDir Directories="$(TargetDir)" /> <!-- bin -->
<RemoveDir Directories="$(SolutionDir).vs" /> <!-- .vs -->
<RemoveDir Directories="$(ProjectDir)$(BaseIntermediateOutputPath)" /> <!-- obj -->
</Target>
</Project>
And then include this file at the very end of each and every one of your *.csproj files like so:
[...]
<Import Project="..\..\Tools\ExtraCleanup.targets"/>
</Project>
This way you can enrich or fine-tune your extra-cleanup-logic centrally, in one place without going through the pains of manually editing each and every *.csproj file by hand every time you want to make an improvement.
This is the more powerful grouping / rollup syntax you'll want to use in SQL Server 2008+. Always useful to specify the version you're using so we don't have to guess.
SELECT
[Type] = COALESCE([Type], 'Total'),
[Total Sales] = SUM([Total Sales])
FROM dbo.Before
GROUP BY GROUPING SETS(([Type]),());
Craig Freedman wrote a great blog post introducing GROUPING SETS
.
Option 1: Using Windows PowerShell
Open the windows menu. Type: "PowerShell" and open the 'Windows PowerShell' command window.
Goto folder with desired files: e.g. cd "C:\house chores" Notice: address must incorporate quotes "" if there are spaces involved.
You can use 'dir' to see all the files in the folder. Using '|' will pipeline the output of 'dir' for the command that follows.
Notes: 'dir' is an alias of 'Get-ChildItem'. See: wiki: cmdlets. One can provide further functionality. e.g. 'dir -recurse' outputs all the files, folders and sub-folders.
What if I only want a range of files?
Instead of 'dir |' I can use:
dir | where-object -filterscript {($_.Name -ge 'DSC_20') -and ($_.Name -le 'DSC_31')} |
For batch-renaming with the directory name as a prefix:
dir | Rename-Item -NewName {$_.Directory.Name + " - " + $_.Name}
Option 2: Using Command Prompt
In the folder press shift+right-click : select 'open command-window here'
for %a in (*.*) do ren "%a" "prefix - %a"
If there are a lot of files, it might be good to add an '@echo off' command before this and an 'echo on' command at the end.
The command as written will create new directories and files with the current date and time stamp, and yourself as the owner. If you are the only user on your system and you are doing this daily it may not matter much. But if preserving those attributes matters to you, you can modify your command with
cp -pur /home/abc/* /mnt/windowsabc/
The -p will preserve ownership, timestamps, and mode of the file. This can be pretty important depending on what you're backing up.
The alternative command with rsync would be
rsync -avh /home/abc/* /mnt/windowsabc
With rsync, -a indicates "archive" which preserves all those attributes mentioned above. -v indicates "verbose" which just lists what it's doing with each file as it runs. -z is left out here for local copies, but is for compression, which will help if you are backing up over a network. Finally, the -h tells rsync to report sizes in human-readable formats like MB,GB,etc.
Out of curiosity, I ran one copy to prime the system and avoid biasing against the first run, then I timed the following on a test run of 1GB of files from an internal SSD drive to a USB-connected HDD. These simply copied to empty target directories.
cp -pur : 19.5 seconds
rsync -ah : 19.6 seconds
rsync -azh : 61.5 seconds
Both commands seem to be about the same, although zipping and unzipping obviously tax the system where bandwidth is not a bottleneck.
I'm unsure if this works for all compilers, but it has worked so far for me.
void inner_func(int &i)
{
va_list vars;
va_start(vars, i);
int j = va_arg(vars);
va_end(vars); // Generally useless, but should be included.
}
void func(int i, ...)
{
inner_func(i);
}
You can add the ... to inner_func() if you want, but you don't need it. It works because va_start uses the address of the given variable as the start point. In this case, we are giving it a reference to a variable in func(). So it uses that address and reads the variables after that on the stack. The inner_func() function is reading from the stack address of func(). So it only works if both functions use the same stack segment.
The va_start and va_arg macros will generally work if you give them any var as a starting point. So if you want you can pass pointers to other functions and use those too. You can make your own macros easily enough. All the macros do is typecast memory addresses. However making them work for all the compilers and calling conventions is annoying. So it's generally easier to use the ones that come with the compiler.
try this (a2 is BLOB col)
PreparedStatement ps1 = conn.prepareStatement("update t1 set a2=? where id=1");
Blob blob = conn.createBlob();
blob.setBytes(1, str.getBytes());
ps1.setBlob(1, blob);
ps1.executeUpdate();
it may work even without BLOB, driver will transform types automatically:
ps1.setBytes(1, str.getBytes);
ps1.setString(1, str);
Besides if you work with text CLOB seems to be a more natural col type
The better way is to include it in a rake task. Create import.rake file inside /lib/tasks/ and put this code to that file.
desc "Imports a CSV file into an ActiveRecord table"
task :csv_model_import, [:filename, :model] => [:environment] do |task,args|
lines = File.new(args[:filename], "r:ISO-8859-1").readlines
header = lines.shift.strip
keys = header.split(',')
lines.each do |line|
values = line.strip.split(',')
attributes = Hash[keys.zip values]
Module.const_get(args[:model]).create(attributes)
end
end
After that run this command in your terminal rake csv_model_import[file.csv,Name_of_the_Model]
If you use normalize.css, that stylesheet will do something like input[type="search"] { -webkit-appearance: textfield; }
.
This has a higher specificity than a single class selector like .foo
, so be aware that you then can't do just .my-field { -webkit-appearance: none; }
. If you have no better way to achieve the right specificity, this will help:
.my-field { -webkit-appearance: none !important; }
You need to rename your main class to Main
, it cannot be anything else.
It does not matter how many files as packages and classes you create, you must name your main class Main
.
That's all.
Look for the hidden .android folder in your user home folder. You might rename or delete this folder, recreate your AVD, and restart the emulator. It could be there is a .ini file in that folder that has that setting munged.
You can write a directive to listen the change event on the input and reset the value to the min value if it is too low. StackBlitz
@HostListener('change') onChange() {
const min = +this.elementRef.nativeElement.getAttribute('min');
if (this.valueIsLessThanMin(min, +this.elementRef.nativeElement.value)) {
this.renderer2.setProperty(
this.elementRef.nativeElement,
'value',
min + ''
);
}
}
Also listen for the ngModelChange event to do the same when the form value is set.
@HostListener('ngModelChange', ['$event'])
onModelChange(value: number) {
const min = +this.elementRef.nativeElement.getAttribute('min');
if (this.valueIsLessThanMin(min, value)) {
const formControl = this.formControlName
? this.formControlName.control
: this.formControlDirective.control;
if (formControl) {
if (formControl.updateOn === 'change') {
console.warn(
`minValueDirective: form control ${this.formControlName.name} is set to update on change
this can cause issues with min update values.`
);
}
formControl.reset(min);
}
}
}
Full code:
import {
Directive,
ElementRef,
HostListener,
Optional,
Renderer2,
Self
} from "@angular/core";
import { FormControlDirective, FormControlName } from "@angular/forms";
@Directive({
// tslint:disable-next-line: directive-selector
selector: "input[minValue][min][type=number]"
})
export class MinValueDirective {
@HostListener("change") onChange() {
const min = +this.elementRef.nativeElement.getAttribute("min");
if (this.valueIsLessThanMin(min, +this.elementRef.nativeElement.value)) {
this.renderer2.setProperty(
this.elementRef.nativeElement,
"value",
min + ""
);
}
}
// if input is a form control validate on model change
@HostListener("ngModelChange", ["$event"])
onModelChange(value: number) {
const min = +this.elementRef.nativeElement.getAttribute("min");
if (this.valueIsLessThanMin(min, value)) {
const formControl = this.formControlName
? this.formControlName.control
: this.formControlDirective.control;
if (formControl) {
if (formControl.updateOn === "change") {
console.warn(
`minValueDirective: form control ${
this.formControlName.name
} is set to update on change
this can cause issues with min update values.`
);
}
formControl.reset(min);
}
}
}
constructor(
private elementRef: ElementRef<HTMLInputElement>,
private renderer2: Renderer2,
@Optional() @Self() private formControlName: FormControlName,
@Optional() @Self() private formControlDirective: FormControlDirective
) {}
private valueIsLessThanMin(min: any, value: number): boolean {
return typeof min === "number" && value && value < min;
}
}
Make sure to use this with the form control set to updateOn blur or the user won't be able to enter a +1 digit number if the first digit is below the min value.
this.formGroup = this.formBuilder.group({
test: [
null,
{
updateOn: 'blur',
validators: [Validators.min(5)]
}
]
});
Here's a method using display:flex
:
.container {_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
display: flex;_x000D_
position: fixed;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
}
_x000D_
<div class="container">_x000D_
<div>centered text!</div>_x000D_
</div>
_x000D_
This seems to be working for PostgreSQL 9.1:
#{Rails.root}/lib/tasks/databases.rake
# monkey patch ActiveRecord to avoid There are n other session(s) using the database.
def drop_database(config)
case config['adapter']
when /mysql/
ActiveRecord::Base.establish_connection(config)
ActiveRecord::Base.connection.drop_database config['database']
when /sqlite/
require 'pathname'
path = Pathname.new(config['database'])
file = path.absolute? ? path.to_s : File.join(Rails.root, path)
FileUtils.rm(file)
when /postgresql/
ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
ActiveRecord::Base.connection.select_all("select * from pg_stat_activity order by procpid;").each do |x|
if config['database'] == x['datname'] && x['current_query'] =~ /<IDLE>/
ActiveRecord::Base.connection.execute("select pg_terminate_backend(#{x['procpid']})")
end
end
ActiveRecord::Base.connection.drop_database config['database']
end
end
Lifted from gists found here and here.
Here's a modified version that works for both PostgreSQL 9.1 and 9.2.
You could create a basket service. And generally in JS you use objects instead of lots of parameters.
Here's an example: http://jsfiddle.net/2MbZY/
var app = angular.module('myApp', []);
app.factory('basket', function() {
var items = [];
var myBasketService = {};
myBasketService.addItem = function(item) {
items.push(item);
};
myBasketService.removeItem = function(item) {
var index = items.indexOf(item);
items.splice(index, 1);
};
myBasketService.items = function() {
return items;
};
return myBasketService;
});
function MyCtrl($scope, basket) {
$scope.newItem = {};
$scope.basket = basket;
}
Before doing that Download Node Js 8.11.3 from the URL: download
Open command prompt and run this:
npm install -g [email protected]
use this version this is the stable version which works along with cordova 7.1.0
for installing cordova use : • npm install -g [email protected]
• Run command
• Cordova platform remove android (if you have old android code or code is having some issue)
• Cordova platform add android : for building android app in cordova Running: Corodva run android
Step 1:
npm install jquery
Step 2:
touch loader.js
Somewhere in your project folder
Step 3:
//loader.js
window.$ = window.jQuery = require('jquery')
Step 4:
Import the loader into your root file before you import the files which require jQuery
//App.js
import '<pathToYourLoader>/loader.js'
Step 5:
Now use jQuery anywhere in your code:
//SomeReact.js
class SomeClass extends React.Compontent {
...
handleClick = () => {
$('.accor > .head').on('click', function(){
$('.accor > .body').slideUp();
$(this).next().slideDown();
});
}
...
export default SomeClass
Currently it only works for the .dropdown-menu
:
.dropdown-menu .divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
If you want it for other use, in your own css, following the bootstrap.css create another one:
.divider {
height: 1px;
width:100%;
display:block; /* for use on default inline elements like span */
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
You could add the following VBA code to your sheet:
Private Sub Worksheet_Change(ByVal Target As Range)
If Range("A1") > 0.5 Then
MsgBox "Discount too high"
End If
End Sub
Every time a cell is changed on the sheet, it will check the value of cell A1.
Notes:
Widor uses a different approach (Worksheet_Calculate
instead of Worksheet_Change
):
Conclusion: use Worksheet_Change
if A1 only depends on data located on the same sheet, use Worksheet_Calculate
if not.
Using printf
you can do
printf("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");
If you're using C++, you can achieve the same result using the STL:
using namespace std; // for clarity
string s("A string that is more than 8 chars");
cout << "Here are the first 8 chars: ";
copy(s.begin(), s.begin() + 8, ostream_iterator<char>(cout));
cout << endl;
Or, less efficiently:
cout << "Here are the first 8 chars: " <<
string(s.begin(), s.begin() + 8) << endl;
I am also facing the same issue..
in the login activity what i do is.
Intent myIntent = new Intent(MainActivity.this, ActivityLoggedIn.class);
finish();
MainActivity.this.startActivity(myIntent);
on logout
Intent myIntent = new Intent(ActivityLoggedIn.this, MainActivity.class);
finish();
ActivityLoggedIn.this.startActivity(myIntent);
This works well but when i am in the ActivityLoggedIn and i minimize the app and click on the launcher button icon on the app drawer, the MainActivity starts again :-/ i am using the flag
android:LaunchMode:singleTask
for the MainActivity.
I couldn't get the above posts to do quite what I was after.
After playing around with the other replies here, I made this. It's hacky, but it works!
For this object:
var myObj = {
pageURL : "BLAH",
emailBox : {model:"emailAddress", selector:"#emailAddress"},
passwordBox: {model:"password" , selector:"#password"}
};
... this code:
// Get every value in the object into a separate array item ...
function buildArray(p_MainObj, p_Name) {
var variableList = [];
var thisVar = "";
var thisYes = false;
for (var key in p_MainObj) {
thisVar = p_Name + "." + key;
thisYes = false;
if (p_MainObj.hasOwnProperty(key)) {
var obj = p_MainObj[key];
for (var prop in obj) {
var myregex = /^[0-9]*$/;
if (myregex.exec(prop) != prop) {
thisYes = true;
variableList.push({item:thisVar + "." + prop,value:obj[prop]});
}
}
if ( ! thisYes )
variableList.push({item:thisVar,value:obj});
}
}
return variableList;
}
// Get the object items into a simple array ...
var objectItems = buildArray(myObj, "myObj");
// Now use them / test them etc... as you need to!
for (var x=0; x < objectItems.length; ++x) {
console.log(objectItems[x].item + " = " + objectItems[x].value);
}
... produces this in the console:
myObj.pageURL = BLAH
myObj.emailBox.model = emailAddress
myObj.emailBox.selector = #emailAddress
myObj.passwordBox.model = password
myObj.passwordBox.selector = #password
A more elegant/concise solution:
$(document).on('keydown',function(e){
var $target = $(e.target||e.srcElement);
if(e.keyCode == 8 && !$target.is('input,[contenteditable="true"],textarea'))
{
e.preventDefault();
}
})
Go to Behavior > Site Content > All Pages and put your URI into the search box.
Improving the first "FOR /F.." answer: What I had to do was to call execute every script listed in MyList.txt, so it worked for me:
for /F "tokens=*" %A in (MyList.txt) do CALL %A ARG1
--OR, if you wish to do it over the multiple line:
for /F "tokens=*" %A in (MuList.txt) do (
ECHO Processing %A....
CALL %A ARG1
)
Edit: The example given above is for executing FOR loop from command-prompt; from a batch-script, an extra % needs to be added, as shown below:
---START of MyScript.bat---
@echo off
for /F "tokens=*" %%A in ( MyList.TXT) do (
ECHO Processing %%A....
CALL %%A ARG1
)
@echo on
;---END of MyScript.bat---
I guess image is than corrupted. Example: image size is 195px X 146px.
It will work inside lower resolutions like tablets. When you have 1280 X 800 resolution it will force larger as there is also width 100 %. Maybe CSS inside media query like icons fonts is the best solution.
Changing file permissions from Properties, disabling inheritance and running chmod 400 didn't work for me. The permissions for my private key file were:
-r--r----- 1 alex None 1766 Mar 8 13:04 /home/alex/.ssh/id_rsa
Then I noticed the group was None, so I just ran
chown alex:Administrators ~/.ssh/id_rsa
Then I could successfully change the permissions with chmod 400, and run a git push.
JAVA 8
In plain java 8 you also have the possibility of using Streams/Collectors
to do the job.
Map<String, String> myMap = Stream.of(
new SimpleEntry<>("key1", "value1"),
new SimpleEntry<>("key2", "value2"),
new SimpleEntry<>("key3", "value3"))
.collect(toMap(SimpleEntry::getKey, SimpleEntry::getValue));
This has the advantage of not creating an Anonymous class.
Note that the imports are:
import static java.util.stream.Collectors.toMap;
import java.util.AbstractMap.SimpleEntry;
Of course, as noted in other answers, in java 9 onwards you have simpler ways of doing the same.
I reworked the example you provided in the js fiddle : http://jsfiddle.net/zravs3hp/
I renamed your container
div to overlay
, as semantically this div is not a container, but an overlay. I also placed the loader div as a child of this overlay div.
The resulting html is :
<div class="overlay">
<div id="loading-img"></div>
</div>
<div class="content">
<div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea velit provident sint aliquid eos omnis aperiam officia architecto error incidunt nemo obcaecati adipisci doloremque dicta neque placeat natus beatae cupiditate minima ipsam quaerat explicabo non reiciendis qui sit. ...</div>
<button id="button">Submit</button>
</div>
The css of the overlay is the following
.overlay {
background: #e9e9e9; <- I left your 'gray' background
display: none; <- Not displayed by default
position: absolute; <- This and the following properties will
top: 0; make the overlay, the element will expand
right: 0; so as to cover the whole body of the page
bottom: 0;
left: 0;
opacity: 0.5;
}
I added some dummy text so as to have something to overlay.
Then, in the click
handler we just need to show the overlay :
$("#button").click(function () {
$(".overlay").show();
});
To disable a specific rule for the file:
/* eslint-disable no-use-before-define */
Note there is a bug in eslint where single line comment will not work -
// eslint-disable max-classes-per-file
// This fails!
byte[] toByteArray(int value) {
return ByteBuffer.allocate(4).putInt(value).array();
}
byte[] toByteArray(int value) {
return new byte[] {
(byte)(value >> 24),
(byte)(value >> 16),
(byte)(value >> 8),
(byte)value };
}
int fromByteArray(byte[] bytes) {
return ByteBuffer.wrap(bytes).getInt();
}
// packing an array of 4 bytes to an int, big endian, minimal parentheses
// operator precedence: <<, &, |
// when operators of equal precedence (here bitwise OR) appear in the same expression, they are evaluated from left to right
int fromByteArray(byte[] bytes) {
return bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);
}
// packing an array of 4 bytes to an int, big endian, clean code
int fromByteArray(byte[] bytes) {
return ((bytes[0] & 0xFF) << 24) |
((bytes[1] & 0xFF) << 16) |
((bytes[2] & 0xFF) << 8 ) |
((bytes[3] & 0xFF) << 0 );
}
When packing signed bytes into an int, each byte needs to be masked off because it is sign-extended to 32 bits (rather than zero-extended) due to the arithmetic promotion rule (described in JLS, Conversions and Promotions).
There's an interesting puzzle related to this described in Java Puzzlers ("A Big Delight in Every Byte") by Joshua Bloch and Neal Gafter . When comparing a byte value to an int value, the byte is sign-extended to an int and then this value is compared to the other int
byte[] bytes = (…)
if (bytes[0] == 0xFF) {
// dead code, bytes[0] is in the range [-128,127] and thus never equal to 255
}
Note that all numeric types are signed in Java with exception to char being a 16-bit unsigned integer type.
Docker requires your command to keep running in the foreground. Otherwise, it thinks that your applications stops and shutdown the container.
So if your docker entry script is a background process like following:
/usr/local/bin/confd -interval=30 -backend etcd -node $CONFIG_CENTER &
The '&' makes the container stop and exit if there are no other foreground process triggered later. So the solution is just remove the '&' or have another foreground CMD running after it, such as
tail -f server.log
First of all, you need to login as root and than go to /etc directory and execute some commands which are given below.
[root@localhost~]# cd /etc
[root@localhost /etc]# vi sudoers
and enter this line at the end
kundan ALL=NOPASSWD: ALL
where kundan is the username and than save it. and then try to transfer the file and add sudo
as a prefix to the command you want to execute:
sudo cp hello.txt /home/rahul/program/
where rahul is the second user in the same server.
assuming certain column names...
INSERT one
newToner = Toner(toner_id = 1,
toner_color = 'blue',
toner_hex = '#0F85FF')
dbsession.add(newToner)
dbsession.commit()
INSERT multiple
newToner1 = Toner(toner_id = 1,
toner_color = 'blue',
toner_hex = '#0F85FF')
newToner2 = Toner(toner_id = 2,
toner_color = 'red',
toner_hex = '#F01731')
dbsession.add_all([newToner1, newToner2])
dbsession.commit()
UPDATE
q = dbsession.query(Toner)
q = q.filter(Toner.toner_id==1)
record = q.one()
record.toner_color = 'Azure Radiance'
dbsession.commit()
or using a fancy one-liner using MERGE
record = dbsession.merge(Toner( **kwargs))
Yes, you can do print all keys using below bash script,
for key in $(redis-cli -p 6379 keys \*);
do echo "Key : '$key'"
redis-cli -p 6379 GET $key;
done
where, 6379 is a port on which redis is running.
As mentioned in the above answers, unset GNUPLOT_DRIVER_DIR
should work if you have used export
to set the variable. If you have set it permanently in ~/.bashrc
or ~/.zshrc
then simply removing it from there will work.
Since November 2017, one can use tomcat8-maven-plugin:
<!-- https://mvnrepository.com/artifact/org.apache.tomcat.maven/tomcat8-maven-plugin -->
<dependency>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat8-maven-plugin</artifactId>
<version>2.2</version>
</dependency>
Note that this plugin resides in ICM repo (not in Maven Central), hence you should add the repo to your pluginsRepositories in your pom.xml:
<pluginRepositories>
<pluginRepository>
<id>icm</id>
<name>Spring Framework Milestone Repository</name>
<url>http://maven.icm.edu.pl/artifactory/repo</url>
</pluginRepository>
</pluginRepositories>
<select [(ngModel)]="selectedcarrera" (change)="mostrardatos()" class="form-control" name="carreras">
<option *ngFor="let x of carreras" [ngValue]="x"> {{x.nombre}} </option>
</select>
In ts
mostrardatos(){
}
ALTER TABLE Testing ALTER COLUMN TestDec decimal(16,1)
Just put decimal(precision, scale)
, replacing the precision and scale with your desired values.
I haven't done any testing with this with data in the table, but if you alter the precision, you would be subject to losing data if the new precision is lower.
They appear to be the same... Documentation from the click() function:
This method is a shortcut for .bind('click', handler)
Documentation from the on() function:
As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). To remove events bound with .on(), see .off().
For lists, use contains
:
[1,2,3].contains(1) == true
Works perfect for me:
(SELECT content FROM tblopportunitycomments WHERE opportunityid = 1 ORDER BY dateadded DESC LIMIT 1);
strstr(request, "favicon") != NULL
As of May 2017, multiple FROM
s can be used in a single Dockerfile.
See "Builder pattern vs. Multi-stage builds in Docker" (by Alex Ellis) and PR 31257 by Tõnis Tiigi.
The general syntax involves adding
FROM
additional times within your Dockerfile - whichever is the lastFROM
statement is the final base image. To copy artifacts and outputs from intermediate images useCOPY --from=<base_image_number>
.
FROM golang:1.7.3 as builder
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html
COPY app.go .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/github.com/alexellis/href-counter/app .
CMD ["./app"]
The result would be two images, one for building, one with just the resulting app (much, much smaller)
REPOSITORY TAG IMAGE ID CREATED SIZE
multi latest bcbbf69a9b59 6 minutes ago 10.3MB
golang 1.7.3 ef15416724f6 4 months ago 672MB
what is a base image?
A set of files, plus EXPOSE
'd ports, ENTRYPOINT
and CMD
.
You can add files and build a new image based on that base image, with a new Dockerfile
starting with a FROM
directive: the image mentioned after FROM
is "the base image" for your new image.
does it mean that if I declare
neo4j/neo4j
in aFROM
directive, that when my image is run the neo database will automatically run and be available within the container on port 7474?
Only if you don't overwrite CMD
and ENTRYPOINT
.
But the image in itself is enough: you would use a FROM neo4j/neo4j
if you had to add files related to neo4j
for your particular usage of neo4j
.
Welcome to the world of Data Oriented Design. The basic mantra is to Sort, Eliminate Branches, Batch, Eliminate virtual
calls - all steps towards better locality.
Since you tagged the question with C++, here's the obligatory typical C++ Bullshit. Tony Albrecht's Pitfalls of Object Oriented Programming is also a great introduction into the subject.
Someone posted this link to the MDN in a comment, and I think it was very helpful. It describes things like ErrorTypes very thoroughly.
EvalError --- Creates an instance representing an error that occurs regarding the global function eval().
InternalError --- Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".
RangeError --- Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.
ReferenceError --- Creates an instance representing an error that occurs when de-referencing an invalid reference.
SyntaxError --- Creates an instance representing a syntax error that occurs while parsing code in eval().
TypeError --- Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.
URIError --- Creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters.
I had the same problem you had. I used a for loop with the sorted function passing in the dictionary like so:
for item in sorted(mydict):
print(item)
The best and easy way to get the activity context is putting .this
after the name of the Activity. For example: If your Activity's name is SecondActivity
, its context will be SecondActivity.this
In case of image stacks, I find it easier to use scikit-image
to read, and matplotlib
to show or save. I have handled 16-bit TIFF image stacks with the following code.
from skimage import io
import matplotlib.pyplot as plt
# read the image stack
img = io.imread('a_image.tif')
# show the image
plt.imshow(mol,cmap='gray')
plt.axis('off')
# save the image
plt.savefig('output.tif', transparent=True, dpi=300, bbox_inches="tight", pad_inches=0.0)
**
: exponentiation^
: exclusive-or (bitwise)%
: modulus//
: divide with integral result (discard remainder)To preserve the order:
l = [1, 1, 2, 2, 3]
result = list()
map(lambda x: not x in result and result.append(x), l)
result
# [1, 2, 3]
Java's Double
class has members containing the Min and Max value for the type.
2^-1074 <= x <= (2-2^-52)·2^1023 // where x is the double.
Check out the Min_VALUE
and MAX_VALUE
static final members of Double
.
(some)People will suggest against using floating point types for things where accuracy and precision are critical because rounding errors can throw off calculations by measurable (small) amounts.
I came across this issue twice once in upgrading to 3.2.18 from 3.2.1 and 4.3.5 from 3.2.8. In both cases, this error is because of different version of spring modules
There is an easy way with Sharpeserializer (open source) :
http://www.sharpserializer.com/
It can directly serialize/de-serialize dictionary.
There is no need to mark your object with any attribute, nor do you have to give the object type in the Serialize method (See here ).
To install via nuget : Install-package sharpserializer
Then it is very simple :
Hello World (from the official website):
// create fake obj
var obj = createFakeObject();
// create instance of sharpSerializer
// with standard constructor it serializes to xml
var serializer = new SharpSerializer();
// serialize
serializer.Serialize(obj, "test.xml");
// deserialize
var obj2 = serializer.Deserialize("test.xml");
I checked all above said project version, module version, project bytecode version, target bytecode version settings in IntelliJ Idea
, but all were the same as I scratched.
I face this error Error:java: invalid source release: 1.8
in IntelliJ Idea 2017.2.6
because I upgraded the dependency version Maven
pom file, which(dependency) were supposed to build for JDK 1.8 application and I were building my application on and with maven compiler source and target JDK 1.7.
Hence I again downgrade the dependency version to earlier one in Maven
pom, and the error gone after project Rebuild Module 'xyz_project'.
We can use another way as well for example to insert the value with special characters 'Java_22 & Oracle_14' into db we can use the following format..
'Java_22 '||'&'||' Oracle_14'
Though it consider as 3 different tokens we dont have any option as the handling of escape sequence provided in the oracle documentation is incorrect.
I think that there is a more simple approach to all given here, and is the method Number.toFixed()
already implemented in JavaScript.
simply write:
var myNumber = 2;
myNumber.toFixed(2); //returns "2.00"
myNumber.toFixed(1); //returns "2.0"
etc...
it worked for me
$(document).scroll(function() {
var y = $(document).scrollTop(), //get page y value
header = $("#myarea"); // your div id
if(y >= 400) {
header.css({position: "fixed", "top" : "0", "left" : "0"});
} else {
header.css("position", "static");
}
});
Its better to access the count with the laravels count method
$count = Model::where('status','=','1')->count();
or
$count = Model::count();
Distributed (a)synchronous computing.
A real world example could be an application-wide notification framework, which sends mails to the stakeholders at various points during the course of application usage. So the application would act as a Producer
by create a Message
object, putting it on a particular Queue
, and moving forward.
There would be a set of Consumer
s who would subscribe to the Queue
in question, and would take care handling the Message
sent across. Note that during the course of this transaction, the Producer
s are decoupled from the logic of how a given Message
would be handled.
Messaging frameworks (ActiveMQ and the likes) act as a backbone to facilitate such Message
transactions by providing MessageBroker
s.
Have you copied this method from other page/application ? if yes then it will not work, So you need to delete the event and event name assigned to the button then go to design and go to button even properties go to onClick event double click next to it, it will generate event and it automatically assigns event name to the button. this should work
Carriage returns or line-feeds within the placeholder text must be treated as line breaks when rendering the hint.
This means that if you just jump to a new line, it should be rendered correctly. I.e.
<textarea placeholder="The car horn plays La Cucaracha.
You can choose your own color as long as it's black.
The GPS has the voice of Darth Vader.
"></textarea>
should render like this:
Most answers talks about constructing std::string
.
If already constructed, just use assignment operator.
std::string oString;
char* pStr;
... // Here allocate and get character string (e.g. using fgets as you mentioned)
oString = pStr; // This is it! It copies contents from pStr to oString
Some of the those leaving comments have noted that setting System.Net.ServicePointManager.SecurityProtocol
to specific values means that your app won't be able to take advantage of future TLS versions that may become the default values in future updates to .NET. Instead of specifying a fixed list of protocols, you can instead turn on or off protocols you know and care about, leaving any others as they are.
To turn on TLS 1.1 and 1.2 without affecting other protocols:
System.Net.ServicePointManager.SecurityProtocol |=
SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
Notice the use of |=
to turn on these flags without turning others off.
To turn off SSL3 without affecting other protocols:
System.Net.ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3;
The Build number is an internal number that indicates the current state of the app. It differs from the Version number in that it's typically not user facing and doesn't denote any difference/features/upgrades like a version number typically would.
Think of it like this:
CFBundleVersion
): The number of the build. Usually you start this at 1 and increase by 1 with each build of the app. It quickly allows for comparisons of which build is more recent and it denotes the sense of progress of the codebase. These can be overwhelmingly valuable when working with QA and needing to be sure bugs are logged against the right builds.CFBundleShortVersionString
): The user-facing number you are using to denote this version of your app. Usually this follows a Major.minor version scheme (e.g. MyAwesomeApp 1.2) to let users know which releases are smaller maintenance updates and which are big deal new features.To use this effectively in your projects, Apple provides a great tool called agvtool
. I highly recommend using this as it is MUCH more simple than scripting up plist changes. It allows you to easily set both the build number and the marketing version. It is particularly useful when scripting (for instance, easily updating the build number on each build or even querying what the current build number is). It can even do more exotic things like tag your SVN for you when you update the build number.
To use it:
agvtool new-version 1
(set the Build number to 1)agvtool new-marketing-version 1.0
(set the Marketing version to 1.0)See the man page of agvtool
for a ton of good info
rand() returns the next (pseudo) random number in a series. What's happening is you have the same series each time its run (default '1'). To seed a new series, you have to call srand() before you start calling rand().
If you want something random every time, you might try:
srand (time (0));
A very concise code without any other php file include of oauth etc. Please note to obtain following keys you need to sign up with https://dev.twitter.com and create application.
<?php
$token = 'YOUR_TOKEN';
$token_secret = 'YOUR_TOKEN_SECRET';
$consumer_key = 'CONSUMER_KEY';
$consumer_secret = 'CONSUMER_SECRET';
$host = 'api.twitter.com';
$method = 'GET';
$path = '/1.1/statuses/user_timeline.json'; // api call path
$query = array( // query parameters
'screen_name' => 'twitterapi',
'count' => '5'
);
$oauth = array(
'oauth_consumer_key' => $consumer_key,
'oauth_token' => $token,
'oauth_nonce' => (string)mt_rand(), // a stronger nonce is recommended
'oauth_timestamp' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_version' => '1.0'
);
$oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
$query = array_map("rawurlencode", $query);
$arr = array_merge($oauth, $query); // combine the values THEN sort
asort($arr); // secondary sort (value)
ksort($arr); // primary sort (key)
// http_build_query automatically encodes, but our parameters
// are already encoded, and must be by this point, so we undo
// the encoding step
$querystring = urldecode(http_build_query($arr, '', '&'));
$url = "https://$host$path";
// mash everything together for the text to hash
$base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring);
// same with the key
$key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);
// generate the hash
$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));
// this time we're using a normal GET query, and we're only encoding the query params
// (without the oauth params)
$url .= "?".http_build_query($query);
$url=str_replace("&","&",$url); //Patch by @Frewuill
$oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
ksort($oauth); // probably not necessary, but twitter's demo does it
// also not necessary, but twitter's demo does this too
function add_quotes($str) { return '"'.$str.'"'; }
$oauth = array_map("add_quotes", $oauth);
// this is the full value of the Authorization line
$auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));
// if you're doing post, you need to skip the GET building above
// and instead supply query parameters to CURLOPT_POSTFIELDS
$options = array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
// do our business
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
foreach ($twitter_data as &$value) {
$tweetout .= preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/", '<a href="http://$2$3" target="_blank">$1$2$4</a>', $value->text);
$tweetout = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $tweetout);
$tweetout = preg_replace("/#(\w+)/", "<a href=\"http://search.twitter.com/search?q=\\1\" target=\"_blank\">#\\1</a>", $tweetout);
}
echo $tweetout;
?>
Regards
The problem with the new version of QuickText seems to be that it is set to react to the TAB key. Previously it was set to use CTRL-ENTER. If you change the key combination in the shortcut mapper then your TAB key should start working again, and QuickText should also work (with whatever new key you've assigned).
Use ternary operator:
echo (($test == '') ? $redText : '');
echo $test == '' ? $redText : ''; //removed parenthesis
But in this case you can't use shorter reversed version because it will return bool(true)
in first condition.
echo (($test != '') ?: $redText); //this will not work properly for this case
You don't have to know what ports are open on your local machine to connect to some remote TCP service (unless you want to use a specific local port, but usually that is not the case).
Every TCP/IP connection is identified by 4 values: remote IP, remote port number, local IP, local port number, but you only need to know remote IP and remote port number to establish a connection.
When you create tcp connection using
TcpClient c; c = new TcpClient(remote_ip, remote_port);
Your system will automatically assign one of many free local port numbers to your connection. You don't need to do anything. You might also want to check if a remote port is open. but there is no better way to do that than just trying to connect to it.
The profile choices need to be setup as a ManyToManyField for this to work correctly.
So... your model should be like this:
class Choices(models.Model):
description = models.CharField(max_length=300)
class Profile(models.Model):
user = models.ForeignKey(User, blank=True, unique=True, verbose_name='user')
choices = models.ManyToManyField(Choices)
Then, sync the database and load up Choices with the various options you want available.
Now, the ModelForm will build itself...
class ProfileForm(forms.ModelForm):
Meta:
model = Profile
exclude = ['user']
And finally, the view:
if request.method=='POST':
form = ProfileForm(request.POST)
if form.is_valid():
profile = form.save(commit=False)
profile.user = request.user
profile.save()
else:
form = ProfileForm()
return render_to_response(template_name, {"profile_form": form}, context_instance=RequestContext(request))
It should be mentioned that you could setup a profile in a couple different ways, including inheritance. That said, this should work for you as well.
Good luck.
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 certificate in store.Certificates){
//TODO's
}
I did 2 things to solve this problem.
EDITOR=emacs crontab -e
(I have no idea why vim does not work)crontab -l
now prints the cronjobs. Now I only need to figure out why the cronjobs are still not running ;-)
I know this is an old post, probably no one would scroll this far, I know I didn't. So, after hours of trying different stuff, I found this blog and dude killed it. Simplest way to do this, tried it and it works like a charm.
In the ViewModel:
...
public bool CanClose { get; set; }
private RelayCommand closeCommand;
public ICommand CloseCommand
{
get
{
if(closeCommand == null)
(
closeCommand = new RelayCommand(param => Close(), param => CanClose);
)
}
}
public void Close()
{
this.Close();
}
...
add an Action property to the ViewModel, but define it from the View’s code-behind file. This will let us dynamically define a reference on the ViewModel that points to the View.
On the ViewModel, we’ll simply add:
public Action CloseAction { get; set; }
And on the View, we’ll define it as such:
public View()
{
InitializeComponent() // this draws the View
ViewModel vm = new ViewModel(); // this creates an instance of the ViewModel
this.DataContext = vm; // this sets the newly created ViewModel as the DataContext for the View
if ( vm.CloseAction == null )
vm.CloseAction = new Action(() => this.Close());
}
Remove the definitions and check if the conditional is on debug mode. You do not need to check if the directive is on release mode.
Something like this:
#if DEBUG
Console.WriteLine("Mode=Debug");
#else
Console.WriteLine("Mode=Release");
#endif
I have same problem but in my case By mistake I added a context in server.xml ($Tomcat_Install_Dir/conf/) and doesn't deployed corresponing war in webapps($Tomcat_Install_Dir/webapps). As I removed that context and restarted tomcat it working fine.
From commons-lang3
org.apache.commons.lang3.text.WordUtils.capitalizeFully(String str)
Immutable version, no side effects (doesn’t mutate original array):
const testArr = [1, 2, 3, 4, 5];
function move(from, to, arr) {
const newArr = [...arr];
const item = newArr.splice(from, 1)[0];
newArr.splice(to, 0, item);
return newArr;
}
console.log(move(3, 1, testArr));
// [1, 4, 2, 3, 5]
codepen: https://codepen.io/mliq/pen/KKNyJZr
You should grab a copy of Erica Sadun's mdhelper command line utility (OS X binary & source). It supports listing and extracting the contents of iPhone/iPod Touch backups, including address book & SMS databases, and other application metadata and settings.
Probably there are some files inside C:\cygwin\bin called xxxxxmake.exe
, try renaming it to make.exe
Best to avoid placing the right column before the left, simply use a negative right-margin.
And be "responsive" by including an @media setting so the right column falls under the left on narrow screens.
<div style="background: #f1f2ea;">
<div id="container">
<div id="content">
<strong>Column 1 - content</strong>
</div>
</div>
<div id="sidebar">
<strong>Column 2 - sidebar</strong>
</div>
<div style="clear:both"></div>
<style type="text/css">
#container {
margin-right: -300px;
float:left;
width:100%;
}
#content {
margin-right: 320px; /* 20px added for center margin */
}
#sidebar {
width:300px;
float:left
}
@media (max-width: 480px) {
#container {
margin-right:0px;
margin-bottom:20px;
}
#content {
margin-right:0px;
width:100%;
}
#sidebar {
clear:left;
}
}
</style>
Are you wanting to take control of the back button behavior? You can override the back button (to go to a specific activity) via one of two methods.
For Android 1.6 and below:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
// do something on back.
return true;
}
return super.onKeyDown(keyCode, event);
}
Or if you are only supporting Android 2.0 or greater:
@Override
public void onBackPressed() {
// do something on back.
return;
}
For more details: http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html
I have solved this if you are using array called for 2 tables. Example you have,
$tableA['yellow']
and $tableA['blue']
. You are getting these 2 values and you want to add another element inside them to separate them by their type
.
foreach ($tableA['yellow'] as $value) {
$value->type = 'YELLOW'; //you are adding new element named 'type'
}
foreach ($tableA['blue'] as $value) {
$value->type = 'BLUE'; //you are adding new element named 'type'
}
So, both of the tables value will have new element called type
.
You can use functional interfaces as mentioned above. below are some of the examples
Function<Integer, Integer> f1 = num->(num*2+1);
System.out.println(f1.apply(10));
Predicate<Integer> f2= num->(num > 10);
System.out.println(f2.test(10));
System.out.println(f2.test(11));
Supplier<Integer> f3= ()-> 100;
System.out.println(f3.get());
Hope it helps
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
int[] arr= stream.mapToInt(x->x.intValue()).toArray();
You don't need to install curl
to download the file into Docker container, use ADD
command, e.g.
ADD https://raw.githubusercontent.com/Homebrew/install/master/install /tmp
RUN ruby -e /tmp/install
Note: Add above lines to your Dockerfile
file.
Another example which installs Azure CLI:
ADD https://aka.ms/InstallAzureCLIDeb /tmp
RUN bash /tmp/InstallAzureCLIDeb
Generally I'd recommend something cross-platform like cURL, POCO, or Qt. However, here is a Windows example!:
#include <atlbase.h>
#include <msxml6.h>
#include <comutil.h> // _bstr_t
HRESULT hr;
CComPtr<IXMLHTTPRequest> request;
hr = request.CoCreateInstance(CLSID_XMLHTTP60);
hr = request->open(
_bstr_t("GET"),
_bstr_t("https://www.google.com/images/srpr/logo11w.png"),
_variant_t(VARIANT_FALSE),
_variant_t(),
_variant_t());
hr = request->send(_variant_t());
// get status - 200 if succuss
long status;
hr = request->get_status(&status);
// load image data (if url points to an image)
VARIANT responseVariant;
hr = request->get_responseStream(&responseVariant);
IStream* stream = (IStream*)responseVariant.punkVal;
CImage *image = new CImage();
image->Load(stream);
stream->Release();
You can use memset
with the size of the struct:
struct x x_instance;
memset (&x_instance, 0, sizeof(x_instance));
for i in range(100):
if i == 50:
continue
dosomething
I finally figured out a how to use Maven. From within Eclipse, create a new Maven project.
Download Maven, extract the archive, add the /bin
folder to path.
Validate install from command-line by running mvn -v
(will print version and java install path)
Change to the project root folder (where pom.xml
is located) and run:
mvn dependency:copy-dependencies
All jar-files are downloaded to /target/dependency
.
To set another output directory:
mvn dependency:copy-dependencies -DoutputDirectory="c:\temp"
Now it's possible to re-use this Maven-project for all dependency downloads by altering the pom.xml
Add jars to java project by build path -> configure build path -> libraries -> add JARs..
Unfortunately node does not support for each ... in
, even though it is specified in JavaScript 1.6. Chrome uses the same JavaScript engine and is reported as having a similar shortcoming.
You'll have to settle for array.forEach(function(item) { /* etc etc */ })
.
EDIT: From Google's official V8 website:
V8 implements ECMAScript as specified in ECMA-262.
On the same MDN website where it says that for each ...in
is in JavaScript 1.6, it says that it is not in any ECMA version - hence, presumably, its absence from Node.
Multiply your rating by 2, then round using Math.Round(rating, MidpointRounding.AwayFromZero)
, then divide that value by 2.
Math.Round(value * 2, MidpointRounding.AwayFromZero) / 2
Update : In angular 7, they are the same as 6
In angular 6
the complete answer found in live example
/** POST: add a new hero to the database */
addHero (hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
catchError(this.handleError('addHero', hero))
);
}
/** GET heroes from the server */
getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
catchError(this.handleError('getHeroes', []))
);
}
it's because of pipeable/lettable operators
which now angular is able to use tree-shakable
and remove unused imports and optimize the app
some rxjs functions are changed
do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize
more in MIGRATION
and Import paths
For JavaScript developers, the general rule is as follows:
rxjs: Creation methods, types, schedulers and utilities
import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent } from 'rxjs';
rxjs/operators: All pipeable operators:
import { map, filter, scan } from 'rxjs/operators';
rxjs/webSocket: The web socket subject implementation
import { webSocket } from 'rxjs/webSocket';
rxjs/ajax: The Rx ajax implementation
import { ajax } from 'rxjs/ajax';
rxjs/testing: The testing utilities
import { TestScheduler } from 'rxjs/testing';
and for backward compatability you can use rxjs-compat
As of 6-6-15 the Web Root location is at /tmp/deployment/application/ROOT using Tomcat.
That directory is part of your user data and you can delete any user data without affecting Xcode seriously. You can delete the whole CoreSimulator/ directory. Xcode will recreate fresh instances there for you when you do your next simulator run. If you can afford losing any previous simulator data of your apps this is the easy way to get space.
Update: A related useful app is "DevCleaner for Xcode" https://apps.apple.com/app/devcleaner-for-xcode/id1388020431
PrimeAdapter
By using PrimeAdapter, handling dividers in RecyclerView
s could be so simple. It provides multiple functionality and more flexibility to create and manage dividers.
You can create an adapter as following: (Please see complete doc about usage in github)
val adapter = PrimeAdapter.with(recyclerView)
.setLayoutManager(LinearLayoutManager(activity))
.set()
.build(ActorAdapter::class.java)
After creating an adapter instance, you can simply add divider simply by using:
//----- default divider:
adapter.setDivider()
//----- divider with custom drawable:
adapter.setDivider(ContextCompat.getDrawable(context, R.drawable.divider))
//----- divider with custom color:
adapter.setDivider(Color.RED)
//----- divider with custom color and custom inset:
adapter.setDivider(Color.RED, insetLeft = 16, insetRight = 16)
//----- deactivate dividers:
adapter.setDivider(null)
Downloading Wget is not necessary; the .NET Framework has web client classes built in.
$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")
Java supports two types of comments:
/* multiline comment */
: The compiler ignores everything from /*
to */
. The comment can span over multiple lines.
// single line
: The compiler ignores everything from //
to the end of the line.
Some tool such as javadoc use a special multiline comment for their purpose. For example /** doc comment */
is a documentation comment used by javadoc when preparing the automatically generated documentation, but for Java it's a simple multiline comment.
It sounds like you're not fully appreciating the difference between synchronous and asynchronous function execution.
The code you provided in your update immediately executes each of your callback functions, which in turn immediately start an animation. The animations, however, execute asyncronously. It works like this:
setTimeout
with a function containing the next animation step and a delaysetTimeout
executes This continues until the last step in the animation completes. In the meantime, your synchronous functions have long ago completed. In other words, your call to the animate
function doesn't really take 3 seconds. The effect is simulated with delays and callbacks.
What you need is a queue. Internally, jQuery queues the animations, only executing your callback once its corresponding animation completes. If your callback then starts another animation, the effect is that they are executed in sequence.
In the simplest case this is equivalent to the following:
window.setTimeout(function() {
alert("!");
// set another timeout once the first completes
window.setTimeout(function() {
alert("!!");
}, 1000);
}, 3000); // longer, but first
Here's a general asynchronous looping function. It will call the given functions in order, waiting for the specified number of seconds between each.
function loop() {
var args = arguments;
if (args.length <= 0)
return;
(function chain(i) {
if (i >= args.length || typeof args[i] !== 'function')
return;
window.setTimeout(function() {
args[i]();
chain(i + 1);
}, 2000);
})(0);
}
Usage:
loop(
function() { alert("sam"); },
function() { alert("sue"); });
You could obviously modify this to take configurable wait times or to immediately execute the first function or to stop executing when a function in the chain returns false
or to apply
the functions in a specified context or whatever else you might need.
I know this is quite an old question -
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Let's say, you want to extract the first 2 rows and first 3 columns
A_NEW = A[0:2, 0:3]
A_NEW = [[1, 2, 3],
[4, 5, 6]]
Understanding the syntax
A_NEW = A[start_index_row : stop_index_row,
start_index_column : stop_index_column)]
If one wants row 2 and column 2 and 3
A_NEW = A[1:2, 1:3]
Reference the numpy indexing and slicing article - Indexing & Slicing
Add the following code to the top of your Markdown files to get MathJax rendering support
<style TYPE="text/css">
code.has-jax {font: inherit; font-size: 100%; background: inherit; border: inherit;}
</style>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [['$','$'], ['\\(','\\)']],
skipTags: ['script', 'noscript', 'style', 'textarea', 'pre'] // removed 'code' entry
}
});
MathJax.Hub.Queue(function() {
var all = MathJax.Hub.getAllJax(), i;
for(i = 0; i < all.length; i += 1) {
all[i].SourceElement().parentNode.className += ' has-jax';
}
});
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-AMS_HTML-full"></script>
and then `$x^2$` or `$$x^2$$` will render as expected :-)
You can always install a local version of MathJax if you don't want to use the online distribution, but you might need to host it through a local webserver.
UPDATE: these days I just use pandoc instead of canonical markdown, but the above is still useful.
In my case below exclusion works!!
<dependency>
<groupId>com.xyz.util</groupId>
<artifactId>xyz-web-util</artifactId>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
Be aware that there is org.codehaus.jackson.annotate.JsonProperty
in Jackson 1.x and com.fasterxml.jackson.annotation.JsonProperty
in Jackson 2.x. Check which ObjectMapper you are using (from which version), and make sure you use the proper annotation.
Quoting from the gcc website:
C++11 features are available as part of the "mainline" GCC compiler in the trunk of GCC's Subversion repository and in GCC 4.3 and later. To enable C++0x support, add the command-line parameter -std=c++0x to your g++ command line. Or, to enable GNU extensions in addition to C++0x extensions, add -std=gnu++0x to your g++ command line. GCC 4.7 and later support -std=c++11 and -std=gnu++11 as well.
So probably you use a version of g++ which doesn't support -std=c++11
. Try -std=c++0x
instead.
Availability of C++11 features is for versions >= 4.3 only.
Epydoc is a tool to generate API documentation from Python source code. It also generates UML class diagrams, using Graphviz in fancy ways. Here is an example of diagram generated from the source code of Epydoc itself.
Because Epydoc performs both object introspection and source parsing it can gather more informations respect to static code analysers such as Doxygen: it can inspect a fair amount of dynamically generated classes and functions, but can also use comments or unassigned strings as a documentation source, e.g. for variables and class public attributes.
Most of the above solutions assume that the parent DateGridView
has .AutoSizeMode
not equal to Fill
. If you set the .AutoSizeMode
for the grid to be Fill
, you need to set the AutoSizeMode for each column to be None
if you want to fix a particular column width (and let the other columns Fill). I found a weird MS exception regarding a null object if you change a Column Width and the .AutoSizeMode
is not None
first.
This works
chart.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
... add some columns here
chart.Column[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
chart.Column[i].Width = 60;
This throws a null exception regarding some internal object regarding setting border thickness.
chart.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
... add some columns here
// chart.Column[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
chart.Column[i].Width = 60;
// This is a working Notification
private static final int NotificID=01;
b= (Button) findViewById(R.id.btn);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Notification notification=new Notification.Builder(MainActivity.this)
.setContentTitle("Notification Title")
.setContentText("Notification Description")
.setSmallIcon(R.mipmap.ic_launcher)
.build();
NotificationManager notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notification.flags |=Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(NotificID,notification);
}
});
}
You can do this with PARTITION
and RANK
:
select * from
(
select MyPK, fmgcms_cpeclaimid, createdon,
Rank() over (Partition BY fmgcms_cpeclaimid order by createdon DESC) as Rank
from Filteredfmgcms_claimpaymentestimate
where createdon < 'reportstartdate'
) tmp
where Rank = 1
Well, i guess M represent the mantissa. Decimal can be used to save money, but it doesn't mean, decimal only used for money.
git
isn't a centralized scm like svn
so you have two options:
It may be annoying to implement for many different platforms (GitHub, GitLab, BitBucket, SourceForge, Launchpad, Gogs, ...) but fetching data is pretty slow (we talk about seconds) - no solution is perfect.
An example with fetching into a temporary directory:
git clone https://github.com/rust-lang/rust.git -b master --depth 3 --bare --filter=blob:none -q .
git log -n 3 --no-decorate --format=oneline
Alternatively:
git init --bare -q
git remote add -t master origin https://github.com/rust-lang/rust.git
git fetch --depth 3 --filter=blob:none -q
git log -n 3 --no-decorate --format=oneline origin/master
Both are optimized for performance by restricting to exactly 3 commits of one branch into a minimal local copy without file contents and preventing console outputs. Though opening a connection and calculating deltas during fetch takes some time.
An example with GitHub:
GET https://api.github.com/repos/rust-lang/rust/commits?sha=master&per_page=3
An example with GitLab:
GET https://gitlab.com/api/v4/projects/inkscape%2Finkscape/repository/commits?ref_name=master&per_page=3
Both are really fast but have different interfaces (like every platform).
Disclaimer: Rust and Inkscape were chosen because of their size and safety to stay, no advertisement
You can check out libvideo. It's much more up-to-date than YoutubeExtractor, and is fast and clean to use.
Everywhere inside the query string, the wildcard should be ?
instead of '?'
. That should solve the problem.
EDIT :
To add to that, you need to change date '?'
to to_date(?, 'yyyy-mm-dd')
. Please try that and let me know.
signal
isn't the most reliable way as it differs in implementations. I would recommend using sigaction
. Tom's code would now look like this :
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
void my_handler(int s){
printf("Caught signal %d\n",s);
exit(1);
}
int main(int argc,char** argv)
{
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = my_handler;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
pause();
return 0;
}
You could change the ul
and li
displays to table
and table-cell
. Then, vertical-align
would work for you:
ul {
height: 20%;
width: 100%;
display: table;
}
li {
display: table-cell;
text-align: center;
vertical-align: middle;
background: silver;
width: 100%;
}
Another thing to check is a combination of previous entries
You can have in your web.xml file this:
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.acme.rest</param-value>
</init-param>
and you can have
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>resteasy.scan.providers</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>resteasy.scan.resources</param-name>
<param-value>false</param-value>
</context-param>
but you cannot have both or you get this sort of error. The fix in this case would be to comment out one or the other (probably the first code snippet would be commented out)
My requirement is to display 10 digit phone number in the jsp. So here's the setup for me.
MySQL: numeric(10)
Java Side:
@NumberFormat(pattern = "#")
private long mobileNumber;
and it worked!
Found the code that I referred to in my comment above. To test it, do this:
Sheet1
change the cell height and width of say A1
as shown in the snapshot below. Start Timer
button on the sheet and click on Assign Macros
. Select StartTimer
macro.End Timer
button on the sheet and click on Assign Macros
. Select EndTimer
macro.Now click on Start Timer button and you will see the time getting updated in cell A1
. To stop time updates, Click on End Timer button.
Code (TRIED AND TESTED)
Public Declare Function SetTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long, _
ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long
Public Declare Function KillTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long) As Long
Public TimerID As Long, TimerSeconds As Single, tim As Boolean
Dim Counter As Long
'~~> Start Timer
Sub StartTimer()
'~~ Set the timer for 1 second
TimerSeconds = 1
TimerID = SetTimer(0&, 0&, TimerSeconds * 1000&, AddressOf TimerProc)
End Sub
'~~> End Timer
Sub EndTimer()
On Error Resume Next
KillTimer 0&, TimerID
End Sub
Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, _
ByVal nIDEvent As Long, ByVal dwTimer As Long)
'~~> Update value in Sheet 1
Sheet1.Range("A1").Value = Time
End Sub
SNAPSHOT
A variation of DixonD's excellent answer (above).
public static bool TryOpen(string path,
FileMode fileMode,
FileAccess fileAccess,
FileShare fileShare,
TimeSpan timeout,
out Stream stream)
{
var endTime = DateTime.Now + timeout;
while (DateTime.Now < endTime)
{
if (TryOpen(path, fileMode, fileAccess, fileShare, out stream))
return true;
}
stream = null;
return false;
}
public static bool TryOpen(string path,
FileMode fileMode,
FileAccess fileAccess,
FileShare fileShare,
out Stream stream)
{
try
{
stream = File.Open(path, fileMode, fileAccess, fileShare);
return true;
}
catch (IOException e)
{
if (!FileIsLocked(e))
throw;
stream = null;
return false;
}
}
private const uint HRFileLocked = 0x80070020;
private const uint HRPortionOfFileLocked = 0x80070021;
private static bool FileIsLocked(IOException ioException)
{
var errorCode = (uint)Marshal.GetHRForException(ioException);
return errorCode == HRFileLocked || errorCode == HRPortionOfFileLocked;
}
Usage:
private void Sample(string filePath)
{
Stream stream = null;
try
{
var timeOut = TimeSpan.FromSeconds(1);
if (!TryOpen(filePath,
FileMode.Open,
FileAccess.ReadWrite,
FileShare.ReadWrite,
timeOut,
out stream))
return;
// Use stream...
}
finally
{
if (stream != null)
stream.Close();
}
}
You want a multiple attribute selector
$("input[type='checkbox'][name='ProductCode']").each(function(){ ...
or
$("input:checkbox[name='ProductCode']").each(function(){ ...
It would be better to use a CSS class to identify those that you want to select however as a lot of the modern browsers implement the document.getElementsByClassName
method which will be used to select elements and be much faster than selecting by the name
attribute
If you're open to using jQuery:
<script type="text/javascript">
function fncsave()
{
$('#<%= savebtn.ClientID %>').click();
}
</script>
Also, if you are using .NET 4 or better you can make the ClientIDMode == static
and simplify the code:
<script type="text/javascript">
function fncsave()
{
$("#savebtn").click();
}
</script>
Reference: MSDN Article for Control.ClientIDMode
Individual components of a filename (i.e. each subdirectory along the path, and the final filename) are limited to 255 characters, and the total path length is limited to approximately 32,000 characters.
However, on Windows, you can't exceed MAX_PATH
value (259 characters for files, 248 for folders). See http://msdn.microsoft.com/en-us/library/aa365247.aspx for full details.
Use:
compile 'com.google.firebase:firebase-auth:11.0.4'
This works.
Rowz = Application.WorksheetFunction.Subtotal(2, Range("A2:A" & Rows(Rows.Count).End(xlUp).Row))
This worked for me quite well
Try creating another SQL view instead of a temporary table and then referencing it in the main SQL view. In other words, a view within a view. You can then drop the first view once you are done creating the main view.
Angular does not support this kind of query string.
The query part of the URL is supposed to be a &
-separated sequence of key-value pairs, thus perfectly interpretable as an object.
There is no API at all to manage query strings that do not represent sets of key-value pairs.
EDIT: Below was the preferred solution in 2014. Nowadays you should use @include
, as mentioned in the other answer.
In Laravel views the dot is used as folder separator. So for example I have this code
return View::make('auth.details', array('id' => $id));
which points to app/views/auth/details.blade.php
And to include a view inside a view you do like this:
file: layout.blade.php
<html>
<html stuff>
@yield('content')
</html>
file: hello.blade.php
@extends('layout')
@section('content')
<html stuff>
@stop
Test step/scenario:
1. Open a browser and navigate to TestURL
2. Maximize the browser
Maximize the browser with C# (.NET):
driver.Manage().Window.Maximize();
Maximize the browser with Java :
driver.manage().window().maximize();
Another way to do with Java:
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenResolution = new Dimension((int)
toolkit.getScreenSize().getWidth(), (int)
toolkit.getScreenSize().getHeight());
driver.manage().window().setSize(screenResolution);
You need DATE_ADD/DATE_SUB
:
AND v.date > (DATE_SUB(CURDATE(), INTERVAL 2 MONTH))
AND v.date < (DATE_SUB(CURDATE(), INTERVAL 1 MONTH))
should work.
<img style="float: right;" alt="" src="http://example.com/image.png" />
<div style="clear: right">
...text...
</div>
khichar.anil covered most of this in his answer.
I am just adding the flag that will remove the tags from the revision names list. This gives us:
git name-rev --name-only --exclude=tags/* $SHA
Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.
UPD 19.03.2019 Here is a version for browser on GitHub.
Assuming there is a table config
with unique index on config_code
column:
CONFIG_CODE PARAM1 PARAM2
--------------- -------- --------
default_config def 000
config1 abc 123
config2 def 456
This query returns line for config1
values, because it exists in the table:
SELECT *
FROM (SELECT *
FROM config
WHERE config_code = 'config1'
OR config_code = 'default_config'
ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END)
WHERE rownum = 1;
CONFIG_CODE PARAM1 PARAM2
--------------- -------- --------
config1 abc 123
This one returns default record as config3
doesn't exist in the table:
SELECT *
FROM (SELECT *
FROM config
WHERE config_code = 'config3'
OR config_code = 'default_config'
ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END)
WHERE rownum = 1;
CONFIG_CODE PARAM1 PARAM2
--------------- -------- --------
default_config def 000
In comparison with other solutions this one queries table config
only once.
I thing ng-if
should work:
<div ng-repeat="product in products" ng-if="product.color === 'red'
|| product.color === 'blue'">
NOTE: This answer addresses enterprise-class development in-the-large.
This is an RDBMS issue, not just SQL Server, and the behavior can be very interesting. For one, while it is common for primary keys to be automatically (uniquely) indexed, it is NOT absolute. There are times when it is essential that a primary key NOT be uniquely indexed.
In most RDBMSs, a unique index will automatically be created on a primary key if one does not already exist. Therefore, you can create your own index on the primary key column before declaring it as a primary key, then that index will be used (if acceptable) by the database engine when you apply the primary key declaration. Often, you can create the primary key and allow its default unique index to be created, then create your own alternate index on that column, then drop the default index.
Now for the fun part--when do you NOT want a unique primary key index? You don't want one, and can't tolerate one, when your table acquires enough data (rows) to make the maintenance of the index too expensive. This varies based on the hardware, the RDBMS engine, characteristics of the table and the database, and the system load. However, it typically begins to manifest once a table reaches a few million rows.
The essential issue is that each insert of a row or update of the primary key column results in an index scan to ensure uniqueness. That unique index scan (or its equivalent in whichever RDBMS) becomes much more expensive as the table grows, until it dominates the performance of the table.
I have dealt with this issue many times with tables as large as two billion rows, 8 TBs of storage, and forty million row inserts per day. I was tasked to redesign the system involved, which included dropping the unique primary key index practically as step one. Indeed, dropping that index was necessary in production simply to recover from an outage, before we even got close to a redesign. That redesign included finding other ways to ensure the uniqueness of the primary key and to provide quick access to the data.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
May be am late to answer this question. But still someone may get benefit out of my answer.
I had similar issue and in my case I can not change the directive since, it is a library and change a code of the library is not a good practice. So what I did was use a variable to wait for page load and use ng-if inside my html to wait render the particular element.
In my controller:
$scope.render=false;
//this will fire after load the the page
angular.element(document).ready(function() {
$scope.render=true;
});
In my html (in my case html component is a canvas)
<canvas ng-if="render"> </canvas>
This will help you to change the name for "no file choose to Select profile picture"
<input type='file'id="files" class="hidden"/>
<label for="files">Select profile picture</label>
you can use two different methods to delete or any query in sqlite android
first method is
public void deleteItem(Student item) {
SQLiteDatabase db = getWritableDatabase();
String whereClause = "id=?";
String whereArgs[] = {item.id.toString()};
db.delete("Items", whereClause, whereArgs);
}
second method
public void deleteAll()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ TABLE_NAME);
db.close();
}
use any method for your use case
Not something completely different, just a bit rewritten recipe from Cookbook. It's futhermore optimized by retaining setdefault
method, instead of each time getting it through the instance:
def inverse(mapping):
'''
A function to inverse mapping, collecting keys with simillar values
in list. Careful to retain original type and to be fast.
>> d = dict(a=1, b=2, c=1, d=3, e=2, f=1, g=5, h=2)
>> inverse(d)
{1: ['f', 'c', 'a'], 2: ['h', 'b', 'e'], 3: ['d'], 5: ['g']}
'''
res = {}
setdef = res.setdefault
for key, value in mapping.items():
setdef(value, []).append(key)
return res if mapping.__class__==dict else mapping.__class__(res)
Designed to be run under CPython 3.x, for 2.x replace mapping.items()
with mapping.iteritems()
On my machine runs a bit faster, than other examples here
Only a few characters in the Windows code page 1252 (Latin-1) are not allowed as names. Note that the Windows Explorer will strip leading spaces from names and not allow you to call a files space dot something (like ?.txt
), although this is allowed in the file system! Only a space and no file extension is invalid however.
If you create files through e.g. a Python script (this is what I did), then you can easily find out what is actually allowed and in what order the characters get sorted. The sort order varies based on your locale! Below are the results of my script, run with Python 2.7.15 on a German Windows 10 Pro 64bit:
Allowed:
32 20 SPACE
! 33 21 EXCLAMATION MARK
# 35 23 NUMBER SIGN
$ 36 24 DOLLAR SIGN
% 37 25 PERCENT SIGN
& 38 26 AMPERSAND
' 39 27 APOSTROPHE
( 40 28 LEFT PARENTHESIS
) 41 29 RIGHT PARENTHESIS
+ 43 2B PLUS SIGN
, 44 2C COMMA
- 45 2D HYPHEN-MINUS
. 46 2E FULL STOP
/ 47 2F SOLIDUS
0 48 30 DIGIT ZERO
1 49 31 DIGIT ONE
2 50 32 DIGIT TWO
3 51 33 DIGIT THREE
4 52 34 DIGIT FOUR
5 53 35 DIGIT FIVE
6 54 36 DIGIT SIX
7 55 37 DIGIT SEVEN
8 56 38 DIGIT EIGHT
9 57 39 DIGIT NINE
; 59 3B SEMICOLON
= 61 3D EQUALS SIGN
@ 64 40 COMMERCIAL AT
A 65 41 LATIN CAPITAL LETTER A
B 66 42 LATIN CAPITAL LETTER B
C 67 43 LATIN CAPITAL LETTER C
D 68 44 LATIN CAPITAL LETTER D
E 69 45 LATIN CAPITAL LETTER E
F 70 46 LATIN CAPITAL LETTER F
G 71 47 LATIN CAPITAL LETTER G
H 72 48 LATIN CAPITAL LETTER H
I 73 49 LATIN CAPITAL LETTER I
J 74 4A LATIN CAPITAL LETTER J
K 75 4B LATIN CAPITAL LETTER K
L 76 4C LATIN CAPITAL LETTER L
M 77 4D LATIN CAPITAL LETTER M
N 78 4E LATIN CAPITAL LETTER N
O 79 4F LATIN CAPITAL LETTER O
P 80 50 LATIN CAPITAL LETTER P
Q 81 51 LATIN CAPITAL LETTER Q
R 82 52 LATIN CAPITAL LETTER R
S 83 53 LATIN CAPITAL LETTER S
T 84 54 LATIN CAPITAL LETTER T
U 85 55 LATIN CAPITAL LETTER U
V 86 56 LATIN CAPITAL LETTER V
W 87 57 LATIN CAPITAL LETTER W
X 88 58 LATIN CAPITAL LETTER X
Y 89 59 LATIN CAPITAL LETTER Y
Z 90 5A LATIN CAPITAL LETTER Z
[ 91 5B LEFT SQUARE BRACKET
\\ 92 5C REVERSE SOLIDUS
] 93 5D RIGHT SQUARE BRACKET
^ 94 5E CIRCUMFLEX ACCENT
_ 95 5F LOW LINE
` 96 60 GRAVE ACCENT
a 97 61 LATIN SMALL LETTER A
b 98 62 LATIN SMALL LETTER B
c 99 63 LATIN SMALL LETTER C
d 100 64 LATIN SMALL LETTER D
e 101 65 LATIN SMALL LETTER E
f 102 66 LATIN SMALL LETTER F
g 103 67 LATIN SMALL LETTER G
h 104 68 LATIN SMALL LETTER H
i 105 69 LATIN SMALL LETTER I
j 106 6A LATIN SMALL LETTER J
k 107 6B LATIN SMALL LETTER K
l 108 6C LATIN SMALL LETTER L
m 109 6D LATIN SMALL LETTER M
n 110 6E LATIN SMALL LETTER N
o 111 6F LATIN SMALL LETTER O
p 112 70 LATIN SMALL LETTER P
q 113 71 LATIN SMALL LETTER Q
r 114 72 LATIN SMALL LETTER R
s 115 73 LATIN SMALL LETTER S
t 116 74 LATIN SMALL LETTER T
u 117 75 LATIN SMALL LETTER U
v 118 76 LATIN SMALL LETTER V
w 119 77 LATIN SMALL LETTER W
x 120 78 LATIN SMALL LETTER X
y 121 79 LATIN SMALL LETTER Y
z 122 7A LATIN SMALL LETTER Z
{ 123 7B LEFT CURLY BRACKET
} 125 7D RIGHT CURLY BRACKET
~ 126 7E TILDE
\x7f 127 7F DELETE
\x80 128 80 EURO SIGN
\x81 129 81
\x82 130 82 SINGLE LOW-9 QUOTATION MARK
\x83 131 83 LATIN SMALL LETTER F WITH HOOK
\x84 132 84 DOUBLE LOW-9 QUOTATION MARK
\x85 133 85 HORIZONTAL ELLIPSIS
\x86 134 86 DAGGER
\x87 135 87 DOUBLE DAGGER
\x88 136 88 MODIFIER LETTER CIRCUMFLEX ACCENT
\x89 137 89 PER MILLE SIGN
\x8a 138 8A LATIN CAPITAL LETTER S WITH CARON
\x8b 139 8B SINGLE LEFT-POINTING ANGLE QUOTATION
\x8c 140 8C LATIN CAPITAL LIGATURE OE
\x8d 141 8D
\x8e 142 8E LATIN CAPITAL LETTER Z WITH CARON
\x8f 143 8F
\x90 144 90
\x91 145 91 LEFT SINGLE QUOTATION MARK
\x92 146 92 RIGHT SINGLE QUOTATION MARK
\x93 147 93 LEFT DOUBLE QUOTATION MARK
\x94 148 94 RIGHT DOUBLE QUOTATION MARK
\x95 149 95 BULLET
\x96 150 96 EN DASH
\x97 151 97 EM DASH
\x98 152 98 SMALL TILDE
\x99 153 99 TRADE MARK SIGN
\x9a 154 9A LATIN SMALL LETTER S WITH CARON
\x9b 155 9B SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
\x9c 156 9C LATIN SMALL LIGATURE OE
\x9d 157 9D
\x9e 158 9E LATIN SMALL LETTER Z WITH CARON
\x9f 159 9F LATIN CAPITAL LETTER Y WITH DIAERESIS
\xa0 160 A0 NON-BREAKING SPACE
\xa1 161 A1 INVERTED EXCLAMATION MARK
\xa2 162 A2 CENT SIGN
\xa3 163 A3 POUND SIGN
\xa4 164 A4 CURRENCY SIGN
\xa5 165 A5 YEN SIGN
\xa6 166 A6 PIPE, BROKEN VERTICAL BAR
\xa7 167 A7 SECTION SIGN
\xa8 168 A8 SPACING DIAERESIS - UMLAUT
\xa9 169 A9 COPYRIGHT SIGN
\xaa 170 AA FEMININE ORDINAL INDICATOR
\xab 171 AB LEFT DOUBLE ANGLE QUOTES
\xac 172 AC NOT SIGN
\xad 173 AD SOFT HYPHEN
\xae 174 AE REGISTERED TRADE MARK SIGN
\xaf 175 AF SPACING MACRON - OVERLINE
\xb0 176 B0 DEGREE SIGN
\xb1 177 B1 PLUS-OR-MINUS SIGN
\xb2 178 B2 SUPERSCRIPT TWO - SQUARED
\xb3 179 B3 SUPERSCRIPT THREE - CUBED
\xb4 180 B4 ACUTE ACCENT - SPACING ACUTE
\xb5 181 B5 MICRO SIGN
\xb6 182 B6 PILCROW SIGN - PARAGRAPH SIGN
\xb7 183 B7 MIDDLE DOT - GEORGIAN COMMA
\xb8 184 B8 SPACING CEDILLA
\xb9 185 B9 SUPERSCRIPT ONE
\xba 186 BA MASCULINE ORDINAL INDICATOR
\xbb 187 BB RIGHT DOUBLE ANGLE QUOTES
\xbc 188 BC FRACTION ONE QUARTER
\xbd 189 BD FRACTION ONE HALF
\xbe 190 BE FRACTION THREE QUARTERS
\xbf 191 BF INVERTED QUESTION MARK
\xc0 192 C0 LATIN CAPITAL LETTER A WITH GRAVE
\xc1 193 C1 LATIN CAPITAL LETTER A WITH ACUTE
\xc2 194 C2 LATIN CAPITAL LETTER A WITH CIRCUMFLEX
\xc3 195 C3 LATIN CAPITAL LETTER A WITH TILDE
\xc4 196 C4 LATIN CAPITAL LETTER A WITH DIAERESIS
\xc5 197 C5 LATIN CAPITAL LETTER A WITH RING ABOVE
\xc6 198 C6 LATIN CAPITAL LETTER AE
\xc7 199 C7 LATIN CAPITAL LETTER C WITH CEDILLA
\xc8 200 C8 LATIN CAPITAL LETTER E WITH GRAVE
\xc9 201 C9 LATIN CAPITAL LETTER E WITH ACUTE
\xca 202 CA LATIN CAPITAL LETTER E WITH CIRCUMFLEX
\xcb 203 CB LATIN CAPITAL LETTER E WITH DIAERESIS
\xcc 204 CC LATIN CAPITAL LETTER I WITH GRAVE
\xcd 205 CD LATIN CAPITAL LETTER I WITH ACUTE
\xce 206 CE LATIN CAPITAL LETTER I WITH CIRCUMFLEX
\xcf 207 CF LATIN CAPITAL LETTER I WITH DIAERESIS
\xd0 208 D0 LATIN CAPITAL LETTER ETH
\xd1 209 D1 LATIN CAPITAL LETTER N WITH TILDE
\xd2 210 D2 LATIN CAPITAL LETTER O WITH GRAVE
\xd3 211 D3 LATIN CAPITAL LETTER O WITH ACUTE
\xd4 212 D4 LATIN CAPITAL LETTER O WITH CIRCUMFLEX
\xd5 213 D5 LATIN CAPITAL LETTER O WITH TILDE
\xd6 214 D6 LATIN CAPITAL LETTER O WITH DIAERESIS
\xd7 215 D7 MULTIPLICATION SIGN
\xd8 216 D8 LATIN CAPITAL LETTER O WITH SLASH
\xd9 217 D9 LATIN CAPITAL LETTER U WITH GRAVE
\xda 218 DA LATIN CAPITAL LETTER U WITH ACUTE
\xdb 219 DB LATIN CAPITAL LETTER U WITH CIRCUMFLEX
\xdc 220 DC LATIN CAPITAL LETTER U WITH DIAERESIS
\xdd 221 DD LATIN CAPITAL LETTER Y WITH ACUTE
\xde 222 DE LATIN CAPITAL LETTER THORN
\xdf 223 DF LATIN SMALL LETTER SHARP S
\xe0 224 E0 LATIN SMALL LETTER A WITH GRAVE
\xe1 225 E1 LATIN SMALL LETTER A WITH ACUTE
\xe2 226 E2 LATIN SMALL LETTER A WITH CIRCUMFLEX
\xe3 227 E3 LATIN SMALL LETTER A WITH TILDE
\xe4 228 E4 LATIN SMALL LETTER A WITH DIAERESIS
\xe5 229 E5 LATIN SMALL LETTER A WITH RING ABOVE
\xe6 230 E6 LATIN SMALL LETTER AE
\xe7 231 E7 LATIN SMALL LETTER C WITH CEDILLA
\xe8 232 E8 LATIN SMALL LETTER E WITH GRAVE
\xe9 233 E9 LATIN SMALL LETTER E WITH ACUTE
\xea 234 EA LATIN SMALL LETTER E WITH CIRCUMFLEX
\xeb 235 EB LATIN SMALL LETTER E WITH DIAERESIS
\xec 236 EC LATIN SMALL LETTER I WITH GRAVE
\xed 237 ED LATIN SMALL LETTER I WITH ACUTE
\xee 238 EE LATIN SMALL LETTER I WITH CIRCUMFLEX
\xef 239 EF LATIN SMALL LETTER I WITH DIAERESIS
\xf0 240 F0 LATIN SMALL LETTER ETH
\xf1 241 F1 LATIN SMALL LETTER N WITH TILDE
\xf2 242 F2 LATIN SMALL LETTER O WITH GRAVE
\xf3 243 F3 LATIN SMALL LETTER O WITH ACUTE
\xf4 244 F4 LATIN SMALL LETTER O WITH CIRCUMFLEX
\xf5 245 F5 LATIN SMALL LETTER O WITH TILDE
\xf6 246 F6 LATIN SMALL LETTER O WITH DIAERESIS
\xf7 247 F7 DIVISION SIGN
\xf8 248 F8 LATIN SMALL LETTER O WITH SLASH
\xf9 249 F9 LATIN SMALL LETTER U WITH GRAVE
\xfa 250 FA LATIN SMALL LETTER U WITH ACUTE
\xfb 251 FB LATIN SMALL LETTER U WITH CIRCUMFLEX
\xfc 252 FC LATIN SMALL LETTER U WITH DIAERESIS
\xfd 253 FD LATIN SMALL LETTER Y WITH ACUTE
\xfe 254 FE LATIN SMALL LETTER THORN
\xff 255 FF LATIN SMALL LETTER Y WITH DIAERESIS
Forbidden:
\x00 0 00 NULL CHAR
\x01 1 01 START OF HEADING
\x02 2 02 START OF TEXT
\x03 3 03 END OF TEXT
\x04 4 04 END OF TRANSMISSION
\x05 5 05 ENQUIRY
\x06 6 06 ACKNOWLEDGEMENT
\x07 7 07 BELL
\x08 8 08 BACK SPACE
\t 9 09 HORIZONTAL TAB
\n 10 0A LINE FEED
\x0b 11 0B VERTICAL TAB
\x0c 12 0C FORM FEED
\r 13 0D CARRIAGE RETURN
\x0e 14 0E SHIFT OUT / X-ON
\x0f 15 0F SHIFT IN / X-OFF
\x10 16 10 DATA LINE ESCAPE
\x11 17 11 DEVICE CONTROL 1 (OFT. XON)
\x12 18 12 DEVICE CONTROL 2
\x13 19 13 DEVICE CONTROL 3 (OFT. XOFF)
\x14 20 14 DEVICE CONTROL 4
\x15 21 15 NEGATIVE ACKNOWLEDGEMENT
\x16 22 16 SYNCHRONOUS IDLE
\x17 23 17 END OF TRANSMIT BLOCK
\x18 24 18 CANCEL
\x19 25 19 END OF MEDIUM
\x1a 26 1A SUBSTITUTE
\x1b 27 1B ESCAPE
\x1c 28 1C FILE SEPARATOR
\x1d 29 1D GROUP SEPARATOR
\x1e 30 1E RECORD SEPARATOR
\x1f 31 1F UNIT SEPARATOR
" 34 22 QUOTATION MARK
* 42 2A ASTERISK
: 58 3A COLON
< 60 3C LESS-THAN SIGN
> 62 3E GREATER-THAN SIGN
? 63 3F QUESTION MARK
| 124 7C VERTICAL LINE
Screenshot of how Explorer sorts the files for me:
The highlighted file with the ? white smiley face was added manually by me (Alt+1) to show where this Unicode character (U+263A) ends up, see Jimbugs' answer.
The first file has a space as name (0x20), the second is the non-breaking space (0xa0). The files in the bottom half of the third row which look like they have no name use the characters with hex codes 0x81, 0x8D, 0x8F, 0x90, 0x9D (in this order from top to bottom).
video/mp4
should be used when you have video content in your file. If there is none, but there is audio, you should use audio/mp4
. If no audio and no video is used, for instance if the file contains only a subtitle track or a metadata track, the MIME should be application/mp4
.
Also, as a server, you should try to include the codecs
or profiles
parameters as defined in RFC6381, as this will help clients determine if they can play the file, prior to downloading it.