You can run brew link openssl
to link it into /usr/local
, if you don't mind the potential problem highlighted in the warning message. Otherwise, you can add the openssl bin directory to your path:
export PATH=$(brew --prefix openssl)/bin:$PATH
A new paper has been released with several tests against reCAPTCHA:
Some highlights:
Google has already fixed the cookie vulnerability and is probably restricting some behaviors based on IPs.
Another interesting finding is that Google runs a VM in JavaScript that obfuscates much of reCAPTCHA code and behavior. This VM is known as botguard and is used to protect other services besides reCAPTCHA:
https://github.com/neuroradiology/InsideReCaptcha
UPDATE 2017
A recent paper (from August) was published on WOOT 2017 achieving 85% accuracy in solving noCAPTCHA reCAPTCHA audio challenges:
http://uncaptcha.cs.umd.edu/papers/uncaptcha_woot17.pdf
UPDATE 2018
Google is introducing reCAPTCHA v3, which looks like a "human score prediction engine" that is calibrated per website. It can be installed into different pages of a website (working like a Google Analytics script) to help reCAPTCHA and the website owner to understand the behaviour of humans vs. bots before filling a reCAPTCHA.
You can enable NuGet packages and update you dlls. so that it work. or you can update the package manually by going through the package manager in your vs if u know which version you require for your solution.
This is how I've recently fixed the error
@app.route('/')
def home():
docs = []
for doc in db.person.find():
doc.pop('_id')
docs.append(doc)
return jsonify(docs)
They have wrapped most stuff need to solve your problem, one of the tests looks like this:
String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " ");
String code = "background: url(folder.png);";
StringWriter writer = new StringWriter();
embedder = new CSSURLEmbedder(new StringReader(code), true);
embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1));
String result = writer.toString();
assertEquals("background: url(" + folderDataURI + ");", result);
Typical, found it right after posting this question in despair; the tool I was looking for was:
$ aapt dump badging <my_apk.apk>
You need to convert your private key to PKCS8 format using following command:
openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file -nocrypt > pkcs8_key
After this your java program can read it.
There was a problem once in ruby where files in windows needed an "fsync" to actually be able to turn around and re-read the file after writing it and closing it. Maybe this is a similar manifestation (and if so, I think a windows bug, really).
just use this:
<script>
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["1","2","3","4","5","6","7","8","9","10","11",],
datasets: [{
label: 'YOUR LABEL',
backgroundColor: [
"#566573",
"#99a3a4",
"#dc7633",
"#f5b041",
"#f7dc6f",
"#82e0aa",
"#73c6b6",
"#5dade2",
"#a569bd",
"#ec7063",
"#a5754a"
],
data: [12, 19, 3, 17, 28, 24, 7, 2,4,14,6],
},]
},
//HERE COMES THE AXIS Y LABEL
options : {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}]
}
}
});
</script>
It sounds like installing the VS2017 update for that specific version didn't also install the .NET Core 2.0 SDK. You can download that here.
To check which version of the SDK you've already got installed, run
dotnet --info
from the command line. Note that if there's a global.json
file in either your current working directory or any ancestor directory, that will override which version of the SDK is run. (That's useful if you want to enforce a particular version for a project, for example.)
Judging by comments, some versions of VS2017 updates do install the .NET Core SDK. I suspect it may vary somewhat over time.
**
operator would be helpful here.
**
operator will unpack the dict elements and thus **{'type':'Event'}
would be treated as type='Event'
func(**{'type':'Event'})
is same as func(type='Event')
i.e the dict elements would be converted to the keyword arguments
.
FYI
*
will unpack the list elements and they would be treated as positional arguments
.
func(*['one', 'two'])
is same as func('one', 'two')
This does it:
Do
c = c + 1
Loop While Cells(c, "A").Value <> ""
'prints the last empty row
Debug.Print c
I know this is old question. But maybe this can help you
var jsonStr = '{ "bool": true, "number": 123, "string": "foo bar" }';
JSON.stringify(JSON.parse(jsonStr), null, 2);
JSON.stringify(JSON.parse(jsonStr));
Strings are immutable and cannot be altered once they have been created. Creating a password as a string will leave stray references to the password on the heap or on the String pool. Now if someone takes a heap dump of the Java process and carefully scans through he might be able to guess the passwords. Of course these non used strings will be garbage collected but that depends on when the GC kicks in.
On the other side char[] are mutable as soon as the authentication is done you can overwrite them with any character like all M's or backslashes. Now even if someone takes a heap dump he might not be able to get the passwords which are not currently in use. This gives you more control in the sense like clearing the Object content yourself vs waiting for the GC to do it.
I will answer your question using a math analogy:
In this instance, the number 0 will represent no value. If you pick a random number, say 15, how many times can 0 be subtracted from 15? Infinite times because 0 has no value, thus you are taking nothing out of 15. Do you have difficulty accepting that 15 - 0 = 15 instead of ERROR? So if we switch this analogy back to Java coding, the String "" represents no value. Pick a random string, say "hello world", how many times can "" be subtracted from "hello world"?
This will work fast:
Case 1 - File2 = File1 + extra text appended.
grep -Fxvf File2.txt File1.txt >> File3.txt
File 1: 80 Lines File 2: 100 Lines File 3: 20 Lines
Accepted answer doesn't work with "use strict" as the "with" statement throws an error. So instead:
$.post(url, function (data) {
var w = window.open('about:blank', 'windowname');
w.document.write(data);
w.document.close();
});
Also, make sure 'windowname' doesn't have any spaces in it because that will fail in IE :)
You can use the Unix-style -l
switch – typically terse and cryptic – or the equivalent --files-with-matches
– longer and more readable.
The output of grep --help
is not easy to read, but it's there:
-l, --files-with-matches print only names of FILEs containing matches
emanuel.directive('hymn', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
// some ode
},
templateUrl: function(elem,attrs) {
return attrs.templateUrl || 'some/path/default.html'
}
}
});
So you can provide templateUrl via markup
<hymn template-url="contentUrl"><hymn>
Now you just take a care that property contentUrl populates with dynamically generated path.
Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx
You can also use command line utility net
to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code
First, in bash "[" is just a command, which expects string "]" as a last argument, so the whitespace before the closing bracket (as well as between "!" and "-d" which need to be two separate arguments too) is important:
if [ ! -d /home/mlzboy/b2c2/shared/db ]; then
mkdir -p /home/mlzboy/b2c2/shared/db;
fi
Second, since you are using -p switch to mkdir
, this check is useless, because this is what does in the first place. Just write:
mkdir -p /home/mlzboy/b2c2/shared/db;
and thats it.
# -*- coding: utf-8 -*-
is a Python 2 thing. In Python 3+, the default encoding of source files is already UTF-8 and that line is useless.
See: Should I use encoding declaration in Python 3?
pyupgrade
is a tool you can run on your code to remove those comments and other no-longer-useful leftovers from Python 2, like having all your classes inherit from object
.
To change DNS to automatic via command, you can run the following command:
netsh interface ip set dns "Local Area Connection" dhcp
I think the best way to do it is to create a global var array. Then do whatever you want to it inside the function data by passing it as a reference. No need to return anything too.
$array = array("white", "black", "yellow");
echo $array[0]; //this echo white
data($array);
function data(&$passArray){ //<<notice &
$passArray[0] = "orange";
}
echo $array[0]; //this now echo orange
You need to set the Format of the DateTimePicker to Custom and then assign the CustomFormat.
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = "dd/MM/yyyy"
End Sub
Aapt2, included in the Android SDK build tools can do this - no third party tools needed.
$(ANDROID_SDK)/build-tools/28.0.3/aapt2 d --file AndroidManifest.xml app-foo-release.apk
Starting with build-tools v29 you have to add the command xmltree
:
$(ANDROID_SDK)/build-tools/29.0.3/aapt2 d xmltree --file AndroidManifest.xml app-foo-release.apk
If someone finds this question like I did, then I'll post my solution which works on Django 2.0:
This tag assigns some settings.py variable value to template's variable:
Usage: {% get_settings_value template_var "SETTINGS_VAR" %}
from django import template
from django.conf import settings
register = template.Library()
class AssignNode(template.Node):
def __init__(self, name, value):
self.name = name
self.value = value
def render(self, context):
context[self.name] = getattr(settings, self.value.resolve(context, True), "")
return ''
@register.tag('get_settings_value')
def do_assign(parser, token):
bits = token.split_contents()
if len(bits) != 3:
raise template.TemplateSyntaxError("'%s' tag takes two arguments" % bits[0])
value = parser.compile_filter(bits[2])
return AssignNode(bits[1], value)
{% load my_custom_tags %}
# Set local template variable:
{% get_settings_value settings_debug "DEBUG" %}
# Output settings_debug variable:
{{ settings_debug }}
# Use variable in if statement:
{% if settings_debug %}
... do something ...
{% else %}
... do other stuff ...
{% endif %}
See Django's documentation how to create custom template tags here: https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/
Late to the game, but most of these seem quite complicated.
Here's how I did it:
var originalSelect = $('#select-2').html();
// filter select-2 on select-1 change
$('#select-1').change(function (e) {
var selected = $(this).val();
// reset select ready for filtering
$('#select-2').html(originalCourseSelect);
if (selected) {
// filter
$('#select-2 option').not('.t' + selected).remove();
}
});
markup of select-1:
<select id='select-1'>
<option value=''>Please select</option>
<option value='1'>One</option>
<option value='2'>Two</option>
</select>
markup of select-2:
<select id='select-2'>
<option class='t1'>One</option>
<option class='t2'>Two</option>
<option>Always visible</option>
</select>
This is what worked for me:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
Turns out that I just have to convert @column
name testName to all small letters, since it was initially in camel case.
Although I was not able to use the official answer, the question was able to help me solve my problem by letting me know what to investigate.
Change:
@Column(name="testName")
private String testName;
To:
@Column(name="testname")
private String testName;
Your command should include the url parameter as stated in the script usage comments. The main function has 2 parameters, url and out (which is set to a default value) C:\python23\python "C:\PathToYourScript\SCRIPT.py" http://yoururl.com "C:\OptionalOutput\"
You can call more of 1 function filters in the same ng-repeat filter
<article data-ng-repeat="result in results | filter:search() | filter:filterFn()" class="result">
you do not need to know pts number, just type:
ps all | grep bash
then:
kill pid1 pid2 pid3 ...
A workaround of mine is to manipulate a model variable just for the ng-class toggling:
For example, I want to toggle class according to the state of my list:
1) Whenever my list is empty, I update my model:
$scope.extract = function(removeItemId) {
$scope.list= jQuery.grep($scope.list, function(item){return item.id != removeItemId});
if (!$scope.list.length) {
$scope.liststate = "empty";
}
}
2) Whenever my list is not empty, I set another state
$scope.extract = function(item) {
$scope.list.push(item);
$scope.liststate = "notempty";
}
3) When my list is not ever touched, I want to give another class (this is where the page is initiated):
$scope.liststate = "init";
3) I use this additional model on my ng-class:
ng-class="{'bg-empty': liststate == 'empty', 'bg-notempty': liststate == 'notempty', 'bg-init': liststate = 'init'}"
Whenever you create child class object then that object has all the features of parent class. Here Super() is the facilty for accession parent.
If you write super() at that time parents's default constructor is called. same if you write super.
this keyword refers the current object same as super key word facilty for accessing parents.
You can check Wikipedia. But mainly when more actions or resources are used. Like if you are familiar with .NET there you can have value types and reference types. Reference types have memory overhead as they require more memory than value types.
hostname(1) can tell the IP address: hostname --ip-address
, or as man says, it's better to use hostname --all-ip-addresses
Simply get a count of the record(s) you're looking for. If count > 0 then record(s) exist.
DECLARE rec_count NUMBER := 0; BEGIN select count(*) into rec_count from EMPLOYEETABLE WHERE employee_id = inEMPLOYEE_ID AND department_nbr = inDEPARTMENT_NBR; if rec_count > 0 then {UPDATE EMPLOYEETABLE} else {INSERT INTO EMPLOYEETABLE} end if; END;
Try putting the btn-group
inside the H4
like this..
<div class="panel-heading">
<h4>Panel header
<span class="btn-group pull-right">
<a href="#" class="btn btn-default btn-sm">## Lock</a>
<a href="#" class="btn btn-default btn-sm">## Delete</a>
<a href="#" class="btn btn-default btn-sm">## Move</a>
</span>
</h4>
</div>
Found this: https://coderwall.com/p/ngisma where Nathan Walker (near bottom of page) suggests a decorator in $rootScope to create func 'safeApply', code:
yourAwesomeModule.config([
'$provide', function($provide) {
return $provide.decorator('$rootScope', [
'$delegate', function($delegate) {
$delegate.safeApply = function(fn) {
var phase = $delegate.$$phase;
if (phase === "$apply" || phase === "$digest") {
if (fn && typeof fn === 'function') {
fn();
}
} else {
$delegate.$apply(fn);
}
};
return $delegate;
}
]);
}
]);
IE has a setting, located in Tools
/ Internet options
/ Advanced
/ Browsing
, called Reuse windows for launching shortcuts
, which is checked by default. For IE versions that support tabbed browsing, this option is relevant only when tab browsing is turned off (in fact, IE9 Beta explicitly mentions this). However, since IE6 does not have tabbed browsing, this option does affect opening URLs through the shell (as in your example).
References are "hidden pointers" (non-null) to things which can change (lvalues). You cannot define them to a constant. It should be a "variable" thing.
EDIT::
I am thinking of
int &x = y;
as almost equivalent of
int* __px = &y;
#define x (*__px)
where __px
is a fresh name, and the #define x
works only inside the block containing the declaration of x
reference.
What about something like this ?
class Configuration
{
private $config;
public function __construct($configIniFilePath)
{
$this->config = parse_ini_file($configIniFilePath, true);
}
/**
* Gets the value for the specified setting name.
*
* @param string $name the setting name
* @param string $section optional, the name of the section containing the
* setting
* @return string|null the value of the setting, or null if it doesn't exist
*/
public function getConfiguration($name, $section = null)
{
$configValue = null;
if ($section === null) {
if (array_key_exists($name, $this->config)) {
$configValue = $this->config[$name];
}
} else {
if (array_key_exists($section, $this->config)) {
$sectionSettings = $this->config[$section];
if (array_key_exists($name, $sectionSettings)) {
$configValue = $sectionSettings[$name];
}
}
}
return $configValue;
}
}
Why not just use .show()/.hide()
instead?
$("#menu").hover(function(){
$('.flyout').show();
},function(){
$('.flyout').hide();
});
you have to take this into account (from DropdownButton docs):
"The items must have distinct values and if value isn't null it must be among them."
So basically you have this list of strings
List<String> _locations = ['A', 'B', 'C', 'D'];
And your value in Dropdown value property is initialised like this:
String _selectedLocation = 'Please choose a location';
Just try with this list:
List<String> _locations = ['Please choose a location', 'A', 'B', 'C', 'D'];
That should work :)
Also check out the "hint" property if you don't want to add a String like that (out of the list context), you could go with something like this:
DropdownButton<int>(
items: locations.map((String val) {
return new DropdownMenuItem<String>(
value: val,
child: new Text(val),
);
}).toList(),
hint: Text("Please choose a location"),
onChanged: (newVal) {
_selectedLocation = newVal;
this.setState(() {});
});
$watch
returns a deregistration function. Calling it would deregister the $watcher
.
var listener = $scope.$watch("quartz", function () {});
// ...
listener(); // Would clear the watch
Your format specifier is incorrect. From the printf()
man page on my machine:
0
A zero '0
' character indicating that zero-padding should be used rather than blank-padding. A '-
' overrides a '0
' if both are used;Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);
Precision: An optional period, '
.
', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;
For your case, your format would be %09.3f
:
#include <stdio.h>
int main(int argc, char **argv)
{
printf("%09.3f\n", 4917.24);
return 0;
}
Output:
$ make testapp
cc testapp.c -o testapp
$ ./testapp
04917.240
Note that this answer is conditional on your embedded system having a printf()
implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.
Use the latest supportLibrary
, version 27.1.1
to solve the problem. worked for me. (many bug fixes included - see changelog)
I don't know why everybody is answering this question in context of .NET. The question was a general one and didn't mention .NET anywhere.
Well, the major differences are:
EXE
DLL
The file format of DLL and exe is essentially the same. Windows recognizes the difference between DLL and EXE through PE Header in the file. For details of PE Header, You can have a look at this Article on MSDN
SqlConnection con = new SqlConnection("Data Source=DShp;Initial Catalog=abc;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("data", con);
da.SelectCommand.CommandType= CommandType.StoredProcedure;
DataSet ds=new DataSet();
da.Fill(ds, "data");
GridView1.DataSource = ds.Tables["data"];
GridView1.DataBind();
This worked for me, converts to nested JSON to easy to read YAML
string JSONDeserialized {get; set;}
public int indentLevel;
private bool JSONDictionarytoYAML(Dictionary<string, object> dict)
{
bool bSuccess = false;
indentLevel++;
foreach (string strKey in dict.Keys)
{
string strOutput = "".PadLeft(indentLevel * 3) + strKey + ":";
JSONDeserialized+="\r\n" + strOutput;
object o = dict[strKey];
if (o is Dictionary<string, object>)
{
JSONDictionarytoYAML((Dictionary<string, object>)o);
}
else if (o is ArrayList)
{
foreach (object oChild in ((ArrayList)o))
{
if (oChild is string)
{
strOutput = ((string)oChild);
JSONDeserialized += strOutput + ",";
}
else if (oChild is Dictionary<string, object>)
{
JSONDictionarytoYAML((Dictionary<string, object>)oChild);
JSONDeserialized += "\r\n";
}
}
}
else
{
strOutput = o.ToString();
JSONDeserialized += strOutput;
}
}
indentLevel--;
return bSuccess;
}
usage
Dictionary<string, object> JSONDic = new Dictionary<string, object>();
JavaScriptSerializer js = new JavaScriptSerializer();
try {
JSONDic = js.Deserialize<Dictionary<string, object>>(inString);
JSONDeserialized = "";
indentLevel = 0;
DisplayDictionary(JSONDic);
return JSONDeserialized;
}
catch (Exception)
{
return "Could not parse input JSON string";
}
If you wish to open the batch file in another window, use start
. This way, you can basically run two scripts at the same time. In other words, you don't have to wait for the script you just called to finish.
All examples below work:
start batch.bat
start call batch.bat
start cmd /c batch.bat
If you want to wait for the script to finish, try start /w call batch.bat
, but the batch.bat has to end with exit
.
The top voted answer does not work for MacOS so for those on a mac, I've successfully tested this:
GATEWAY=`route -n get default | grep gateway`
if [ -z "$GATEWAY" ]
then
echo error
else
ping -q -t 1 -c 1 `echo $GATEWAY | cut -d ':' -f 2` > /dev/null && echo ok || echo error
fi
tested on MacOS High Sierra 10.12.6
There's a surprisingly nice library for Android HTTP available at the link below:
http://loopj.com/android-async-http/
Simple requests are very easy:
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
System.out.println(response);
}
});
To send JSON (credit to `voidberg' at https://github.com/loopj/android-async-http/issues/125):
// params is a JSONObject
StringEntity se = null;
try {
se = new StringEntity(params.toString());
} catch (UnsupportedEncodingException e) {
// handle exceptions properly!
}
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
client.post(null, "www.example.com/objects", se, "application/json", responseHandler);
It's all asynchronous, works well with Android and safe to call from your UI thread. The responseHandler will run on the same thread you created it from (typically, your UI thread). It even has a built-in resonseHandler for JSON, but I prefer to use google gson.
Many distinctions have already been mentioned. Here is one more:
Running npm install
at the top of your source directory will run various scripts: prepublish
, preinstall
, install
, postinstall
. Depending on what these scripts do, a npm install
may do considerably more work than just installing dependencies.
I've just had a use case where prepublish
would call make
and the Makefile
was designed to fetch dependencies if the package.json
got updated. Calling npm install
from within the Makefile
would have lead to an infinite recursion, while calling npm update
worked just fine, installing all dependencies so that the build could proceed even if make
was called directly.
Works for me:
public class BackupService
{
private readonly string _connectionString;
private readonly string _backupFolderFullPath;
private readonly string[] _systemDatabaseNames = { "master", "tempdb", "model", "msdb" };
public BackupService(string connectionString, string backupFolderFullPath)
{
_connectionString = connectionString;
_backupFolderFullPath = backupFolderFullPath;
}
public void BackupAllUserDatabases()
{
foreach (string databaseName in GetAllUserDatabases())
{
BackupDatabase(databaseName);
}
}
public void BackupDatabase(string databaseName)
{
string filePath = BuildBackupPathWithFilename(databaseName);
using (var connection = new SqlConnection(_connectionString))
{
var query = String.Format("BACKUP DATABASE [{0}] TO DISK='{1}'", databaseName, filePath);
using (var command = new SqlCommand(query, connection))
{
connection.Open();
command.ExecuteNonQuery();
}
}
}
private IEnumerable<string> GetAllUserDatabases()
{
var databases = new List<String>();
DataTable databasesTable;
using (var connection = new SqlConnection(_connectionString))
{
connection.Open();
databasesTable = connection.GetSchema("Databases");
connection.Close();
}
foreach (DataRow row in databasesTable.Rows)
{
string databaseName = row["database_name"].ToString();
if (_systemDatabaseNames.Contains(databaseName))
continue;
databases.Add(databaseName);
}
return databases;
}
private string BuildBackupPathWithFilename(string databaseName)
{
string filename = string.Format("{0}-{1}.bak", databaseName, DateTime.Now.ToString("yyyy-MM-dd"));
return Path.Combine(_backupFolderFullPath, filename);
}
}
If you just want to get the information of current directory, you can type:
pwd
and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.
I have managed to modify some of @alpiii's code and discovered that List comprehension is a little faster than for loop. It might be caused by int()
, it is not fair between list comprehension and for loop.
from functools import reduce
import datetime
def time_it(func, numbers, *args):
start_t = datetime.datetime.now()
for i in range(numbers):
func(args[0])
print (datetime.datetime.now()-start_t)
def square_sum1(numbers):
return reduce(lambda sum, next: sum+next*next, numbers, 0)
def square_sum2(numbers):
a = []
for i in numbers:
a.append(i*2)
a = sum(a)
return a
def square_sum3(numbers):
sqrt = lambda x: x*x
return sum(map(sqrt, numbers))
def square_sum4(numbers):
return(sum([i*i for i in numbers]))
time_it(square_sum1, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum2, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum3, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum4, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
0:00:00.101122 #Reduce
0:00:00.089216 #For loop
0:00:00.101532 #Map
0:00:00.068916 #List comprehension
you should use regular expressions to find all you need:
import re
p = re.compile(r'(\d+)') # a pattern for a number
for line in file :
if num in p.findall(line) :
print line
regular expression will return you all numbers in a line as a list, for example:
>>> re.compile(r'(\d+)').findall('123kh234hi56h9234hj29kjh290')
['123', '234', '56', '9234', '29', '290']
so you don't match '200' or '220' for '20'.
The following source code will give you no.of occurrences of a given string in a word entered by user :-
import java.util.Scanner;
public class CountingOccurences {
public static void main(String[] args) {
Scanner inp= new Scanner(System.in);
String str;
char ch;
int count=0;
System.out.println("Enter the string:");
str=inp.nextLine();
while(str.length()>0)
{
ch=str.charAt(0);
int i=0;
while(str.charAt(i)==ch)
{
count =count+i;
i++;
}
str.substring(count);
System.out.println(ch);
System.out.println(count);
}
}
}
There is a comparison of the features and performance of RabbitMQ ActiveMQ and QPID given at
http://bhavin.directi.com/rabbitmq-vs-apache-activemq-vs-apache-qpid/
Personally I have tried all the above three. RabbitMQ is the best performance wise according to me, but it does not have failover and recovery options. ActiveMQ has the most features, but is slower.
Update : HornetQ is also an option you can look into, it is JMS Complaint, a better option than ActiveMQ if you are looking for a JMS based solution.
brilliant example Jonathan Leffler, to make your code work on SLES, I needed to add an additional header to allow the pid_t object :)
#include <sys/types.h>
I got pretty good results with my HTML mailing list by using the following:
p { margin-bottom: 0; }
ul { margin-top: 0; }
This does not reset all margin values but only those that create such a gap before ordered list, and still doesn't assume anything about default margin values.
DevTools: [network] explain empty bars preceeding request
Investigated further and have identified that there's no significant difference between our Stalled and Queueing ranges. Both are calculated from the delta's of other timestamps, rather than provided from netstack or renderer.
Currently, if we're waiting for a socket to become available:
- we'll call it stalled if some proxy negotiation happened
- we'll call it queuing if no proxy/ssl work was required.
In general, pickling a dict
will fail unless you have only simple objects in it, like strings and integers.
Python 2.7.9 (default, Dec 11 2014, 01:21:43)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from numpy import *
>>> type(globals())
<type 'dict'>
>>> import pickle
>>> pik = pickle.dumps(globals())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1374, in dumps
Pickler(file, protocol).dump(obj)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 224, in dump
self.save(obj)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 649, in save_dict
self._batch_setitems(obj.iteritems())
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 663, in _batch_setitems
save(v)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 306, in save
rv = reduce(self.proto)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy_reg.py", line 70, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle module objects
>>>
Even a really simple dict
will often fail. It just depends on the contents.
>>> d = {'x': lambda x:x}
>>> pik = pickle.dumps(d)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1374, in dumps
Pickler(file, protocol).dump(obj)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 224, in dump
self.save(obj)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 649, in save_dict
self._batch_setitems(obj.iteritems())
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 663, in _batch_setitems
save(v)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 748, in save_global
(obj, module, name))
pickle.PicklingError: Can't pickle <function <lambda> at 0x102178668>: it's not found as __main__.<lambda>
However, if you use a better serializer like dill
or cloudpickle
, then most dictionaries can be pickled:
>>> import dill
>>> pik = dill.dumps(d)
Or if you want to save your dict
to a file...
>>> with open('save.pik', 'w') as f:
... dill.dump(globals(), f)
...
The latter example is identical to any of the other good answers posted here (which aside from neglecting the picklability of the contents of the dict
are good).
The term Endpoint was initially used for WCF services. Later even though this word is being used synonymous to API resources, REST recommends to call these URI (URI[s] which understand HTTP verbs and follow REST architecture) as "Resource".
In a nutshell, a Resource or Endpoint is kind of an entry point to a remotely hosted application which lets the users to communicate to it via HTTP protocol.
Chirag Nagariya is right except the '_Fullscreen' addition. it can be solved using any base style which not derived from Dialog style. 'android.R.style.Theme_Black_NoTitleBar' can be used as well.
You could subscribe for the change and keyup events:
$(function() {
$(':input').change(myFunction).keyup(myFunction);
});
where myFunction
is the function you would like executed:
function myFunction() {
alert( 'something happened!' );
}
One way of doing it is to use the ClientScriptManager
:
Page.ClientScript.RegisterStartupScript(
GetType(),
"MyKey",
"Myfunction();",
true);
Abstract Class
1. Contains an abstract method
2. Cannot be directly initialized
3. Cannot create an object of abstract class
4. Only used for inheritance purposes
Abstract Method
1. Cannot contain a body
2. Cannot be defined as private
3. Child classes must define the methods declared in abstract class
Example Code:
abstract class A {
public function test1() {
echo 'Hello World';
}
abstract protected function f1();
abstract public function f2();
protected function test2(){
echo 'Hello World test';
}
}
class B extends A {
public $a = 'India';
public function f1() {
echo "F1 Method Call";
}
public function f2() {
echo "F2 Method Call";
}
}
$b = new B();
echo $b->test1() . "<br/>";
echo $b->a . "<br/>";
echo $b->test2() . "<br/>";
echo $b->f1() . "<br/>";
echo $b->f2() . "<br/>";
Output:
Hello World
India
Hello World test
F1 Method Call
F2 Method Call
To copy dirs, it seems you can use adb pull <remote> <local>
if you want to copy file/dir from device, and adb push <local> <remote>
to copy file/dir to device. Alternatively, just to copy a file, you can use a simple trick: cat source_file > dest_file
. Note that this does not work for user-inaccessible paths.
To edit files, I have not found a simple solution, just some possible workarounds. Try this, it seems you can (after the setup) use it to edit files like busybox vi <filename>
. Nano seems to be possible to use too.
contentType: 'application/x-www-form-urlencoded'
Your logic is correct but you have 2 mistakes apparently everyone missed:
just change if(Number(i) = 'NaN')
to if(Number(i) == NaN)
NaN
is a constant and you should use double equality signs to compare, a single one is used to assign values to variables.
I realize the question might be rather old, but you say the backend is running on the same server. That means on a different port, probably other than the default port 80.
I've read that when you use the "connectionManagement" configuration element, you need to specify the port number if it differs from the default 80.
LINK: maxConnection setting may not work even autoConfig = false in ASP.NET
Secondly, if you choose to use the default configuration (address="*") extended with your own backend specific value, you might consider putting the specific value first! Otherwise, if a request is made, the * matches first and the default of 2 connections is taken. Just like when you use the section in web.config.
LINK: <remove> Element for connectionManagement (Network Settings)
Hope it helps someone.
The runas /netonly /user:domain\username program.exe
command only worked for me on Windows 10
when running the command batch as regular user I got the wrong password issue mentioned by some users on previous comments.
I resolved this by clearing App Data.
Cypress documentation admits that App Data can get corrupted:
Cypress maintains some local application data in order to save user preferences and more quickly start up. Sometimes this data can become corrupted. You may fix an issue you have by clearing this app data.
cypress open
File
-> View App Data
cy
whose content should look something
like this: production
all.log
browsers
bundles
cache
projects
proxy
state.json
cy
folderSource: https://docs.cypress.io/guides/references/troubleshooting.html#To-clear-App-Data
https://developer.mozilla.org/en/CSS/Media_queries#-moz-device-pixel-ratio
-moz-device-pixel-ratio
Gives the number of device pixels per CSS pixel.
this is almost self-explaining. the number describes the ratio of how much "real" pixels (physical pixerls of the screen) are used to display one "virtual" pixel (size set in CSS).
Use this extension:
extension Array {
func contains<T where T : Equatable>(obj: T) -> Bool {
return self.filter({$0 as? T == obj}).count > 0
}
}
Use as:
array.contains(1)
Updated for Swift 2/3
Note that as of Swift 3 (or even 2), the extension is no longer necessary as the global contains
function has been made into a pair of extension method on Array
, which allow you to do either of:
let a = [ 1, 2, 3, 4 ]
a.contains(2) // => true, only usable if Element : Equatable
a.contains { $0 < 1 } // => false
if you are using extracted tomcat then,
startup.sh
and shutdown.sh
are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that
if tomcat is installed then
/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart
int myArray[10][10][10];
should be
int myArray[10][10][10][10];
$('#toptitle').html('New world');
or
$('#toptitle').text('New world');
Faced a similar issue, tried the above solutions as well and it didn't work.
Would like to suggest a simple solution which could help if the above suggestions didn't address the issue.
Solution - Try cleaning up space in the system. My problem was I had only 1GB left while trying to launch the emulator after cleaning up space got 8GB and was able to launch the emulator.
Another way I haven't seen listed yet is to set your sentinel value ahead of time. This method takes advantage of Python's lazy evaluation, in which you don't always have to provide an else
statement. Example:
startingpoint = 'blah'
if len(sys.argv) >= 2:
startingpoint = sys.argv[1]
Or if you're going syntax CRAZY you could use Python's ternary operator:
startingpoint = sys.argv[1] if len(sys.argv) >= 2 else 'blah'
So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:
>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"
Some different and clean way to achieve this is by using HttpClient like this:
public async Task<HttpResponseMessage> PostResult(string url, ResultObject resultObject)
{
using (var client = new HttpClient())
{
HttpResponseMessage response = new HttpResponseMessage();
try
{
response = await client.PostAsJsonAsync(url, resultObject);
}
catch (Exception ex)
{
throw ex
}
return response;
}
}
The 2017 answer is: Use the date and time classes introduced in Java 8 (and also backported to Java 6 and 7 in the ThreeTen Backport).
If you want to interpret the date-time string in the computer’s time zone:
long millisSinceEpoch = LocalDateTime.parse(myDate, DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss"))
.atZone(ZoneId.systemDefault())
.toInstant()
.toEpochMilli();
If another time zone, fill that zone in instead of ZoneId.systemDefault()
. If UTC, use
long millisSinceEpoch = LocalDateTime.parse(myDate, DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss"))
.atOffset(ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
You can use the path
module to join the path of the directory in which helper1.js
lives to the relative path of foobar.json
. This will give you the absolute path to foobar.json
.
var fs = require('fs');
var path = require('path');
var jsonPath = path.join(__dirname, '..', 'config', 'dev', 'foobar.json');
var jsonString = fs.readFileSync(jsonPath, 'utf8');
This should work on Linux, OSX, and Windows assuming a UTF8 encoding.
try this
Object.keys(data).length
If IE < 9, you can loop through the object yourself with a for loop
var len = 0;
var i;
for (i in data) {
if (data.hasOwnProperty(i)) {
len++;
}
}
As Jake has mentioned, the problem might be because of copy/paste code. Check the main.xml under res/layout. If there is no id field in that then you have a problem. A typical example would be as below
<com.androidplot.xy.XYPlot
android:id="@+id/mySimpleXYPlot"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="10px"
android:layout_marginLeft="20px"
android:layout_marginRight="20px"
title="A Simple Example"
/>
if($('#user_inp').length > 0 && $('#user_inp').val() != '')
{
$('#user_inp').css({"font-size":"18px"});
$('#user_line').css({"background-color":"#4cae4c","transition":"0.5s","height":"2px"});
$('#username').css({"color":"#4cae4c","transition":"0.5s","font-size":"18px"});
}
I don't see a reference to this:
SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmmssSSS");
above format is also useful.
One way is that In case of Session Expire, in every action you have to check its session and if it is null then redirect to Login page.
But this is very hectic method
To over come this you need to create your own ActionFilterAttribute
which will do this, you just need to add this attribute in every action method.
Here is the Class which overrides ActionFilterAttribute.
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
// check if session is supported
CurrentCustomer objCurrentCustomer = new CurrentCustomer();
objCurrentCustomer = ((CurrentCustomer)SessionStore.GetSessionValue(SessionStore.Customer));
if (objCurrentCustomer == null)
{
// check if a new session id was generated
filterContext.Result = new RedirectResult("~/Users/Login");
return;
}
base.OnActionExecuting(filterContext);
}
}
Then in action just add this attribute like so:
[SessionExpire]
public ActionResult Index()
{
return Index();
}
This will do you work.
Please try this-
ALTER TABLE TABLE_NAME DROP INDEX `PRIMARY`, ADD PRIMARY KEY (COLUMN1, COLUMN2,..);
The simplest way is to generate a random nuber between 0-1 then strech it by multiplying, and shifting it.
So yo would multiply by (x-y) so the result is in the range of 0 to x-y,
Then add x and you get the random number between x and y.
To get a five multiplier use rounding. If this is unclear let me know and I'll add code snippets.
label
and checkbox
inputKeeps the selected item opened and togglable.
.collapse{_x000D_
cursor: pointer;_x000D_
display: block;_x000D_
background: #cdf;_x000D_
}_x000D_
.collapse + input{_x000D_
display: none; /* hide the checkboxes */_x000D_
}_x000D_
.collapse + input + div{_x000D_
display:none;_x000D_
}_x000D_
.collapse + input:checked + div{_x000D_
display:block;_x000D_
}
_x000D_
<label class="collapse" for="_1">Collapse 1</label>_x000D_
<input id="_1" type="checkbox"> _x000D_
<div>Content 1</div>_x000D_
_x000D_
<label class="collapse" for="_2">Collapse 2</label>_x000D_
<input id="_2" type="checkbox">_x000D_
<div>Content 2</div>
_x000D_
label
and named radio
inputSimilar to checkboxes, it just closes the already opened one.
Use name="c1" type="radio"
on both inputs.
.collapse{_x000D_
cursor: pointer;_x000D_
display: block;_x000D_
background: #cdf;_x000D_
}_x000D_
.collapse + input{_x000D_
display: none; /* hide the checkboxes */_x000D_
}_x000D_
.collapse + input + div{_x000D_
display:none;_x000D_
}_x000D_
.collapse + input:checked + div{_x000D_
display:block;_x000D_
}
_x000D_
<label class="collapse" for="_1">Collapse 1</label>_x000D_
<input id="_1" type="radio" name="c1"> _x000D_
<div>Content 1</div>_x000D_
_x000D_
<label class="collapse" for="_2">Collapse 2</label>_x000D_
<input id="_2" type="radio" name="c1">_x000D_
<div>Content 2</div>
_x000D_
tabindex
and :focus
Similar to radio
inputs, additionally you can trigger the states using the Tab key.
Clicking outside of the accordion will close all opened items.
.collapse > a{_x000D_
background: #cdf;_x000D_
cursor: pointer;_x000D_
display: block;_x000D_
}_x000D_
.collapse:focus{_x000D_
outline: none;_x000D_
}_x000D_
.collapse > div{_x000D_
display: none;_x000D_
}_x000D_
.collapse:focus div{_x000D_
display: block; _x000D_
}
_x000D_
<div class="collapse" tabindex="1">_x000D_
<a>Collapse 1</a>_x000D_
<div>Content 1....</div>_x000D_
</div>_x000D_
_x000D_
<div class="collapse" tabindex="1">_x000D_
<a>Collapse 2</a>_x000D_
<div>Content 2....</div>_x000D_
</div>
_x000D_
:target
Similar to using radio
input, you can additionally use Tab and ⏎ keys to operate
.collapse a{_x000D_
display: block;_x000D_
background: #cdf;_x000D_
}_x000D_
.collapse > div{_x000D_
display:none;_x000D_
}_x000D_
.collapse > div:target{_x000D_
display:block; _x000D_
}
_x000D_
<div class="collapse">_x000D_
<a href="#targ_1">Collapse 1</a>_x000D_
<div id="targ_1">Content 1....</div>_x000D_
</div>_x000D_
_x000D_
<div class="collapse">_x000D_
<a href="#targ_2">Collapse 2</a>_x000D_
<div id="targ_2">Content 2....</div>_x000D_
</div>
_x000D_
<detail>
and <summary>
tags (pure HTML)You can use HTML5's detail and summary tags to solve this problem without any CSS styling or Javascript. Please note that these tags are not supported by Internet Explorer.
<details>_x000D_
<summary>Collapse 1</summary>_x000D_
<p>Content 1...</p>_x000D_
</details>_x000D_
<details>_x000D_
<summary>Collapse 2</summary>_x000D_
<p>Content 2...</p>_x000D_
</details>
_x000D_
If you also want it to be a command you can reference without remembering the arguments, you could simply alias it:
alias df-gb='df -BG'
So if you type:
df-gb
into a terminal, you'll get your intended output of the disk usage in GB.
EDIT: or even use just df -h
to get it in a standard, human readable format.
Newer versions: (from 8.4 - mentioned in release notes)
TABLE mytablename;
Longer but works on all versions:
SELECT * FROM mytablename;
You may wish to use \x
first if it's a wide table, for readability.
For long data:
SELECT * FROM mytable LIMIT 10;
or similar.
For wide data (big rows), in the psql
command line client, it's useful to use \x
to show the rows in key/value form instead of tabulated, e.g.
\x
SELECT * FROM mytable LIMIT 10;
Note that in all cases the semicolon at the end is important.
Iterate through the string and make sure all the characters have a value less than 128.
Java Strings are conceptually encoded as UTF-16. In UTF-16, the ASCII character set is encoded as the values 0 - 127 and the encoding for any non ASCII character (which may consist of more than one Java char) is guaranteed not to include the numbers 0 - 127
This will work if you are not blocking.
If you are planing on doing sleeps, its absolutely imperative that you use the event to do the sleep. If you leverage the event to sleep, if someone tells you to stop while "sleeping" it will wake up. If you use time.sleep()
your thread will only stop after it wakes up.
import threading
import time
duration = 2
def main():
t1_stop = threading.Event()
t1 = threading.Thread(target=thread1, args=(1, t1_stop))
t2_stop = threading.Event()
t2 = threading.Thread(target=thread2, args=(2, t2_stop))
time.sleep(duration)
# stops thread t2
t2_stop.set()
def thread1(arg1, stop_event):
while not stop_event.is_set():
stop_event.wait(timeout=5)
def thread2(arg1, stop_event):
while not stop_event.is_set():
stop_event.wait(timeout=5)
99.999% of my time is looking at history by git lg
and the 0.001% is by git log
.
I just want to share two log aliases that might be useful (configure from .gitconfig):
[Alias]
lg = log --graph --pretty=format:'%Cred%h%Creset %ad %s %C(yellow)%d%Creset %C(bold blue)<%an>%Creset' --date=short
hist = log --graph --full-history --all --pretty=format:'%Cred%h%Creset %ad %s %C(yellow)%d%Creset %C(bold blue)<%an>%Creset' --date=short
git lg
will see the current branch history.git hist
will see the whole branch history.In my opinion the better way is to do this with the Parameters property of the SqlCommand class:
public static void AddCommandParameter(SqlCommand myCommand)
{
myCommand.Parameters.AddWithValue(
"@AgeIndex",
(AgeItem.AgeIndex== null) ? DBNull.Value : AgeItem.AgeIndex);
}
There is a batch file called resetroot.bat
located in the xammp folders 'C:\xampp\mysql' run this and it will delete the phpmyadmin
passwords. Then all you need to do is start the MySQL
service in xamp
and click the admin button.
With mysql 5.7, date value like 0000-00-00 00:00:00 is not allowed.
If you want to allow it, you have to update your my.cnf like:
sudo nano /etc/mysql/my.cnf
find
[mysqld]
Add after:
sql_mode="NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
Restart mysql service:
sudo service mysql restart
Done!
To embed this in your script, you can do it like this:
Write-Output $server.name | Out-File '(Your Path)\Servers.txt' -Append
That should do the trick.
For a bit more flexibility than with micronyks answer, you can do it like that:
1. In your template, add #myIdentifier
to the element you want to obtain the width from. Example:
<p #myIdentifier>
my-component works!
</p>
2. In your controller, you can use this with @ViewChild('myIdentifier')
to get the width:
import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss']
})
export class MyComponentComponent implements AfterViewInit {
constructor() { }
ngAfterViewInit() {
console.log(this.myIdentifier.nativeElement.offsetWidth);
}
@ViewChild('myIdentifier')
myIdentifier: ElementRef;
}
Security
About the security risk with ElementRef
, like this, there is none. There would be a risk, if you would modify the DOM using an ElementRef. But here you are only getting DOM Elements so there is no risk. A risky example of using ElementRef
would be: this.myIdentifier.nativeElement.onclick = someFunctionDefinedBySomeUser;
. Like this Angular doesn't get a chance to use its sanitisation mechanisms since someFunctionDefinedBySomeUser
is inserted directly into the DOM, skipping the Angular sanitisation.
Using apache commons..
//For midnight today
Date today = new Date();
DateUtils.truncate(today, Calendar.DATE);
//For midnight tomorrow
Date tomorrow = DateUtils.addDays(today, 1);
DateUtils.truncate(tomorrow, Calendar.DATE);
Just use CSS to increase it's height:
<input type="text" style="height:30px;" name="item" align="left" />
Or, often times, you want to increase it's height by using padding instead of specifying an exact height:
<input type="text" style="padding: 5px;" name="item" align="left" />
There is a css3 solution here if that is acceptable. It supports the graceful degradation approach where css3 isn't supported. you just won't have any transparency.
body {
font-family: tahoma, helvetica, arial, sans-serif;
font-size: 12px;
text-align: center;
background: #000;
color: #ddd4d4;
padding-top: 12px;
line-height: 2;
background-image: url('images/background.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-size: 100%;
background: rgb(0, 0, 0); /* for older browsers */
background: rgba(0, 0, 0, 0.8); /* R, G, B, A */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#CC000000, endColorstr=#CC0000); /* AA, RR, GG, BB */
}
to get the hex equivalent of 80% (CC) take (pct / 100) * 255 and convert to hex.
Here's the Xamarin iOS equivalent of drawnonward's answer.
class WebviewDelegate : UIWebViewDelegate {
public override bool ShouldStartLoad (UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType) {
if (navigationType == UIWebViewNavigationType.LinkClicked) {
UIApplication.SharedApplication.OpenUrl (request.Url);
return false;
}
return true;
}
}
Same problem with me when I used this syntax problem solved.
Syntax:
Use [YourDatabaseName]
Your Query Here
one of the easy way to do that is use landa function without any problem like
userControl_Material1.simpleButton4.Click += (s, ee) =>
{
Save_mat(mat_global);
};
I had the same problem try this:
python manage.py sqlsequencereset table_name
Eg:
python manage.py sqlsequencereset auth
you need to run this in production settings(if you have) and you need Postgres installed to run this on the server
The problem I was having with the rewrite is that some .htaccess files for Codeigniter, etc come with
RewriteBase /
Which doesn't seem to work in MAMP...at least for me.
Here is my best shot at it. I added another Div and made it red and changed you parent's height to 200px just to test it. The idea is the the child now becomes the grandchild and the parent becomes the grandparent. So the parent respects its parent. Hope you get my idea.
<html>
<body>
<div style="background-color: blue; padding: 10px; position: relative; height: 200px;">
<div style="background-color: red; position: relative; height: 100%;">
<div style="background-color: gray; position: absolute; left: 0px; right: 0px;bottom: 0px;">css sux</div>
</div>
</div>
</body>
</html>
Edit:
I think what you are trying to do can't be done. Absolute position means that you are going to give it co-ordinates it must honor. What if the parent has a padding of 5px. And you absolutely position the child at top: -5px; left: -5px. How is it suppose to honor the parent and you at the same time??
My solution
If you want it to honor the parent, don't absolutely position it then.
Best solution: Goto jboss-as-7.1.1.Final\standalone\deployments folder and delete all existing files....
Run again your problem will be solved
Backticks (`
) are used to define template literals. Template literals are a new feature in ECMAScript 6 to make working with strings easier.
Features:
Note: we can easily use single quotes ('
) and double quotes ("
) inside the backticks (`
).
Example:
var nameStr = `I'm "Rohit" Jindal`;
To interpolate the variables or expression we can use the ${expression}
notation for that.
var name = 'Rohit Jindal';
var text = `My name is ${name}`;
console.log(text); // My name is Rohit Jindal
Multi-line strings means that you no longer have to use \n
for new lines anymore.
Example:
const name = 'Rohit';
console.log(`Hello ${name}!
How are you?`);
Output:
Hello Rohit!
How are you?
Or even simpler?
<div class="accordion">
<h3><a href="#">First</a></h3>
<div>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.</div>
</div>
<div class="accordion">
<h3><a href="#">Second</a></h3>
<div>Phasellus mattis tincidunt nibh.</div>
</div>
<div class="accordion">
<h3><a href="#">Third</a></h3>
<div>Nam dui erat, auctor a, dignissim quis.</div>
</div>
<script type="text/javascript">
$(".accordion").accordion({ collapsible: true, active: false });
</script>
This is sort of coming at the question from the other end but I thought I'd throw it in as I really had to dig on the internet to find this out.
There is a lot of stuff about how to check roles but not much saying what you are actually checking when you say hasRole("blah")
HasRole checks the granted authorities for the currently authenticated principal
So really when you see hasRole("blah") really means hasAuthority("blah").
In the case I've seen, you do this with a class that Implements UserDetails which defines a method called getAuthorities. In this you'll basically add some new SimpleGrantedAuthority("some name")
to a list based on some logic. The names in this list are the things checked by the hasRole statements.
I guess in this context the UserDetails object is the currently authenticated principal. There's some magic that happens in and around authentication providers and more specifically the authentication-manager that makes this happen.
You could check the answer in a related question. https://stackoverflow.com/a/16894324/1465756
Just import library https://github.com/jasonpolites/gesture-imageview.
into your project and add the following in your layout file:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:gesture-image="http://schemas.polites.com/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.polites.android.GestureImageView
android:id="@+id/image"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/image"
gesture-image:min-scale="0.1"
gesture-image:max-scale="10.0"
gesture-image:strict="false"/>`
You can try this code:
function FormatNumber(number, numberOfDigits = 2) {
try {
return new Intl.NumberFormat('en-US').format(parseFloat(number).toFixed(2));
} catch (error) {
return 0;
}
}
var test1 = FormatNumber('1000000.4444');
alert(test1); // 1,000,000.44
var test2 = FormatNumber(100000000000.55555555, 4);
alert(test2); // 100,000,000,000.56
Similar answers:
Here is a plunker: http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview
app.directive("myDir", function($compile) {
return {
priority:1001, // compiles first
terminal:true, // prevent lower priority directives to compile after it
compile: function(el) {
el.removeAttr('my-dir'); // necessary to avoid infinite compile loop
el.attr('ng-click', 'fxn()');
var fn = $compile(el);
return function(scope){
fn(scope);
};
}
};
});
ngClick
at all:A plunker: http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=preview
app.directive("myDir", function($parse) {
return {
compile: function(tElm,tAttrs){
var exp = $parse('fxn()');
return function (scope,elm){
elm.bind('click',function(){
exp(scope);
});
};
}
};
});
(I'm a few points shy of commenting privileges)
If you decide to forgo the +1 day in CMS's elegant solution, note that if your start date and end date are in the same weekend, you get a negative answer. Ie., 2008/10/26 to 2008/10/26 returns -1.
my rather simplistic solution:
select @Result = (..CMS's answer..)
if (@Result < 0)
select @Result = 0
RETURN @Result
.. which also sets all erroneous posts with start date after end date to zero. Something you may or may not be looking for.
I think using multiple Jframe
s is not a good idea.
Instead we can use JPanel
s more than one or more JPanel
in the same JFrame
.
Also we can switch between this JPanel
s. So it gives us freedom to display more than on thing in the JFrame
.
For each JPanel
we can design different things and all this JPanel
can be displayed on the single JFrame
one at a time.
To switch between this JPanel
s use JMenuBar
with JMenuItems
for each JPanel
or 'JButtonfor each
JPanel`.
More than one JFrame
is not a good practice, but there is nothing wrong if we want more than one JFrame
.
But its better to change one JFrame
for our different needs rather than having multiple JFrame
s.
You can try this code:
cur.execute( "SELECT * FROM records WHERE email LIKE %s", (search,) )
You can see the documentation
One way to see the contents would be:
for my_bucket_object in my_bucket.objects.all():
print(my_bucket_object)
Another easier way to do it is to upload your file to google sheets, then add a pivot, for the columns and rows select the same as you would with Excel, however, for values select Calculated Field and then in the formula type in =
If you have Apache2.4 check 000-default.conf
- remove DocumentRoot
and add
Redirect permanent / https://[your-domain]/
When Python parses a function, it notes when a variable assignment is made. When there is an assignment, it assumes by default that that variable is a local variable. To declare that the assignment refers to a global variable, you must use the global
declaration.
When you access a variable in a function, its value is looked up using the LEGB scoping rules.
So, the first example
x = 1
def inc():
x += 5
inc()
produces an UnboundLocalError
because Python determined x
inside inc
to be a local variable,
while accessing x
works in your second example
def inc():
print x
because here, in accordance with the LEGB rule, Python looks for x
in the local scope, does not find it, then looks for it in the extended scope, still does not find it, and finally looks for it in the global scope successfully.
Compass adjusts the way partials are imported. It allows importing components based solely on their name, without specifying the path.
Before you can do @import 'compass';
, you should:
Install Compass as a Ruby gem:
gem install compass
After that, you should use Compass's own command line tool to compile your SASS code:
cd path/to/your/project/
compass compile
Note that Compass reqiures a configuration file called config.rb
. You should create it for Compass to work.
The minimal config.rb
can be as simple as this:
css_dir = "css"
sass_dir = "sass"
And your SASS code should reside in sass/
.
Instead of creating a configuration file manually, you can create an empty Compass project with compass create <project-name>
and then copy your SASS code inside it.
Note that if you want to use Compass extensions, you will have to:
config.rb
;More info here: http://compass-style.org/help/
Negatives are your friend here:
SELECT Col1
FROM TABLE
WHERE Col1 like '%[^a-Z0-9]%'
Which says that you want any rows where Col1
consists of any number of characters, then one character not in the set a-Z0-9, and then any number of characters.
If you have a case sensitive collation, it's important that you use a range that includes both upper and lower case A
, a
, Z
and z
, which is what I've given (originally I had it the wrong way around. a
comes before A
. Z
comes after z
)
Or, to put it another way, you could have written your original WHERE
as:
Col1 LIKE '[!@#$%]'
But, as you observed, you'd need to know all of the characters to include in the []
.
You are using the wrong iteration counter, replace inp.charAt(i)
with inp.charAt(j)
.
EDIT
I wrote a snippet that emulate the EventListener interface and the ie8 one, is callable even on plain objects: https://github.com/antcolag/iEventListener/blob/master/iEventListener.js
OLD ANSWER
this is a way for emulate addEventListener or attachEvent on browsers that don't support one of those
hope will help
(function (w,d) { //
var
nc = "", nu = "", nr = "", t,
a = "addEventListener",
n = a in w,
c = (nc = "Event")+(n?(nc+= "", "Listener") : (nc+="Listener","") ),
u = n?(nu = "attach", "add"):(nu = "add","attach"),
r = n?(nr = "detach","remove"):(nr = "remove","detach")
/*
* the evtf function, when invoked, return "attach" or "detach" "Event" functions if we are on a new browser, otherwise add "add" or "remove" "EventListener"
*/
function evtf(whoe){return function(evnt,func,capt){return this[whoe]((n?((t = evnt.split("on"))[1] || t[0]) : ("on"+evnt)),func, (!n && capt? (whoe.indexOf("detach") < 0 ? this.setCapture() : this.removeCapture() ) : capt ))}}
w[nu + nc] = Element.prototype[nu + nc] = document[nu + nc] = evtf(u+c) // (add | attach)Event[Listener]
w[nr + nc] = Element.prototype[nr + nc] = document[nr + nc] = evtf(r+c) // (remove | detach)Event[Listener]
})(window, document)
One that I've found works for the site I test is this one:
waitForCondition | selenium.browserbot.getUserWindow().$.active==0 | 20000
Klendathu
I've found it simple and fast...
# find . -type f -exec basename {} \; | awk -F"." '{print $NF}' > /tmp/outfile.txt
# cat /tmp/outfile.txt | sort | uniq -c| sort -n > tmp/outfile_sorted.txt
Try this:
From this question.
Implementation 1 is the perp dot product of the two vectors. The best reference I know of for 2D graphics is the excellent Graphics Gems series. If you're doing scratch 2D work, it's really important to have these books. Volume IV has an article called "The Pleasures of Perp Dot Products" that goes over a lot of uses for it.
One major use of perp dot product is to get the scaled sin
of the angle between the two vectors, just like the dot product returns the scaled cos
of the angle. Of course you can use dot product and perp dot product together to determine the angle between two vectors.
Here is a post on it and here is the Wolfram Math World article.
I have experienced this issue with images taken from camera or saved in camera roll which are taken from camera. Images downloaded in photo library from safari browser does not rotate when uploaded.
I was able to solve this issue by making the image data as JPEG before uploading.
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
let data = UIImageJPEGRepresentation(image, 1.0)
We can now use the data for uploading and the image will not get rotated after upload.
Hope this will work.
There's a very simple way if you got your APK allready on your Smartphone. Just use one of these APPs:
Faced the same problem. 'conda update'
does not work; It gives the error : "CondaValueError: no package names supplied"
On executing the following commands, I was able to launch the Anaconda navigator:
conda update -n base conda
conda update anaconda-navigator
I tried the two top-voted solutions but found some issues even though both work to some extent.
After some experiments I found the following method works well for me.
If you just need to change the last part of package name, use the method outlined by GreyBeardedGeek, namely
Right-click on the package in the Project pane. Choose Refactor -> Rename from the context menu
If you need to change the whole package name, do the following.
Right-click on the package in the Project pane. Choose Refactor -> Move from the context menu
This will create a new package folder (when necessary) but will keep the last part of your package name as before. If you need to change the last part, do the rename accordingly.
Note also that you may need to modify package names in e.g. build.gradle, manifest, and/or any xml resource files, or even in your code if hardcoded. After all that, do Sync/Clean/Rebuild project as necessary.
The answer is on the example link you provided:
http://getbootstrap.com/javascript/#modals-usage
i.e.
Call a modal with id myModal with a single line of JavaScript:
$('#myModal').modal('show');
Compile your application with -g
, then you'll have debug symbols in the binary file.
Use gdb
to open the gdb console.
Use file
and pass it your application's binary file in the console.
Use run
and pass in any arguments your application needs to start.
Do something to cause a Segmentation Fault.
Type bt
in the gdb
console to get a stack trace of the Segmentation Fault.
The quickest way is to use a tool, like RazorSQL or Toad for doing this.
Here is a truly and completely RESTful authentication solution:
When a client authenticates:
3.1. issue a token which contains the following:
3.2. Encrypt the token with the private key.
3.3. Send the encrypted token back to the user.
When the user accesses any API they must also pass in their auth token.
This is stateless/RESTful authentication.
Note, that if a password hash were included the user would also send the unencrypted password along with the authentication token. The server could verify that the password matched the password that was used to create the authentication token by comparing hashes. A secure connection using something like HTTPS would be necessary. Javascript on the client side could handle getting the user's password and storing it client side, either in memory or in a cookie, possibly encrypted with the server's public key.
There's a much easier way to do this, using iconv
- from the user notes, this seems to be what you want to do: characters transliteration
// PHP.net User notes
<?php
$string = "?ABBASABAD";
echo iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $string);
// output: [nothing, and you get a notice]
echo iconv('UTF-8', 'ISO-8859-1//IGNORE', $string);
// output: ABBSBD
echo iconv('UTF-8', 'ISO-8859-1//TRANSLIT//IGNORE', $string);
// output: ABBASABAD
// Yay! That's what I wanted!
?>
Be very conscientious with your character encodings, so you are keeping the same encoding at all stages in the process - front end, form submission, encoding of the source files. Default encoding in PHP and in forms is ISO-8859-1, before PHP 5.4 where it changed to be UTF8 (finally!).
There's a couple of functions you can play around with for ideas. First is from CakePHP's inflector class, called slug
:
public static function slug($string, $replacement = '_') {
$quotedReplacement = preg_quote($replacement, '/');
$merge = array(
'/[^\s\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]/mu' => ' ',
'/\\s+/' => $replacement,
sprintf('/^[%s]+|[%s]+$/', $quotedReplacement, $quotedReplacement) => '',
);
$map = self::$_transliteration + $merge;
return preg_replace(array_keys($map), array_values($map), $string);
}
It depends on a self::$_transliteration
array which is similar to what you were doing in your question - you can see the source for inflector on github.
Another is a function I use personally, which comes from here.
function slugify($text,$strict = false) {
$text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
// replace non letter or digits by -
$text = preg_replace('~[^\\pL\d.]+~u', '-', $text);
// trim
$text = trim($text, '-');
setlocale(LC_CTYPE, 'en_GB.utf8');
// transliterate
if (function_exists('iconv')) {
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
}
// lowercase
$text = strtolower($text);
// remove unwanted characters
$text = preg_replace('~[^-\w.]+~', '', $text);
if (empty($text)) {
return 'empty_$';
}
if ($strict) {
$text = str_replace(".", "_", $text);
}
return $text;
}
What those functions do is transliterate and create 'slugs' from arbitrary text input, which is a very very useful thing to have in your toolchest when making web apps. Hope this helps!
Following line is hurting JSON encoder,
now = datetime.datetime.now()
now = datetime.datetime.strftime(now, '%Y-%m-%dT%H:%M:%S.%fZ')
print json.dumps({'current_time': now}) // this is the culprit
I got a temporary fix for it
print json.dumps( {'old_time': now.encode('ISO-8859-1').strip() })
Marking this as correct as a temporary fix (Not sure so).
In order to solve this problem, I recognize two solutions:
The first one goes with AJAX, with which you'll have to load the template from another file and just add everytime you want with .clone()
.
$.get('url/to/template', function(data) {
temp = data
$('.search').keyup(function() {
$('.list-items').html(null);
$.each(items, function(index) {
$(this).append(temp.clone())
});
});
});
Take into account that the event should be added once the ajax has completed to be sure the data is available!
The second one would be to directly add it anywhere in the original html, select it and hide it in jQuery:
temp = $('.list_group_item').hide()
You can after add a new instance of the template with
$('.search').keyup(function() {
$('.list-items').html(null);
$.each(items, function(index) {
$(this).append(temp.clone())
});
});
Same as the previous one, but if you don't want the template to remain there, but just in the javascript, I think you can use (have not tested it!) .detach()
instead of hide.
temp = $('.list_group_item').detach()
.detach()
removes elements from the DOM while keeping the data and events alive (.remove() does not!).
If we define dx = x2 - x1
and dy = y2 - y1
, then the normals are (-dy, dx)
and (dy, -dx)
.
Note that no division is required, and so you're not risking dividing by zero.
The only way to get the users e-mail address is to request extended permissions on the email field. The user must allow you to see this and you cannot get the e-mail addresses of the user's friends.
http://developers.facebook.com/docs/authentication/permissions
You can do this if you are using Facebook connect by passing scope=email in the get string of your call to the Auth Dialog.
I'd recommend using an SDK instead of file_get_contents as it makes it far easier to perform the Oauth authentication.
spoiler: possible Server Side Problem
Here is what i've found, my code expected the responce from my server, when the server returned just 200 code, it wasnt enough herefrom json parser thrown the error error unexpected end of input
fetch(url, {
method: 'POST',
body: JSON.stringify(json),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => res.json()) // here is my code waites the responce from the server
.then((res) => {
toastr.success('Created Type is sent successfully');
})
.catch(err => {
console.log('Type send failed', err);
toastr.warning('Type send failed');
})
I built this little function to automatically format anything into a nice currency format.
function formatDollars($dollars)
{
return "$".number_format(sprintf('%0.2f', preg_replace("/[^0-9.]/", "", $dollars)),2);
}
Edit
It was pointed out that this does not show negative values. I broke it into two lines so it's easier to edit the formatting. Wrap it in parenthesis if it's a negative value:
function formatDollars($dollars)
{
$formatted = "$" . number_format(sprintf('%0.2f', preg_replace("/[^0-9.]/", "", $dollars)), 2);
return $dollars < 0 ? "({$formatted})" : "{$formatted}";
}
Just been struggling with this too on Android, managed to stumble upon Uri.encode(String, String) while specific to android (android.net.Uri) might be useful to some.
static String encode(String s, String allow)
just to answer your question...btw sry that i'm 9 months late:D...there's a "workaround" 4 this kind of problems. i.e.
new AlertDialog.Builder(some_class.this).setTitle("bla").setMessage("bla bla").show();
wait();
simply add wait();
and them in the OnClickListener start the class again with notify() something like this
@Override
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_LONG).show();
**notify**();
dialog.cancel();
}
the same workaround goes 4 toasts and other async calls in android
Try the following code to find the optimal camera position
Use print to get the camera positions
def move_view(event):
ax.autoscale(enable=False, axis='both')
koef = 8
zkoef = (ax.get_zbound()[0] - ax.get_zbound()[1]) / koef
xkoef = (ax.get_xbound()[0] - ax.get_xbound()[1]) / koef
ykoef = (ax.get_ybound()[0] - ax.get_ybound()[1]) / koef
## Map an motion to keyboard shortcuts
if event.key == "ctrl+down":
ax.set_ybound(ax.get_ybound()[0] + xkoef, ax.get_ybound()[1] + xkoef)
if event.key == "ctrl+up":
ax.set_ybound(ax.get_ybound()[0] - xkoef, ax.get_ybound()[1] - xkoef)
if event.key == "ctrl+right":
ax.set_xbound(ax.get_xbound()[0] + ykoef, ax.get_xbound()[1] + ykoef)
if event.key == "ctrl+left":
ax.set_xbound(ax.get_xbound()[0] - ykoef, ax.get_xbound()[1] - ykoef)
if event.key == "down":
ax.set_zbound(ax.get_zbound()[0] - zkoef, ax.get_zbound()[1] - zkoef)
if event.key == "up":
ax.set_zbound(ax.get_zbound()[0] + zkoef, ax.get_zbound()[1] + zkoef)
# zoom option
if event.key == "alt+up":
ax.set_xbound(ax.get_xbound()[0]*0.90, ax.get_xbound()[1]*0.90)
ax.set_ybound(ax.get_ybound()[0]*0.90, ax.get_ybound()[1]*0.90)
ax.set_zbound(ax.get_zbound()[0]*0.90, ax.get_zbound()[1]*0.90)
if event.key == "alt+down":
ax.set_xbound(ax.get_xbound()[0]*1.10, ax.get_xbound()[1]*1.10)
ax.set_ybound(ax.get_ybound()[0]*1.10, ax.get_ybound()[1]*1.10)
ax.set_zbound(ax.get_zbound()[0]*1.10, ax.get_zbound()[1]*1.10)
# Rotational movement
elev=ax.elev
azim=ax.azim
if event.key == "shift+up":
elev+=10
if event.key == "shift+down":
elev-=10
if event.key == "shift+right":
azim+=10
if event.key == "shift+left":
azim-=10
ax.view_init(elev= elev, azim = azim)
# print which ever variable you want
ax.figure.canvas.draw()
fig.canvas.mpl_connect("key_press_event", move_view)
plt.show()
public void showAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View alertDialogView = inflater.inflate(R.layout.test_dialog, null);
alertDialog.setView(alertDialogView);
TextView textDialog = (TextView) alertDialogView.findViewById(R.id.text_testDialogMsg);
textDialog.setText(questionMissing);
alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
where .test_dialog is of xml custom
Default values cannot be supplied for parameters that are not declared 'optional
'
Function GetFindBooks(id As Integer, ByVal pid As Integer, Optional sort As String = "DESC", Optional limit As Integer = 99)
In your WebApiConfig
config.Routes.MapHttpRoute( _
name:="books", _
routeTemplate:="api/{controller}/{action}/{id}/{pid}/{sort}/{limit}", _
defaults:=New With {.id = RouteParameter.Optional, .pid = RouteParameter.Optional, .sort = UrlParameter.Optional, .limit = UrlParameter.Optional} _
)
As noted in the comments, the query in Saharsh Shah's answer must be run multiple times if items are duplicated more than once.
Here's a solution that doesn't delete any data, and keeps the data in the original table the entire time, allowing for duplicates to be deleted while keeping the table 'live':
alter table tableA add column duplicate tinyint(1) not null default '0';
update tableA set
duplicate=if(@member_id=member_id
and @quiz_num=quiz_num
and @question_num=question_num
and @answer_num=answer_num,1,0),
member_id=(@member_id:=member_id),
quiz_num=(@quiz_num:=quiz_num),
question_num=(@question_num:=question_num),
answer_num=(@answer_num:=answer_num)
order by member_id, quiz_num, question_num, answer_num;
delete from tableA where duplicate=1;
alter table tableA drop column duplicate;
This basically checks to see if the current row is the same as the last row, and if it is, marks it as duplicate (the order statement ensures that duplicates will show up next to each other). Then you delete the duplicate records. I remove the duplicate
column at the end to bring it back to its original state.
It looks like alter table ignore
also might go away soon: http://dev.mysql.com/worklog/task/?id=7395
Use Counter
>>> from collections import Counter
>>> MyList = ["a", "b", "a", "c", "c", "a", "c"]
>>> c = Counter(MyList)
>>> c
Counter({'a': 3, 'c': 3, 'b': 1})
nop... just open the four dateis: content.xml; server.xml; tomcat-users.xml and web.xml in the tap servers. There are some text. Change the number of port 8080 to 8081
For those who are looking for imperial/english naming conventions.
Based on @Salman's answer
var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
function inWords (num) {
if ((num = num.toString()).length > 12) return 'overflow';
n = ('00000000000' + num).substr(-12).match(/^(\d{3})(\d{3})(\d{3})(\d{1})(\d{2})$/);
if (!n) return; var str = '';
str += (n[1] != 0) ? (Number(n[1]) > 99 ? this.a[Number(n[1][0])] + 'hundred ' : '') + (a[Number(n[1])] || b[n[1][1]] + ' ' + a[n[1][2]]) + 'billion ' : '';
str += (n[2] != 0) ? (Number(n[2]) > 99 ? this.a[Number(n[2][0])] + 'hundred ' : '') + (a[Number(n[2])] || b[n[2][1]] + ' ' + a[n[2][2]]) + 'million ' : '';
str += (n[3] != 0) ? (Number(n[3]) > 99 ? this.a[Number(n[3][0])] + 'hundred ' : '') + (a[Number(n[3])] || b[n[3][1]] + ' ' + a[n[3][2]]) + 'thousand ' : '';
str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
str += (Number(n[5]) !== 0) ? ((str !== '') ? 'and ' : '') +
(this.a[Number(n[5])] || this.b[n[5][0]] + ' ' +
this.a[n[5][1]]) + '' : '';
return str;
}
document.getElementById('number').onkeyup = function () {
document.getElementById('words').innerHTML = inWords(document.getElementById('number').value);
};
_x000D_
<span id="words"></span>
<input id="number" type="text" />
_x000D_
I try this same method, but with a different list with more values in the function map. My problem was to forget a return statement. This is very important :)
bottom: new TabBar(
controller: _controller,
isScrollable: true,
tabs:
moviesTitles.map((title) { return Tab(text: title)}).toList()
,
),
You want to look at using something like Enum.GetValues
I had this same issue on Windows 10. I bypassed it by running the Docker daemon in experimental mode:
"experimental": true
you are using onclick
which is javascript event.
there is two ways
Javascript
<input type="button" value="Home" class="homebutton" id="btnHome"
onClick="window.location = 'http://google.com'" />
Or PHP
create another page as redirect.php and put
<?php header('location : google.com') ?>
and insert this link on any page within the same directory
<a href="redirect.php">google<a/>
hope this helps its simplest!!
In linux terminal try this:
sudo service postgresql start
: to start the serversudo service postgresql stop
: to stop thee serversudo service postgresql status
: to check server statusTry this on Debian/Ubuntu:
sudo apt-get install python-mechanize
Set the opacity of its view it is showed in.
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithName:@"SomeName.png"]];
imageView.alpha = 0.5; //Alpha runs from 0.0 to 1.0
Use this in an animation. You can change the alpha in an animation for an duration.
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1.0];
//Set alpha
[UIView commitAnimations];
var q = from b in listOfBoxes
group b by b.Owner into g
select new
{
Owner = g.Key,
Boxes = g.Count(),
TotalWeight = g.Sum(item => item.Weight),
TotalVolume = g.Sum(item => item.Volume)
};
This will list only modified files:
svn status -u | grep M
Firstly, the Django docs strongly recommend not using NULL values for string-based fields such as CharField or TextField. Read the documentation for the explanation:
https://docs.djangoproject.com/en/dev/ref/models/fields/#null
Solution: You can also chain together methods on QuerySets, I think. Try this:
Name.objects.exclude(alias__isnull=True).exclude(alias="")
That should give you the set you're looking for.
As mentioned here, markdown do not support right aligned text or blocks. But the HTML result does it, via Cascading Style Sheets (CSS).
On my Jekyll Blog is use a syntax which works in markdown as well. To "terminate" a block use two spaces at the end or two times new line.
Of course you can also add a css-class with {: .right }
instead of {: style="text-align: right" }
.
Text to right
{: style="text-align: right" }
This text is on the right
Text as block
{: style="text-align: justify" }
This text is a block
Cleanest way of saving image locally using request:
const request = require('request');
request('http://link/to/your/image/file.png').pipe(fs.createWriteStream('fileName.png'))
If you need to add authentication token in headers do this:
const request = require('request');
request({
url: 'http://link/to/your/image/file.png',
headers: {
"X-Token-Auth": TOKEN,
}
}).pipe(fs.createWriteStream('filename.png'))
Try the Jquery Hotkeys plugin instead - it'll do everything you require.
jQuery Hotkeys is a plug-in that lets you easily add and remove handlers for keyboard events anywhere in your code supporting almost any key combination.
This plugin is based off of the plugin by Tzury Bar Yochay: jQuery.hotkeys
The syntax is as follows:
$(expression).bind(types, keys, handler); $(expression).unbind(types, handler);
$(document).bind('keydown', 'ctrl+a', fn);
// e.g. replace '$' sign with 'EUR'
// $('input.foo').bind('keyup', '$', function(){
// this.value = this.value.replace('$', 'EUR'); });
// Regex - Check Singapore valid mobile numbers
public static boolean isSingaporeMobileNo(String str) {
Pattern mobNO = Pattern.compile("^(((0|((\\+)?65([- ])?))|((\\((\\+)?65\\)([- ])?)))?[8-9]\\d{7})?$");
Matcher matcher = mobNO.matcher(str);
if (matcher.find()) {
return true;
} else {
return false;
}
}
FragmentStatePagerAdapter:
with FragmentStatePagerAdapter
,your unneeded fragment is
destroyed.A transaction is committed to completely remove the
fragment from your activity's FragmentManager
.
The state in FragmentStatePagerAdapter
comes from the fact that it
will save out your fragment's Bundle
from savedInstanceState
when
it is destroyed.When the user navigates back,the new fragment will be
restored using the fragment's state.
FragmentPagerAdapter:
By comparision FragmentPagerAdapter
does nothing of the kind.When
the fragment is no longer needed.FragmentPagerAdapter
calls
detach(Fragment)
on the transaction instead of remove(Fragment)
.
This destroy's the fragment's view but leaves the fragment's instance
alive in the FragmentManager
.so the fragments created in the
FragmentPagerAdapter
are never destroyed.
You would need to always consider the state of all checkboxes!
You could increase or decrease a number on checking or unchecking, but imagine the site loads with three of them checked.
So you always need to check all of them:
<script type="text/javascript">
<!--
function showMe (it, box) {
// consider all checkboxes with same name
var checked = amountChecked(box.name);
var vis = (checked >= 3) ? "block" : "none";
document.getElementById(it).style.display = vis;
}
function amountChecked(name) {
var all = document.getElementsByName(name);
// count checked
var result = 0;
all.forEach(function(el) {
if (el.checked) result++;
});
return result;
}
//-->
</script>
If you want to create multiple select dropdowns in the same page:
.multiselect {
width: 200px;
}
.selectBox {
position: relative;
}
.selectBox select {
width: 100%;
font-weight: bold;
}
.overSelect {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
#checkboxes {
display: none;
border: 1px #dadada solid;
}
#checkboxes label {
display: block;
}
#checkboxes label:hover {
background-color: #1e90ff;
}
Html:
<form>
<div class="multiselect">
<div class="selectBox" onclick="showCheckboxes()">
<select>
<option>Select an option</option>
</select>
<div class="overSelect"></div>
</div>
<div id="checkboxes">
<label for="one">
<input type="checkbox" id="one" />First checkbox</label>
<label for="two">
<input type="checkbox" id="two" />Second checkbox</label>
<label for="three">
<input type="checkbox" id="three" />Third checkbox</label>
</div>
</div>
<div class="multiselect">
<div class="selectBox" onclick="showCheckboxes()">
<select>
<option>Select an option</option>
</select>
<div class="overSelect"></div>
</div>
<div id="checkboxes">
<label for="one">
<input type="checkbox" id="one" />First checkbox</label>
<label for="two">
<input type="checkbox" id="two" />Second checkbox</label>
<label for="three">
<input type="checkbox" id="three" />Third checkbox</label>
</div>
</div>
</form>
Using Jquery:
function showCheckboxes(elethis) {
if($(elethis).next('#checkboxes').is(':hidden')){
$(elethis).next('#checkboxes').show();
$('.selectBox').not(elethis).next('#checkboxes').hide();
}else{
$(elethis).next('#checkboxes').hide();
$('.selectBox').not(elethis).next('#checkboxes').hide();
}
}
"Sleep" state connections are most often created by code that maintains persistent connections to the database.
This could include either connection pools created by application frameworks, or client-side database administration tools.
As mentioned above in the comments, there is really no reason to worry about these connections... unless of course you have no idea where the connection is coming from.
(CAVEAT: If you had a long list of these kinds of connections, there might be a danger of running out of simultaneous connections.)
There is no such particular way in which you can initialize the array after declaring it once.
There are three options only:
1.) initialize them in different lines :
int array[SIZE];
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
//...
//...
//...
But thats not what you want i guess.
2.) Initialize them using a for or while loop:
for (i = 0; i < MAX ; i++) {
array[i] = i;
}
This is the BEST WAY by the way to achieve your goal.
3.) In case your requirement is to initialize the array in one line itself, you have to define at-least an array with initialization. And then copy it to your destination array, but I think that there is no benefit of doing so, in that case you should define and initialize your array in one line itself.
And can I ask you why specifically you want to do so???
Currently with swift 5 the easiest way to check if the player is playing or paused is to check the .timeControlStatus variable.
player.timeControlStatus == .paused
player.timeControlStatus == .playing
You could have a div for the top with one background and another for the main page, and seperate the page content between them or put the content in a floating div on another z-level. The way you are doing it may work but I doubt it will work across every browser you encounter.
Hmm..i tried everything to get url to user image.The perfect solution was fql use like this->
$fql_b = 'SELECT pic from user where uid = ' . $user_id;
$ret_obj_b = $facebook->api(array(
'method' => 'fql.query',
'query' => $fql_b,
));
$dp_url =$ret_obj_b[0]['pic'];
replace pic by big,pic_square to get other desired results. Hope IT HELPED....
It depends on the shell (and its configuration) in standard bash only the command is stored without the date and time (check .bash_history
if there is any timestamp there).
To have bash store the timestamp you need to set HISTTIMEFORMAT
before executing the commands, e.g. in .bashrc
or .bash_profile
. This will cause bash to store the timestamps in .bash_history
(see the entries starting with #
).
Six Dependency scopes:
src/main
and src/test
src/test
<dependencyManagement/>
, only available in Maven 2.0.9 or later (like java import
)Use the web browser control. This requires Adobe reader to be installed but most likely you have it anyway. Set the UrL of the control to the file location.
This is an old question but there is no a clean solution yet. This probably is not answering this specific question, but those looking for answers on 'how to gracefully exit from an R script' will probably land here. It seems that R developers forgot to implement an exit() function. Anyway, the trick I've found is:
continue <- TRUE
tryCatch({
# You do something here that needs to exit gracefully without error.
...
# We now say bye-bye
stop("exit")
}, error = function(e) {
if (e$message != "exit") {
# Your error message goes here. E.g.
stop(e)
}
continue <<-FALSE
})
if (continue) {
# Your code continues here
...
}
cat("done.\n")
Basically, you use a flag to indicate the continuation or not of a specified block of code. Then you use the stop()
function to pass a customized message to the error handler of a tryCatch()
function. If the error handler receives your message to exit gracefully, then it just ignores the error and set the continuation flag to FALSE
.
Functions from .py file (can (of course) be in different directory) can be simply imported by writing directories first and then the file name without .py extension:
from directory_name.file_name import function_name
And later be used: function_name()
Coming late to this party, but I recently implemented this with a dedicated section in a config file for a list:
[paths]
path1 = /some/path/
path2 = /another/path/
...
and using config.items( "paths" )
to get an iterable list of path items, like so:
path_items = config.items( "paths" )
for key, path in path_items:
#do something with path
Hope this helps other folk Googling this question ;)
I know you've accepted an answer for this, but there's now a solution that lets you get an intellisense style completion box pop up like for the other excel functions, via an Excel-DNA add in, or by registering an intellisense server inside your own add in. See here.
Now, i prefer the C# way of doing it - it's much simpler, as inside Excel-DNA, any class that implements IExcelAddin
is picked up by the addin framework and has AutoOpen()
and AutoClose()
run when you open/close the add in. So you just need this:
namespace MyNameSpace {
public class Intellisense : IExcelAddIn {
public void AutoClose() {
}
public void AutoOpen() {
IntelliSenseServer.Register();
}
}
}
and then (and this is just taken from the github page), you just need to use the ExcelDNA annotations on your functions:
[ExcelFunction(Description = "A useful test function that adds two numbers, and returns the sum.")]
public static double AddThem(
[ExcelArgument(Name = "Augend", Description = "is the first number, to which will be added")]
double v1,
[ExcelArgument(Name = "Addend", Description = "is the second number that will be added")]
double v2)
{
return v1 + v2;
}
which are annotated using the ExcelDNA annotations, the intellisense server will pick up the argument names and descriptions.
There are examples for using it with just VBA too, but i'm not too into my VBA, so i don't use those parts.
You need to move your angular app code below the inclusion of the angular libraries. At the time your angular code runs, angular
does not exist yet. This is an error (see your dev tools console).
In this line:
var app = angular.module(`
you are attempting to access a variable called angular
. Consider what causes that variable to exist. That is found in the angular.js script which must then be included first.
<h1>{{2+3}}</h1>
<!-- In production use:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
-->
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>
<script>
var app = angular.module('myApp',[]);
app.directive('myDirective',function(){
return function(scope, element,attrs) {
element.bind('click',function() {alert('click')});
};
});
</script>
For completeness, it is true that your directive is similar to the already existing directive ng-click
, but I believe the point of this exercise is just to practice writing simple directives, so that makes sense.
Is that your actual code? A javascript object (which is what you've given us) does not have a length property, so in this case exampleArray.length
returns undefined rather than 5.
This stackoverflow explains the length differences between an object and an array, and this stackoverflow shows how to get the 'size' of an object.
The best way I know to sort HTML table with javascript is with the following function.
Just pass to it the id of the table you'd like to sort and the column number on the row. it assumes that the column you are sorting is numeric or has numbers in it and will do regex replace to get the number itself (great for currencies and other numbers with symbols in it).
function sortTable(table_id, sortColumn){
var tableData = document.getElementById(table_id).getElementsByTagName('tbody').item(0);
var rowData = tableData.getElementsByTagName('tr');
for(var i = 0; i < rowData.length - 1; i++){
for(var j = 0; j < rowData.length - (i + 1); j++){
if(Number(rowData.item(j).getElementsByTagName('td').item(sortColumn).innerHTML.replace(/[^0-9\.]+/g, "")) < Number(rowData.item(j+1).getElementsByTagName('td').item(sortColumn).innerHTML.replace(/[^0-9\.]+/g, ""))){
tableData.insertBefore(rowData.item(j+1),rowData.item(j));
}
}
}
}
Using example:
$(function(){
// pass the id and the <td> place you want to sort by (td counts from 0)
sortTable('table_id', 3);
});
Slight modification to the code. Having na=False will skip empty values. Otherwise you can get an error TypeError: bad operand type for unary ~: float
df[~df.C.str.contains("XYZ", na=False)]
I think the simpliest is just to convert a string into a date object and convert it back to a string. The given date string is fine if both strings still match.
public boolean isDateValid(String dateString, String pattern)
{
try
{
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
if (sdf.format(sdf.parse(dateString)).equals(dateString))
return true;
}
catch (ParseException pe) {}
return false;
}
I want to clarify some things here for the original poster which others have alluded to but haven't really explicitly stated. When you say that you want a Unique List, that is the very definition of an Ordered Set. Some other key differences between the Set Interface and the List interface are that List allows you to specify the insert index. So, the question is do you really need the List Interface (i.e. for compatibility with a 3rd party library, etc.), or can you redesign your software to use the Set interface? You also have to consider what you are doing with the interface. Is it important to find elements by their index? How many elements do you expect in your set? If you are going to have many elements, is ordering important?
If you really need a List which just has a unique constraint, there is the Apache Common Utils class org.apache.commons.collections.list.SetUniqueList which will provide you with the List interface and the unique constraint. Mind you, this breaks the List interface though. You will, however, get better performance from this if you need to seek into the list by index. If you can deal with the Set interface, and you have a smaller data set, then LinkedHashSet might be a good way to go. It just depends on the design and intent of your software.
Again, there are certain advantages and disadvantages to each collection. Some fast inserts but slow reads, some have fast reads but slow inserts, etc. It makes sense to spend a fair amount of time with the collections documentation to fully learn about the finer details of each class and interface.
Not sure of this is helpful but this what worked for me in Rails 4
Foo.where.not(bar: nil)
double d = Double.parseDouble(aString);
This should convert the string aString into the double d.
In version 2.1.5
changeDate has been renamed to change.dp so changedate was not working for me
$("#datetimepicker").datetimepicker().on('change.dp', function (e) {
FillDate(new Date());
});
also needed to change css class from datepicker to datepicker-input
<div id='datetimepicker' class='datepicker-input input-group controls'>
<input id='txtStartDate' class='form-control' placeholder='Select datepicker' data-rule-required='true' data-format='MM-DD-YYYY' type='text' />
<span class='input-group-addon'>
<span class='icon-calendar' data-time-icon='icon-time' data-date-icon='icon-calendar'></span>
</span>
</div>
Date formate also works in capitals like this data-format='MM-DD-YYYY'
it might be helpful for someone it gave me really hard time :)
Similar to @Akash but here is another approach that I've used. It uses str
than lambda
because python lambda
always gives me an alien-feelings.
import argparse
from distutils.util import strtobool
parser = argparse.ArgumentParser()
parser.add_argument("--my_bool", type=str, default="False")
args = parser.parse_args()
if bool(strtobool(args.my_bool)) is True:
print("OK")
I'll start with your last question:
Why are these new categories needed?
The C++ standard contains many rules that deal with the value category of an expression. Some rules make a distinction between lvalue and rvalue. For example, when it comes to overload resolution. Other rules make a distinction between glvalue and prvalue. For example, you can have a glvalue with an incomplete or abstract type but there is no prvalue with an incomplete or abstract type. Before we had this terminology the rules that actually need to distinguish between glvalue/prvalue referred to lvalue/rvalue and they were either unintentionally wrong or contained lots of explaining and exceptions to the rule a la "...unless the rvalue is due to unnamed rvalue reference...". So, it seems like a good idea to just give the concepts of glvalues and prvalues their own name.
What are these new categories of expressions? How do these new categories relate to the existing rvalue and lvalue categories?
We still have the terms lvalue and rvalue that are compatible with C++98. We just divided the rvalues into two subgroups, xvalues and prvalues, and we refer to lvalues and xvalues as glvalues. Xvalues are a new kind of value category for unnamed rvalue references. Every expression is one of these three: lvalue, xvalue, prvalue. A Venn diagram would look like this:
______ ______
/ X \
/ / \ \
| l | x | pr |
\ \ / /
\______X______/
gl r
Examples with functions:
int prvalue();
int& lvalue();
int&& xvalue();
But also don't forget that named rvalue references are lvalues:
void foo(int&& t) {
// t is initialized with an rvalue expression
// but is actually an lvalue expression itself
}
saveLeaves(vec,msh);
I'm assuming takes the msh
pointer and puts it inside of vec
. Since msh
is just a pointer to the memory, if you delete it, it will also get deleted inside of the vector.
I was looking into this but wanted to have a different transition rate for in and out.
This is what I ended up doing:
//css
.addedClass {
background: #5eb4fc;
}
// js
function setParentTransition(id, prop, delay, style, callback) {
$(id).css({'-webkit-transition' : prop + ' ' + delay + ' ' + style});
$(id).css({'-moz-transition' : prop + ' ' + delay + ' ' + style});
$(id).css({'-o-transition' : prop + ' ' + delay + ' ' + style});
$(id).css({'transition' : prop + ' ' + delay + ' ' + style});
callback();
}
setParentTransition(id, 'background', '0s', 'ease', function() {
$('#elementID').addClass('addedClass');
});
setTimeout(function() {
setParentTransition(id, 'background', '2s', 'ease', function() {
$('#elementID').removeClass('addedClass');
});
});
This instantly turns the background color to #5eb4fc and then slowly fades back to normal over 2 seconds.
Here's a fiddle
Pika is a CDN that takes care of providing module versions of popular packages
<script type='module'>
import * as $ from 'https://cdn.skypack.dev/jquery';
// use it!
$('#myDev').on('click', alert);
</script>
Skypack is Pika, so you could also use: import * as $ from 'https://cdn.pika.dev/jquery@^3.5.1';
So I used python3 -m pip install matplotlib' then
import matplotlib.pyplot as plt` and it worked.
Even I was facing a similar error. Try below 2 steps (the first of which has been recommended here already) -
1. Add the dependencies to your pom.xml
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
jar
files in your .m2\repository\javax\<folder>\<version>\
directory.Note: You want to do this against un-minified js.
Now you will see an object tree you can expand with all declared objects.