You can create new Event handler in the ViewModel like this.
public event EventHandler RequestClose;
protected void OnRequestClose()
{
if (RequestClose != null)
RequestClose(this, EventArgs.Empty);
}
Then Define RelayCommand for ExitCommand.
private RelayCommand _CloseCommand;
public ICommand CloseCommand
{
get
{
if(this._CloseCommand==null)
this._CloseCommand=new RelayCommand(CloseClick);
return this._CloseCommand;
}
}
private void CloseClick(object obj)
{
OnRequestClose();
}
Then In XAML file set
<Button Command="{Binding CloseCommand}" />
Set the DataContext in the xaml.cs File and Subscribe to the event we created.
public partial class MainWindow : Window
{
private ViewModel mainViewModel = null;
public MainWindow()
{
InitializeComponent();
mainViewModel = new ViewModel();
this.DataContext = mainViewModel;
mainViewModel.RequestClose += delegate(object sender, EventArgs args) { this.Close(); };
}
}
I haven't done much testing with this but it seems to work. Here's what I came up with:
namespace OrtzIRC.WPF
{
using System;
using System.Windows;
using OrtzIRC.WPF.ViewModels;
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private MainViewModel viewModel = new MainViewModel();
private MainWindow window = new MainWindow();
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
viewModel.RequestClose += ViewModelRequestClose;
window.DataContext = viewModel;
window.Closing += Window_Closing;
window.Show();
}
private void ViewModelRequestClose(object sender, EventArgs e)
{
viewModel.RequestClose -= ViewModelRequestClose;
window.Close();
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
window.Closing -= Window_Closing;
viewModel.RequestClose -= ViewModelRequestClose; //Otherwise Close gets called again
viewModel.CloseCommand.Execute(null);
}
}
}
If you want to put the content of example
into install
folder after build:
code/
src/
example/
CMakeLists.txt
try add the following to your CMakeLists.txt
:
install(DIRECTORY example/ DESTINATION example)
You have to make Progressdialog
object in onPreExecute
method of AsyncTask
and you should dismiss
it on onPostExecute
method.
This should be set directly in the CSS.
.forum {background-color: #123456}
.forum:hover {background-color: #380606}
If you are worried about the fact the IE6 will not accept hover over elements which are not links, you can use the hover event of jQuery for compatibility.
You need to put the last()
indexing on the nodelist result, rather than as part of the selection criteria. Try:
(//element[@name='D'])[last()]
I'm assuming that by empty you mean "has no properties of its own".
// Speed up calls to hasOwnProperty
var hasOwnProperty = Object.prototype.hasOwnProperty;
function isEmpty(obj) {
// null and undefined are "empty"
if (obj == null) return true;
// Assume if it has a length property with a non-zero value
// that that property is correct.
if (obj.length > 0) return false;
if (obj.length === 0) return true;
// If it isn't an object at this point
// it is empty, but it can't be anything *but* empty
// Is it empty? Depends on your application.
if (typeof obj !== "object") return true;
// Otherwise, does it have any properties of its own?
// Note that this doesn't handle
// toString and valueOf enumeration bugs in IE < 9
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) return false;
}
return true;
}
Examples:
isEmpty(""), // true
isEmpty(33), // true (arguably could be a TypeError)
isEmpty([]), // true
isEmpty({}), // true
isEmpty({length: 0, custom_property: []}), // true
isEmpty("Hello"), // false
isEmpty([1,2,3]), // false
isEmpty({test: 1}), // false
isEmpty({length: 3, custom_property: [1,2,3]}) // false
If you only need to handle ECMAScript5 browsers, you can use Object.getOwnPropertyNames
instead of the hasOwnProperty
loop:
if (Object.getOwnPropertyNames(obj).length > 0) return false;
This will ensure that even if the object only has non-enumerable properties isEmpty
will still give you the correct results.
The linker takes some environment variables into account. one is LD_PRELOAD
from man 8 ld-linux
:
LD_PRELOAD
A whitespace-separated list of additional, user-specified, ELF
shared libraries to be loaded before all others. This can be
used to selectively override functions in other shared
libraries. For setuid/setgid ELF binaries, only libraries in
the standard search directories that are also setgid will be
loaded.
Therefore the linker will try to load libraries listed in the LD_PRELOAD
variable before others are loaded.
What could be the case that inside the variable is listed a library that can't be pre-loaded. look inside your .bashrc
or .bash_profile
environment where the LD_PRELOAD
is set and remove that library from the variable.
If you are using angular pre v1.1.5 (i.e. no ternary operator) and you still want an equivalent way to set a value in both conditions you can do something like this:
ng-class="{'class1':item.isReadOnly == false, 'class2':item.isReadOnly == true}"
Using server request time to Add days. Working as expected.
25/08/19 => 27/09/19
$timestamp = $_SERVER['REQUEST_TIME'];
$dateNow = date('d/m/y', $timestamp);
$newDate = date('d/m/y', strtotime('+2 day', $timestamp));
Here '+2 days' to add any number of days.
npm start
in Node.js Command Prompt.c:\users\MyUser\npm-debug.log
C:\\Program Files\\nodejs\\\\node.exe
Call node.exe + <full path to your server file.js>
Server is listening on port 1337 !
Make sure your drive has enough space left
You can also use translate(). If the third argument is too short, the corresponding characters from the second argument are deleted. Unlike regexp_replace() you don't need to worry about special characters. Source code.
You need to do
Update table_xpto
set column_xpto = x.xpto_New
,column2 = x.column2New
from table_xpto xpto
inner join table_xptoNew xptoNew ON xpto.bla = xptoNew.Bla
where <clause where>
If you need a better answer, you can give us more information :)
If you want to automatically stash your changes and unstash them for every rebase, you can do this:
git config --global rebase.autoStash true
ALTER TABLE users CHANGE id int( 30 ) NOT NULL AUTO_INCREMENT
the integer parameter is based on my default sql setting have a nice day
All DDL statements in Oracle PL/SQL should use Execute Immediate before the statement. Hence you should use:
execute immediate 'truncate table schema.tablename';
Part of the confusion regarding regsvr32 is that on 64-bit windows the name and path have not changed, but it now registers 64-bit DLLs. The 32-bit regsvr32 exists in SysWOW64, a name that appears to represent 64-bit applications. However the WOW64 in the name refers to Windows on Windows 64, or more explicity Windows 32-bit on Windows 64-bit. When you think of it this way the name makes sense even though it is confusing in this context.
I cannot find my original source on an MSDN blog but it is referenced in this Wikipedia article http://en.wikipedia.org/wiki/WoW64
Update:
MongoServer.Create
is obsolete now (thanks to @aknuds1). Instead this use following code:
var _server = new MongoClient(connectionString).GetServer();
It's easy. You should first take database name from connection string and then get database by name. Complete example:
var connectionString = "mongodb://localhost:27020/mydb";
//take database name from connection string
var _databaseName = MongoUrl.Create(connectionString).DatabaseName;
var _server = MongoServer.Create(connectionString);
//and then get database by database name:
_server.GetDatabase(_databaseName);
Important: If your database and auth database are different, you can add a authSource= query parameter to specify a different auth database. (thank you to @chrisdrobison)
NOTE If you are using the database segment as the initial database to use, but the username and password specified are defined in a different database, you can use the authSource option to specify the database in which the credential is defined. For example, mongodb://user:pass@hostname/db1?authSource=userDb would authenticate the credential against the userDb database instead of db1.
var result = System.Text.Encoding.Unicode.GetBytes(text);
One more option that I saw is missing here:
const string APP_CONFIG_FILE = "APP_CONFIG_FILE";
string defaultSysConfigFilePath = (string)AppDomain.CurrentDomain.GetData(APP_CONFIG_FILE);
NSString *folderName=[NSString stringWithFormat:@"/documents/%@",[tempDictLitrature objectForKey:@"folder"]];
NSString *fileName=[tempDictLitrature objectForKey:@"name"];
[self.navigationItem setTitle:fileName];
NSString *type=[tempDictLitrature objectForKey:@"type"];
NSString *path=[[NSBundle mainBundle]pathForResource:fileName ofType:type inDirectory:folderName];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
webView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 1024, 730)];
[webView setBackgroundColor:[UIColor lightGrayColor]];
webView.scalesPageToFit = YES;
[[webView scrollView] setContentOffset:CGPointZero animated:YES];
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.scrollTo(0.0, 50.0)"]];
[webView loadRequest:request];
[self.view addSubview:webView];
I had the same problem. mysql -u root -p
worked for me. It later asks you for a password. You should then enter the password that you had set for mysql. The default password could be password
, if you did not set one. More info here.
Why not just put an executable somewhere in my $PATH
~/.local/bin directory
is theoretically expected to be in your $PATH
.
According to these people it's a bug not adding it in the $PATH
when using systemd
.
This answer explains it more extensively.
But even if your distro includes the ~/.local/bin
directory to the $PATH
, it might be in the following form (inside ~/.profile
):
if [ -d "$HOME/.local/bin" ] ; then
PATH="$HOME/.local/bin:$PATH"
fi
which would require you to logout and login again, if the directory was not there before.
I cannot create a file with the name+period+extnesion in WS 2012 Explorer longer than 224 characters. Don't shoot the messenger!
In the CMD of the same server I cannot create a longer than 235 character name:
The system cannot find the path specified.
The file with a 224 character name created in the Explorer cannot be opened in Notepad++ - it just comes up with a new file instead.
I would prevent loops in general if i can, set approaches are much more efficient:
INSERT INTO tblFoo
SELECT TOP (300) n = ROW_NUMBER()OVER (ORDER BY [object_id])
FROM sys.all_objects ORDER BY n;
If you are looking for the solution in Android Studio :
If you got white space in your branch then you will get this error.
All of the suggestions above work, but if you want your computations to by more efficient, you should take advantage of numpy vector operations (as pointed out here).
import pandas as pd
import numpy as np
df = pd.DataFrame ({'a' : np.random.randn(6),
'b' : ['foo', 'bar'] * 3,
'c' : np.random.randn(6)})
Example 1: looping with pandas.apply()
:
%%timeit
def my_test2(row):
return row['a'] % row['c']
df['Value'] = df.apply(my_test2, axis=1)
The slowest run took 7.49 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 481 µs per loop
Example 2: vectorize using pandas.apply()
:
%%timeit
df['a'] % df['c']
The slowest run took 458.85 times longer than the fastest. This could mean that an intermediate result is being cached. 10000 loops, best of 3: 70.9 µs per loop
Example 3: vectorize using numpy arrays:
%%timeit
df['a'].values % df['c'].values
The slowest run took 7.98 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 6.39 µs per loop
So vectorizing using numpy arrays improved the speed by almost two orders of magnitude.
For the lazy like myself:
Kip's answer (from above) in coffeescript, using an "enum", and operating on the same object:
Date.UNIT =
YEAR: 0
QUARTER: 1
MONTH: 2
WEEK: 3
DAY: 4
HOUR: 5
MINUTE: 6
SECOND: 7
Date::add = (unit, quantity) ->
switch unit
when Date.UNIT.YEAR then @setFullYear(@getFullYear() + quantity)
when Date.UNIT.QUARTER then @setMonth(@getMonth() + (3 * quantity))
when Date.UNIT.MONTH then @setMonth(@getMonth() + quantity)
when Date.UNIT.WEEK then @setDate(@getDate() + (7 * quantity))
when Date.UNIT.DAY then @setDate(@getDate() + quantity)
when Date.UNIT.HOUR then @setTime(@getTime() + (3600000 * quantity))
when Date.UNIT.MINUTE then @setTime(@getTime() + (60000 * quantity))
when Date.UNIT.SECOND then @setTime(@getTime() + (1000 * quantity))
else throw new Error "Unrecognized unit provided"
@ # for chaining
Always show errors on a testing server. Never show errors on a production server.
Write a script to determine whether the page is on a local, testing, or live server, and set $state to "local", "testing", or "live". Then:
if( $state == "local" || $state == "testing" )
{
ini_set( "display_errors", "1" );
error_reporting( E_ALL & ~E_NOTICE );
}
else
{
error_reporting( 0 );
}
on this web http://quirksmode.org/css/css2/columns.html i found that easy way
<table>
<col style="background-color: #6374AB; color: #ffffff" />
<col span="2" style="background-color: #07B133; color: #ffffff;" />
<tr>..
If you want to list last 3 chars, simplest way is
select substr('123456',-3) from dual;
Jon's answer didn't work for me as I got a compiler error CS0453 C# The type must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method
This worked for me though:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SomeObject>().HasOptional(m => m.somefield);
base.OnModelCreating(modelBuilder);
}
I don't think putting %AppData% in a string like that will work.
try
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString()
More universal can be: for each v Selection : v.value = "'" & v.value : next and selecting range of cells before execution
try this:
a = new Array();
a.push(10);
a.push(60);
a.push(20);
a.push(30);
a.push(100);
a.sort(Test)
document.write(a);
function Test(a,b)
{
return a > b ? true : false;
}
You can just read from a file, jsonifying
each line as you go:
tweets = []
for line in open('tweets.json', 'r'):
tweets.append(json.loads(line))
This avoids storing intermediate python objects. As long as your write one full tweet per append()
call, this should work.
Not really refreshing the page but thought it would help someone else out there looking for something simple
ngOnInit(){
startUp()
}
startUp(){
// Codes
}
refresh(){
// Code to destroy child component
startUp()
}
Remove pathlib
and reinstall it. Delete the pathlib in sitepackages
folder and reinstall the pathlib package by using pip command:
pip install pathlib
I suspect it's already mentioned in some of the answers, but I'll slightly modify this to have complete working answer (easier to find and use).
Go to: https://nodejs.org/en/download/. Install nodejs.
Install http-server by running command from command prompt npm install -g http-server
.
Change into your working directory, where index.html
/yoursome.html
resides.
Start your http server by running command http-server -c-1
Open web browser to http://localhost:8080
or http://localhost:8080/yoursome.html
- depending on your html filename.
Note: you should use the accepted answer if possible. It's better than mine.
It's quite easy with the GD library.
It's built in usually, you probably have it (use phpinfo()
to check)
$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagejpeg($image, "folder/file.jpg");
The above answer is better (faster) for most situations, but with GD you can also modify it in some form (cropping for example).
$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagecopy($image, $image, 0, 140, 0, 0, imagesx($image), imagesy($image));
imagejpeg($image, "folder/file.jpg");
This only works if allow_url_fopen
is true
(it is by default)
Here's a reasonably compact solution, though I suspect not particularly efficient (to put it mildly):
>>> ds = [{'id':1,'name':'john', 'age':34},
... {'id':1,'name':'john', 'age':34},
... {'id':2,'name':'hanna', 'age':30}
... ]
>>> map(dict, set(tuple(sorted(d.items())) for d in ds))
[{'age': 30, 'id': 2, 'name': 'hanna'}, {'age': 34, 'id': 1, 'name': 'john'}]
Sometimes two classes may have some parameter names in common. In that case, you can't pop the key-value pairs off of **kwargs
or remove them from *args
. Instead, you can define a Base
class which unlike object
, absorbs/ignores arguments:
class Base(object):
def __init__(self, *args, **kwargs): pass
class A(Base):
def __init__(self, *args, **kwargs):
print "A"
super(A, self).__init__(*args, **kwargs)
class B(Base):
def __init__(self, *args, **kwargs):
print "B"
super(B, self).__init__(*args, **kwargs)
class C(A):
def __init__(self, arg, *args, **kwargs):
print "C","arg=",arg
super(C, self).__init__(arg, *args, **kwargs)
class D(B):
def __init__(self, arg, *args, **kwargs):
print "D", "arg=",arg
super(D, self).__init__(arg, *args, **kwargs)
class E(C,D):
def __init__(self, arg, *args, **kwargs):
print "E", "arg=",arg
super(E, self).__init__(arg, *args, **kwargs)
print "MRO:", [x.__name__ for x in E.__mro__]
E(10)
yields
MRO: ['E', 'C', 'A', 'D', 'B', 'Base', 'object']
E arg= 10
C arg= 10
A
D arg= 10
B
Note that for this to work, Base
must be the penultimate class in the MRO.
Try this:
<video height="256" loop autoplay controls id="vid">
<source type="video/mp4" src="video_file.mp4"></source>
<source type="video/ogg" src="video_file.ogg"></source>
This is how I normally do it. loop, controls and autoplay do not require a value they are boolean attributes.
Try this:
function createcodes() {
$('.authors-list tr').each(function () {
//processing this row
//how to process each cell(table td) where there is checkbox
$(this).find('td input:checked').each(function () {
// it is checked, your code here...
});
});
}
Have you googled about it - insert update delete access vb.net, there are lots of reference about this.
Insert Update Delete Navigation & Searching In Access Database Using VB.NET
what could be the easier way to connect and manipulate the DB?
Use OleDBConnection class to make connection with DB
is it by using MS ACCESS 2003 or MS ACCESS 2007?
you can use any you want to use or your client will use on their machine.
it seems that you want to find some example of opereations fo the database. Here is an example of Access 2010 for your reference:
Example code snippet:
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class DBUtil
Private connectionString As String
Public Sub New()
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
Dim dbSource = "Data Source=d:\DB\Database11.accdb"
connectionString = dbProvider & dbSource
End Sub
Public Function GetCategories() As DataSet
Dim query As String = "SELECT * FROM Categories"
Dim cmd As New OleDbCommand(query)
Return FillDataSet(cmd, "Categories")
End Function
Public SubUpdateCategories(ByVal name As String)
Dim query As String = "update Categories set name = 'new2' where name = ?"
Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("Name", name)
Return FillDataSet(cmd, "Categories")
End Sub
Public Function GetItems() As DataSet
Dim query As String = "SELECT * FROM Items"
Dim cmd As New OleDbCommand(query)
Return FillDataSet(cmd, "Items")
End Function
Public Function GetItems(ByVal categoryID As Integer) As DataSet
'Create the command.
Dim query As String = "SELECT * FROM Items WHERE Category_ID=?"
Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("category_ID", categoryID)
'Fill the dataset.
Return FillDataSet(cmd, "Items")
End Function
Public Sub AddCategory(ByVal name As String)
Dim con As New OleDbConnection(connectionString)
'Create the command.
Dim insertSQL As String = "INSERT INTO Categories "
insertSQL &= "VALUES(?)"
Dim cmd As New OleDbCommand(insertSQL, con)
cmd.Parameters.AddWithValue("Name", name)
Try
con.Open()
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
End Sub
Public Sub AddItem(ByVal title As String, ByVal description As String, _
ByVal price As Decimal, ByVal categoryID As Integer)
Dim con As New OleDbConnection(connectionString)
'Create the command.
Dim insertSQL As String = "INSERT INTO Items "
insertSQL &= "(Title, Description, Price, Category_ID)"
insertSQL &= "VALUES (?, ?, ?, ?)"
Dim cmd As New OleDb.OleDbCommand(insertSQL, con)
cmd.Parameters.AddWithValue("Title", title)
cmd.Parameters.AddWithValue("Description", description)
cmd.Parameters.AddWithValue("Price", price)
cmd.Parameters.AddWithValue("CategoryID", categoryID)
Try
con.Open()
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
End Sub
Private Function FillDataSet(ByVal cmd As OleDbCommand, ByVal tableName As String) As DataSet
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
Dim dbSource = "Data Source=D:\DB\Database11.accdb"
connectionString = dbProvider & dbSource
con.ConnectionString = connectionString
cmd.Connection = con
Dim adapter As New OleDbDataAdapter(cmd)
Dim ds As New DataSet()
Try
con.Open()
adapter.Fill(ds, tableName)
Finally
con.Close()
End Try
Return ds
End Function
End Class
Refer these links:
Insert, Update, Delete & Search Values in MS Access 2003 with VB.NET 2005
INSERT, DELETE, UPDATE AND SELECT Data in MS-Access with VB 2008
How Add new record ,Update record,Delete Records using Vb.net Forms when Access as a back
select true from tablename where condition limit 1;
I believe that this is the query that postgres uses for checking foreign keys.
In your case, you could do this in one go too:
insert into yourtable select $userid, $rightid, $count where not (select true from yourtable where userid = $userid limit 1);
According to the docs (http://ca3.php.net/language.oop5.cloning):
$a = clone $b;
I'm surprised that nobody has mentioned the use of this
in the event handler. It works automatically in modern browsers and can be made to work in other browsers. If you use addEventListener
or attachEvent
to install your event handler, then you can make the value of this
automatically be assigned to the object the created the event.
Further, the user of programmatically installed event handlers allows you to separate javascript code from HTML which is often considered a good thing.
Here's how you would do that in your code in plain javascript:
Remove the onmouseover="zoom()"
from your HTML and install the event handler in your javascript like this:
// simplified utility function to register an event handler cross-browser
function setEventHandler(obj, name, fn) {
if (typeof obj == "string") {
obj = document.getElementById(obj);
}
if (obj.addEventListener) {
return(obj.addEventListener(name, fn));
} else if (obj.attachEvent) {
return(obj.attachEvent("on" + name, function() {return(fn.call(obj));}));
}
}
function zoom() {
// you can use "this" here to refer to the object that caused the event
// this here will refer to the calling object (which in this case is the <map>)
console.log(this.id);
document.getElementById("preview").src="http://photos.smugmug.com/photos/344290962_h6JjS-Ti.jpg";
}
// register your event handler
setEventHandler("nose", "mouseover", zoom);
If you want to keep existing params and not expose yourself to XSS attacks, be sure to clean the params hash, leaving only the params that your app can be sending:
# inline
<%= link_to 'Link', params.slice(:sort).merge(per_page: 20) %>
If you use it in multiple places, clean the params in the controller:
# your_controller.rb
@params = params.slice(:sort, :per_page)
# view
<%= link_to 'Link', @params.merge(per_page: 20) %>
There is no way to "discard" the time component.
DateTime.Today
is the same as:
DateTime d = DateTime.Now.Date;
If you only want to display only the date portion, simply do that - use ToString
with the format string you need.
For example, using the standard format string "D" (long date format specifier):
d.ToString("D");
Try this:
MarginLayoutParams params = (MarginLayoutParams) view.getLayoutParams();
params.width = 250;
params.leftMargin = 50;
params.topMargin = 50;
A correct answer has already been supplied, but for you to learn how to help yourself I thought I'd throw in something helpful in a different way; if you can sum up what you're trying to achieve in one word, there's a mighty fine help feature on Linux.
man -k <your search term>
What that does is to list all commands that have your search term in the short description. There's usually a pretty good chance that you will find what you're after. ;)
That output can sometimes be somewhat overwhelming, and I'd recommend narrowing it down to the executables, rather than all available man-pages, like so:
man -k find | egrep '\(1\)'
or, if you also want to look for commands that require higher privilege levels, like this:
man -k find | egrep '\([18]\)'
Say you want to save the string I'm a "foobar"
in the database.
Your query will look something like INSERT INTO foos (text) VALUES ("$text")
.
With the $text
variable replaced, this will look like this:
INSERT INTO foos (text) VALUES ("I'm a "foobar"")
Now, where exactly does the string end? You may know, an SQL parser doesn't. Not only will this simply break this query, it can also be abused to inject SQL commands you didn't intend.
mysql_real_escape_string
makes sure such ambiguities do not occur by escaping characters which have special meaning to an SQL parser:
mysql_real_escape_string($text) => I\'m a \"foobar\"
This becomes:
INSERT INTO foos (text) VALUES ("I\'m a \"foobar\"")
This makes the statement unambiguous and safe. The \
signals that the following character is not to be taken by its special meaning as string terminator. There are a few such characters that mysql_real_escape_string
takes care of.
Escaping is a pretty universal thing in programming languages BTW, all along the same lines. If you want to type the above sentence literally in PHP, you need to escape it as well for the same reasons:
$text = 'I\'m a "foobar"';
// or
$text = "I'm a \"foobar\"";
As others have noted, this is the default serialisation of an object. But why is it [object Object]
and not just [object]
?
That is because there are different types of objects in Javascript!
stringify(function (){})
-> [object Function]
stringify([])
-> [object Array]
stringify(/x/)
-> [object RegExp]
stringify(new Date)
-> [object Date]
stringify({})
-> [object Object]
That's because the constructor function is called Object
(with a capital "O"), and the term "object" (with small "o") refers to the structural nature of the thingy.
Usually, when you're talking about "objects" in Javascript, you actually mean "Object objects", and not the other types.
where stringify
should look like this:
function stringify (x) {
console.log(Object.prototype.toString.call(x));
}
Your regex pattern should have the g modifier:
var pattern = /[somepattern]+/g;
notice the g at the end. it tells the replacer to do a global replace.
Also you dont need to use the RegExp object you can construct your pattern as above. Example pattern:
var pattern = /[0-9a-zA-Z]+/g;
a pattern is always surrounded by / on either side - with modifiers after the final /, the g modifier being the global.
EDIT: Why does it matter if pattern is a variable? In your case it would function like this (notice that pattern is still a variable):
var pattern = /[0-9a-zA-Z]+/g;
repeater.replace(pattern, "1234abc");
But you would need to change your replace function to this:
this.markup = this.markup.replace(pattern, value);
For Compare two date like MM/DD/YYYY to MM/DD/YYYY . Remember First thing column type of Field must be dateTime. Example : columnName : payment_date dataType : DateTime .
after that you can easily compare it. Query is :
select * from demo_date where date >= '3/1/2015' and date <= '3/31/2015'.
It very simple ...... It tested it.....
I found how to fix this issue (for me at least). Why it worked, I'm not sure, but it did. (I just tried against a second website that was having the same problem and the following solution worked for that as well).
I tried the normal cleaning of the projects and rebuilding, shutting down all my Visual Studio instances and restarting them, even tried restarting my computer.
What actually worked was opening up the project in Visual Studio, closing all the open tabs, and then shutting it down.
Before I had left the tabs open because I didn't think it mattered (and I hardly ever close the tabs I'm using).
As far as I know you can only have the same method when using different http methods.
i.e.
[AcceptVerbs("GET")]
public ActionResult MyAction()
{
}
[AcceptVerbs("POST")]
public ActionResult MyAction(FormResult fm)
{
}
Based on Matt Johanson's comment on the solution provided by Sheldon Griffin I created the following code:
Date.prototype.stdTimezoneOffset = function() {
var fy=this.getFullYear();
if (!Date.prototype.stdTimezoneOffset.cache.hasOwnProperty(fy)) {
var maxOffset = new Date(fy, 0, 1).getTimezoneOffset();
var monthsTestOrder=[6,7,5,8,4,9,3,10,2,11,1];
for(var mi=0;mi<12;mi++) {
var offset=new Date(fy, monthsTestOrder[mi], 1).getTimezoneOffset();
if (offset!=maxOffset) {
maxOffset=Math.max(maxOffset,offset);
break;
}
}
Date.prototype.stdTimezoneOffset.cache[fy]=maxOffset;
}
return Date.prototype.stdTimezoneOffset.cache[fy];
};
Date.prototype.stdTimezoneOffset.cache={};
Date.prototype.isDST = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
};
It tries to get the best of all worlds taking into account all the comments and previously suggested answers and specifically it:
1) Caches the result for per year stdTimezoneOffset so that you don't need to recalculate it when testing multiple dates in the same year.
2) It does not assume that DST (if it exists at all) is necessarily in July, and will work even if it will at some point and some place be any month. However Performance-wise it will work faster if indeed July (or near by months) are indeed DST.
3) Worse case it will compare the getTimezoneOffset of the first of each month. [and do that Once per tested year].
The assumption it does still makes is that the if there is DST period is larger then a single month.
If someone wants to remove that assumption he can change loop into something more like whats in the solutin provided by Aaron Cole - but I would still jump half a year ahead and break out of the loop when two different offsets are found]
I think this will bring it back using 3.0
.navbar .divider-vertical {
height: 50px;
margin: 0 9px;
border-right: 1px solid #ffffff;
border-left: 1px solid #f2f2f2;
}
.navbar-inverse .divider-vertical {
border-right-color: #222222;
border-left-color: #111111;
}
@media (max-width: 767px) {
.navbar-collapse .nav > .divider-vertical {
display: none;
}
}
To show:
<img src="//graph.facebook.com/{{fid}}/picture">
<img src="//graph.facebook.com/{{fid}}/picture?type=large">
NOTE: Don't use this. See @Foreever's comment below.
$img = file_get_contents('https://graph.facebook.com/'.$fid.'/picture?type=large');
$file = dirname(__file__).'/avatar/'.$fid.'.jpg';
file_put_contents($file, $img);
Where $fid is your user id on Facebook.
NOTE: In case of images marked as "18+" you will need a valid access_token from a 18+ user:
<img src="//graph.facebook.com/{{fid}}/picture?access_token={{access_token}}">
Graph API v2.0 can't be queried using usernames, you should use userId
always.
Because these days ASP.NET is open source, you can find it on GitHub: AspNet.Identity 3.0 and AspNet.Identity 2.0.
From the comments:
/* =======================
* HASHED PASSWORD FORMATS
* =======================
*
* Version 2:
* PBKDF2 with HMAC-SHA1, 128-bit salt, 256-bit subkey, 1000 iterations.
* (See also: SDL crypto guidelines v5.1, Part III)
* Format: { 0x00, salt, subkey }
*
* Version 3:
* PBKDF2 with HMAC-SHA256, 128-bit salt, 256-bit subkey, 10000 iterations.
* Format: { 0x01, prf (UInt32), iter count (UInt32), salt length (UInt32), salt, subkey }
* (All UInt32s are stored big-endian.)
*/
Instead of editing every model I would recommend to write one template tag which will return all field of any model given.
Every object has list of fields ._meta.fields
.
Every field object has attribute name
that will return it's name and method value_to_string()
that supplied with your model object
will return its value.
The rest is as simple as it's said in Django documentation.
Here is my example how this templatetag might look like:
from django.conf import settings
from django import template
if not getattr(settings, 'DEBUG', False):
raise template.TemplateSyntaxError('get_fields is available only when DEBUG = True')
register = template.Library()
class GetFieldsNode(template.Node):
def __init__(self, object, context_name=None):
self.object = template.Variable(object)
self.context_name = context_name
def render(self, context):
object = self.object.resolve(context)
fields = [(field.name, field.value_to_string(object)) for field in object._meta.fields]
if self.context_name:
context[self.context_name] = fields
return ''
else:
return fields
@register.tag
def get_fields(parser, token):
bits = token.split_contents()
if len(bits) == 4 and bits[2] == 'as':
return GetFieldsNode(bits[1], context_name=bits[3])
elif len(bits) == 2:
return GetFieldsNode(bits[1])
else:
raise template.TemplateSyntaxError("get_fields expects a syntax of "
"{% get_fields <object> [as <context_name>] %}")
On x86 at least, g++ 4.6.1 just uses IDIVL and gets both from that single instruction.
C++ code:
void foo(int a, int b, int* c, int* d)
{
*c = a / b;
*d = a % b;
}
x86 code:
__Z3fooiiPiS_:
LFB4:
movq %rdx, %r8
movl %edi, %edx
movl %edi, %eax
sarl $31, %edx
idivl %esi
movl %eax, (%r8)
movl %edx, (%rcx)
ret
These days it's very easy - right click any item displayed in the console log and select save as and save the whole log output to a file on your computer.
Another alternative is to use Pycharm IDE. For each project, you can set the Project Interpreter in Settings.
For example, if anaconda is installed in /home/user/anaconda2/bin/python, you can select the Project Interpreter and set to this folder.
Since the whole project is set to Anaconda's path, you can import any module which is packaged within Anaconda.
class MathsOperations:
def __init__ (self, x, y):
self.a = x
self.b = y
def testAddition (self):
return (self.a + self.b)
def testMultiplication (self):
return (self.a * self.b)
then
temp = MathsOperations()
print(temp.testAddition())
If you use a CLR function, you can convert the float to a string that looks just like the float, without all the extra 0's at the end.
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
[return: SqlFacet(MaxSize = 50)]
public static SqlString float_to_str(double Value, int TruncAfter)
{
string rtn1 = Value.ToString("R");
string rtn2 = Value.ToString("0." + new string('0', TruncAfter));
if (rtn1.Length < rtn2.Length) { return rtn1; } else { return rtn2; }
}
.
create table #temp (value float)
insert into #temp values (0.73), (0), (0.63921), (-0.70945), (0.28), (0.72000002861023), (3.7), (-0.01), (0.86), (0.55489), (0.439999997615814)
select value,
dbo.float_to_str(value, 18) as converted,
case when value = cast(dbo.float_to_str(value, 18) as float) then 1 else 0 end as same
from #temp
drop table #temp
.
value converted same
---------------------- -------------------------- -----------
0.73 0.73 1
0 0 1
0.63921 0.63921 1
-0.70945 -0.70945 1
0.28 0.28 1
0.72000002861023 0.72000002861023 1
3.7 3.7 1
-0.01 -0.01 1
0.86 0.86 1
0.55489 0.55489 1
0.439999997615814 0.439999997615814 1
.
All converted strings are truncated at 18 decimal places, and there are no trailing zeros. 18 digits of precision is not a problem for us. And, 100% of our FP numbers (close to 100,000 values) look identical as string values as they do in the database as FP numbers.
SharpCompress is in my opinion one of the smartest compression libraries out there. It supports LZMA (7-zip), is easy to use and under active development.
As it has LZMA streaming support already, at the time of writing it unfortunately only supports 7-zip archive reading. BUT archive writing is on their todo list (see readme). For future readers: Check to get the current status here: https://github.com/adamhathcock/sharpcompress/blob/master/FORMATS.md
Session.Abandon()
http://msdn.microsoft.com/en-us/library/ms524310.aspx
Here is a little more detail on the HttpSessionState
object:
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate_members.aspx
An alternative way of doing it is by using the choice
method of the Generator
class, https://github.com/numpy/numpy/issues/10835
import numpy as np
# generate the random array
A = np.random.randint(5, size=(10,3))
# use the choice method of the Generator class
rng = np.random.default_rng()
A_sampled = rng.choice(A, 2)
leading to a sampled data,
array([[1, 3, 2],
[1, 2, 1]])
The running time is also profiled compared as follows,
%timeit rng.choice(A, 2)
15.1 µs ± 115 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit np.random.permutation(A)[:2]
4.22 µs ± 83.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit A[np.random.randint(A.shape[0], size=2), :]
10.6 µs ± 418 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
But when the array goes big, A = np.random.randint(10, size=(1000,300))
. working on the index is the best way.
%timeit A[np.random.randint(A.shape[0], size=50), :]
17.6 µs ± 657 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit rng.choice(A, 50)
22.3 µs ± 134 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit np.random.permutation(A)[:50]
143 µs ± 1.33 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
So the permutation
method seems to be the most efficient one when your array is small while working on the index is the optimal solution when your array goes big.
Try using head or tail. If you want the 5 most-recently modified files:
ls -1t | head -5
The -1 (that's a one) says one file per line and the head says take the first 5 entries.
If you want the last 5 try
ls -1t | tail -5
As of SQL SERVER 2016 you can use the new DROP PROCEDURE IF EXISTS
.
DROP { PROC | PROCEDURE } [ IF EXISTS ] { [ schema_name. ] procedure } [ ,...n ]
Reference : https://msdn.microsoft.com/en-us/library/ms174969.aspx
clean and easy solution:
max_elements_i = np.expand_dims(np.argmax(p, axis=1), axis=1)
one_hot = np.zeros(p.shape)
np.put_along_axis(one_hot, max_elements_i, 1, axis=1)
New Excel versions
=IF(ISNA(VLOOKUP(A1,B,B,1,FALSE)),"",A1)
Older Excel versions
=IF(ISNA(VLOOKUP(A1;B:B;1;FALSE));"";A1)
That is: "If the value of A1 exists in the B column, display it here. If it doesn't exist, leave it empty."
Just in case you can't / don't use CURLOPT_HEADERFUNCTION
or other solutions;
$nextCheck = function($body) {
return ($body && strpos($body, 'HTTP/') === 0);
};
[$headers, $body] = explode("\r\n\r\n", $result, 2);
if ($nextCheck($body)) {
do {
[$headers, $body] = explode("\r\n\r\n", $body, 2);
} while ($nextCheck($body));
}
C# 7 adds support for local functions
Here is the previous example using a local function
void Method()
{
string localFunction(string source)
{
// add your functionality here
return source ;
};
// call the inline function
localFunction("prefix");
}
The first improvement would be to simplify the three cases in the main loop: Rather than iterating while some of the sequence has elements, iterate while both sequences have elements. When leaving the loop, one of them will be empty, we don't know which, but we don't care: We append them at the end of the result.
def msort2(x):
if len(x) < 2:
return x
result = [] # moved!
mid = int(len(x) / 2)
y = msort2(x[:mid])
z = msort2(x[mid:])
while (len(y) > 0) and (len(z) > 0):
if y[0] > z[0]:
result.append(z[0])
z.pop(0)
else:
result.append(y[0])
y.pop(0)
result += y
result += z
return result
The second optimization is to avoid pop
ping the elements. Rather, have two indices:
def msort3(x):
if len(x) < 2:
return x
result = []
mid = int(len(x) / 2)
y = msort3(x[:mid])
z = msort3(x[mid:])
i = 0
j = 0
while i < len(y) and j < len(z):
if y[i] > z[j]:
result.append(z[j])
j += 1
else:
result.append(y[i])
i += 1
result += y[i:]
result += z[j:]
return result
A final improvement consists in using a non recursive algorithm to sort short sequences. In this case I use the built-in sorted
function and use it when the size of the input is less than 20:
def msort4(x):
if len(x) < 20:
return sorted(x)
result = []
mid = int(len(x) / 2)
y = msort4(x[:mid])
z = msort4(x[mid:])
i = 0
j = 0
while i < len(y) and j < len(z):
if y[i] > z[j]:
result.append(z[j])
j += 1
else:
result.append(y[i])
i += 1
result += y[i:]
result += z[j:]
return result
My measurements to sort a random list of 100000 integers are 2.46 seconds for the original version, 2.33 for msort2, 0.60 for msort3 and 0.40 for msort4. For reference, sorting all the list with sorted
takes 0.03 seconds.
Depends on what your target browsers are. In newer ones it's as simple as:
-moz-box-shadow: 0 0 5px #fff;
-webkit-box-shadow: 0 0 5px #fff;
box-shadow: 0 0 5px #fff;
For older browsers you have to implement workarounds, e.g., based on this example, but you will most probably need extra mark-up.
Made Simple with XML only
res/anim/layout_animation.xml
<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
android:animation="@anim/item_animation_fall_down"
android:animationOrder="normal"
android:delay="15%" />
res/anim/item_animation_fall_down.xml
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="500">
<translate
android:fromYDelta="-20%"
android:toYDelta="0"
android:interpolator="@android:anim/decelerate_interpolator"
/>
<alpha
android:fromAlpha="0"
android:toAlpha="1"
android:interpolator="@android:anim/decelerate_interpolator"
/>
<scale
android:fromXScale="105%"
android:fromYScale="105%"
android:toXScale="100%"
android:toYScale="100%"
android:pivotX="50%"
android:pivotY="50%"
android:interpolator="@android:anim/decelerate_interpolator"
/>
</set>
Use in layouts and recylcerview like:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layoutAnimation="@anim/layout_animation"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
Remember that a JavaScript code unit is 16 bits wide. Therefore the hex string form will be 4 digits per code unit.
usage:
var str = "\u6f22\u5b57"; // "\u6f22\u5b57" === "??"
alert(str.hexEncode().hexDecode());
String to hex form:
String.prototype.hexEncode = function(){
var hex, i;
var result = "";
for (i=0; i<this.length; i++) {
hex = this.charCodeAt(i).toString(16);
result += ("000"+hex).slice(-4);
}
return result
}
Back again:
String.prototype.hexDecode = function(){
var j;
var hexes = this.match(/.{1,4}/g) || [];
var back = "";
for(j = 0; j<hexes.length; j++) {
back += String.fromCharCode(parseInt(hexes[j], 16));
}
return back;
}
Try this one in your controller, in the same order:
$scope.typeOptions = [
{ name: 'Feature', value: 'feature' },
{ name: 'Bug', value: 'bug' },
{ name: 'Enhancement', value: 'enhancement' }
];
$scope.form.type = $scope.typeOptions[0];
Try to log the stack trace like below:
logger.error("Exception :: " , e);
Check How to: Define Constants in C# on MSDN:
In C# the
#define
preprocessor directive cannot be used to define constants in the way that is typically used in C and C++.
Refer to Automatically Wrap Text in Label. It describes how to create your own growing label.
Here is the full source taken from the above reference:
using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
public class GrowLabel : Label {
private bool mGrowing;
public GrowLabel() {
this.AutoSize = false;
}
private void resizeLabel() {
if (mGrowing) return;
try {
mGrowing = true;
Size sz = new Size(this.Width, Int32.MaxValue);
sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
this.Height = sz.Height;
}
finally {
mGrowing = false;
}
}
protected override void OnTextChanged(EventArgs e) {
base.OnTextChanged(e);
resizeLabel();
}
protected override void OnFontChanged(EventArgs e) {
base.OnFontChanged(e);
resizeLabel();
}
protected override void OnSizeChanged(EventArgs e) {
base.OnSizeChanged(e);
resizeLabel();
}
}
Another way to do something similar is with flexbox on a wrapper element, i.e.,
.row {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}
_x000D_
<div class="row">_x000D_
<div>Left</div>_x000D_
<div>Right</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
exec bash
at the endA bash script operates on its current environment or on that of its children, but never on its parent environment.
However, this question often gets asked because one wants to be left at a (new) bash prompt in a certain directory after execution of a bash script from another directory.
If this is the case, simply execute a child bash instance at the end of the script:
#!/usr/bin/env bash
cd /home/tree/projects/java
exec bash
At least with newer versions of bash
, the exec
on the last line is no longer required. Furthermore, the script could be made to work with whatever preferred shell by using the $SHELL
environment variable. This then gives:
#!/usr/bin/env bash
cd desired/directory
$SHELL
Just click the button to download using following code.
in html
<a class="btn" ng-click="saveJSON()" ng-href="{{ url }}">Export to JSON</a>
_x000D_
In controller
$scope.saveJSON = function () {_x000D_
$scope.toJSON = '';_x000D_
$scope.toJSON = angular.toJson($scope.data);_x000D_
var blob = new Blob([$scope.toJSON], { type:"application/json;charset=utf-8;" }); _x000D_
var downloadLink = angular.element('<a></a>');_x000D_
downloadLink.attr('href',window.URL.createObjectURL(blob));_x000D_
downloadLink.attr('download', 'fileName.json');_x000D_
downloadLink[0].click();_x000D_
};
_x000D_
Heads up! This solution is CSS-only.
I recommend you take advantage of CSS3 to do that, by hidding the by-default input radio button with CSS3 rules:
.options input{
margin:0;padding:0;
-webkit-appearance:none;
-moz-appearance:none;
appearance:none;
}
I just make an example a few days ago.
If you are accessing a plain HTML form, it has to be submitted to the server via a submit button (or via javascript post). This usually means that your form definition will look like this (I'm going off of memory, make sure you check the html elements are correct):
<form method="POST" action="page.aspx">
<input id="customerName" name="customerName" type="Text" />
<input id="customerPhone" name="customerPhone" type="Text" />
<input value="Save" type="Submit" />
</form>
You should be able to access the customerName and customerPhone data like this:
string n = String.Format("{0}", Request.Form["customerName"]);
If you have method="GET"
in the form (not recommended, it messes up your URL space), you will have to access the form data like this:
string n = String.Format("{0}", Request.QueryString["customerName"]);
This of course will only work if the form was 'Posted', 'Submitted', or done via a 'Postback'. (i.e. somebody clicked the 'Save' button, or this was done programatically via javascript.)
Also, keep in mind that accessing these elements in this manner can only be done when you are not using server controls (i.e. runat="server"
), with server controls the id and name are different.
first , you dont need to use a local assigment for your job, just check the above answer
second, its simple to use locals() and globals() to got the variables table and then change the value
check this sample code:
print [locals().__setitem__('x', 'Hillo :]'), x][-1]
if you need to change the add a global variable to your environ, try to replace locals() with globals()
python's list comp is cool but most of the triditional project dont accept this(like flask :[)
hope it could help
This is only true if you're iterating through an array; what if you were iterating through a different kind of collection that has no notion of accessing by index? In the array case, the easiest way to retain the index is to simply use a vanilla for loop.
nmon shows a nice display of disk activity per device. It is available for linux.
? Disk I/O ?????(/proc/diskstats)????????all data is Kbytes per second??????????????????????????????????????????????????????????????? ?DiskName Busy Read WriteKB|0 |25 |50 |75 100| ? ?sda 0% 0.0 127.9|> | ? ?sda1 1% 0.0 127.9|> | ? ?sda2 0% 0.0 0.0|> | ? ?sda5 0% 0.0 0.0|> | ? ?sdb 61% 385.6 9708.7|WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWR> | ? ?sdb1 61% 385.6 9708.7|WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWR> | ? ?sdc 52% 353.6 9686.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR > | ? ?sdc1 53% 353.6 9686.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR > | ? ?sdd 56% 359.6 9800.6|WWWWWWWWWWWWWWWWWWWWWWWWWWWW> | ? ?sdd1 56% 359.6 9800.6|WWWWWWWWWWWWWWWWWWWWWWWWWWWW> | ? ?sde 57% 371.6 9574.9|WWWWWWWWWWWWWWWWWWWWWWWWWWWWR> | ? ?sde1 57% 371.6 9574.9|WWWWWWWWWWWWWWWWWWWWWWWWWWWWR> | ? ?sdf 53% 371.6 9740.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR > | ? ?sdf1 53% 371.6 9740.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR > | ? ?md0 0% 1726.0 2093.6|>disk busy not available | ? ??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
I love the answers from Kiril V. Lyadvinsky and CC. but my problem was a little more specific than just case-insensitivity; I needed a lazy Unicode-supported command-line argument parser that could eliminate false-positives/negatives when dealing with alphanumeric string searches that could have special characters in the base string used to format alphanum keywords I was searching against, e.g., Wolfjäger
shouldn't match jäger
but <jäger>
should.
It's basically just Kiril/CC's answer with extra handling for alphanumeric exact-length matches.
/* Undefined behavior when a non-alpha-num substring parameter is used. */
bool find_alphanum_string_CI(const std::wstring& baseString, const std::wstring& subString)
{
/* Fail fast if the base string was smaller than what we're looking for */
if (subString.length() > baseString.length())
return false;
auto it = std::search(
baseString.begin(), baseString.end(), subString.begin(), subString.end(),
[](char ch1, char ch2)
{
return std::toupper(ch1) == std::toupper(ch2);
}
);
if(it == baseString.end())
return false;
size_t match_start_offset = it - baseString.begin();
std::wstring match_start = baseString.substr(match_start_offset, std::wstring::npos);
/* Typical special characters and whitespace to split the substring up. */
size_t match_end_pos = match_start.find_first_of(L" ,<.>;:/?\'\"[{]}=+-_)(*&^%$#@!~`");
/* Pass fast if the remainder of the base string where
the match started is the same length as the substring. */
if (match_end_pos == std::wstring::npos && match_start.length() == subString.length())
return true;
std::wstring extracted_match = match_start.substr(0, match_end_pos);
return (extracted_match.length() == subString.length());
}
query.setParameterList("name", new String[] { "Ron", "Som", "Roxi"}); fixed my issue
PHPMailer has the ability to automatically embed images from your HTML email. You have to give full path in the file system, when writing your HTML:
<img src="/var/www/host/images/photo.png" alt="my photo" />
It will automaticaly convert to:
<img src="cid:photo.png" alt="my photo" />
Is Perl easily available to you?
$ perl -n -e 'if ($. == 7) { print; exit(0); }'
Obviously substitute whatever number you want for 7.
If you are using jQuery UI, you can format any date with:
<html>
<body>
Your date formated: <span id="date1"></span><br/>
</body>
</html>
var myDate = '30.11.2011';
var parsedDate = $.datepicker.parseDate('dd.mm.yy', myDate);
$('#date1').text($.datepicker.formatDate('M d, yy', parsedDate));
There are a couple of things to consider.
If your growth is 0 for that month, it'd be 0 in change from 0. So it is meaningful in that sense. You could adjust by adding a small number, so it'd be change from 0.1 to 0.1. Then change and percentage change would be 0 and 0%.
Then to think about case where you change from 0 to 20. Such practice would result in massive reporting issues. Depending on what small number you choose to add, eg if you use 0.1 or 0.001, your percentage change would be 100 fold difference. So there is a problem with such practice.
It is possible however if you have a change from 1 to 20, then the %change would be 19/1=1900%. Here the % change doesn't make too much sense when you start off so low, it becomes very sensitive to any change and may skew your results if other data points are on different scale.
So it is important to understand your data, and in this case, how frequent you encounter 0s and extreme numbers in your data.
You can't do that in plain HTML, but you can do it with jQuery:
JavaScript Image Dropdown
Are you tired with your old fashion dropdown? Try this new one. Image combo box. You can add an icon with each option. It works with your existing "select" element or you can create by JSON object.
Albeit this question is quite old, some people still may stumble upon it when looking for solution to improve UX of modals on mobile phones.
I've made a lib to improve Bootrsrap modals' behavior on phones.
Bootstrap 3: https://github.com/keaukraine/bootstrap-fs-modal
Bootstrap 4: https://github.com/keaukraine/bootstrap4-fs-modal
in light of the ambiguity as to the number of non-user databases, you should probably add:
WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb');
and add the names of the reporting services databases
I think not, and the reason is that default values are evaluated to constants and values passed by reference must be able to change, unless you also declare it to be constant reference.
If you want system back color in white then you can use this code
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:elevation="0dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar_notification"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
app:contentInsetStartWithNavigation="0dp">
<include layout="@layout/action_bar_notification" />
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
Note:- android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
is key
The paste is in your activity where you want to show back button on action bar
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_notification);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(false);
I encountered the LNK2019 error while working on a DLL project in Visual Studio 2013.
I added a new configuration to the project. But instead of having the "Configuration Type" as "Dynamic Library", visual studio added it as "Application". This resulted in the LNK2019 error.
Fixed the LNK2019 error by going to Project -> Properties -> Configuration Properties -> General and changing "Configuration Type" to "Dynamic Library (.dll)" and "Target Extension" to ".dll".
Yes, the original question talks about a console/application project, which is a different problem than my answer. But I believe adding this answer might help someone (like me) that stumbles upon this thread.
Don't use this as suggested in other answers
.filter(f.col("dateColumn") < f.lit('2017-11-01'))
But use this instead
.filter(f.col("dateColumn") < f.unix_timestamp(f.lit('2017-11-01 00:00:00')).cast('timestamp'))
This will use the TimestampType
instead of the StringType
, which will be more performant in some cases. For example Parquet predicate pushdown will only work with the latter.
using Calendar is simple:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Madrid"));
Date currentDate = calendar.getTime();
If you have this setup
/app
/public/index.html
/media
Then this should get what you wanted
var express = require('express');
//var server = express.createServer();
// express.createServer() is deprecated.
var server = express(); // better instead
server.configure(function(){
server.use('/media', express.static(__dirname + '/media'));
server.use(express.static(__dirname + '/public'));
});
server.listen(3000);
The trick is leaving this line as last fallback
server.use(express.static(__dirname + '/public'));
As for documentation, since Express uses connect middleware, I found it easier to just look at the connect source code directly.
For example this line shows that index.html is supported https://github.com/senchalabs/connect/blob/2.3.3/lib/middleware/static.js#L140
In View
<select ng-model="boxmodel"><option ng-repeat="lst in list" value="{{lst.id}}">{{lst.name}}</option></select>
JS:
In side controller
$scope.boxModel = 600;
My 'idiomatic one-liner' for this is:
int count = StringUtils.countMatches("a.b.c.d", ".");
Why write it yourself when it's already in commons lang?
Spring Framework's oneliner for this is:
int occurance = StringUtils.countOccurrencesOf("a.b.c.d", ".");
What type of sql database are using (MSSQL, Oracle etc)? I believe what you have written is correct.
You could also write the first query like this:
SELECT s.sid, s.name
FROM Supplier s
WHERE (SELECT COUNT(DISTINCT pr.jid)
FROM Supplies su, Projects pr
WHERE su.sid = s.sid
AND pr.jid = su.jid) >= 2
It's a little more readable, and less mind-bending than trying to do it with GROUP BY. Performance may differ though.
If you want to set environment variables permanently in Git-Bash, you have two options:
Set a regular Windows environment variable. Git-bash gets all existing Windows environment variables at startupp.
Set up env variables in .bash_profile
file.
.bash_profile
is by default located in a user home folder, like C:\users\userName\git-home\.bash_profile
. You can change the path to the bash home folder by setting HOME
Windows environment variable.
.bash_profile
file uses the regular Bash syntax and commands
# Export a variable in .bash_profile
export DIR=c:\dir
# Nix path style works too
export DIR=/c/dir
# And don't forget to add quotes if a variable contains whitespaces
export ANOTHER_DIR="c:\some dir"
Read more information about Bash configurations files.
If you look at the bootstrap-button.js source, you'll see that the bootstrap plugin replaces the buttons inner html with whatever is in data-loading-text when calling $(myElem).button('loading')
.
For your case, I think you should just be able to do this:
<button type="button"
class="btn btn-primary start"
id="btnStartUploads"
data-loading-text="<i class='icon-spinner icon-spin icon-large'></i> @Localization.Uploading">
<i class="icon-upload icon-large"></i>
<span>@Localization.StartUpload</span>
</button>
I was having this till today when I start grunt watch
. Finally solved by
watch: {
options: {
maxListeners: 99,
livereload: true
},
}
The annoying message is gone.
Or you can get 'Bluetooth File Transfer' from Google Play and set the home folder to /system/
. Then you can even go to /
.
Is it possible to restart a single container
Not through kubectl
, although depending on the setup of your cluster you can "cheat" and docker kill the-sha-goes-here
, which will cause kubelet to restart the "failed" container (assuming, of course, the restart policy for the Pod says that is what it should do)
how do I restart the pod
That depends on how the Pod was created, but based on the Pod name you provided, it appears to be under the oversight of a ReplicaSet, so you can just kubectl delete pod test-1495806908-xn5jn
and kubernetes will create a new one in its place (the new Pod will have a different name, so do not expect kubectl get pods
to return test-1495806908-xn5jn
ever again)
You can use a turn-around and just deploy the application into tomcat server: just copy/paste under the webapps folder. Once tomcat is started, it will create a folder with the app name and you can access the contents directly
use [\\W+]
or "[^a-zA-Z0-9]"
as regex to match any special characters and also use String.replaceAll(regex, String) to replace the spl charecter with an empty string. remember as the first arg of String.replaceAll is a regex you have to escape it with a backslash to treat em as a literal charcter.
String c= "hjdg$h&jk8^i0ssh6";
Pattern pt = Pattern.compile("[^a-zA-Z0-9]");
Matcher match= pt.matcher(c);
while(match.find())
{
String s= match.group();
c=c.replaceAll("\\"+s, "");
}
System.out.println(c);
eval(s);
Remember though, that eval is very powerful and quite unsafe. You better be confident that the script you are executing is safe and unmutable by users.
Steps to take:
method
type for the form.submit()
method on the form.Code:
var Form = document.createElement("form");
Form.action = '/DashboardModule/DevicesInfo/RedirectToView?TerminalId='+marker.data;
Form.method = "post";
var formToSubmit = document.body.appendChild(Form);
formToSubmit.submit();
'Load'- inserts a file's contents.(Parse file every time the file is being called)
'Require'- inserts a file parsed content.(File parsed once and stored in memory)
'Include'- includes the module into the class and can use methods inside the module as class's instance method
'Extend'- includes the module into the class and can use methods inside the module as class method
Try this,
window.location.href="sample.html";
Here sample.html
is a next page. It will go to the next page.
For macOS Users Updated to MacOs Catalina,
~/.bash_profile changed to ~/.zshrc
So ,to run adb command and all other commands already exported to ~/.bash_profile easy walkaround is to export bash_profile to zshrc
To do that,
1) Navigate to the home directory in finder
2) I used Cmd + Shift + . to show the hidden files in Finder
3) Create .zshrc file if already not exist
4) Add line "source ~/.bash_profile" without quotes
5) Save
6) Quit and open terminal
start using adb devices
def Isprime(z):
'''returns True if the number is prime OTW returns false'''
if z<1:
return False
elif z==1:
return False
elif z==2:
return True
else:
for i in range(2,z):
if z%i==0:
return False
else:
return True
This is the way I did it. Of course, there are so many ways you can do it.
You can also use Uploadify, which is a great jQuery upload plugin, it let's you upload multiple files, and also style the file fields easily. http://www.uploadify.com
Important: if you are creating a new object with jQuery and binding an event, you MUST use prop and not attr, like this:
$("<div/>",{ id: "yourId", class: "yourClass", html: "<span></span>" }).on("click", function(e) { alert($(this).prop("id")); }).appendTo("#something");
when ob1 is created then the constructor is called where "t.start()" is written but still run() method is not executed rather main() method is executed further. So why is this happening?
here your threads and main thread has equal priority.Execution of equal priority thread totally depends on the Thread schedular
.You can't expect which to execute first.
join() method is used to wait until the thread on which it is called does not terminates, but here in output we see alternate outputs of the thread why??
Here your calling below statements from main thread.
ob1.t.join();
ob2.t.join();
ob3.t.join();
So main thread waits for ob1.t
,ob2.t
,ob3.t
threads to die(look into Thread#join doc).So all three threads executes successfully and main thread completes after that
For completeness sake, you might also want to bind it to DOMContentLoaded, which is now widely supported
document.addEventListener("DOMContentLoaded", function(event){
// your code here
});
More info: https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
I am using OSX -v 10.10.4. The solution above is a quick & easy.
Happening OSX does not have the connection library by default.
First you should install the connector:
brew install mysql-connector-c
Then install with pip mysql
pip install mysql-python
I'd recommend making "apple" its own class. You should avoid the starts-with/ends-with if you can because being able to select using div.apple
would be a lot faster. That's the more elegant solution. Don't be afraid to split things out into separate classes if it makes the task simpler/faster.
Comment This Line in gradle.properties
android.useAndroidX=true
string hex = "#FFFFFF";
Color _color = System.Drawing.ColorTranslator.FromHtml(hex);
Note: the hash is important!
This is a clever little trick (that I think I've seen on SO before):
var str = "" + 1
var pad = "0000"
var ans = pad.substring(0, pad.length - str.length) + str
JavaScript is more forgiving than some languages if the second argument to substring is negative so it will "overflow correctly" (or incorrectly depending on how it's viewed):
That is, with the above:
Supporting negative numbers is left as an exercise ;-)
Happy coding.
You need to do
./configure --with-ssl=openssl --with-libssl-prefix=/usr/local/ssl
Instead of this
./configure --with-ssl=openssl
Here's a very nice Gist that covers all the possible cases: https://gist.github.com/nepsilon/156387acf9e1e72d48fa35c4fabef0b4
Overview:
git rebase -i HEAD~X
# X is the number of commits to go back
# Move to the line of your commit, change pick into edit,
# then change your commit message:
git commit --amend
# Finish the rebase with:
git rebase --continue
If that is the entire line, it very well might be because you are missing a ;
at the end of the line.
Following was working for me. hope this helps you
<add name="getconn" connectionString="Data Source=servername;Initial Catalog=DBName;Persist Security Info=True;User ID=sa;Password=***" />
I have tried it hope it works for you
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
int unitFlags =NSDayCalendarUnit;
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
NSDate *myDate; //= [[NSDate alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
myDate = [dateFormatter dateFromString:self.strPrevioisDate];
NSDateComponents *comps = [gregorian components:unitFlags fromDate:myDate toDate:[NSDate date] options:0];
NSInteger day=[comps day];
The previous answers may describe the best understanding about the difference between .NET Core, .NET Standard and .NET Framework, so I just want to share my experience when choosing this over that.
In the project that you need to mix between .NET Framework, .NET Core and .NET Standard. For example, at the time we build the system with .NET Core 1.0, there is no support for Window Services hosting with .NET Core.
The next reason is we were using Active Report which doesn't support .NET Core.
So we want to build an infrastructure library that can be used for both .NET Core (ASP.NET Core) and Windows Service and Reporting (.NET Framework) -> That's why we chose .NET Standard for this kind of library. Choosing .NET standard means you need to carefully consider every class in the library should be simple and cross .NET (Core, Framework, and Standard).
Conclusion:
Microsoft just announced .NET 5: Introducing .NET 5
Microsoft introduced schema in version 2008. For those who didn’t know about schema, and those who didn’t care, objects were put into a default schema dbo
.
dbo
stands for DataBase Owner, but that’s not really important.
Think of a schema as you would a folder for files:
You can always access any object from any schema.
Because dbo
is the default, you normally don’t need to specify it within a single database:
SELECT * FROM customers;
SELECT * FROM dbo.customers;
mean the same thing.
I am inclined to disagree with the notion of always using the dbo.
prefix, since the more you clutter your code with unnecessary detail, the harder it is to read and manage.
For the most part, you can ignore the schema. However, the schema will make itself apparent in the following situations:
If you view the tables in either the object navigator or in an external application, such as Microsoft Excel or Access, you will see the dbo.
prefix. You can still ignore it.
If you reference a table in another database, you will need its full name in the form database.schema.table
:
SELECT * FROM bookshop.dbo.customers;
For historical reasons, if you write a user defined scalar function, you will need to call it with the schema prefix:
CREATE FUNCTION tax(@amount DECIMAL(6,2) RETURNS DECIMAL(6,2) AS
BEGIN
RETURN @amount * 0.1;
END;
GO
SELECT total, dbo.tax(total) FROM pricelist;
This does not apply to other objects, such as table functions, procedures and views.
You can use schema to overcome naming conflicts. For example, if every user has a personal schema, they can create additional objects without having to fight with other users over the name.
Websites in general can check authorization in many different ways, but the one you're targeting seems to make it reasonably easy for you.
All you need is to POST
to the auth/login
URL a form-encoded blob with the various fields you see there (forget the labels for
, they're decoration for human visitors). handle=whatever&password-clear=pwd
and so on, as long as you know the values for the handle (AKA email) and password you should be fine.
Presumably that POST will redirect you to some "you've successfully logged in" page with a Set-Cookie
header validating your session (be sure to save that cookie and send it back on further interaction along the session!).
Also be sure your app is subclassing MultiDexApplication
import android.support.multidex.MultiDexApplication
class App : MultiDexApplication()
or if not subclassing Application class, add to AndroidManifest.xml
<application
android:name="android.support.multidex.MultiDexApplication"
another way to create a data url from blob url may be using canvas.
var canvas = document.createElement("canvas")
var context = canvas.getContext("2d")
context.drawImage(img, 0, 0) // i assume that img.src is your blob url
var dataurl = canvas.toDataURL("your prefer type", your prefer quality)
as what i saw in mdn, canvas.toDataURL is supported well by browsers. (except ie<9, always ie<9)
You can't serialize a class that implements IDictionary. Check out this link.
Q: Why can't I serialize hashtables?
A: The XmlSerializer cannot process classes implementing the IDictionary interface. This was partly due to schedule constraints and partly due to the fact that a hashtable does not have a counterpart in the XSD type system. The only solution is to implement a custom hashtable that does not implement the IDictionary interface.
So I think you need to create your own version of the Dictionary for this. Check this other question.
It is so simple, you have 2 objects with the same name and when you say: bank_holiday[month] python thinks you wanna run your function and got ERROR.
Just rename your array to bank_holidays <--- add a 's' at the end! like this:
bank_holidays= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month
def bank_holiday(month):
if month <1 or month > 12:
print("Error: Out of range")
return
print(bank_holidays[month-1],"holiday(s) in this month ")
bank_holiday(int(input("Which month would you like to check out: ")))
Code & detects ctrl+z
document.onkeyup = function(e) {
if(e.ctrlKey && e.keyCode == 90) {
// ctrl+z pressed
}
}
The easiest way is to redirect the output of the echo
by >>
:
echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile
First, having the url in href
is best because it allows users to copy links, open in another tab, etc.
In some cases (e.g. sites with frequent HTML changes) it is not practical to bind links every time there is an update.
Normal link:
<a href="https://www.google.com/">Google<a/>
And something like this for JS:
$("a").click(function (e) {
e.preventDefault();
var href = $(this).attr("href");
window.open(href);
return false;
});
The benefits of this method are clean separation of markup and behavior and doesn't have to repeat the function calls in every link.
If you don't want to bind every time, however, you can use onclick and pass in the element and event, e.g.:
<a href="https://www.google.com/" onclick="return Handler(this, event);">Google</a>
And this for JS:
function Handler(self, e) {
e.preventDefault();
var href = $(self).attr("href");
window.open(href);
return false;
}
The benefit to this method is that you can load in new links (e.g. via AJAX) whenever you want without having to worry about binding every time.
HEAD
is (direct or indirect, i.e. symbolic) reference to the current commit. It is a commit that you have checked in the working directory (unless you made some changes, or equivalent), and it is a commit on top of which "git commit" would make a new one. Usually HEAD
is symbolic reference to some other named branch; this branch is currently checked out branch, or current branch. HEAD
can also point directly to a commit; this state is called "detached HEAD", and can be understood as being on unnamed, anonymous branch.
And @
alone is a shortcut for HEAD
, since Git 1.8.5
ORIG_HEAD
is previous state of HEAD
, set by commands that have possibly dangerous behavior, to be easy to revert them. It is less useful now that Git has reflog: HEAD@{1}
is roughly equivalent to ORIG_HEAD
(HEAD@{1}
is always last value of HEAD
, ORIG_HEAD
is last value of HEAD
before dangerous operation).
For more information read git(1) manpage / [gitrevisions(7) manpage][git-revisions], Git User's Manual, the Git Community Book and Git Glossary
Don't know about android but in POJ I use
public final class MyJSONObject extends JSONObject {
public MyJSONObject(URL url) throws IOException {
super(getServerData(url));
}
static String getServerData(URL url) throws IOException {
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader ir = new BufferedReader(new InputStreamReader(con.getInputStream()));
String text = ir.lines().collect(Collectors.joining("\n"));
return (text);
}
}
thanks for the ideas but none works here. So i did that... I am using xampp last version on 2014. go to \xampp\apache\conf\extra\httpd-xampp.conf.
we will find this bit of code:
<IfModule php5_module>
**<FilesMatch "\.php$">**
SetHandler application/x-httpd-php
</FilesMatch>
<FilesMatch "\.phps$">
SetHandler application/x-httpd-php-source
</FilesMatch>
PHPINIDir "C:/xampp/php"
</IfModule>
Focus on second line, so we must to change to:
<IfModule php5_module>
**<FilesMatch "\.(php|html)$">**
SetHandler application/x-httpd-php
</FilesMatch>
<FilesMatch "\.phps$">
SetHandler application/x-httpd-php-source
</FilesMatch>
PHPINIDir "C:/xampp/php"
</IfModule>
And that is it. Works good!
Since version 4.14 of Linux kernel, vfs_read
and vfs_write
functions are no longer exported for use in modules. Instead, functions exclusively for kernel's file access are provided:
# Read the file from the kernel space.
ssize_t kernel_read(struct file *file, void *buf, size_t count, loff_t *pos);
# Write the file from the kernel space.
ssize_t kernel_write(struct file *file, const void *buf, size_t count,
loff_t *pos);
Also, filp_open
no longer accepts user-space string, so it can be used for kernel access directly (without dance with set_fs
).
like this:
import operator
list1 = sorted(csv1, key=operator.itemgetter(1, 2))
Finally, I got a solution!
My Context is:- I want disconnect socket connection when activity destroyed, I tried to finish() activity but it didn't work me, its keep connection live somewhere.
so I use android.os.Process.killProcess(android.os.Process.myPid());
its kill my activity and i used android:excludeFromRecents="true"
for remove from recent activity .
First, we must make a distinction between layers and tiers. Layers are the way to logically break code into components and tiers are the physical nodes to place the components on. This question explains it better: What's the difference between "Layers" and "Tiers"?
A two layer architecture is usually just a presentation layer and data store layer. These can be on 1 tier (1 machine) or 2 tiers (2 machines) to achieve better performance by distributing the work load.
A three layer architecture usually puts something between the presentation and data store layers such as a business logic layer or service layer. Again, you can put this into 1,2, or 3 tiers depending on how much money you have for hardware and how much load you expect.
Putting multiple machines in a tier will help with the robustness of the system by providing redundancy.
Below is a good example of a layered architecture:
(source: microsoft.com)
A good reference for all of this can be found here on MSDN: http://msdn.microsoft.com/en-us/library/ms978678.aspx
Plugin: jupyter-vim
So you can send lines (<leader>E
), visual selection (<leader>e
) to a running jupyter-client
(the replacement of ipython
)
I prefer to separate editor and interpreter (each one in its shell). Imagine you send a bad input reading command ...
The clearest explanation I found was not in the current 2.4 apache docs, but in version 2.0.
# /abc/def/.htaccess -- per-dir config file for directory /abc/def
# Remember: /abc/def is the physical path of /xyz, i.e., the server
# has a 'Alias /xyz /abc/def' directive e.g.
RewriteEngine On
# let the server know that we were reached via /xyz and not
# via the physical path prefix /abc/def
RewriteBase /xyz
How does it work? For you apache hackers, this 2.0 doc goes on to give "detailed information about the internal processing steps."
Lesson learned: While we need to be familiar with "current," gems can be found in the annals.
Answers
Q: What is a lambda expression in C++11?
A: Under the hood, it is the object of an autogenerated class with overloading operator() const. Such object is called closure and created by compiler. This 'closure' concept is near with the bind concept from C++11. But lambdas typically generate better code. And calls through closures allow full inlining.
Q: When would I use one?
A: To define "simple and small logic" and ask compiler perform generation from previous question. You give a compiler some expressions which you want to be inside operator(). All other stuff compiler will generate to you.
Q: What class of problem do they solve that wasn't possible prior to their introduction?
A: It is some kind of syntax sugar like operators overloading instead of functions for custom add, subrtact operations...But it save more lines of unneeded code to wrap 1-3 lines of real logic to some classes, and etc.! Some engineers think that if the number of lines is smaller then there is a less chance to make errors in it (I'm also think so)
Example of usage
auto x = [=](int arg1){printf("%i", arg1); };
void(*f)(int) = x;
f(1);
x(1);
Extras about lambdas, not covered by question. Ignore this section if you're not interest
1. Captured values. What you can to capture
1.1. You can reference to a variable with static storage duration in lambdas. They all are captured.
1.2. You can use lambda for capture values "by value". In such case captured vars will be copied to the function object (closure).
[captureVar1,captureVar2](int arg1){}
1.3. You can capture be reference. & -- in this context mean reference, not pointers.
[&captureVar1,&captureVar2](int arg1){}
1.4. It exists notation to capture all non-static vars by value, or by reference
[=](int arg1){} // capture all not-static vars by value
[&](int arg1){} // capture all not-static vars by reference
1.5. It exists notation to capture all non-static vars by value, or by reference and specify smth. more. Examples: Capture all not-static vars by value, but by reference capture Param2
[=,&Param2](int arg1){}
Capture all not-static vars by reference, but by value capture Param2
[&,Param2](int arg1){}
2. Return type deduction
2.1. Lambda return type can be deduced if lambda is one expression. Or you can explicitly specify it.
[=](int arg1)->trailing_return_type{return trailing_return_type();}
If lambda has more then one expression, then return type must be specified via trailing return type. Also, similar syntax can be applied to auto functions and member-functions
3. Captured values. What you can not capture
3.1. You can capture only local vars, not member variable of the object.
4. ?onversions
4.1 !! Lambda is not a function pointer and it is not an anonymous function, but capture-less lambdas can be implicitly converted to a function pointer.
p.s.
More about lambda grammar information can be found in Working draft for Programming Language C++ #337, 2012-01-16, 5.1.2. Lambda Expressions, p.88
In C++14 the extra feature which has named as "init capture" have been added. It allow to perform arbitarily declaration of closure data members:
auto toFloat = [](int value) { return float(value);};
auto interpolate = [min = toFloat(0), max = toFloat(255)](int value)->float { return (value - min) / (max - min);};
I have a funny hack idea.
Create an npm package name suitably as a comment divider for dependencies
and devDependencies
block in file package.json, for example x----x----x
{
"name": "app-name",
"dependencies": {
"x----x----x": "this is the first line of a comment",
"babel-cli": "6.x.x",
"babel-core": "6.x.x",
"x----x----x": "this is the second line of a comment",
"knex": "^0.11.1",
"mocha": "1.20.1",
"x----x----x": "*"
}
}
NOTE: You must add the last comment divider line with a valid version, like *
in the block.
I understand that the compiler needs the expression to be known at compile time to compile a switch, but why isn't Foo.BA_ constant?
While they are constant from the perspective of any code that executes after the fields have been initialized, they are not a compile time constant in the sense required by the JLS; see §15.28 Constant Expressions for the specification of a constant expression1. This refers to §4.12.4 Final Variables which defines a "constant variable" as follows:
We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28) a constant variable. Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9) and definite assignment (§16).
In your example, the Foo.BA* variables do not have initializers, and hence do not qualify as "constant variables". The fix is simple; change the Foo.BA* variable declarations to have initializers that are compile-time constant expressions.
In other examples (where the initializers are already compile-time constant expressions), declaring the variable as final
may be what is needed.
You could change your code to use an enum
rather than int
constants, but that brings another couple of different restrictions:
default
case, even if you have case
for every known value of the enum
; see Why is default required for a switch on an enum?case
labels must all be explicit enum
values, not expressions that evaluate to enum
values.1 - The constant expression restrictions can be summarized as follows. Constant expressions a) can use primitive types and String
only, b) allow primaries that are literals (apart from null
) and constant variables only, c) allow constant expressions possibly parenthesised as subexpressions, d) allow operators except for assignment operators, ++
, --
or instanceof
, and e) allow type casts to primitive types or String
only.
Note that this doesn't include any form of method or lambda calls, new
, .class
. .length
or array subscripting. Furthermore, any use of array values, enum
values, values of primitive wrapper types, boxing and unboxing are all excluded because of a).
I used a function to get current datetime
protected function getCurrentDate()
{
$now = Carbon::now();
return $now->toDateTimeString('');
}
However I get an error.
Carbon\Exceptions\UnitException
Precision unit expected among: minute, second, millisecond and microsecond.
Any ideas how to get the time in a format like day.month.Year Hour:minute
I was getting this env: node: No such file or directory
error when running the job through Jenkins.
What I did to fix it - added export PATH="$PATH:"/usr/local/bin/
at the beginning of the script that Jenkins job executes.
Try adding $(document).ready(function(){
to the beginning of your script, and then });
. Also, does the div
have the id in it properly, i.e., as an id, not a class, etc.?
The closest equivalent to Java's toString
is to implement __str__
for your class. Put this in your class definition:
def __str__(self):
return "foo"
You may also want to implement __repr__
to aid in debugging.
See here for more information:
describe [db_name.]table_name;
for formatted output, or
show create table [db_name.]table_name;
for the SQL statement that can be used to create a table.
try
$this->load->view('home/home_view',$data);
(and note the " ' " not the " ‘ " that you used)
Seems like you can use the prefs:<area>
URL to open the settings and go to specific areas. Apple could change these and break your app so always check if you can open them first.
From this article they have listed some of them for iOS 13.1:
Settings URLs
iCloud
prefs:root=CASTLE
prefs:root=CASTLE&path=BACKUP
Wireless Radios
prefs:root=WIFI
prefs:root=Bluetooth
prefs:root=MOBILE_DATA_SETTINGS_ID
Personal Hotspot
prefs:root=INTERNET_TETHERING
prefs:root=INTERNET_TETHERING&path=Family%20Sharing
prefs:root=INTERNET_TETHERING&path=Wi-Fi%20Password
VPN
prefs:root=General&path=VPN
Notifications
prefs:root=NOTIFICATIONS_ID
prefs:root=NOTIFICATIONS_ID&path=Siri%20Suggestions
Sounds
prefs:root=Sounds
prefs:root=Sounds&path=Ringtone
Do Not Disturb
prefs:root=DO_NOT_DISTURB
prefs:root=DO_NOT_DISTURB&path=Allow%20Calls%20From
Screen Time
prefs:root=SCREEN_TIME
prefs:root=SCREEN_TIME&path=DOWNTIME
prefs:root=SCREEN_TIME&path=APP_LIMITS
prefs:root=SCREEN_TIME&path=ALWAYS_ALLOWED
General
prefs:root=General
prefs:root=General&path=About
prefs:root=General&path=SOFTWARE_UPDATE_LINK
prefs:root=General&path=CARPLAY
prefs:root=General&path=AUTO_CONTENT_DOWNLOAD
prefs:root=General&path=MULTITASKING
prefs:root=General&path=DATE_AND_TIME
prefs:root=General&path=Keyboard
prefs:root=General&path=Keyboard/KEYBOARDS
prefs:root=General&path=Keyboard/Hardware%20Keyboard
prefs:root=General&path=Keyboard/USER_DICTIONARY
prefs:root=General&path=Keyboard/ReachableKeyboard
prefs:root=General&path=INTERNATIONAL
prefs:root=General&path=DICTIONARY
prefs:root=General&path=ManagedConfigurationList
prefs:root=General&path=Reset
Control Center
prefs:root=ControlCenter
prefs:root=ControlCenter&path=CUSTOMIZE_CONTROLS
Display
prefs:root=DISPLAY
prefs:root=DISPLAY&path=AUTOLOCK
prefs:root=DISPLAY&path=TEXT_SIZE
Accessibility
prefs:root=ACCESSIBILITY
Wallpaper
prefs:root=Wallpaper
Siri
prefs:root=SIRI
Apple Pencil
prefs:root=Pencil
Face ID
prefs:root=PASSCODE
Emergency SOS
prefs:root=EMERGENCY_SOS
Battery
prefs:root=BATTERY_USAGE
prefs:root=BATTERY_USAGE&path=BATTERY_HEALTH
Privacy
prefs:root=Privacy
prefs:root=Privacy&path=LOCATION
prefs:root=Privacy&path=CONTACTS
prefs:root=Privacy&path=CALENDARS
prefs:root=Privacy&path=REMINDERS
prefs:root=Privacy&path=PHOTOS
prefs:root=Privacy&path=MICROPHONE
prefs:root=Privacy&path=SPEECH_RECOGNITION
prefs:root=Privacy&path=CAMERA
prefs:root=Privacy&path=MOTION\
App Store
prefs:root=STORE
prefs:root=STORE&path=App%20Downloads
prefs:root=STORE&path=Video%20Autoplay
Wallet
prefs:root=PASSBOOK
Passwords & Accounts
prefs:root=ACCOUNTS_AND_PASSWORDS
prefs:root=ACCOUNTS_AND_PASSWORDS&path=FETCH_NEW_DATA
prefs:root=ACCOUNTS_AND_PASSWORDS&path=ADD_ACCOUNT
prefs:root=MAIL
prefs:root=MAIL&path=Preview
prefs:root=MAIL&path=Swipe%20Options
prefs:root=MAIL&path=NOTIFICATIONS
prefs:root=MAIL&path=Blocked
prefs:root=MAIL&path=Muted%20Thread%20Action
prefs:root=MAIL&path=Blocked%20Sender%20Options
prefs:root=MAIL&path=Mark%20Addresses
prefs:root=MAIL&path=Increase%20Quote%20Level
prefs:root=MAIL&path=Include%20Attachments%20with%20Replies
prefs:root=MAIL&path=Signature
prefs:root=MAIL&path=Default%20Account
Contacts
prefs:root=CONTACTS
Calendar
prefs:root=CALENDAR
prefs:root=CALENDAR&path=Alternate%20Calendars
prefs:root=CALENDAR&path=Sync
prefs:root=CALENDAR&path=Default%20Alert%20Times
prefs:root=CALENDAR&path=Default%20Calendar
Notes
prefs:root=NOTES
prefs:root=NOTES&path=Default%20Account
prefs:root=NOTES&path=Password
prefs:root=NOTES&path=Sort%20Notes%20By
prefs:root=NOTES&path=New%20Notes%20Start%20With
prefs:root=NOTES&path=Sort%20Checked%20Items
prefs:root=NOTES&path=Lines%20%26%20Grids
prefs:root=NOTES&path=Access%20Notes%20from%20Lock%20Screen
Reminders
prefs:root=REMINDERS
prefs:root=REMINDERS&path=DEFAULT_LIST
Voice Memos
prefs:root=VOICE_MEMOS
Phone
prefs:root=Phone
Messages
prefs:root=MESSAGES
FaceTime
prefs:root=FACETIME
Maps
prefs:root=MAPS
prefs:root=MAPS&path=Driving%20%26%20Navigation
prefs:root=MAPS&path=Transit
Compass
prefs:root=COMPASS
Measure
prefs:root=MEASURE
Safari
prefs:root=SAFARI
prefs:root=SAFARI&path=Content%20Blockers
prefs:root=SAFARI&path=DOWNLOADS
prefs:root=SAFARI&path=Close%20Tabs
prefs:root=SAFARI&path=CLEAR_HISTORY_AND_DATA
prefs:root=SAFARI&path=Page%20Zoom
prefs:root=SAFARI&path=Request%20Desktop%20Website
prefs:root=SAFARI&path=Reader
prefs:root=SAFARI&path=Camera
prefs:root=SAFARI&path=Microphone
prefs:root=SAFARI&path=Location
prefs:root=SAFARI&path=ADVANCED
News
prefs:root=NEWS
Health
prefs:root=HEALTH
Shortcuts
prefs:root=SHORTCUTS
Music
prefs:root=MUSIC
prefs:root=MUSIC&path=com.apple.Music:CellularData
prefs:root=MUSIC&path=com.apple.Music:OptimizeStorage
prefs:root=MUSIC&path=com.apple.Music:EQ
prefs:root=MUSIC&path=com.apple.Music:VolumeLimit
TV
prefs:root=TVAPP
Photos
prefs:root=Photos
Camera
prefs:root=CAMERA
prefs:root=CAMERA&path=Record%20Video
prefs:root=CAMERA&path=Record%20Slo-mo
Books
prefs:root=IBOOKS
Game Center
prefs:root=GAMECENTER
Basically it boils down to using a fixed-width page and setting the width for those labels and controls. This is the most common way in which table-less layouts are implemented.
There are many ways to go about setting widths. Blueprint.css is a very popular css framework which can help you set up columns/widths.
Somewhere you will need to set a fixed height, instead of using auto everywhere. You will find that if you set a fixed height on your content and/or container, then using auto for things inside it will work.
Also, your boxes will still expand height-wise with more content in, even though you have set a height for it - so don't worry about that :)
#container {
height:500px;
min-height:500px;
}
XWindows is probably the closest to what could be called 'native' :)
Do you want the input fields to be centered? A trick to center elements: specify the width of the element and set the margin to auto, eg:
margin : 0px auto;
width:300px
A link to your updated fiddle:
Did you remember to die() after sending the header? The 404 header doesn't automatically stop processing, so it may appear not to have done anything if there is further processing happening.
It's not good to REDIRECT to your 404 page, but you can INCLUDE the content from it with no problem. That way, you have a page that properly sends a 404 status from the correct URL, but it also has your "what are you looking for?" page for the human reader.
its a simple
{!! $text !!}
laravel compile as a dom element and {{$text}}
print as a string
... just a little bit late :)
you might give a try at http://code.google.com/p/tarlog-plugins/. It gives you options like open shell
and open explorer
from Project Explorer context menu.
There's also http://sourceforge.net/projects/explorerplugin/ but it seems kind of stuck at 2009.
In the client side handle the click event of the button, use the ClientID property to get he id of the button:
$(document).ready(function() {
$("#<%=myButton.ClientID %>,#<%=muSecondButton.ClientID%>").click(
function() {
$.get("/myPage.aspx",{id:$(this).attr('id')},function(data) {
// do something with the data
return false;
}
});
});
In your page on the server:
protected void Page_Load(object sender,EventArgs e) {
// check if it is an ajax request
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest") {
if (Request.QueryString["id"]==myButton.ClientID) {
// call the click event handler of the myButton here
Response.End();
}
if (Request.QueryString["id"]==mySecondButton.ClientID) {
// call the click event handler of the mySecondButton here
Response.End();
}
}
}
Sub NumToText(ByRef sRng As String, Optional ByVal WS As Worksheet)
'---Converting visible range form Numbers to Text
Dim Temp As Double
Dim vRng As Range
Dim Cel As Object
If WS Is Nothing Then Set WS = ActiveSheet
Set vRng = WS.Range(sRng).SpecialCells(xlCellTypeVisible)
For Each Cel In vRng
If Not IsEmpty(Cel.Value) And IsNumeric(Cel.Value) Then
Temp = Cel.Value
Cel.ClearContents
Cel.NumberFormat = "@"
Cel.Value = CStr(Temp)
End If
Next Cel
End Sub
Sub Macro1()
Call NumToText("A2:A100", ActiveSheet)
End Sub
You can use this cross-platform function:
#ifdef WIN32
#include <windows.h>
#elif _POSIX_C_SOURCE >= 199309L
#include <time.h> // for nanosleep
#else
#include <unistd.h> // for usleep
#endif
void sleep_ms(int milliseconds){ // cross-platform sleep function
#ifdef WIN32
Sleep(milliseconds);
#elif _POSIX_C_SOURCE >= 199309L
struct timespec ts;
ts.tv_sec = milliseconds / 1000;
ts.tv_nsec = (milliseconds % 1000) * 1000000;
nanosleep(&ts, NULL);
#else
if (milliseconds >= 1000)
sleep(milliseconds / 1000);
usleep((milliseconds % 1000) * 1000);
#endif
}
If you need one item to be left aligned (like a header) but then multiple items right aligned (like 3 images), then you would do something like this:
h1 {
flex-basis: 100%; // forces this element to take up any remaining space
}
img {
margin: 0 5px; // small margin between images
height: 50px; // image width will be in relation to height, in case images are large - optional if images are already the proper size
}
Here's what that will look like (only relavent CSS was included in snippet above)
Don't run this command on shell, enter this script at a command prompt with your database name, collection name, and file name, all replacing the placeholders..
mongoexport --db (Database name) --collection (Collection Name) --out (File name).json
It works for me.
I'd just like to add to Jon's example. To get a reference to your own assembly, you can use:
Assembly myAssembly = Assembly.GetExecutingAssembly();
System.Reflection
namespace.
If you want to examine an assembly that you have no reference to, you can use either of these:
Assembly assembly = Assembly.ReflectionOnlyLoad(fullAssemblyName);
Assembly assembly = Assembly.ReflectionOnlyLoadFrom(fileName);
If you intend to instantiate your type once you've found it:
Assembly assembly = Assembly.Load(fullAssemblyName);
Assembly assembly = Assembly.LoadFrom(fileName);
See the Assembly class documentation for more information.
Once you have the reference to the Assembly
object, you can use assembly.GetTypes()
like Jon already demonstrated.
Fell into the same trouble with inlining functions into so libraries. It seems that inlined functions are not compiled into the library. as a result the linker puts out a "undefined reference" error, if a executable wants to use the inlined function of the library. (happened to me compiling Qt source with gcc 4.5.
Some browsers repeat the thead
element on each page, as they are supposed to. Others need some help: Add this to your CSS:
thead {display: table-header-group;}
tfoot {display: table-header-group;}
Opera 7.5 and IE 5 won't repeat headers no matter what you try.
(source)
Change your second style to this:
input, select, textarea{
color: #ff0000;
}
At the moment, you are telling the form to change the text to black
once the focus is off. The above remedies that.
Also, it is a good idea to place the normal state styles ahead of the :focus
and :hover
styles in your stylesheet. That helps prevent this problem. So
input, select, textarea{
color: #ff0000;
}
textarea:focus, input:focus {
color: #ff0000;
}
Try:
select v.*, row_number() over (partition by id order by elem) rn from
(select
id,
unnest(string_to_array(elements, ',')) AS elem
from myTable) v
I've just had the same issue - for me Privacy Badger on Firefox was the issue - not adblocker. Posting for posterity
The main reason you use the default queue over the main queue is to run tasks in the background.
For instance, if I am downloading a file from the internet and I want to update the user on the progress of the download, I will run the download in the priority default queue and update the UI in the main queue asynchronously.
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Thread
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
});
});
Using self.class.blah
is NOT the same as using ClassName.blah
when it comes to inheritance.
class Truck
def self.default_make
"mac"
end
def make1
self.class.default_make
end
def make2
Truck.default_make
end
end
class BigTruck < Truck
def self.default_make
"bigmac"
end
end
ruby-1.9.3-p0 :021 > b=BigTruck.new
=> #<BigTruck:0x0000000307f348>
ruby-1.9.3-p0 :022 > b.make1
=> "bigmac"
ruby-1.9.3-p0 :023 > b.make2
=> "mac"
On Android 2.2+ use this:
boolean isEmailValid(CharSequence email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
for example:
EditText emailid = (EditText) loginView.findViewById(R.id.login_email);
String getEmailId = emailid.getText().toString();
// Check if email id is valid or not
if (!isEmailValid(getEmailId)){
new CustomToast().Show_Toast(getActivity(), loginView,
"Your Email Id is Invalid.");
}
public void swap(int[] arr,int a,int b)
{
int temp=arr[a];
arr[a]=arr[b];
arr[b]=temp;
}
public int[] reverseArray(int[] arr){
int size=arr.length-1;
for(int i=0;i<size;i++){
swap(arr,i,size--);
}
return arr;
}
It is always better to use create a namespace and declare a variable in it instead of adding it to the global object. We can also create a function to get and set the value
See the below code snippet:
//creating a namespace in which all the variables will be defined.
var myObjects={};
//function that will set the name property in the myObjects namespace
function setName(val){
myObjects.Name=val;
}
//function that will return the name property in the myObjects namespace
function getName(){
return myObjects.Name;
}
//now we can use it like:
setName("kevin");
var x = getName();
var y = x;
console.log(y) //"kevin"
var z = "y";
console.log(z); //"y"
console.log(eval(z)); //"kevin"
In this similar way, we can declare and use multiple variables. Although this will increase the line of code but the code will be more robust and less error-prone.
Public Function arrayIsEmpty(arrayToCheck() As Variant) As Boolean
On Error GoTo Err:
Dim forCheck
forCheck = arrayToCheck(0)
arrayIsEmpty = False
Exit Function
Err:
arrayIsEmpty = True
End Function
Adding the @ElementCollection
to the List field solved this issue:
@Column
@ElementCollection(targetClass=Integer.class)
private List<Integer> countries;
I had the same problem, and I have solved it with the module line-by-line
https://www.npmjs.com/package/line-by-line
At least for me works like a charm, both in synchronous and asynchronous mode.
Also, the problem with lines terminating not terminating \n can be solved with the option:
{ encoding: 'utf8', skipEmptyLines: false }
Synchronous processing of lines:
var LineByLineReader = require('line-by-line'),
lr = new LineByLineReader('big_file.txt');
lr.on('error', function (err) {
// 'err' contains error object
});
lr.on('line', function (line) {
// 'line' contains the current line without the trailing newline character.
});
lr.on('end', function () {
// All lines are read, file is closed now.
});
It has been said that it's not necessary to export in bash when spawning subshells, while others said the exact opposite. It is important to note the difference between subshells (those that are created by ()
, ``
, $()
or loops) and subprocesses (processes that are invoked by name, for example a literal bash
appearing in your script).
What is common in these two constructs is that neither can pass variables back to the parent shell.
$ noexport=noexport; export export=export; (echo subshell: $noexport $export; subshell=subshell); bash -c 'echo subprocess: $noexport $export; subprocess=subprocess'; echo parent: $subshell $subprocess
subshell: noexport export
subprocess: export
parent:
There is one more source of confusion: some think that 'forked' subprocesses are the ones that don't see non-exported variables. Usually fork()s are immediately followed by exec()s, and that's why it would seem that the fork() is the thing to look for, while in fact it's the exec(). You can run commands without fork()ing first with the exec
command, and processes started by this method will also have no access to unexported variables:
$ noexport=noexport; export export=export; exec bash -c 'echo execd process: $noexport $export; execd=execd'; echo parent: $execd
execd process: export
Note that we don't see the parent:
line this time, because we have replaced the parent shell with the exec
command, so there's nothing left to execute that command.
dispatchTouchEvent handles before onInterceptTouchEvent.
Using this simple example:
main = new LinearLayout(this){
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
System.out.println("Event - onInterceptTouchEvent");
return super.onInterceptTouchEvent(ev);
//return false; //event get propagated
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
System.out.println("Event - dispatchTouchEvent");
return super.dispatchTouchEvent(ev);
//return false; //event DONT get propagated
}
};
main.setBackgroundColor(Color.GRAY);
main.setLayoutParams(new LinearLayout.LayoutParams(320,480));
viewA = new EditText(this);
viewA.setBackgroundColor(Color.YELLOW);
viewA.setTextColor(Color.BLACK);
viewA.setTextSize(16);
viewA.setLayoutParams(new LinearLayout.LayoutParams(320,80));
main.addView(viewA);
setContentView(main);
You can see that the log willl be like:
I/System.out(25900): Event - dispatchTouchEvent
I/System.out(25900): Event - onInterceptTouchEvent
So in case you are working with these 2 handlers use dispatchTouchEvent to handle on first instance the event, which will go to onInterceptTouchEvent.
Another difference is that if dispatchTouchEvent return 'false' the event dont get propagated to the child, in this case the EditText, whereas if you return false in onInterceptTouchEvent the event still get dispatch to the EditText
For me the code:
<form (submit)="addTodo()">_x000D_
<input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
throws error, but I added name attribute to input:
<form (submit)="addTodo()">_x000D_
<input type="text" [(ngModel)]="text" name="text">_x000D_
</form>
_x000D_
and it started to work.
You can use the UNPIVOT function to convert the columns into rows:
select id, entityId,
indicatorname,
indicatorvalue
from yourtable
unpivot
(
indicatorvalue
for indicatorname in (Indicator1, Indicator2, Indicator3)
) unpiv;
Note, the datatypes of the columns you are unpivoting must be the same so you might have to convert the datatypes prior to applying the unpivot.
You could also use CROSS APPLY
with UNION ALL to convert the columns:
select id, entityid,
indicatorname,
indicatorvalue
from yourtable
cross apply
(
select 'Indicator1', Indicator1 union all
select 'Indicator2', Indicator2 union all
select 'Indicator3', Indicator3 union all
select 'Indicator4', Indicator4
) c (indicatorname, indicatorvalue);
Depending on your version of SQL Server you could even use CROSS APPLY with the VALUES clause:
select id, entityid,
indicatorname,
indicatorvalue
from yourtable
cross apply
(
values
('Indicator1', Indicator1),
('Indicator2', Indicator2),
('Indicator3', Indicator3),
('Indicator4', Indicator4)
) c (indicatorname, indicatorvalue);
Finally, if you have 150 columns to unpivot and you don't want to hard-code the entire query, then you could generate the sql statement using dynamic SQL:
DECLARE @colsUnpivot AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @colsUnpivot
= stuff((select ','+quotename(C.column_name)
from information_schema.columns as C
where C.table_name = 'yourtable' and
C.column_name like 'Indicator%'
for xml path('')), 1, 1, '')
set @query
= 'select id, entityId,
indicatorname,
indicatorvalue
from yourtable
unpivot
(
indicatorvalue
for indicatorname in ('+ @colsunpivot +')
) u'
exec sp_executesql @query;
In your fpm.conf file you haven't set 2 variable which are only for error logging.
The variables are error_log
(file path of your error log file) and log_level
(error logging level).
; Error log file
; Note: the default prefix is /usr/local/php/var
; Default Value: log/php-fpm.log
error_log = log/php-fpm.log
; Log level
; Possible Values: alert, error, warning, notice, debug
; Default Value: notice
log_level = notice