Angular treats all values as untrusted by default. When a value is inserted into the DOM from a template, via property, attribute, style, class binding, or interpolation, Angular sanitizes and escapes untrusted values.
So if you are manipulating DOM directly and inserting content it, you need to sanitize it otherwise Angular will through errors.
I have created the pipe SanitizeUrlPipe for this
import { PipeTransform, Pipe } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";
@Pipe({
name: "sanitizeUrl"
})
export class SanitizeUrlPipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) { }
transform(v: string): SafeHtml {
return this._sanitizer.bypassSecurityTrustResourceUrl(v);
}
}
and this is how you can use
<iframe [src]="url | sanitizeUrl" width="100%" height="500px"></iframe>
If you want to add HTML, then SanitizeHtmlPipe can help
import { PipeTransform, Pipe } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";
@Pipe({
name: "sanitizeHtml"
})
export class SanitizeHtmlPipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) { }
transform(v: string): SafeHtml {
return this._sanitizer.bypassSecurityTrustHtml(v);
}
}
Read more about angular security here.
If you're in control of the string, you could also use a 'Raw' string type:
>>> string = r"abcd\n"
>>> print(string)
abcd\n
function findSize() {
var fileInput = document.getElementById("fUpload");
try{
alert(fileInput.files[0].size); // Size returned in bytes.
}catch(e){
var objFSO = new ActiveXObject("Scripting.FileSystemObject");
var e = objFSO.getFile( fileInput.value);
var fileSize = e.size;
alert(fileSize);
}
}
From Mac OS Catalina .bash_profile is replaced with .zprofile
Step 1: Create a .zprofile
touch .zprofile
Step 2:
nano .zprofile
type below line in this
source ~/.bash_profile
and save(ctrl+o return ctrl+x)
Step 3: Restart your terminal
To Add Git Branch Name Now you can add below lines in .bash_profile
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h \[\033[32m\]\w - \$(parse_git_branch)\[\033[00m\] $ "
Restart your terminal this will work.
Note: Even you can rename .bash_profile to .zprofile that also works.
You can use following code snippet
((ch.qos.logback.classic.Logger)LoggerFactory.getLogger(packageName)).setLevel(ch.qos.logback.classic.Level.toLevel(logLevel));
I have not worked on my answer but the way I know it StaggridLayoutManager with no. of grid 1 can solve your problem as StaggridLayout will automatically adjust its height and width on the size of the content. if it works dont forget to check it as a right answer.Cheers..
Maybe this will help:
<select onchange="location = this.value;">
<option value="home.html">Home</option>
<option value="contact.html">Contact</option>
<option value="about.html">About</option>
</select>
I've been strugglin with this problem for hours till found this post. Just like @ligi said, some people have two SDK folders (Android Studio, which is bundled and Eclipse). The problem is that it doesn't matter if you downloaded the Google Play Services library on both SDK folders, your ANDROID_HOME enviroment variable must be pointing to the SDK folder used by the Android Studio.
SDK Folder A (Used on Eclipse)
SDK Folder B (Used on AS)
ANDROID_HOME=<path to SDK Folder B>
After change the path of this variable the error was gone.
For completeness, we should mention PEP3119 where ABC was introduced and compared with interfaces, and original Talin's comment.
The abstract class is not perfect interface:
But if you consider writing it your own way:
def some_function(self):
raise NotImplementedError()
interface = type(
'your_interface', (object,),
{'extra_func': some_function,
'__slots__': ['extra_func', ...]
...
'__instancecheck__': your_instance_checker,
'__subclasscheck__': your_subclass_checker
...
}
)
ok, rather as a class
or as a metaclass
and fighting with python to achieve the immutable object
and doing refactoring
...
you'll quite fast realize that you're inventing the wheel
to eventually achieve
abc.ABCMeta
abc.ABCMeta
was proposed as a useful addition of the missing interface functionality,
and that's fair enough in a language like python.
Certainly, it was able to be enhanced better whilst writing version 3, and adding new syntax and immutable interface concept ...
Conclusion:
The abc.ABCMeta IS "pythonic" interface in python
This works for me, the source is here
int MY_PERMISSIONS_REQUEST_CAMERA=0;
// Here, this is the current activity
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA))
{
}
else
{
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA );
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
If you really have to avoid operators then use Math.signum()
Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero.
EDIT : As per the comments, this works for only double and float values. For integer values you can use the method:
I usually set it to whatever I expect to be returned from the function.
If a string, than i will set it to an empty string ='', same for object ={} and array=[], integers = 0.
using this method saves me the need to check for null / undefined. my function will know how to handle string/array/object regardless of the result.
You can use these links to download Visual Studio 2015
Community Edition:
And for anyone in the future who might be looking for the other editions here are the links for them as well:
Professional Edition:
Enterprise Edition:
From: https://github.com/philipperemy/keras-visualize-activations/blob/master/read_activations.py
import keras.backend as K
def get_activations(model, model_inputs, print_shape_only=False, layer_name=None):
print('----- activations -----')
activations = []
inp = model.input
model_multi_inputs_cond = True
if not isinstance(inp, list):
# only one input! let's wrap it in a list.
inp = [inp]
model_multi_inputs_cond = False
outputs = [layer.output for layer in model.layers if
layer.name == layer_name or layer_name is None] # all layer outputs
funcs = [K.function(inp + [K.learning_phase()], [out]) for out in outputs] # evaluation functions
if model_multi_inputs_cond:
list_inputs = []
list_inputs.extend(model_inputs)
list_inputs.append(0.)
else:
list_inputs = [model_inputs, 0.]
# Learning phase. 0 = Test mode (no dropout or batch normalization)
# layer_outputs = [func([model_inputs, 0.])[0] for func in funcs]
layer_outputs = [func(list_inputs)[0] for func in funcs]
for layer_activations in layer_outputs:
activations.append(layer_activations)
if print_shape_only:
print(layer_activations.shape)
else:
print(layer_activations)
return activations
You say you want to delete any column with the title "Percent Margin of Error" so let's try to make this dynamic instead of naming columns directly.
Sub deleteCol()
On Error Resume Next
Dim wbCurrent As Workbook
Dim wsCurrent As Worksheet
Dim nLastCol, i As Integer
Set wbCurrent = ActiveWorkbook
Set wsCurrent = wbCurrent.ActiveSheet
'This next variable will get the column number of the very last column that has data in it, so we can use it in a loop later
nLastCol = wsCurrent.Cells.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
'This loop will go through each column header and delete the column if the header contains "Percent Margin of Error"
For i = nLastCol To 1 Step -1
If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) > 0 Then
wsCurrent.Columns(i).Delete Shift:=xlShiftToLeft
End If
Next i
End Sub
With this you won't need to worry about where you data is pasted/imported to, as long as the column headers are in the first row.
EDIT: And if your headers aren't in the first row, it would be a really simple change. In this part of the code: If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare)
change the "1" in Cells(1, i)
to whatever row your headers are in.
EDIT 2: Changed the For
section of the code to account for completely empty columns.
I had the same problem, there was no extension=php_soap.dll in my php.ini But this was because I had copied the php.ini from a old and previous php version (not a good idea). I found the dll in the ext directory so I just could put it myself into the php.ini extension=php_soap.dll After Apache restart all worked with soap :)
Try (maybe as root)
lsof -i -P
and grep the output for the port you are looking for.
For example to check for port 80 do
lsof -i -P | grep :80
MY PREFERRED METHOD is using fopen,fwrite and fclose [it will cost less CPU]
$f=fopen('myfile.txt','w');
fwrite($f,'new content');
fclose($f);
Warning for those using file_put_contents
It'll affect a lot in performance, for example [on the same class/situation] file_get_contents too: if you have a BIG FILE, it'll read the whole content in one shot and that operation could take a long waiting time
The .ToString()
method for reference types usually resolves back to System.Object.ToString()
unless you override it in a derived type (possibly using extension methods for the built-in types). The default behavior for this method is to output the name of the type on which it's called. So what you're seeing is expected behavior.
You could try something like string.Join(", ", myList.ToArray());
to achieve this. It's an extra step, but it could be put in an extension method on System.Collections.Generic.List<T>
to make it a bit easier. Something like this:
public static class GenericListExtensions
{
public static string ToString<T>(this IList<T> list)
{
return string.Join(", ", list);
}
}
(Note that this is free-hand and untested code. I don't have a compiler handy at the moment. So you'll want to experiment with it a little.)
Use Convert.ToDouble(value)
rather than (double)value
. It takes an object
and supports all of the types you asked for! :)
Also, your method is always returning a string
in the code above; I'd recommend having the method indicate so, and give it a more obvious name (public string FormatLargeNumber(object value)
)
By the way, a good tip on quickly selecting color on the newer versions of AS is simply to type #fff and then using the color picker on the side of the code to choose the one you want. Quick and easier than remembering all the color hexadecimals. For example:
android:background="#fff"
I have other methods for that, the first is :
public static void playAudio(String filePath){
try{
InputStream mus = new FileInputStream(new File(filePath));
AudioStream aud = new AudioStream(mus);
}catch(Exception e){
JOptionPane.showMessageDialig(null, "You have an Error");
}
And the second is :
try{
JFXPanel x = JFXPanel();
String u = new File("021.mp3").toURI().toString();
new MediaPlayer(new Media(u)).play();
} catch(Exception e){
JOPtionPane.showMessageDialog(null, e);
}
And if we want to make loop to this audio we use this method.
try{
AudioData d = new AudioStream(new FileInputStream(filePath)).getData();
ContinuousAudioDataStream s = new ContinuousAudioDataStream(d);
AudioPlayer.player.start(s);
} catch(Exception ex){
JOPtionPane.showMessageDialog(null, ex);
}
if we want to stop this loop we add this libreries in the try:
AudioPlayer.player.stop(s);
for this third method we add the folowing imports :
import java.io.FileInputStream;
import sun.audio.AudioData;
import sun.audio.AudioStream;
import sun.audio.ContinuousAudioDataStream;
Dates are stored in their timestamp format. If you want everything that belongs to a specific month, query for the start and the end of the month.
var start = new Date(2010, 11, 1);
var end = new Date(2010, 11, 30);
db.posts.find({created_on: {$gte: start, $lt: end}});
//taken from http://cookbook.mongodb.org/patterns/date_range/
Try this one:
$('body').tooltip({
selector: '[rel=tooltip]'
});
This is how I solved it:
Integer.toHexString(System.identityHashCode(object));
To answer the second part of this question, the two packages shown in pip list
but not pip freeze
are setuptools
(which is easy_install) and pip
itself.
It looks like pip freeze
just doesn't list packages that pip itself depends on. You may use the --all
flag to show also those packages.
From the documentation:
--all
Do not skip these packages in the output: pip, setuptools, distribute, wheel
You can also set
-Djava.net.useSystemProxies=true
On Windows and Linux this will use the system settings so you don't need to repeat yourself (DRY)
http://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html#Proxies
You can try like this:
Sum({Tablename.Columnname})
It will work without creating a summarize field in formulae.
Simple jQuery way:
This is what I use:
DictionaryObj being the JavaScript dictionary object you want to go through. And value, key of course being the names of them in the dictionary.
$.each(DictionaryObj, function (key, value) {
$("#storeDuplicationList")
.append($("<li></li>")
.attr("value", key)
.text(value));
});
After reading the Wikipedia page and other pages on real-time computing. I made the following inferences:
1> For a Hard real-time system, if the system fails to meet the deadline even once the system is considered to have Failed.
2> For a Firm real-time system, even if the system fails to meet the deadline, possibly more than once (i.e. for multiple requests), the system is not considered to have failed. Also, the responses for the requests (replies to a query, result of a task, etc.) are worthless once the deadline for that particular request has passed (The usefulness of a result is zero after its deadline). A hypothetical example can be a storm forecast system (if a storm is predicted before arrival, then the system has done its job, prediction after the event has already happened or when it is happening is of no value).
3> For a Soft real-time system, even if the system fails to meet the deadline, possibly more than once (i.e. for multiple requests), the system is not considered to have failed. But, in this case the results of the requests are not worthless value for a result after its deadline, is not zero, rather it degrades as time passes after the deadline. Eg.: Streaming audio-video.
Here is a link to a resource that was very helpful.
There's still one thing that is not highlighted enough, in my opinion, and that is unwanted inheritance.
Here's an incremental example:
I declare in my parent
pom:
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
</dependencies>
boom! I have it in my Child A
, Child B
and Child C
modules:
version 18.0
in a Child B
if I want to.But what if I end up not needing guava in Child C
, and neither in the future Child D
and Child E
modules?
They will still inherit it and this is undesired! This is just like Java God Object code smell, where you inherit some useful bits from a class, and a tonn of unwanted stuff as well.
This is where <dependencyManagement>
comes into play. When you add this to your parent pom, all of your child modules STOP seeing it. And thus you are forced to go into each individual module that DOES need it and declare it again (Child A
and Child B
, without the version though).
And, obviously, you don't do it for Child C
, and thus your module remains lean.
Take some base date which is the 31st of some month e.g. '20011231'. Then use the
following procedure (I have given 3 identical examples below, only the @dt value differs).
declare @dt datetime;
set @dt = '20140312'
SELECT DATEADD(month, DATEDIFF(month, '20011231', @dt), '20011231');
set @dt = '20140208'
SELECT DATEADD(month, DATEDIFF(month, '20011231', @dt), '20011231');
set @dt = '20140405'
SELECT DATEADD(month, DATEDIFF(month, '20011231', @dt), '20011231');
Pandas magic at work. All logic is out.
The error message "ValueError: If using all scalar values, you must pass an index"
Says you must pass an index.
This does not necessarily mean passing an index makes pandas do what you want it to do
When you pass an index, pandas will treat your dictionary keys as column names and the values as what the column should contain for each of the values in the index.
a = 2
b = 3
df2 = pd.DataFrame({'A':a,'B':b}, index=[1])
A B
1 2 3
Passing a larger index:
df2 = pd.DataFrame({'A':a,'B':b}, index=[1, 2, 3, 4])
A B
1 2 3
2 2 3
3 2 3
4 2 3
An index is usually automatically generated by a dataframe when none is given. However, pandas does not know how many rows of 2
and 3
you want. You can however be more explicit about it
df2 = pd.DataFrame({'A':[a]*4,'B':[b]*4})
df2
A B
0 2 3
1 2 3
2 2 3
3 2 3
The default index is 0 based though.
I would recommend always passing a dictionary of lists to the dataframe constructor when creating dataframes. It's easier to read for other developers. Pandas has a lot of caveats, don't make other developers have to experts in all of them in order to read your code.
I was uninstalled compass 1.0.1 and install compass 0.12.7, this fix problem for me
$ sudo gem uninstall compass
$ sudo gem install compass -v 0.12.7
You can limit the depth of the history while cloning:
--depth <depth>
Create a shallow clone with a history truncated to the specified
number of revisions.
Use this if you want limited history, but still some.
For your stated desire to "check if a property exists" you can directly use Lo-Dash's has
.
var exists = _.has(myObject, propertyNameToCheck);
Please also consider "salting" your hash (not a culinary concept!). Basically, that means appending some random text to the password before you hash it.
To store password hashes:
a) Generate a random salt value:
byte[] salt = new byte[32];
System.Security.Cryptography.RNGCryptoServiceProvider.Create().GetBytes(salt);
b) Append the salt to the password.
// Convert the plain string pwd into bytes
byte[] plainTextBytes = System.Text UnicodeEncoding.Unicode.GetBytes(plainText);
// Append salt to pwd before hashing
byte[] combinedBytes = new byte[plainTextBytes.Length + salt.Length];
System.Buffer.BlockCopy(plainTextBytes, 0, combinedBytes, 0, plainTextBytes.Length);
System.Buffer.BlockCopy(salt, 0, combinedBytes, plainTextBytes.Length, salt.Length);
c) Hash the combined password & salt:
// Create hash for the pwd+salt
System.Security.Cryptography.HashAlgorithm hashAlgo = new System.Security.Cryptography.SHA256Managed();
byte[] hash = hashAlgo.ComputeHash(combinedBytes);
d) Append the salt to the resultant hash.
// Append the salt to the hash
byte[] hashPlusSalt = new byte[hash.Length + salt.Length];
System.Buffer.BlockCopy(hash, 0, hashPlusSalt, 0, hash.Length);
System.Buffer.BlockCopy(salt, 0, hashPlusSalt, hash.Length, salt.Length);
e) Store the result in your user store database.
This approach means you don't need to store the salt separately and then recompute the hash using the salt value and the plaintext password value obtained from the user.
Edit: As raw computing power becomes cheaper and faster, the value of hashing -- or salting hashes -- has declined. Jeff Atwood has an excellent 2012 update too lengthy to repeat in its entirety here which states:
This (using salted hashes) will provide the illusion of security more than any actual security. Since you need both the salt and the choice of hash algorithm to generate the hash, and to check the hash, it's unlikely an attacker would have one but not the other. If you've been compromised to the point that an attacker has your password database, it's reasonable to assume they either have or can get your secret, hidden salt.
The first rule of security is to always assume and plan for the worst. Should you use a salt, ideally a random salt for each user? Sure, it's definitely a good practice, and at the very least it lets you disambiguate two users who have the same password. But these days, salts alone can no longer save you from a person willing to spend a few thousand dollars on video card hardware, and if you think they can, you're in trouble.
I'll tell you what worked for me:
int id = int.Parse(insertItem.OwnerTableView.DataKeyValues[insertItem.ItemIndex]["id_usuario"].ToString());
var query = user.First(x => x.id_usuario == id);
tbUsername.Text = query.username;
tbEmail.Text = query.email;
tbPassword.Text = query.password;
My id is the row I want to query, in this case I got it from a radGrid, then I used it to query, but this query returns a row, then you can assign the values you got from the query to textbox, or anything, I had to assign those to textbox.
Simplest way to create customize a progress bar in Android:
Initialize and show dialog:
MyProgressDialog progressdialog = new MyProgressDialog(getActivity());
progressdialog.show();
Create method:
public class MyProgressDialog extends AlertDialog {
public MyProgressDialog(Context context) {
super(context);
getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
}
@Override
public void show() {
super.show();
setContentView(R.layout.dialog_progress);
}
}
Create layout XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent"
android:clickable="true">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<ProgressBar
android:id="@+id/progressbarr"
android:layout_width="@dimen/eightfive"
android:layout_height="@dimen/eightfive"
android:layout_centerInParent="true"
android:indeterminateDrawable="@drawable/progresscustombg" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@+id/progressbarr"
android:layout_marginTop="@dimen/_3sdp"
android:textColor="@color/white"
android:text="Please wait"/>
</RelativeLayout>
</RelativeLayout>
Create shape progresscustombg.xml and put res/drawable:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="360" >
<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:thicknessRatio="20"
android:useLevel="false" >
<size
android:height="@dimen/eightfive"
android:width="@dimen/eightfive" />
<gradient
android:centerY="0.50"
android:endColor="@color/color_green_icash"
android:startColor="#FFFFFF"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
If you want to check if an element exists, just use the following code:
if (object) {
//if isset, return true
} else {
//else return false
}
This is sample:
function switchDiv() {_x000D_
if (document.querySelector("#divId")) {_x000D_
document.querySelector("#divId").remove();_x000D_
} else {_x000D_
var newDiv = document.createElement("div");_x000D_
newDiv.id = "divId";_x000D_
document.querySelector("body").appendChild(newDiv);_x000D_
}_x000D_
}_x000D_
_x000D_
document.querySelector("#btn").addEventListener("click", switchDiv);
_x000D_
#divId {_x000D_
background: red;_x000D_
height: 100px;_x000D_
width: 100px;_x000D_
position: relative;_x000D_
_x000D_
}
_x000D_
<body>_x000D_
<button id="btn">Let's Diiiv!</button>_x000D_
</body>
_x000D_
Same with something more complex...getting the ec2 instance region from within the instance.
INSTANCE_REGION=$(curl -s 'http://169.254.169.254/latest/dynamic/instance-identity/document' | python -c "import sys, json; print json.load(sys.stdin)['region']")
echo $INSTANCE_REGION
Blowfish isn't better than MD5 or SHA512, as they serve different purposes. MD5 and SHA512 are hashing algorithms, Blowfish is an encryption algorithm. Two entirely different cryptographic functions.
Some type of input hasn't got the :after or :before pseudo-element, so you can use a background-image with an SVG text element:
input {
background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='50px' width='120px'><text x='0' y='15' fill='gray' font-size='15'>Type Something...</text></svg>");
background-repeat: no-repeat;
}
input:focus {
background-image: none;
}
My codepen: https://codepen.io/Scario/pen/BaagbeZ
I had this error too, I changed the code like this then it worked.
html
<html ng-app="app">
<div ng-controller="firstCtrl">
...
</div>
</html>
app.js
(function(){
var app = angular.module('app',[]);
app.controller('firstCtrl',function($scope){
...
})
})();
You have to make sure that the name in module is same as ng-app
then div will be in the scope of firstCtrl
I received such an error in a Python-based web API's response .text
, but it led me here, so this may help others with a similar issue (it's very difficult to filter response and request issues in a search when using requests
..)
Using json.dumps()
on the request data
arg to create a correctly-escaped string of JSON before POSTing fixed the issue for me
requests.post(url, data=json.dumps(data))
Your problem is the typo in the function CreateDectionary().You should change it to CreateDictionary(). collect2: error: ld returned 1 exit status is the same problem in both C and C++, usually it means that you have unresolved symbols. In your case is the typo that i mentioned before.
You could raise SystemExit(0)
instead of going to all the trouble to import sys; sys.exit(0)
.
I think there is no need to specify
'http://localhost:8080`"
in the URI part.. because. if you specify it, You'll have to change it manually for every environment.
Only
"/restws/json/product/get" also works
We can not bind this to setTimeout()
, as it always execute with global object (Window), if you want to access this
context in the callback function then by using bind()
to the callback function we can achieve as:
setTimeout(function(){
this.methodName();
}.bind(this), 2000);
Try this, it will insert the list item at index 0;
DropDownList1.Items.Insert(0, new ListItem("Add New", ""));
Give Mobiscroll a try. The scroller style date and time picker was especially created for interaction on touch devices. It is pretty flexible, and easily customizable. It comes with iOS/Android themes.
If the row contains some leading (or trailing) th
tags before the td
you should use the :first-of-type
and the :last-of-type
selectors. Otherwise the first td
won't be selected if it's not the first element of the row.
This gives:
td:first-of-type, td:last-of-type {
/* styles */
}
One example is when you write a parser function and pass it a source pointer to read from, if the function is supposed to push that pointer forward behind the last character which has been correctly recognized by the parser. Using a reference to a pointer makes it clear then that the function will move the original pointer to update its position.
In general, you use references to pointers if you want to pass a pointer to a function and let it move that original pointer to some other position instead of just moving a copy of it without affecting the original.
I had this problem. I had the DLL included into the project and the setting to Copy Local was true by default. Don't know why it started, since that DLL was in the project for a long while. I've heard some mentions of ReSharper possibly removing it, but I can't say I've ran a unused reference removal.
What helped me was: - Running "Update-Package Microsoft.Web.Infrastructure -Reinstall" on the project, which updated the whole solution, but didn't end up helping in and of itself. - Then I went through the projects' references and set the Copy Local to false, and then back to true. This actually resulted in a line being added into CSPROJ file under the DLL reference: True. Or something along the lines... Either way, now the build was copying the files as expected.
Turns out I had a .csv file at the end of the folder from which I was reading all the images. Once I deleted that it worked alright
Make sure that it's all images and that you don't have any other type of file
Join like this:
ON a.userid = b.sourceid AND a.listid = b.destinationid;
You can use the --append
feature of tee
:
cat file01.txt | tee --append bothFiles.txt
cat file02.txt | tee --append bothFiles.txt
Or shorter,
cat file01.txt file02.txt | tee --append bothFiles.txt
I assume the request for no redirection (>>
) comes from the need to use this in xargs
or similar. So if that doesn't count, you can mute the output with >/dev/null
.
The RxJS functions need to be specifically imported. An easy way to do this is to import all of its features with import * as Rx from "rxjs/Rx"
Then make sure to access the Observable
class as Rx.Observable
.
Primary Key and Unique Key are Entity integrity constraints
Primary key allows each row in a table to be uniquely identified and ensures that no duplicate rows exist and no null values are entered.
Unique key constraint is used to prevent the duplication of key values within the rows of a table and allow null values. (In oracle one null is not equal to another null).
see Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL?
Ok, here's a simple box that follows the cursor
Doing the rest is a simple case of remembering the last cursor position and applying a formula to get the box to move other than exactly where the cursor is. A timeout would also be handy if the box has a limited acceleration and must catch up to the cursor after it stops moving. Replacing the box with an image is simple CSS (which can replace most of the setup code for the box). I think the actual thinking code in the example is about 8 lines.
Select the right image (use a sprite) to orientate the rocket.
Yeah, annoying as hell. :-)
function getMouseCoords(e) {
var e = e || window.event;
document.getElementById('container').innerHTML = e.clientX + ', ' +
e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}
var followCursor = (function() {
var s = document.createElement('div');
s.style.position = 'absolute';
s.style.margin = '0';
s.style.padding = '5px';
s.style.border = '1px solid red';
s.textContent = ""
return {
init: function() {
document.body.appendChild(s);
},
run: function(e) {
var e = e || window.event;
s.style.left = (e.clientX - 5) + 'px';
s.style.top = (e.clientY - 5) + 'px';
getMouseCoords(e);
}
};
}());
window.onload = function() {
followCursor.init();
document.body.onmousemove = followCursor.run;
}
_x000D_
#container {
width: 1000px;
height: 1000px;
border: 1px solid blue;
}
_x000D_
<div id="container"></div>
_x000D_
In Java 11 we can use Collection.toArray(generator)
method. The following code will create a new array of String:
Set<String> set = Set.of("one", "two", "three");
String[] array = set.toArray(String[]::new)
Currently the best documentation is the source. You can take a look at it here (attrs.xml).
You can define attributes in the top <resources>
element or inside of a <declare-styleable>
element. If I'm going to use an attr in more than one place I put it in the root element. Note, all attributes share the same global namespace. That means that even if you create a new attribute inside of a <declare-styleable>
element it can be used outside of it and you cannot create another attribute with the same name of a different type.
An <attr>
element has two xml attributes name
and format
. name
lets you call it something and this is how you end up referring to it in code, e.g., R.attr.my_attribute
. The format
attribute can have different values depending on the 'type' of attribute you want.
You can set the format to multiple types by using |
, e.g., format="reference|color"
.
enum
attributes can be defined as follows:
<attr name="my_enum_attr">
<enum name="value1" value="1" />
<enum name="value2" value="2" />
</attr>
flag
attributes are similar except the values need to be defined so they can be bit ored together:
<attr name="my_flag_attr">
<flag name="fuzzy" value="0x01" />
<flag name="cold" value="0x02" />
</attr>
In addition to attributes there is the <declare-styleable>
element. This allows you to define attributes a custom view can use. You do this by specifying an <attr>
element, if it was previously defined you do not specify the format
. If you wish to reuse an android attr, for example, android:gravity, then you can do that in the name
, as follows.
An example of a custom view <declare-styleable>
:
<declare-styleable name="MyCustomView">
<attr name="my_custom_attribute" />
<attr name="android:gravity" />
</declare-styleable>
When defining your custom attributes in XML on your custom view you need to do a few things. First you must declare a namespace to find your attributes. You do this on the root layout element. Normally there is only xmlns:android="http://schemas.android.com/apk/res/android"
. You must now also add xmlns:whatever="http://schemas.android.com/apk/res-auto"
.
Example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:whatever="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<org.example.mypackage.MyCustomView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
whatever:my_custom_attribute="Hello, world!" />
</LinearLayout>
Finally, to access that custom attribute you normally do so in the constructor of your custom view as follows.
public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, defStyle, 0);
String str = a.getString(R.styleable.MyCustomView_my_custom_attribute);
//do something with str
a.recycle();
}
The end. :)
Example:
\Large\begin{verbatim}
<how to set font size here to 10 px ? />
\end{verbatim}
\normalsize
\Large
can be obviously substituted by one of:
\tiny
\scriptsize
\footnotesize
\small
\normalsize
\large
\Large
\LARGE
\huge
\Huge
If you need arbitrary font sizes:
I would really like to see your TABLE's styling. E.g. "border-collapse"
Just a guess, but it might affect how 'hidden' rows are being rendered.
This is not possible due to the Same Origin Policy.
You will need to switch the Ajax requests to https, too.
Use the format()
function with a '02x'
format.
>>> format(255, '02x')
'ff'
>>> format(2, '02x')
'02'
The 02
part tells format()
to use at least 2 digits and to use zeros to pad it to length, x
means lower-case hexadecimal.
The Format Specification Mini Language also gives you X
for uppercase hex output, and you can prefix the field width with #
to include a 0x
or 0X
prefix (depending on wether you used x
or X
as the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters:
>>> format(255, '02X')
'FF'
>>> format(255, '#04x')
'0xff'
>>> format(255, '#04X')
'0XFF'
<select name="FakeName" id="Fake-ID" aria-required="true" required> <?php $options=nl2br(file_get_contents("employees.txt")); $options=explode("<br />",$options); foreach ($options as $item_array) { echo "<option value='".$item_array"'>".$item_array"</option>"; } ?> </select>
const obj = { id: 1, name: 'Neel' };_x000D_
let str = '';_x000D_
str = Object.entries(obj).map(([key, val]) => `${key}=${val}`).join('&');_x000D_
console.log(str);
_x000D_
I recently ran into an issue with IEnumerable
v. IQueryable
. The algorithm being used first performed an IQueryable
query to obtain a set of results. These were then passed to a foreach
loop, with the items instantiated as an Entity Framework (EF) class. This EF class was then used in the from
clause of a Linq to Entity query, causing the result to be IEnumerable
.
I'm fairly new to EF and Linq for Entities, so it took a while to figure out what the bottleneck was. Using MiniProfiling, I found the query and then converted all of the individual operations to a single IQueryable
Linq for Entities query. The IEnumerable
took 15 seconds and the IQueryable
took 0.5 seconds to execute. There were three tables involved and, after reading this, I believe that the IEnumerable
query was actually forming a three table cross-product and filtering the results.
Try to use IQueryables as a rule-of-thumb and profile your work to make your changes measurable.
this datepicker is an excellent solution. datepickers are a must if you want to avoid code injection.
I use SimpleJpaRepository as the base class of repository implementation and add custom method in the interface,eg:
public interface UserRepository {
User FindOrInsert(int userId);
}
@Repository
public class UserRepositoryImpl extends SimpleJpaRepository implements UserRepository {
private RedisClient redisClient;
public UserRepositoryImpl(RedisClient redisClient, EntityManager em) {
super(User.class, em);
this.redisClient = redisClient;
}
@Override
public User FindOrInsert(int userId) {
User u = redisClient.getOrSet("test key.. User.class, () -> {
Optional<User> ou = this.findById(Integer.valueOf(userId));
return ou.get();
});
…………
return u;
}
Shell calls to reverse (as mentioned above) are very good to debug these problems, but there are two critical conditions:
Yes, it's logical. Yes, it's also confusing because reverse will only throw the exception and won't give you any further hints.
An example of URL pattern:
url(r'^cookies/(?P<hostname>[^/]+)/(?P<url_id>\d+)/$', 'register_site.views.show_cookies', name='show_cookies'),
And then what happens in shell:
>>> from register_site.views import show_cookies
>>> reverse(show_cookies)
NoReverseMatch: Reverse for 'register_site.views.show_cookies' with arguments '()' and keyword arguments '{}' not found.
It doesn't work because I supplied no arguments.
>>> reverse('show_cookies', kwargs={'url_id':123,'hostname': 'aaa'})
'/cookies/aaa/123'
Now it worked, but...
>>> reverse('show_cookies', kwargs={'url_id':'x','hostname': 'www.dupa.com'})
NoReverseMatch: Reverse for 'show_cookies' with arguments '()' and keyword arguments '{'url_id': 'x', 'hostname': 'www.dupa.com'}' not found.
Now it didn't work because url_id didn't match the regexp (expected numeric, supplied string).
You can use reverse with both positional arguments and keyword arguments. The syntax is:
reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None)
As it comes to the url template tag, there's funny thing about it. Django documentation gives example of using quoted view name:
{% url 'news.views.year_archive' yearvar %}
So I used it in a similar way in my HTML template:
{% url 'show_cookies' hostname=u.hostname url_id=u.pk %}
But this didn't work for me. But the exception message gave me a hint of what could be wrong - note the double single quotes around view name:
Reverse for ''show_cookies'' with arguments...
It started to work when I removed the quotes:
{% url show_cookies hostname=u.hostname url_id=u.pk %}
And this is confusing.
Create two hidden iframes (add "display: none;" to the css style). Make your second iframe point to something on your own domain.
Create a hidden form, set its method to "post" with target = your first iframe, and optionally set enctype to "multipart/form-data" (I'm thinking you want to do POST because you want to send multipart data like pictures?)
When ready, make the form submit() the POST.
If you can get the other domain to return javascript that will do Cross-Domain Communication With Iframes (http://softwareas.com/cross-domain-communication-with-iframes) then you are in luck, and you can capture the response as well.
Of course, if you want to use your server as a proxy, you can avoid all this. Simply submit the form to your own server, which will proxy the request to the other server (assuming the other server isn't set up to notice IP discrepancies), get the response, and return whatever you like.
This may be of help to a few who are struggling like I was:
var data = myform.getRange("A:AA").getValues().pop();
var myvariable1 = data[4];
var myvariable2 = data[7];
Late to the party, so answering more for future reference.
Advances in the field + Mozilla's mindset and agenda led to these two projects towards that end:
The latter has a 12GB data-set for download. The former allows for training a model with your own audio files to my understanding
For people who want to use multiple images of course importing them one by one would be a problem. The solution is to move the images folder to the public folder. So if you had an image at public/images/logo.jpg, you could display that image this way:
function Header() {
return (
<div>
<img src="images/logo.jpg" alt="logo"/>
</div>
);
}
Yes, no need to use /public/ in the source.
Read further: https://daveceddia.com/react-image-tag/.
This is what I use to display images from blob:
echo '<img src="data:image/jpeg;base64,'.base64_encode($image->load()) .'" />';
In your entity for that table, add the DatabaseGenerated
attribute above the column for which identity insert is set:
Example:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int TaskId { get; set; }
I moved my htdocs folder from C:\xampp\htdocs to D:\htdocs without editing the Apache config file (httpd.conf).
Step 1) Move C:\xampp\htdocs
folder to D:\htdocs
Step 2) Create a symbolic link in C:\xampp\htdocs linked to D:\htdocs using mklink command.
D:\>mklink /J C:\xampp\htdocs D:\htdocs
Junction created for C:\xampp\htdocs <<===>> D:\htdocs
D:\>
Step 3) Done!
Simplest solution seems to be specifying the ylim
range. Here is some code to do this automatically (left default, right - adjusted):
# default y-axis
barplot(dat, beside=TRUE)
# automatically adjusted y-axis
barplot(dat, beside=TRUE, ylim=range(pretty(c(0, dat))))
The trick is to use pretty()
which returns a list of interval breaks covering all values of the provided data. It guarantees that the maximum returned value is 1) a round number 2) greater than maximum value in the data.
In the example 0 was also added pretty(c(0, dat))
which makes sure that axis starts from 0.
Using useEffect hook:
useEffect(() => {
const ourRequest = Axios.CancelToken.source() // <-- 1st step
const fetchPost = async () => {
try {
const response = await Axios.get(`endpointURL`, {
cancelToken: ourRequest.token, // <-- 2nd step
})
console.log(response.data)
setPost(response.data)
setIsLoading(false)
} catch (err) {
console.log('There was a problem or request was cancelled.')
}
}
fetchPost()
return () => {
ourRequest.cancel() // <-- 3rd step
}
}, [])
Note: For POST request, pass cancelToken as 3rd argument
Axios.post(`endpointURL`, {data}, {
cancelToken: ourRequest.token, // 2nd step
})
During some work with an auto-focus lens, I came across this very useful set of algorithms for detecting image focus. It's implemented in MATLAB, but most of the functions are quite easy to port to OpenCV with filter2D.
It's basically a survey implementation of many focus measurement algorithms. If you want to read the original papers, references to the authors of the algorithms are provided in the code. The 2012 paper by Pertuz, et al. Analysis of focus measure operators for shape from focus (SFF) gives a great review of all of these measure as well as their performance (both in terms of speed and accuracy as applied to SFF).
EDIT: Added MATLAB code just in case the link dies.
function FM = fmeasure(Image, Measure, ROI)
%This function measures the relative degree of focus of
%an image. It may be invoked as:
%
% FM = fmeasure(Image, Method, ROI)
%
%Where
% Image, is a grayscale image and FM is the computed
% focus value.
% Method, is the focus measure algorithm as a string.
% see 'operators.txt' for a list of focus
% measure methods.
% ROI, Image ROI as a rectangle [xo yo width heigth].
% if an empty argument is passed, the whole
% image is processed.
%
% Said Pertuz
% Abr/2010
if ~isempty(ROI)
Image = imcrop(Image, ROI);
end
WSize = 15; % Size of local window (only some operators)
switch upper(Measure)
case 'ACMO' % Absolute Central Moment (Shirvaikar2004)
if ~isinteger(Image), Image = im2uint8(Image);
end
FM = AcMomentum(Image);
case 'BREN' % Brenner's (Santos97)
[M N] = size(Image);
DH = Image;
DV = Image;
DH(1:M-2,:) = diff(Image,2,1);
DV(:,1:N-2) = diff(Image,2,2);
FM = max(DH, DV);
FM = FM.^2;
FM = mean2(FM);
case 'CONT' % Image contrast (Nanda2001)
ImContrast = inline('sum(abs(x(:)-x(5)))');
FM = nlfilter(Image, [3 3], ImContrast);
FM = mean2(FM);
case 'CURV' % Image Curvature (Helmli2001)
if ~isinteger(Image), Image = im2uint8(Image);
end
M1 = [-1 0 1;-1 0 1;-1 0 1];
M2 = [1 0 1;1 0 1;1 0 1];
P0 = imfilter(Image, M1, 'replicate', 'conv')/6;
P1 = imfilter(Image, M1', 'replicate', 'conv')/6;
P2 = 3*imfilter(Image, M2, 'replicate', 'conv')/10 ...
-imfilter(Image, M2', 'replicate', 'conv')/5;
P3 = -imfilter(Image, M2, 'replicate', 'conv')/5 ...
+3*imfilter(Image, M2, 'replicate', 'conv')/10;
FM = abs(P0) + abs(P1) + abs(P2) + abs(P3);
FM = mean2(FM);
case 'DCTE' % DCT energy ratio (Shen2006)
FM = nlfilter(Image, [8 8], @DctRatio);
FM = mean2(FM);
case 'DCTR' % DCT reduced energy ratio (Lee2009)
FM = nlfilter(Image, [8 8], @ReRatio);
FM = mean2(FM);
case 'GDER' % Gaussian derivative (Geusebroek2000)
N = floor(WSize/2);
sig = N/2.5;
[x,y] = meshgrid(-N:N, -N:N);
G = exp(-(x.^2+y.^2)/(2*sig^2))/(2*pi*sig);
Gx = -x.*G/(sig^2);Gx = Gx/sum(Gx(:));
Gy = -y.*G/(sig^2);Gy = Gy/sum(Gy(:));
Rx = imfilter(double(Image), Gx, 'conv', 'replicate');
Ry = imfilter(double(Image), Gy, 'conv', 'replicate');
FM = Rx.^2+Ry.^2;
FM = mean2(FM);
case 'GLVA' % Graylevel variance (Krotkov86)
FM = std2(Image);
case 'GLLV' %Graylevel local variance (Pech2000)
LVar = stdfilt(Image, ones(WSize,WSize)).^2;
FM = std2(LVar)^2;
case 'GLVN' % Normalized GLV (Santos97)
FM = std2(Image)^2/mean2(Image);
case 'GRAE' % Energy of gradient (Subbarao92a)
Ix = Image;
Iy = Image;
Iy(1:end-1,:) = diff(Image, 1, 1);
Ix(:,1:end-1) = diff(Image, 1, 2);
FM = Ix.^2 + Iy.^2;
FM = mean2(FM);
case 'GRAT' % Thresholded gradient (Snatos97)
Th = 0; %Threshold
Ix = Image;
Iy = Image;
Iy(1:end-1,:) = diff(Image, 1, 1);
Ix(:,1:end-1) = diff(Image, 1, 2);
FM = max(abs(Ix), abs(Iy));
FM(FM<Th)=0;
FM = sum(FM(:))/sum(sum(FM~=0));
case 'GRAS' % Squared gradient (Eskicioglu95)
Ix = diff(Image, 1, 2);
FM = Ix.^2;
FM = mean2(FM);
case 'HELM' %Helmli's mean method (Helmli2001)
MEANF = fspecial('average',[WSize WSize]);
U = imfilter(Image, MEANF, 'replicate');
R1 = U./Image;
R1(Image==0)=1;
index = (U>Image);
FM = 1./R1;
FM(index) = R1(index);
FM = mean2(FM);
case 'HISE' % Histogram entropy (Krotkov86)
FM = entropy(Image);
case 'HISR' % Histogram range (Firestone91)
FM = max(Image(:))-min(Image(:));
case 'LAPE' % Energy of laplacian (Subbarao92a)
LAP = fspecial('laplacian');
FM = imfilter(Image, LAP, 'replicate', 'conv');
FM = mean2(FM.^2);
case 'LAPM' % Modified Laplacian (Nayar89)
M = [-1 2 -1];
Lx = imfilter(Image, M, 'replicate', 'conv');
Ly = imfilter(Image, M', 'replicate', 'conv');
FM = abs(Lx) + abs(Ly);
FM = mean2(FM);
case 'LAPV' % Variance of laplacian (Pech2000)
LAP = fspecial('laplacian');
ILAP = imfilter(Image, LAP, 'replicate', 'conv');
FM = std2(ILAP)^2;
case 'LAPD' % Diagonal laplacian (Thelen2009)
M1 = [-1 2 -1];
M2 = [0 0 -1;0 2 0;-1 0 0]/sqrt(2);
M3 = [-1 0 0;0 2 0;0 0 -1]/sqrt(2);
F1 = imfilter(Image, M1, 'replicate', 'conv');
F2 = imfilter(Image, M2, 'replicate', 'conv');
F3 = imfilter(Image, M3, 'replicate', 'conv');
F4 = imfilter(Image, M1', 'replicate', 'conv');
FM = abs(F1) + abs(F2) + abs(F3) + abs(F4);
FM = mean2(FM);
case 'SFIL' %Steerable filters (Minhas2009)
% Angles = [0 45 90 135 180 225 270 315];
N = floor(WSize/2);
sig = N/2.5;
[x,y] = meshgrid(-N:N, -N:N);
G = exp(-(x.^2+y.^2)/(2*sig^2))/(2*pi*sig);
Gx = -x.*G/(sig^2);Gx = Gx/sum(Gx(:));
Gy = -y.*G/(sig^2);Gy = Gy/sum(Gy(:));
R(:,:,1) = imfilter(double(Image), Gx, 'conv', 'replicate');
R(:,:,2) = imfilter(double(Image), Gy, 'conv', 'replicate');
R(:,:,3) = cosd(45)*R(:,:,1)+sind(45)*R(:,:,2);
R(:,:,4) = cosd(135)*R(:,:,1)+sind(135)*R(:,:,2);
R(:,:,5) = cosd(180)*R(:,:,1)+sind(180)*R(:,:,2);
R(:,:,6) = cosd(225)*R(:,:,1)+sind(225)*R(:,:,2);
R(:,:,7) = cosd(270)*R(:,:,1)+sind(270)*R(:,:,2);
R(:,:,7) = cosd(315)*R(:,:,1)+sind(315)*R(:,:,2);
FM = max(R,[],3);
FM = mean2(FM);
case 'SFRQ' % Spatial frequency (Eskicioglu95)
Ix = Image;
Iy = Image;
Ix(:,1:end-1) = diff(Image, 1, 2);
Iy(1:end-1,:) = diff(Image, 1, 1);
FM = mean2(sqrt(double(Iy.^2+Ix.^2)));
case 'TENG'% Tenengrad (Krotkov86)
Sx = fspecial('sobel');
Gx = imfilter(double(Image), Sx, 'replicate', 'conv');
Gy = imfilter(double(Image), Sx', 'replicate', 'conv');
FM = Gx.^2 + Gy.^2;
FM = mean2(FM);
case 'TENV' % Tenengrad variance (Pech2000)
Sx = fspecial('sobel');
Gx = imfilter(double(Image), Sx, 'replicate', 'conv');
Gy = imfilter(double(Image), Sx', 'replicate', 'conv');
G = Gx.^2 + Gy.^2;
FM = std2(G)^2;
case 'VOLA' % Vollath's correlation (Santos97)
Image = double(Image);
I1 = Image; I1(1:end-1,:) = Image(2:end,:);
I2 = Image; I2(1:end-2,:) = Image(3:end,:);
Image = Image.*(I1-I2);
FM = mean2(Image);
case 'WAVS' %Sum of Wavelet coeffs (Yang2003)
[C,S] = wavedec2(Image, 1, 'db6');
H = wrcoef2('h', C, S, 'db6', 1);
V = wrcoef2('v', C, S, 'db6', 1);
D = wrcoef2('d', C, S, 'db6', 1);
FM = abs(H) + abs(V) + abs(D);
FM = mean2(FM);
case 'WAVV' %Variance of Wav...(Yang2003)
[C,S] = wavedec2(Image, 1, 'db6');
H = abs(wrcoef2('h', C, S, 'db6', 1));
V = abs(wrcoef2('v', C, S, 'db6', 1));
D = abs(wrcoef2('d', C, S, 'db6', 1));
FM = std2(H)^2+std2(V)+std2(D);
case 'WAVR'
[C,S] = wavedec2(Image, 3, 'db6');
H = abs(wrcoef2('h', C, S, 'db6', 1));
V = abs(wrcoef2('v', C, S, 'db6', 1));
D = abs(wrcoef2('d', C, S, 'db6', 1));
A1 = abs(wrcoef2('a', C, S, 'db6', 1));
A2 = abs(wrcoef2('a', C, S, 'db6', 2));
A3 = abs(wrcoef2('a', C, S, 'db6', 3));
A = A1 + A2 + A3;
WH = H.^2 + V.^2 + D.^2;
WH = mean2(WH);
WL = mean2(A);
FM = WH/WL;
otherwise
error('Unknown measure %s',upper(Measure))
end
end
%************************************************************************
function fm = AcMomentum(Image)
[M N] = size(Image);
Hist = imhist(Image)/(M*N);
Hist = abs((0:255)-255*mean2(Image))'.*Hist;
fm = sum(Hist);
end
%******************************************************************
function fm = DctRatio(M)
MT = dct2(M).^2;
fm = (sum(MT(:))-MT(1,1))/MT(1,1);
end
%************************************************************************
function fm = ReRatio(M)
M = dct2(M);
fm = (M(1,2)^2+M(1,3)^2+M(2,1)^2+M(2,2)^2+M(3,1)^2)/(M(1,1)^2);
end
%******************************************************************
A few examples of OpenCV versions:
// OpenCV port of 'LAPM' algorithm (Nayar89)
double modifiedLaplacian(const cv::Mat& src)
{
cv::Mat M = (Mat_<double>(3, 1) << -1, 2, -1);
cv::Mat G = cv::getGaussianKernel(3, -1, CV_64F);
cv::Mat Lx;
cv::sepFilter2D(src, Lx, CV_64F, M, G);
cv::Mat Ly;
cv::sepFilter2D(src, Ly, CV_64F, G, M);
cv::Mat FM = cv::abs(Lx) + cv::abs(Ly);
double focusMeasure = cv::mean(FM).val[0];
return focusMeasure;
}
// OpenCV port of 'LAPV' algorithm (Pech2000)
double varianceOfLaplacian(const cv::Mat& src)
{
cv::Mat lap;
cv::Laplacian(src, lap, CV_64F);
cv::Scalar mu, sigma;
cv::meanStdDev(lap, mu, sigma);
double focusMeasure = sigma.val[0]*sigma.val[0];
return focusMeasure;
}
// OpenCV port of 'TENG' algorithm (Krotkov86)
double tenengrad(const cv::Mat& src, int ksize)
{
cv::Mat Gx, Gy;
cv::Sobel(src, Gx, CV_64F, 1, 0, ksize);
cv::Sobel(src, Gy, CV_64F, 0, 1, ksize);
cv::Mat FM = Gx.mul(Gx) + Gy.mul(Gy);
double focusMeasure = cv::mean(FM).val[0];
return focusMeasure;
}
// OpenCV port of 'GLVN' algorithm (Santos97)
double normalizedGraylevelVariance(const cv::Mat& src)
{
cv::Scalar mu, sigma;
cv::meanStdDev(src, mu, sigma);
double focusMeasure = (sigma.val[0]*sigma.val[0]) / mu.val[0];
return focusMeasure;
}
No guarantees on whether or not these measures are the best choice for your problem, but if you track down the papers associated with these measures, they may give you more insight. Hope you find the code useful! I know I did.
function colorOf(r,g,b){
var f = function (x) {
return (x<16 ? '0' : '') + x.toString(16)
};
return "#" + f(r) + f(g) + f(b);
}
When compiling for x64, the difference between int and long is somewhere between 0 and 4 bytes, depending on what compiler you use.
GCC uses the LP64 model, which means that ints are 32-bits but longs are 64-bits under 64-bit mode.
MSVC for example uses the LLP64 model, which means both ints and longs are 32-bits even in 64-bit mode.
PowerShell 3 has the $PSScriptRoot
automatic variable:
Contains the directory from which a script is being run.
In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.
Don't be fooled by the poor wording. PSScriptRoot
is the directory of the current file.
In PowerShell 2, you can calculate the value of $PSScriptRoot
yourself:
# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
The following (C# implementation, but similar in Java) allows you to determine if there is an alert without exceptions and without creating the WebDriverWait
object.
boolean isDialogPresent(WebDriver driver) {
IAlert alert = ExpectedConditions.AlertIsPresent().Invoke(driver);
return (alert != null);
}
Don't loop through every file line. Use readfile instead, its faster. This is off the php site: http://php.net/manual/en/function.readfile.php
$file = $_GET["file"];
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Type: application/force-download");
header('Content-Disposition: attachment; filename=' . urlencode(basename($file)));
// header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
Make sure to sanitize your get variable as someone could download some php files...
The test has to be done on a page that queries a database so yes typically that is a login page because it's the page that can do the most harm but could be an unsecure page as well.
Generally you would have your database queries behind a secure login but if you just have a listing of items or something that you don't care if the world sees a hacker could append some sql injection to the end of the querystring.
The key with SQL Injection is the person doing the injection would have to know that your querying a database so if your not querying a database then no sql inject can be done. If your form is submitting to a database then yes they could SQL Inject that. It's always good practice to use either stored procedures to select/insert/update/delete or make sure you prepare or escape out all the statements that will be hitting the database.
The id is supposed to be unique, use the attribute "name" and "getelementsbyname" instead, and you'll have your array.
As @gaurang171 mentioned, we can use .closest() which will return the first ancestor, or the closest to our delete button, and use .remove() to remove it.
This is how we can implement it using jQuery click event instead of using JavaScript onclick.
HTML:
<table id="myTable">
<tr>
<th width="30%" style="color:red;">ID</th>
<th width="25%" style="color:red;">Name</th>
<th width="25%" style="color:red;">Age</th>
<th width="1%"></th>
</tr>
<tr>
<td width="30%" style="color:red;">SSS-001</td>
<td width="25%" style="color:red;">Ben</td>
<td width="25%" style="color:red;">25</td>
<td><button type='button' class='btnDelete'>x</button></td>
</tr>
<tr>
<td width="30%" style="color:red;">SSS-002</td>
<td width="25%" style="color:red;">Anderson</td>
<td width="25%" style="color:red;">47</td>
<td><button type='button' class='btnDelete'>x</button></td>
</tr>
<tr>
<td width="30%" style="color:red;">SSS-003</td>
<td width="25%" style="color:red;">Rocky</td>
<td width="25%" style="color:red;">32</td>
<td><button type='button' class='btnDelete'>x</button></td>
</tr>
<tr>
<td width="30%" style="color:red;">SSS-004</td>
<td width="25%" style="color:red;">Lee</td>
<td width="25%" style="color:red;">15</td>
<td><button type='button' class='btnDelete'>x</button></td>
</tr>
jQuery
$(document).ready(function(){
$("#myTable").on('click','.btnDelete',function(){
$(this).closest('tr').remove();
});
});
Try in JSFiddle: click here.
Seems like at least 10 questions rolled into one here, a couple points.
Response.Clear - it really depends on what else is going on in the app - if you have httpmodules early in the pipeline that might be writing stuff you don't want - then clear it. Test it and find out. Fiddler or Wireshark useful for this.
Content Type to text/xml - yup - good idea - read up on HTTP spec as to why this is important. IMO anyone doing web work should have read the 1.0 and 1.1 spec at least once.
Encoding - how is your xml encoded - if it is utf-8, then say so, if not, say something else appropriate, just make sure they all match.
Page - personally, would use ashx or httpmodule, if you are using page, and want it a bit faster, get rid of autoeventwireup and bind the event handlers manually.
Would probably be a bit of a waste of memory to dump the xml into a string first, but it depends a lot on the size of the xml as to whether you would ever notice.
As others have suggested, saving the xml to the output stream probably the fastest, I would normally do that, but if you aren't sure, test it, don't rely on what you read on the interweb. Don't just believe anything I say.
For another approach, if the xml doesn't change that much, you could just write it to the disk and serve the file directly, which would likely be quite performant, but like everything in programming, it depends...
see this code what i am used in my application
String data="{'foo':'bar','coolness':2.0, 'altitude':39000, 'pilot':{'firstName':'Buzz','lastName':'Aldrin'}, 'mission':'apollo 11'}";
I retrieved like this
JSONObject json = (JSONObject) JSONSerializer.toJSON(data);
double coolness = json.getDouble( "coolness" );
int altitude = json.getInt( "altitude" );
JSONObject pilot = json.getJSONObject("pilot");
String firstName = pilot.getString("firstName");
String lastName = pilot.getString("lastName");
System.out.println( "Coolness: " + coolness );
System.out.println( "Altitude: " + altitude );
System.out.println( "Pilot: " + lastName );
Find Microsoft Visual C++ 2010 x86/x64 Redistributable – 10.0.xxxxx in the control panel of the add or remove programs if xxxxx > 30319 renmove it
You can access any DGV cell as follows :
dataGridView1.Rows[rowIndex].Cells[columnIndex].Value = value;
But usually it's better to use databinding : you bind the DGV to a data source (DataTable
, collection...) through the DataSource
property, and only work on the data source itself. The DataGridView
will automatically reflect the changes, and changes made on the DataGridView
will be reflected on the data source
For classes that you create (ie. are not part of the Android) its possible to avoid the crash completely.
Any class that implements finalize()
has some unavoidable probability of crashing as explained by @oba. So instead of using finalizers to perform cleanup, use a PhantomReferenceQueue
.
For an example check out the implementation in React Native: https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/jni/DestructorThread.java
After misunderstanding, I finally got what you are trying to do. You should check your server configuration files; are you using apache2 or some other server software?
Look for lines that start with LoadModule php
...
There probably are configuration files/directories named mods
or something like that, start from there.
You could also check output from php -r 'phpinfo();' | grep php
and compare lines to phpinfo();
from web server.
php
interactively:(so you can paste/write code in the console)
php -a
php -f file.php
php -f file.php > results.html
To run only small part, one line or like, you can use:
php -r '$x = "Hello World"; echo "$x\n";'
If you are running linux then do man php
at console.
if you need/want to run php through fpm, use cli fcgi
SCRIPT_NAME="file.php" SCRIP_FILENAME="file.php" REQUEST_METHOD="GET" cgi-fcgi -bind -connect "/var/run/php-fpm/php-fpm.sock"
where /var/run/php-fpm/php-fpm.sock is your php-fpm socket file.
As an extend to @Eugene's answer another version which will work to push code from local repo to master/develop branch .
Switch to branch ‘master’:
$ git checkout master
Merge from local repo to master:
$ git merge --no-ff FEATURE/<branch_Name>
Push to master:
$ git push
You can pass data to the view using the with method.
return view('greeting', ['name' => 'James']);
This function does what you want, and performs a lot faster than the option suggested in the accepted answer :
var repeat = function(str, count) {
var array = [];
for(var i = 0; i <= count;)
array[i++] = str;
return array.join('');
}
You use it like this :
var repeatedCharacter = repeat("a", 10);
To compare the performance of this function with that of the option proposed in the accepted answer, see this Fiddle and this Fiddle for benchmarks.
In modern browsers, you can now also do this :
var repeatedCharacter = "a".repeat(10) };
This option is even faster. However, unfortunately it doesn't work in any version of Internet explorer.
The numbers in the table specify the first browser version that fully supports the method :
See the "Source Test Tools" link on the Software QA Testing and Test Tool Resources page for a list of similar tools.
I've used BoundsChecker,DevPartner Studio and Intel V-Tune in the past for profiling. I liked V-Tune the best; you could emulate various Intel chipsets and it would give you hints on how to optimize for that platform.
s.index(x[, i[, j]])
index of the first occurrence of x in s (at or after index i and before index j)
Total Commander also has a binary compare option:
go to: File \\Compare by content
ps. I guess some people may alredy be using this tool and may not be aware of the built-in feature.
Use boost::filesystem. It will be incorporated into the next standard anyway so you may as well get used to it.
You'll need to check menuItem.getItemId()
against android.R.id.home
in the onOptionsItemSelected
method
Duplicate of Android Sherlock ActionBar Up button
This way work for me:
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(GApplication.getInstance().getTheme());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Then you want to change a new theme:
GApplication.getInstance().setTheme(R.style.LightTheme);
recreate();
For "100% of the browser window", if you mean this literally, you should use fixed positioning. The top, bottom, right, and left properties are then used to offset the divs edges from the respective edges of the viewport:
#nav, #content{position:fixed;top:0px;bottom:0px;}
#nav{left:0px;right:235px;}
#content{left:235px;right:0px}
This will set up a screen with the left 235 pixels devoted to the nav, and the right rest of the screen to content.
Note, however, you won't be able to scroll the whole screen at once. Though you can set it to scroll either pane individually, by applying overflow:auto
to either div.
Note also: fixed positioning is not supported in IE6 or earlier.
I had a similar issue when working on local. You url is going to be the path to the local file e.g. file:///Users/PeterP/Desktop/folder/index.html.
Please note that I am on a MAC.
I got round this by installing http-server globally. https://www.npmjs.com/package/http-server
Steps:
npm install http-server -g
http-server ~/Desktop/folder/
PS: I assume you have node installed, otherwise you wont get very far running npm commands.
There's a pretty good explanation of first level caching on the Streamline Logic blog.
Basically, first level caching happens on a per session basis where as second level caching can be shared across multiple sessions.
After lots of toil and fiddling with the Uri class, and other solutions, here're my string extension methods to solve my problems.
using System;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
public static class StringExtensions
{
public static string AddToQueryString(this string url, params object[] keysAndValues)
{
return UpdateQueryString(url, q =>
{
for (var i = 0; i < keysAndValues.Length; i += 2)
{
q.Set(keysAndValues[i].ToString(), keysAndValues[i + 1].ToString());
}
});
}
public static string RemoveFromQueryString(this string url, params string[] keys)
{
return UpdateQueryString(url, q =>
{
foreach (var key in keys)
{
q.Remove(key);
}
});
}
public static string UpdateQueryString(string url, Action<NameValueCollection> func)
{
var urlWithoutQueryString = url.Contains('?') ? url.Substring(0, url.IndexOf('?')) : url;
var queryString = url.Contains('?') ? url.Substring(url.IndexOf('?')) : null;
var query = HttpUtility.ParseQueryString(queryString ?? string.Empty);
func(query);
return urlWithoutQueryString + (query.Count > 0 ? "?" : string.Empty) + query;
}
}
first Create a new repository on the command line, name like Ademo.git
Create a new repository on the command line
touch README.md git init git add README.md git commit -m "first commit" git remote add origin https://github.com/your_name/Ademo.git git push -u origin master
Push an existing repository from the command line
git remote add origin https://github.com/your_name/Ademo.git git push -u origin master
Swift 4.2 | Xcode 10
extension UIImage {
/// EZSE: Returns base64 string
public var base64: String {
return self.jpegData(compressionQuality: 1.0)!.base64EncodedString()
}
}
Use the cmd activity start-activity
(or the alternative am start
) command, which is a command-line interface to the ActivityManager. Use am
to start activities as shown in this help:
$ adb shell am
usage: am [start|instrument]
am start [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]
[-c <CATEGORY> [-c <CATEGORY>] ...]
[-e <EXTRA_KEY> <EXTRA_VALUE> [-e <EXTRA_KEY> <EXTRA_VALUE> ...]
[-n <COMPONENT>] [-D] [<URI>]
...
For example, to start the Contacts application, and supposing you know only the package name but not the Activity
, you can use
$ pkg=com.google.android.contacts
$ comp=$(adb shell cmd package resolve-activity --brief -c android.intent.category.LAUNCHER $pkg | tail -1)
$ adb shell cmd activity start-activity $comp
or the alternative
$ adb shell am start -n $comp
See also http://www.kandroid.org/online-pdk/guide/instrumentation_testing.html (may be a copy of obsolete url : http://source.android.com/porting/instrumentation_testing.html ) for other details.
To terminate the application you can use
$ adb shell am kill com.google.android.contacts
or the more drastic
$ adb shell am force-stop com.google.android.contacts
All I have to do in order to get rid of that error was to restart my wamp server.
Swift 4:
NotificationCenter.default.addObserver( self, selector: #selector(ControllerClassName.keyboardWillShow(_:)),
name: Notification.Name.UIKeyboardWillShow,
object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ControllerClassName.keyboardWillHide(_:)),
name: Notification.Name.UIKeyboardWillHide,
object: nil)
Next, adding method to stop listening for notifications when the object’s life ends:-
Then add the promised methods from above to the view controller:
deinit {
NotificationCenter.default.removeObserver(self)
}
func adjustKeyboardShow(_ open: Bool, notification: Notification) {
let userInfo = notification.userInfo ?? [:]
let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let height = (keyboardFrame.height + 20) * (open ? 1 : -1)
scrollView.contentInset.bottom += height
scrollView.scrollIndicatorInsets.bottom += height
}
@objc func keyboardWillShow(_ notification: Notification) {
adjustKeyboardShow(true, notification: notification)
}
@objc func keyboardWillHide(_ notification: Notification) {
adjustKeyboardShow(false, notification: notification)
}
What about something like:
Alter Table Products
Add LastUpdate varchar(200) null
Do you need something more complex than this?
You can see in this List of useful HTTP headers.
X-XSS-Protection: This header enables the Cross-site scripting (XSS) filter built into most recent web browsers. It's usually enabled by default anyway, so the role of this header is to re-enable the filter for this particular website if it was disabled by the user. This header is supported in IE 8+, and in Chrome (not sure which versions). The anti-XSS filter was added in Chrome 4. Its unknown if that version honored this header.
If you want to see what is run in the database use dd(DB::getQueryLog())
to see what queries were run.
Try this
BookingDates::where('email', Input::get('email'))
->orWhere('name', 'like', '%' . Input::get('name') . '%')->get();
Run the following commands in the terminal:
rm -Rf /Applications/Android\ Studio.app
rm -Rf ~/Library/Preferences/AndroidStudio*
rm -Rf ~/Library/Preferences/com.google.android.*
rm -Rf ~/Library/Preferences/com.android.*
rm -Rf ~/Library/Application\ Support/AndroidStudio*
rm -Rf ~/Library/Logs/AndroidStudio*
rm -Rf ~/Library/Caches/AndroidStudio*
rm -Rf ~/.AndroidStudio*
rm -Rf ~/.gradle
rm -Rf ~/.android
rm -Rf ~/Library/Android*
rm -Rf /usr/local/var/lib/android-sdk/
To delete all projects:
rm -Rf ~/AndroidStudioProjects
Apache denies all URLs with %2F
in the path part, for security reasons: scripts can't normally (ie. without rewriting) tell the difference between %2F
and /
due to the PATH_INFO
environment variable being automatically URL-decoded (which is stupid, but a long-standing part of the CGI specification so there's nothing can be done about it).
You can turn this feature off using the AllowEncodedSlashes
directive, but note that other web servers will still disallow it (with no option to turn that off), and that other characters may also be taboo (eg. %5C
), and that %00
in particular will always be blocked by both Apache and IIS. So if your application relied on being able to have %2F
or other characters in a path part you'd be limiting your compatibility/deployment options.
I am using urlencode() while preparing the search URL
You should use rawurlencode()
, not urlencode()
for escaping path parts. urlencode()
is misnamed, it is actually for application/x-www-form-urlencoded
data such as in the query string or the body of a POST request, and not for other parts of the URL.
The difference is that +
doesn't mean space in path parts. rawurlencode()
will correctly produce %20
instead, which will work both in form-encoded data and other parts of the URL.
You can't (usefully) compare strings using !=
or ==
, you need to use strcmp
:
while (strcmp(check,input) != 0)
The reason for this is because !=
and ==
will only compare the base addresses of those strings. Not the contents of the strings themselves.
Old style using ResultSet
@Transactional(readOnly=true)
public void accessUser() {
EntityManager em = this.getEntityManager();
org.hibernate.Session session = em.unwrap(org.hibernate.Session.class);
session.doWork(new Work() {
@Override
public void execute(Connection con) throws SQLException {
try (PreparedStatement stmt = con.prepareStatement(
"SELECT u.username, u.name, u.email, 'blabla' as passe, login_type as loginType FROM users u")) {
ResultSet rs = stmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.print(rsmd.getColumnName(i) + " (" + rsmd.getColumnTypeName(i) + ") / ");
}
System.out.println("");
while (rs.next()) {
System.out.println("Found username " + rs.getString("USERNAME") + " name " + rs.getString("NAME") + " email " + rs.getString("EMAIL") + " passe " + rs.getString("PASSE") + " email " + rs.getInt("LOGIN_TYPE"));
}
}
}
});
}
If you don't like anonymous functions:
try {
DB::connection()->pdo->beginTransaction();
// database queries here
DB::connection()->pdo->commit();
} catch (\PDOException $e) {
// Woopsy
DB::connection()->pdo->rollBack();
}
Update: For laravel 4, the pdo
object isn't public anymore so:
try {
DB::beginTransaction();
// database queries here
DB::commit();
} catch (\PDOException $e) {
// Woopsy
DB::rollBack();
}
this happened with me because I tried to access UI
component in another thread insted of UI thread
like this
private void button_Click(object sender, RoutedEventArgs e)
{
new Thread(SyncProcces).Start();
}
private void SyncProcces()
{
string val1 = null, val2 = null;
//here is the problem
val1 = textBox1.Text;//access UI in another thread
val2 = textBox2.Text;//access UI in another thread
localStore = new LocalStore(val1);
remoteStore = new RemoteStore(val2);
}
to solve this problem, wrap any ui call inside what Candide mentioned above in his answer
private void SyncProcces()
{
string val1 = null, val2 = null;
this.Dispatcher.Invoke((Action)(() =>
{//this refer to form in WPF application
val1 = textBox.Text;
val2 = textBox_Copy.Text;
}));
localStore = new LocalStore(val1);
remoteStore = new RemoteStore(val2 );
}
The zero-width space entity can be used in place of <wbr>
tag reliably on virtually every platform.
​
Also useful is the word joiner entity, that can be used to prohibit a break. (Insert between each character of a word, except where you want the break.)
⁠
With the two of these, you can do anything.
I ended up using GitKraken . I've installed, auth and connected to my repo in 30 seconds.
const destroy = container => {
document.getElementById(container).innerHTML = '';
};
Faster previous
const destroyFast = container => {
const el = document.getElementById(container);
while (el.firstChild) el.removeChild(el.firstChild);
};
The embed URL for a channel's live stream is:
https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID
You can find your CHANNEL_ID at https://www.youtube.com/account_advanced
No one has updated answer for latest Angular CLI.With latest Angular CLI
With latest version
of angular-cli in which angular-cli.json renamed to angular.json
, you can change the port by editing angular.json
file
you now specify a port per "project"
projects": {
"my-cool-project": {
... rest of project config omitted
"architect": {
"serve": {
"options": {
"port": 4500
}
}
}
}
}
Read more about it here
I have following idea how you can deal with such Access Device ID (ADID):
Gen ADID
Use device
In this approach, as long user use same browser and don't make device reset, the device has access to data. If someone made device-reset then again trusted user need to login and gen ADID.
You can even create some ADID management system for trusted user where on generate ADID he can also input device serial-number and in future in case of device reset he can find this device and regenerate ADID for it (which not increase whitelist size) and he can also drop some ADID from whitelist for devices which he will not longer give access to server data.
In case when sytem use many domains/subdomains te manager after login should see many "Give access from domain xyz.com to this device" buttons - each button will redirect device do proper domain, gent ADID and redirect back.
Simpler approach based on links:
You can use below statement to write the contents of dataframe in CSV format
df.write.csv("/data/home/csv")
If you need to write the whole dataframe into a single CSV file, then use
df.coalesce(1).write.csv("/data/home/sample.csv")
For spark 1.x, you can use spark-csv to write the results into CSV files
Below scala snippet would help
import org.apache.spark.sql.hive.HiveContext
// sc - existing spark context
val sqlContext = new HiveContext(sc)
val df = sqlContext.sql("SELECT * FROM testtable")
df.write.format("com.databricks.spark.csv").save("/data/home/csv")
To write the contents into a single file
import org.apache.spark.sql.hive.HiveContext
// sc - existing spark context
val sqlContext = new HiveContext(sc)
val df = sqlContext.sql("SELECT * FROM testtable")
df.coalesce(1).write.format("com.databricks.spark.csv").save("/data/home/sample.csv")
I have found that the Worksheet ".UsedRange" method is superior in many instances to solve this problem. I struggled with a truncation issue that is a normal behaviour of the ".CurrentRegion" method. Using [ Worksheets("Sheet1").Range("A1").CurrentRegion ] does not yield the results I desired when the worksheet consists of one column with blanks in the rows (and the blanks are wanted). In this case, the ".CurrentRegion" will truncate at the first record. I implemented a work around but recently found an even better one; see code below that allows copying the whole set to another sheet or to identify the actual address (or just rows and columns):
Sub mytest_GetAllUsedCells_in_Worksheet()
Dim myRange
Set myRange = Worksheets("Sheet1").UsedRange
'Alternative code: set myRange = activesheet.UsedRange
'use msgbox or debug.print to show the address range and counts
MsgBox myRange.Address
MsgBox myRange.Columns.Count
MsgBox myRange.Rows.Count
'Copy the Range of data to another sheet
'Note: contains all the cells with that are non-empty
myRange.Copy (Worksheets("Sheet2").Range("A1"))
'Note: transfers all cells starting at "A1" location.
' You can transfer to another area of the 2nd sheet
' by using an alternate starting location like "C5".
End Sub
Yes, constructors can throw exceptions. Usually this means that the new object is immediately eligible for garbage collection (although it may not be collected for some time, of course). It's possible for the "half-constructed" object to stick around though, if it's made itself visible earlier in the constructor (e.g. by assigning a static field, or adding itself to a collection).
One thing to be careful of about throwing exceptions in the constructor: because the caller (usually) will have no way of using the new object, the constructor ought to be careful to avoid acquiring unmanaged resources (file handles etc) and then throwing an exception without releasing them. For example, if the constructor tries to open a FileInputStream
and a FileOutputStream
, and the first succeeds but the second fails, you should try to close the first stream. This becomes harder if it's a subclass constructor which throws the exception, of course... it all becomes a bit tricky. It's not a problem very often, but it's worth considering.
Interestingly, this very site has issues with the approach you describe in connection with some proxy setups, even though it should be fail-safe.
Check this Meta Stack Overflow discussion.
So in light of that, it might make sense not to use a GET parameter to update, but the actual file name:
href="/css/scriptname/versionNumber.css"
even though this is more work to do, as you'll have to actually create the file, or build a URL rewrite for it.
use jquery : $("#id").css("background","red");
Advisory locking has been used for ages and it can be used in bash scripts. I prefer simple flock
(from util-linux[-ng]
) over lockfile
(from procmail
). And always remember about a trap on exit (sigspec == EXIT
or 0
, trapping specific signals is superfluous) in those scripts.
In 2009 I released my lockable script boilerplate (originally available at my wiki page, nowadays available as gist). Transforming that into one-instance-per-user is trivial. Using it you can also easily write scripts for other scenarios requiring some locking or synchronization.
Here is the mentioned boilerplate for your convenience.
#!/bin/bash
# SPDX-License-Identifier: MIT
## Copyright (C) 2009 Przemyslaw Pawelczyk <[email protected]>
##
## This script is licensed under the terms of the MIT license.
## https://opensource.org/licenses/MIT
#
# Lockable script boilerplate
### HEADER ###
LOCKFILE="/var/lock/`basename $0`"
LOCKFD=99
# PRIVATE
_lock() { flock -$1 $LOCKFD; }
_no_more_locking() { _lock u; _lock xn && rm -f $LOCKFILE; }
_prepare_locking() { eval "exec $LOCKFD>\"$LOCKFILE\""; trap _no_more_locking EXIT; }
# ON START
_prepare_locking
# PUBLIC
exlock_now() { _lock xn; } # obtain an exclusive lock immediately or fail
exlock() { _lock x; } # obtain an exclusive lock
shlock() { _lock s; } # obtain a shared lock
unlock() { _lock u; } # drop a lock
### BEGIN OF SCRIPT ###
# Simplest example is avoiding running multiple instances of script.
exlock_now || exit 1
# Remember! Lock file is removed when one of the scripts exits and it is
# the only script holding the lock or lock is not acquired at all.
Here is the solution :
This is kind of hack , but it will work
<input type="number"
placeholder="Charge"
[(ngModel)]="rateInput"
name="rateInput"
pattern="^$|^([0-9]|[1-9][0-9]|[1][0][0])?"
required
#rateInput2 = "ngModel">
<div *ngIf="rateInput2.errors && (rateInput2.dirty || rateInput2.touched)"
<div [hidden]="!rateInput2.errors.pattern">
Number should be between 0 and 100
</div>
</div>
Here is the link to the plunker , please have a look.
In order to build an AJAX webservice, you need TWO files :
So, first you call your webservice using this JQuery syntax, in the JavaScript file :
$.ajax({
url : 'mywebservice.php',
type : 'POST',
data : 'records_to_export=' + selected_ids, // On fait passer nos variables, exactement comme en GET, au script more_com.php
dataType : 'json',
success: function (data) {
alert("The file is "+data.fichierZIP);
},
error: function(data) {
//console.log(data);
var responseText=JSON.parse(data.responseText);
alert("Error(s) while building the ZIP file:\n"+responseText.messages);
}
});
Your PHP file (mywebservice.php, as written in the AJAX call) should include something like this in its end, to return a correct Success or Error status:
<?php
//...
//I am processing the data that the calling Javascript just ordered (it is in the $_POST). In this example (details not shown), I built a ZIP file and have its filename in variable "$filename"
//$errors is a string that may contain an error message while preparing the ZIP file
//In the end, I check if there has been an error, and if so, I return an error object
//...
if ($errors==''){
//if there is no error, the header is normal, and you return your JSON object to the calling JavaScript
header('Content-Type: application/json; charset=UTF-8');
$result=array();
$result['ZIPFILENAME'] = basename($filename);
print json_encode($result);
} else {
//if there is an error, you should return a special header, followed by another JSON object
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
$result=array();
$result['messages'] = $errors;
//feel free to add other information like $result['errorcode']
die(json_encode($result));
}
?>
This won't solve your problem but the mongodb shell has a copyTo
method that copies a collection into another one in the same database:
db.mycoll.copyTo('my_other_collection');
It also translates from BSON to JSON, so mongodump
/mongorestore
are the best way to go, as others have said.
A WSDL (Web Service Definition Language) is a meta-data file that describes the web service.
Things like operation name, parameters etc.
The soap messages are the actual payloads
Perhaps you'd consider using android:shadowColor, android:shadowDx
, android:shadowDy
, android:shadowRadius
; alternatively setShadowLayer() ?
You can use the instanceof
operator:
if (obj instanceof jQuery){
console.log('object is jQuery');
}
Explanation: the jQuery
function (aka $
) is implemented as a constructor function. Constructor functions are to be called with the new
prefix.
When you call $(foo)
, internally jQuery translates this to new jQuery(foo)
1. JavaScript proceeds to initialize this
inside the constructor function to point to a new instance of jQuery
, setting it's properties to those found on jQuery.prototype
(aka jQuery.fn
). Thus, you get a new
object where instanceof jQuery
is true
.
1It's actually new jQuery.prototype.init(foo)
: the constructor logic has been offloaded to another constructor function called init
, but the concept is the same.
As a supplement to the question and above answers there is also an important difference between plt.subplots()
and plt.subplot()
, notice the missing 's'
at the end.
One can use plt.subplots()
to make all their subplots at once and it returns the figure and axes (plural of axis) of the subplots as a tuple. A figure can be understood as a canvas where you paint your sketch.
# create a subplot with 2 rows and 1 columns
fig, ax = plt.subplots(2,1)
Whereas, you can use plt.subplot()
if you want to add the subplots separately. It returns only the axis of one subplot.
fig = plt.figure() # create the canvas for plotting
ax1 = plt.subplot(2,1,1)
# (2,1,1) indicates total number of rows, columns, and figure number respectively
ax2 = plt.subplot(2,1,2)
However, plt.subplots()
is preferred because it gives you easier options to directly customize your whole figure
# for example, sharing x-axis, y-axis for all subplots can be specified at once
fig, ax = plt.subplots(2,2, sharex=True, sharey=True)
whereas, with plt.subplot()
, one will have to specify individually for each axis which can become cumbersome.
Try this one for current selection:
Sub A_SelectAllMakeTable2()
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
or equivalent of your macro (for Ctrl+Shift+End range selection):
Sub A_SelectAllMakeTable()
Dim tbl As ListObject
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
In function post():
todo.author = users.get_current_user()
So, to get str(todo.author), you need str(users.get_current_user()). What is returned by get_current_user() function ?
If it is an object, check does it contain a str()" function?
I think the error lies there.
Why can't we create Object of Abstract Class ? When we create a pure virtual function in Abstract class, we reserve a slot for a function in the VTABLE(studied in last topic), but doesn't put any address in that slot. Hence the VTABLE will be incomplete. As the VTABLE for Abstract class is incomplete, hence the compiler will not let the creation of object for such class and will display an errror message whenever you try to do so.
Pure Virtual definitions
Pure Virtual functions can be given a small definition in the Abstract class, which you want all the derived classes to have. Still you cannot create object of Abstract class. Also, the Pure Virtual function must be defined outside the class definition. If you will define it inside the class definition, complier will give an error. Inline pure virtual definition is Illegal.
In addition to the "raw" tools provided by MutationObserver
API, there exist "convenience" libraries to work with DOM mutations.
Consider: MutationObserver represents each DOM change in terms of subtrees. So if you're, for instance, waiting for a certain element to be inserted, it may be deep inside the children of mutations.mutation[i].addedNodes[j]
.
Another problem is when your own code, in reaction to mutations, changes DOM - you often want to filter it out.
A good convenience library that solves such problems is mutation-summary
(disclaimer: I'm not the author, just a satisfied user), which enables you to specify queries of what you're interested in, and get exactly that.
Basic usage example from the docs:
var observer = new MutationSummary({
callback: updateWidgets,
queries: [{
element: '[data-widget]'
}]
});
function updateWidgets(summaries) {
var widgetSummary = summaries[0];
widgetSummary.added.forEach(buildNewWidget);
widgetSummary.removed.forEach(cleanupExistingWidget);
}
I ran into this issue when I didn't have an environment variable set.
docker push ${repo}${image_name}:${tag}
repo
and image_name
were defined but tag
wasn't.
This resulted in docker push repo/image_name:
.
Which threw the docker: invalid reference format.
My below code solve this issue, but i suggest First of all you need to understand what causing this issue and try the solution which you can find by changing code
I can give another way to solve this issue but better solution is to check your coding structure and try to analyse what makes this happen,if you do not find any solution then you can go with this code below
try{
Start:
///Put your file access code here
}catch (Exception ex)
{
//by anyway you need to handle this error with below code
if (ex.Message.StartsWith("The process cannot access the file"))
{
//Wait for 5 seconds to free that file and then start execution again
Thread.Sleep(5000);
goto Start;
}
}
Use the following code in your controller:
return Json(new { success = string }, JsonRequestBehavior.AllowGet);
and in JavaScript:
success: function (data) {
var response = data.success;
....
}
Try doing:
RecyclerView v = (RecyclerView) findViewById(...);
v.setNestedScrollingEnabled(false);
As an alternative, you can modify your layout using the support design library. I guess your current layout is something like:
<ScrollView >
<LinearLayout >
<View > <!-- upper content -->
<RecyclerView > <!-- with custom layoutmanager -->
</LinearLayout >
</ScrollView >
You can modify that to:
<CoordinatorLayout >
<AppBarLayout >
<CollapsingToolbarLayout >
<!-- with your content, and layout_scrollFlags="scroll" -->
</CollapsingToolbarLayout >
</AppBarLayout >
<RecyclerView > <!-- with standard layoutManager -->
</CoordinatorLayout >
However this is a longer road to take, and if you are OK with the custom linear layout manager, then just disable nested scrolling on the recycler view.
The v 23.2
release of the support libraries now includes a factory “wrap content” feature in all default LayoutManager
s. I didn’t test it, but you should probably prefer it to that library you were using.
<ScrollView >
<LinearLayout >
<View > <!-- upper content -->
<RecyclerView > <!-- with wrap_content -->
</LinearLayout >
</ScrollView >
A natural key, if available, is usually best. So, if datetime/char uniquely identifies the row and both parts are meaningful to the row, that's great.
If just the datetime is meaningful, and the char is just tacked on to make it unique, then you might as well just go with an identify field.
It's a convention in Ruby that methods that return boolean values end in a question mark. There's no more significance to it than that.
Setting window full height for empty divs
1st solution with absolute positioning - FIDDLE
.div1 {
position: absolute;
top: 0;
bottom: 0;
width: 25%;
}
.div2 {
position: absolute;
top: 0;
left: 25%;
bottom: 0;
width: 75%;
}
2nd solution with static (also can be used a relative) positioning & jQuery - FIDDLE
.div1 {
float: left;
width: 25%;
}
.div2 {
float: left;
width: 75%;
}
$(function(){
$('.div1, .div2').css({ height: $(window).innerHeight() });
$(window).resize(function(){
$('.div1, .div2').css({ height: $(window).innerHeight() });
});
});
You can access Gist by visiting the following url gist.github.com. Alternatively you can access it from within your Github account (after logging in) as shown in the picture below:
Github: A hosting service that houses a web-based git repository. It includes all the fucntionality of git with additional features added in.
Gist: Is an additional feature added to github to allow the sharing of code snippets, notes, to do lists and more. You can save your Gists as secret or public. Secret Gists are hidden from search engines but visible to anyone you share the url with.
For example. If you wanted to write a private to-do list. You could write one using Github Markdown as follows:
NB: It is important to preserve the whitespace as shown above between the dash and brackets. It is also important that you save the file with the extension .md because we want the markdown to format properly. Remember to save this Gist as secret if you do not want others to see it.
The end result looks like the image below. The checkboxes are clickable because we saved this Gist with the extension .md
In response to @A.M.K's question about how to do transitions without jQuery. A very simple example I threw together. If I had time to think this through some more, I might be able to eliminate the JavaScript code altogether:
<style>
body {
background-color: red;
transition: background-color 2s ease-in;
}
</style>
<script>
window.onload = function() {
document.body.style.backgroundColor = '#00f';
}
</script>
<body>
<p>test</p>
</body>
Well, did you DO what the error says? You go to some length telling about installation, but what about the obvious?
Found a possible workaround that I don't believe was mentioned.
Here is a good description of the problem: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Basically as long as you use forms/url-encoded/plain text content types you are fine.
$.ajax({
type: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'text/plain'
},
dataType: "json",
url: "http://localhost/endpoint",
data: JSON.stringify({'DataToPost': 123}),
success: function (data) {
alert(JSON.stringify(data));
}
});
I use it with ASP.NET WebAPI2. So on the other end:
public static void RegisterWebApi(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
}
This way Json formatter gets used when parsing plain text content type.
And don't forget in Web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST" />
</customHeaders>
</httpProtocol>
Hope this helps.
Initialization error occurred. There is not enough memory or disk space, or you entered an invalid drive name or invalid syntax on the command line.
So basically it could be just about anything haha...try running the command one at a time from the command prompt to figure out which part of which command is giving you trouble.
I suppose your dictMap is of type HashMap
, which makes it default to HashMap<Object, Object>
. If you want it to be more specific, declare it as HashMap<String, ArrayList>
, or even better, as HashMap<String, ArrayList<T>>
If you've come here for react-select v2, and still having trouble - version 2 now only accepts an object as value
, defaultValue
, etc.
That is, try using value={{value: 'one', label: 'One'}}
, instead of just value={'one'}
.
Assumptions: x
is the horizontal axis, and increases when moving from left to right.
y
is the vertical axis, and increases from bottom to top. (touch_x, touch_y)
is the
point selected by the user. (center_x, center_y)
is the point at the center of the
screen. theta
is measured counter-clockwise from the +x
axis. Then:
delta_x = touch_x - center_x
delta_y = touch_y - center_y
theta_radians = atan2(delta_y, delta_x)
Edit: you mentioned in a comment that y increases from top to bottom. In that case,
delta_y = center_y - touch_y
But it would be more correct to describe this as expressing (touch_x, touch_y)
in polar coordinates relative to (center_x, center_y)
. As ChrisF mentioned,
the idea of taking an "angle between two points" is not well defined.
you can use url module to collect parameters by using url.parse
var url = require('url');
var url_data = url.parse(request.url, true);
var query = url_data.query;
In expressjs it's done by,
var id = req.query.id;
Eg:
var express = require('express');
var app = express();
app.get('/login', function (req, res, next) {
console.log(req.query);
console.log(req.query.id); //Give parameter id
});
This example will exit after 5 seconds if another instance is already running.
// unique id for global mutex - Global prefix means it is global to the machine
const string mutex_id = "Global\\{B1E7934A-F688-417f-8FCB-65C3985E9E27}";
static void Main(string[] args)
{
using (var mutex = new Mutex(false, mutex_id))
{
try
{
try
{
if (!mutex.WaitOne(TimeSpan.FromSeconds(5), false))
{
Console.WriteLine("Another instance of this program is running");
Environment.Exit(0);
}
}
catch (AbandonedMutexException)
{
// Log the fact the mutex was abandoned in another process, it will still get aquired
}
// Perform your work here.
}
finally
{
mutex.ReleaseMutex();
}
}
}
In order to get the value of the selected item you can do the following:
this.options[this.selectedIndex].text
Here the different options
of the select are accessed, and the SelectedIndex
is used to choose the selected one, then its text
is being accessed.
Read more about the select DOM here.
The problem is that IE does not have the standard addEventListener
method. IE uses its own attachEvent
which does pretty much the same.
Good explanation of the differences, and also about the 3rd parameter can be found at quirksmode.
2-D Array Dynamic Memory Allocation
int **a,i;
// for any number of rows & columns this will work
a = (int **)malloc(rows*sizeof(int *));
for(i=0;i<rows;i++)
*(a+i) = (int *)malloc(cols*sizeof(int));
Shog9 is right that this doesn't make all that much sense to ask, since an object could be referred to by multiple variables. If you don't really care about that, and all you want is to find the name of one of the global variables that refers to that object, you could do the following hack:
function myClass() {
this.myName = function () {
// search through the global object for a name that resolves to this object
for (var name in this.global)
if (this.global[name] == this)
return name
}
}
// store the global object, which can be referred to as this at the top level, in a
// property on our prototype, so we can refer to it in our object's methods
myClass.prototype.global = this
// create a global variable referring to an object
var myVar = new myClass()
myVar.myName() // returns "myVar"
Note that this is an ugly hack, and should not be used in production code. If there is more than one variable referring to an object, you can't tell which one you'll get. It will only search the global variables, so it won't work if a variable is local to a function. In general, if you need to name something, you should pass the name in to the constructor when you create it.
edit: To respond to your clarification, if you need to be able to refer to something from an event handler, you shouldn't be referring to it by name, but instead add a function that refers to the object directly. Here's a quick example that I whipped up that shows something similar, I think, to what you're trying to do:
function myConstructor () {
this.count = 0
this.clickme = function () {
this.count += 1
alert(this.count)
}
var newDiv = document.createElement("div")
var contents = document.createTextNode("Click me!")
// This is the crucial part. We don't construct an onclick handler by creating a
// string, but instead we pass in a function that does what we want. In order to
// refer to the object, we can't use this directly (since that will refer to the
// div when running event handler), but we create an anonymous function with an
// argument and pass this in as that argument.
newDiv.onclick = (function (obj) {
return function () {
obj.clickme()
}
})(this)
newDiv.appendChild(contents)
document.getElementById("frobnozzle").appendChild(newDiv)
}
window.onload = function () {
var myVar = new myConstructor()
}
It's used to load modules. Let's use a simple example.
In file circle_object.js
:
var Circle = function (radius) {
this.radius = radius
}
Circle.PI = 3.14
Circle.prototype = {
area: function () {
return Circle.PI * this.radius * this.radius;
}
}
We can use this via require
, like:
node> require('circle_object')
{}
node> Circle
{ [Function] PI: 3.14 }
node> var c = new Circle(3)
{ radius: 3 }
node> c.area()
The require()
method is used to load and cache JavaScript modules. So, if you want to load a local, relative JavaScript module into a Node.js application, you can simply use the require()
method.
Example:
var yourModule = require( "your_module_name" ); //.js file extension is optional
If your need is to modify an existing workbook, the safest way would be to use pyoo. You need to have some libraries installed and it takes a few hoops to jump through but once its set up, this would be bulletproof as you are leveraging the wide and solid API's of LibreOffice / OpenOffice.
Please see my Gist on how to set up a linux system and do some basic coding using pyoo.
Here is an example of the code:
#!/usr/local/bin/python3
import pyoo
# Connect to LibreOffice using a named pipe
# (named in the soffice process startup)
desktop = pyoo.Desktop(pipe='oo_pyuno')
wkbk = desktop.open_spreadsheet("<xls_file_name>")
sheet = wkbk.sheets['Sheet1']
# Write value 'foo' to cell E5 on Sheet1
sheet[4,4].value='foo'
wkbk.save()
wkbk.close()
Try below code,
UIView *view1 = [[UIView alloc]init];
view1.backgroundColor = [UIColor blackColor];
[view1 setFrame:CGRectMake(0, 0, 50, 50)];
UIView *view2 = [[UIView alloc]init];
view2.backgroundColor = [UIColor greenColor];
[view2 setFrame:CGRectMake(0, 100, 100, 100)];
NSArray *subView = [NSArray arrayWithObjects:view1,view2, nil];
[self.stack1 initWithArrangedSubviews:subView];
Hope it works. Please let me know if you need anymore clarification.
If you also need to disable the drop-down (not to hide the text) then set the lengthChange
option to false
$('#datatable').dataTable( {
"lengthChange": false
} );
Works for DataTables 1.10+
Read more in the official documentation
This is my solution:
private string RandomString(int length)
{
char[] symbols = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
};
Stack<byte> bytes = new Stack<byte>();
string output = string.Empty;
for (int i = 0; i < length; i++)
{
if (bytes.Count == 0)
{
bytes = new Stack<byte>(Guid.NewGuid().ToByteArray());
}
byte pop = bytes.Pop();
output += symbols[(int)pop % symbols.Length];
}
return output;
}
// get 1st random string
string Rand1 = RandomString(4);
// get 2nd random string
string Rand2 = RandomString(4);
// create full rand string
string docNum = Rand1 + "-" + Rand2;
CSS:
tr {
width: 100%;
display: inline-table;
height:60px; // <-- the rows height
}
table{
height:300px; // <-- Select the height of the table
display: -moz-groupbox; // For firefox bad effect
}
tbody{
overflow-y: scroll;
height: 200px; // <-- Select the height of the body
width: 100%;
position: absolute;
}
Bootply : http://www.bootply.com/AgI8LpDugl
This can be caused by having invalid characters in a variable name. Variables names must follow these rules:
Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
public static function normalizeUrl(string $url) {
$parts = parse_url($url);
return $parts['scheme'] .
'://' .
$parts['host'] .
implode('/', array_map('rawurlencode', explode('/', $parts['path'])));
}
Lists typically preserve the order in which items are added. Do you definitely need a list, or would a sorted set (e.g. TreeSet<E>
) be okay for you? Basically, do you need to need to preserve duplicates?
I'm leaving the below post for reference purposes.
Please read Apple's documentation Human Interface Guidelines - Launch Screens for details on launch screens and recommendations.
Thanks
Drekka
July 2012 - As this reply is rather old, but stills seems popular. I've written a blog post based on Apple's doco and placed it on my blog. I hope you guys find it useful.
Yes. In iPhone/iPad development the Default.png
file is displayed by the device automatically so you don't have to program it which is really useful. I don't have it with me, but you need different PNGs for the iPad with specific names. I googled iPad default png
and got this info from the phunkwerks site:
To deal with various orientation options, a new naming convention has been created for iPad launch images. The screen size of the iPad is 768×1024, notice in the dimensions that follow the height takes into account a 20 pixel status bar.
Default-Portrait.png
* — 768w x 1024hDefault-PortraitUpsideDown.png
— 768w x 1024hDefault-Landscape.png
** — 1024w x 748hDefault-LandscapeLeft.png
— 1024w x 748hDefault-LandscapeRight.png
— 1024w x 748hiPad-Retina–Portrait.png
— 1536w x 2048hiPad-Retina–Landscape.png
— 2048w x 1496hDefault.png
— Not recommended*—If you have not specified a Default-PortraitUpsideDown.png
file, this file will take precedence.
**—If you have not specified a Default-LandscapeLeft.png
or Default-LandscapeRight.png
image file, this file will take precedence.
This link to "Apple's Developer Library" is useful, too.
The following code works fine:
@using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
and generates as expected:
<form action="/Upload/Upload" enctype="multipart/form-data" method="post">
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
</form>
On the other hand if you are writing this code inside the context of other server side construct such as an if
or foreach
you should remove the @
before the using
. For example:
@if (SomeCondition)
{
using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
}
As far as your server side code is concerned, here's how to proceed:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Upload");
}
you could try
if (isValid) {
document.getElementById("endTimeLabel").style.display = "none";
}else {
document.getElementById("endTimeLabel").style.display = "block";
}
alone those lines
Using jQuery 1.9 and above:
$("#mySelect :selected").prop('selected', false);
You would want to use CSS to achieve that.
say you have a table with the attribute id="my_table"
You would want to write the following in your css file
#my_table{
margin-top:10px //moves your table 10pixels down
margin-left:10px //moves your table 10pixels right
}
if you do not have a CSS file then you may just add margin-top:10px, margin-left:10px
to the style attribute in your table element like so
<table style="margin-top:10px; margin-left:10px;">
....
</table>
There are a lot of resources on the net describing CSS and HTML in detail
To switch the sign of an integer, you just use the sign operator:
myInt = -myInt;
To make it negative regardless if the original value is negative or not, you first use the Abs method:
myInt = -Math.Abs(myInt);
use the val() function
You can use the request object to find the logged in user
def my_view(request):
username = None
if request.user.is_authenticated():
username = request.user.username
According to https://docs.djangoproject.com/en/2.0/releases/1.10/
In version Django 2.0 the syntax has changed to
request.user.is_authenticated
You could use String.Split method.
class ExampleClass
{
public ExampleClass()
{
string exampleString = "there is a cat";
// Split string on spaces. This will separate all the words in a string
string[] words = exampleString.Split(' ');
foreach (string word in words)
{
Console.WriteLine(word);
// there
// is
// a
// cat
}
}
}
For more information see Sam Allen's article about splitting strings in c# (Performance, Regex)
This should work.
<div my-method='theMethodToBeCalled'></div>
app.directive("myMethod",function($parse) {
restrict:'A',
scope: {theMethodToBeCalled: "="}
link:function(scope,element,attrs) {
$(element).on('theEvent',function( e, rowid ) {
id = // some function called to determine id based on rowid
scope.theMethodToBeCalled(id);
}
}
}
app.controller("myController",function($scope) {
$scope.theMethodToBeCalled = function(id) { alert(id); };
}
I may have missed something here, but why can't you just declare your string with the desired size? For example, in my VBA code I often use something like:
Dim AString As String * 1024
which provides for a 1k string. Obviously, you can use whatever declaration you like within the larger limits of Excel and available memory etc.
This may be a little inefficient in some cases, and you will probably wish to use Trim(AString) like constructs to obviate any superfluous trailing blanks. Still, it easily exceeds 256 chars.
Use the Set
type:
A_set = Set([6,7,8,9,10,11,12])
subset_of_A_set = Set([6,9,12])
result = A_set - subset_of_A_set
It's significantly easier to grant management permissions to a service using one of these tools:
Here's the MSKB article with instructions for Windows Server 2008 / Windows 7, but the instructions are the same for 2000 and 2003.
You can try Microsoft's Face API. It can detect and identify people. learn more about face API here.
in my system it was
nano /usr/local/etc/my.cnf.default
as template and
nano /usr/local/etc/my.cnf
as working.
func dateDiff(dateStr:String) -> String {
var f:NSDateFormatter = NSDateFormatter()
f.timeZone = NSTimeZone.localTimeZone()
f.dateFormat = "yyyy-M-dd'T'HH:mm:ss.SSSZZZ"
var now = f.stringFromDate(NSDate())
var startDate = f.dateFromString(dateStr)
var endDate = f.dateFromString(now)
var calendar: NSCalendar = NSCalendar.currentCalendar()
let calendarUnits = NSCalendarUnit.CalendarUnitWeekOfMonth | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitSecond
let dateComponents = calendar.components(calendarUnits, fromDate: startDate!, toDate: endDate!, options: nil)
let weeks = abs(dateComponents.weekOfMonth)
let days = abs(dateComponents.day)
let hours = abs(dateComponents.hour)
let min = abs(dateComponents.minute)
let sec = abs(dateComponents.second)
var timeAgo = ""
if (sec > 0){
if (sec > 1) {
timeAgo = "\(sec) Seconds Ago"
} else {
timeAgo = "\(sec) Second Ago"
}
}
if (min > 0){
if (min > 1) {
timeAgo = "\(min) Minutes Ago"
} else {
timeAgo = "\(min) Minute Ago"
}
}
if(hours > 0){
if (hours > 1) {
timeAgo = "\(hours) Hours Ago"
} else {
timeAgo = "\(hours) Hour Ago"
}
}
if (days > 0) {
if (days > 1) {
timeAgo = "\(days) Days Ago"
} else {
timeAgo = "\(days) Day Ago"
}
}
if(weeks > 0){
if (weeks > 1) {
timeAgo = "\(weeks) Weeks Ago"
} else {
timeAgo = "\(weeks) Week Ago"
}
}
print("timeAgo is===> \(timeAgo)")
return timeAgo;
}
let's do try and checkout For Swift 3...
UIView.transition(with: mysuperview, duration: 0.75, options:UIViewAnimationOptions.transitionFlipFromRight , animations: {
myview.removeFromSuperview()
}, completion: nil)
I just built a sandbox environment with your code and it worked for me. Here is what I used:
<html>
<head>
<title>test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<form id="chatTickets" method="post" action="/admin/index.cfm/">
<input id="ticketID1" type="radio" checked="checked" value="myvalue1" name="ticketID"/>
<input id="ticketID2" type="radio" checked="checked" value="myvalue2" name="ticketID"/>
</form>
<a href="#" title="Load ActiveChat" id="loadActive">Load Active</a>
<script>
jQuery("#loadActive").click(function() {
//I have other code in here that runs before this function call
writeData();
});
function writeData() {
jQuery("input[name='ticketID']").each(function(i) {
jQuery(this).attr('disabled', 'disabled');
});
}
</script>
</body>
</html>
I tested in FF3.5, moving to IE8 now. And it works fine in IE8 too. What browser are you using?
IMHO, a very nice solution is to use c++11 emplace_back function:
revenue.emplace_back("string", map[i].second);
It just creates a new element in place.
I just ran into this problem in Visual Studio 2013. Apparently now, having two projects in the same solution and setting the the dependencies is not enough. You need to add a project reference between them. To do that:
Although this question is rather old, I'd like to share my solution for angular 1 developers. The point is to just reuse the original angular filter, but transparently passing any objects as an array.
app.filter('objectFilter', function ($filter) {
return function (items, searchToken) {
// use the original input
var subject = items;
if (typeof(items) == 'object' && !Array.isArray(items)) {
// or use a wrapper array, if we have an object
subject = [];
for (var i in items) {
subject.push(items[i]);
}
}
// finally, apply the original angular filter
return $filter('filter')(subject, searchToken);
}
});
use it like this:
<div>
<input ng-model="search" />
</div>
<div ng-repeat="item in test | objectFilter : search">
{{item | json}}
</div>
here is a plunker
I don't know anything provided by the Framework (beyond what you want to avoid) that would do what you want but (as I suspect you know) it would be pretty easy to create something simple yourself:
private DataTable GetDataTableFromDGV(DataGridView dgv) {
var dt = new DataTable();
foreach (DataGridViewColumn column in dgv.Columns) {
if (column.Visible) {
// You could potentially name the column based on the DGV column name (beware of dupes)
// or assign a type based on the data type of the data bound to this DGV column.
dt.Columns.Add();
}
}
object[] cellValues = new object[dgv.Columns.Count];
foreach (DataGridViewRow row in dgv.Rows) {
for (int i = 0; i < row.Cells.Count; i++) {
cellValues[i] = row.Cells[i].Value;
}
dt.Rows.Add(cellValues);
}
return dt;
}
One way is to loop through the keys of the dictionary, which I recommend:
foreach(int key in sp.Keys)
dynamic value = sp[key];
Another way, is to loop through the dictionary as a sequence of pairs:
foreach(KeyValuePair<int, dynamic> pair in sp)
{
int key = pair.Key;
dynamic value = pair.Value;
}
I recommend the first approach, because you can have more control over the order of items retrieved if you decorate the Keys
property with proper LINQ statements, e.g., sp.Keys.OrderBy(x => x)
helps you retrieve the items in ascending order of the key. Note that Dictionary
uses a hash table data structure internally, therefore if you use the second method the order of items is not easily predictable.
Update (01 Dec 2016): replaced var
s with actual types to make the answer more clear.