For some programs setting the super secret __COMPAT_LAYER
environment variable to RunAsInvoker
will work.Check this :
set "__COMPAT_LAYER=RunAsInvoker"
start regedit.exe
Though like this there will be no UAC prompting the user will continue without admin permissions.
As an alternative that doesn't require elevation or netsh you could also use TcpListener for instance.
The following is a modified excerpt of this sample: https://github.com/googlesamples/oauth-apps-for-windows/tree/master/OAuthDesktopApp
// Generates state and PKCE values.
string state = randomDataBase64url(32);
string code_verifier = randomDataBase64url(32);
string code_challenge = base64urlencodeNoPadding(sha256(code_verifier));
const string code_challenge_method = "S256";
// Creates a redirect URI using an available port on the loopback address.
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
string redirectURI = string.Format("http://{0}:{1}/", IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port);
output("redirect URI: " + redirectURI);
// Creates the OAuth 2.0 authorization request.
string authorizationRequest = string.Format("{0}?response_type=code&scope=openid%20profile&redirect_uri={1}&client_id={2}&state={3}&code_challenge={4}&code_challenge_method={5}",
authorizationEndpoint,
System.Uri.EscapeDataString(redirectURI),
clientID,
state,
code_challenge,
code_challenge_method);
// Opens request in the browser.
System.Diagnostics.Process.Start(authorizationRequest);
// Waits for the OAuth authorization response.
var client = await listener.AcceptTcpClientAsync();
// Read response.
var response = ReadString(client);
// Brings this app back to the foreground.
this.Activate();
// Sends an HTTP response to the browser.
WriteStringAsync(client, "<html><head><meta http-equiv='refresh' content='10;url=https://google.com'></head><body>Please close this window and return to the app.</body></html>").ContinueWith(t =>
{
client.Dispose();
listener.Stop();
Console.WriteLine("HTTP server stopped.");
});
// TODO: Check the response here to get the authorization code and verify the code challenge
The read and write methods being:
private string ReadString(TcpClient client)
{
var readBuffer = new byte[client.ReceiveBufferSize];
string fullServerReply = null;
using (var inStream = new MemoryStream())
{
var stream = client.GetStream();
while (stream.DataAvailable)
{
var numberOfBytesRead = stream.Read(readBuffer, 0, readBuffer.Length);
if (numberOfBytesRead <= 0)
break;
inStream.Write(readBuffer, 0, numberOfBytesRead);
}
fullServerReply = Encoding.UTF8.GetString(inStream.ToArray());
}
return fullServerReply;
}
private Task WriteStringAsync(TcpClient client, string str)
{
return Task.Run(() =>
{
using (var writer = new StreamWriter(client.GetStream(), new UTF8Encoding(false)))
{
writer.Write("HTTP/1.0 200 OK");
writer.Write(Environment.NewLine);
writer.Write("Content-Type: text/html; charset=UTF-8");
writer.Write(Environment.NewLine);
writer.Write("Content-Length: " + str.Length);
writer.Write(Environment.NewLine);
writer.Write(Environment.NewLine);
writer.Write(str);
}
});
}
This script does the trick! Just paste it into the top of your bat file. If you want to review the output of your script, add a "pause" command at the bottom of your batch file.
UPDATE: This script is now slightly edited to support command line arguments and a 64 bit OS.
Thank you Eneerge @ https://sites.google.com/site/eneerge/scripts/batchgotadmin
@echo off
:: BatchGotAdmin
:-------------------------------------
REM --> Check for permissions
IF "%PROCESSOR_ARCHITECTURE%" EQU "amd64" (
>nul 2>&1 "%SYSTEMROOT%\SysWOW64\cacls.exe" "%SYSTEMROOT%\SysWOW64\config\system"
) ELSE (
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
)
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
echo Requesting administrative privileges...
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params= %*
echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params:"=""%", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
:gotAdmin
pushd "%CD%"
CD /D "%~dp0"
:--------------------------------------
<YOUR BATCH SCRIPT HERE>
As ivan.sim writes in his answer
- Ensure that your user account has administrator privilege.
- Disable UAC(User Account Control) as it restricts certain administrative function needed to run a web server.
- Install in C://xampp.
Problem with the correct answer is in the explanation of point 2., and magicandre1981 writes more about it
Moving the slider down doesn't completely disable UAC since Windows 8. This is changed compared to Windows 7, because the new Store apps require an active UAC. With UAC off, they no longer run.
How can we then disable UAC and install XAMPP?
Easy. Go to Registry Editor and navigate to
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
Right click EnableLUA and modify the Value data to 0.
Then restart your computer and you're ready to install XAMPP.
This issue has to do with granting the necessary authorization to the user account the application runs on. To read a similar situation and a detailed response for the correct solution, as documented by Microsoft, feel free to visit this post: http://rambletech.wordpress.com/2011/10/17/requested-registry-access-is-not-allowed/
You can do this by installing the task while running as administrator via the TaskSchedler library. I'm making the assumption here that .NET/C# is a suitable platform/language given your related questions.
This library gives you granular access to the Task Scheduler API, so you can adjust settings that you cannot otherwise set via the command line by calling schtasks
, such as the priority of the startup. Being a parental control application, you'll want it to have a startup priority of 0 (maximum), which schtasks
will create by default a priority of 7.
Below is a code example of installing a properly configured startup task to run the desired application as administrator indefinitely at logon. This code will install a task for the very process that it's running from.
/*
Copyright © 2017 Jesse Nicholson
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/// <summary>
/// Used for synchronization when creating run at startup task.
/// </summary>
private ReaderWriterLockSlim m_runAtStartupLock = new ReaderWriterLockSlim();
public void EnsureStarupTaskExists()
{
try
{
m_runAtStartupLock.EnterWriteLock();
using(var ts = new Microsoft.Win32.TaskScheduler.TaskService())
{
// Start off by deleting existing tasks always. Ensure we have a clean/current install of the task.
ts.RootFolder.DeleteTask(Process.GetCurrentProcess().ProcessName, false);
// Create a new task definition and assign properties
using(var td = ts.NewTask())
{
td.Principal.RunLevel = Microsoft.Win32.TaskScheduler.TaskRunLevel.Highest;
// This is not normally necessary. RealTime is the highest priority that
// there is.
td.Settings.Priority = ProcessPriorityClass.RealTime;
td.Settings.DisallowStartIfOnBatteries = false;
td.Settings.StopIfGoingOnBatteries = false;
td.Settings.WakeToRun = false;
td.Settings.AllowDemandStart = false;
td.Settings.IdleSettings.RestartOnIdle = false;
td.Settings.IdleSettings.StopOnIdleEnd = false;
td.Settings.RestartCount = 0;
td.Settings.AllowHardTerminate = false;
td.Settings.Hidden = true;
td.Settings.Volatile = false;
td.Settings.Enabled = true;
td.Settings.Compatibility = Microsoft.Win32.TaskScheduler.TaskCompatibility.V2;
td.Settings.ExecutionTimeLimit = TimeSpan.Zero;
td.RegistrationInfo.Description = "Runs the content filter at startup.";
// Create a trigger that will fire the task at this time every other day
var logonTrigger = new Microsoft.Win32.TaskScheduler.LogonTrigger();
logonTrigger.Enabled = true;
logonTrigger.Repetition.StopAtDurationEnd = false;
logonTrigger.ExecutionTimeLimit = TimeSpan.Zero;
td.Triggers.Add(logonTrigger);
// Create an action that will launch Notepad whenever the trigger fires
td.Actions.Add(new Microsoft.Win32.TaskScheduler.ExecAction(Process.GetCurrentProcess().MainModule.FileName, "/StartMinimized", null));
// Register the task in the root folder
ts.RootFolder.RegisterTaskDefinition(Process.GetCurrentProcess().ProcessName, td);
}
}
}
finally
{
m_runAtStartupLock.ExitWriteLock();
}
}
You can make a shortcut somewhere and as the target use: python yourscript.py then under properties and advanced select run as administrator.
When the user executes the shortcut it will ask them to elevate the application.
NOTE in recent VS versions (2015+) it seems this extension no longer exists/has this feature.
You can also download VSCommands for VS2012 by Squared Infinity which has a feature to change it to run as admin (as well as some other cool bits and pieces)
Update
One can install the commands from the Visual Studio menu bar using Tools
->Extensions and Updates
selecting Online
and searching for vscommands
where then one selects VSCommands for Visual Studio 20XX
depending on whether using 2012 or 2013 (or greater going forward) and download and install.
With the useEffect
hook it's possible to detect route changes without adding a listener.
import React, { useEffect } from 'react';
import { Switch, Route, withRouter } from 'react-router-dom';
import Main from './Main';
import Blog from './Blog';
const App = ({history}) => {
useEffect( () => {
// When route changes, history.location.pathname changes as well
// And the code will execute after this line
}, [history.location.pathname]);
return (<Switch>
<Route exact path = '/' component = {Main}/>
<Route exact path = '/blog' component = {Blog}/>
</Switch>);
}
export default withRouter(App);
h1 {
margin-top:0;
padding-top: 0;}
It' s just a misunderstanding with h1 tag. You have to set h1 tag margin-top and padding-top to 0 (zero).
If you don't mention the random_state in the code, then whenever you execute your code a new random value is generated and the train and test datasets would have different values each time.
However, if you use a particular value for random_state(random_state = 1 or any other value) everytime the result will be same,i.e, same values in train and test datasets. Refer below code:
import pandas as pd
from sklearn.model_selection import train_test_split
test_series = pd.Series(range(100))
size30split = train_test_split(test_series,random_state = 1,test_size = .3)
size25split = train_test_split(test_series,random_state = 1,test_size = .25)
common = [element for element in size25split[0] if element in size30split[0]]
print(len(common))
Doesn't matter how many times you run the code, the output will be 70.
70
Try to remove the random_state and run the code.
import pandas as pd
from sklearn.model_selection import train_test_split
test_series = pd.Series(range(100))
size30split = train_test_split(test_series,test_size = .3)
size25split = train_test_split(test_series,test_size = .25)
common = [element for element in size25split[0] if element in size30split[0]]
print(len(common))
Now here output will be different each time you execute the code.
One of the easiest way is to use a common table expression (since you're already on SQL 2005):
with cte as (
select
im.itemid
,im.sku as iSku
,gm.SKU as GSKU
,mm.ManufacturerId as ManuId
,mm.ManufacturerName
,im.mf_item_number
,mm.ManufacturerID
, <your other field>
from
item_master im, group_master gm, Manufacturer_Master mm
where
im.mf_item_number like 'STA%'
and im.sku=gm.sku
and gm.ManufacturerID = mm.ManufacturerID
and gm.manufacturerID=34)
update cte set mf_item_number = <your other field>
The query execution engine will figure out on its own how to update the record.
If you just want a maximum length, use StringUtils.left
! No if
or ternary ?:
needed.
int maxLength = 5;
StringUtils.left(string, maxLength);
Output:
null -> null
"" -> ""
"a" -> "a"
"abcd1234" -> "abcd1"
I've used Spring.NET in the past and had great success with it. I never noticed any substantial overhead with it, though the project we used it on was fairly heavy on its own. It only took a little time reading through the documentation to get it set up.
str_replace('"', "", $string);
str_replace("'", "", $string);
I assume you mean quotation marks?
Otherwise, go for some regex, this will work for html quotes for example:
preg_replace("/<!--.*?-->/", "", $string);
C-style quotes:
preg_replace("/\/\/.*?\n/", "\n", $string);
CSS-style quotes:
preg_replace("/\/*.*?\*\//", "", $string);
bash-style quotes:
preg-replace("/#.*?\n/", "\n", $string);
Etc etc...
There are cases where you don't want to use v-model
. If you have two inputs, and each depend on each other, you might have circular referential issues. Common use cases is if you're building an accounting calculator.
In these cases, it's not a good idea to use either watchers or computed properties.
Instead, take your v-model
and split it as above answer indicates
<input
:value="something"
@input="something = $event.target.value"
>
In practice, if you are decoupling your logic this way, you'll probably be calling a method.
This is what it would look like in a real world scenario:
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
<input :value="extendedCost" @input="_onInputExtendedCost" />_x000D_
<p> {{ extendedCost }}_x000D_
</div>_x000D_
_x000D_
<script>_x000D_
var app = new Vue({_x000D_
el: "#app",_x000D_
data: function(){_x000D_
return {_x000D_
extendedCost: 0,_x000D_
}_x000D_
},_x000D_
methods: {_x000D_
_onInputExtendedCost: function($event) {_x000D_
this.extendedCost = parseInt($event.target.value);_x000D_
// Go update other inputs here_x000D_
}_x000D_
}_x000D_
});_x000D_
</script>
_x000D_
Try this...
<div class="row">
<div class="col-xs-3">
Menu
</div>
<div class="col-xs-9">
<div class="row">
<div class="col-sm-4 col-sm-push-8">
Right content
</div>
<div class="col-sm-8 col-sm-pull-4">
Content
</div>
</div>
</div>
</div>
git branch --set-upstream master origin/master
This will add the following info to your config
file:
[branch "master"]
remote = origin
merge = refs/heads/master
If you have branch.autosetuprebase = always
then it will also add:
rebase = true
If i understand your question right then,
Yes you can set style of individual element if its id or name is available,
e.g.
if id available then u can get control over the element like,
<input type="submit" value="Go" name="goButton">
var v_obj = document.getElementsById('goButton');
v_obj.setAttribute('style','color:red;background:none');
else if name is available then u can get control over the element like,
<input type="submit" value="Go" name="goButton">
var v_obj = document.getElementsByName('goButton');
v_obj.setAttribute('style','color:red;background:none');
I actual ran into the same requirement. I simply used CSS override like this
.navbar .btn-toolbar { margin-top: 0; margin-bottom: 0 }
You need python-dev installed.
For Ubuntu :
sudo apt-get install python-dev # for python2.x installs
sudo apt-get install python3-dev # for python3.x installs
For more distros, refer -
https://stackoverflow.com/a/21530768/6841045
This simple combination of COALESCE and NULLIF should do the trick:
SELECT
Coalesce(NULLIF(listing.OfferText, ''), company.OfferText) As Offer_Text
...
Note: Add another empty string as the last COALESCE argument if you want the statement to return an empty string instead of NULL if both values are NULL.
I installed Android SDK manager and Android SDK yestoday, and I get this error too when I tried to run the Android emulator immediately. But, right now this error disappear, I think restarting your system when the SDK has installed may solve this problem.
If you are doing a presentation, and you don't care about anything lining up, Verdana is a good choice.
If you are going to distribute your presentation, use a font that you know is on everyone's machine, since using something else is going to cause the machine to fall back to one of the common fonts (like Arial or Times) anyway.
If you do care about things lining up, and are not distributing the presentation, consider Consolas:
It is highly legible, reminiscent of Verdana, and is monospaced. The color choices are, of course, a matter of taste.
If you are in the home directory first move to apache tomcat use below command
cd apache-tomcat/
then move to logs
cd logs/
then open the catelina.out use the below command
tail -f catalina.out
You can do it with CSS:
<iframe style="position: absolute; height: 100%; border: none"></iframe>
Be aware that this will by default place it in the upper-left corner of the page, but I guess that is what you want to achieve. You can position with the left
,right
, top
and bottom
CSS properties.
You can use .filter()
method of the Array
object:
var filtered = workItems.filter(function(element) {
// Create an array using `.split()` method
var cats = element.category.split(' ');
// Filter the returned array based on specified filters
// If the length of the returned filtered array is equal to
// length of the filters array the element should be returned
return cats.filter(function(cat) {
return filtersArray.indexOf(cat) > -1;
}).length === filtersArray.length;
});
Some old browsers like IE8 doesn't support .filter()
method of the Array
object, if you are using jQuery you can use .filter()
method of jQuery object.
jQuery version:
var filtered = $(workItems).filter(function(i, element) {
var cats = element.category.split(' ');
return $(cats).filter(function(_, cat) {
return $.inArray(cat, filtersArray) > -1;
}).length === filtersArray.length;
});
I have not tried, but if you know Perl you can use the Parse-Stata-DtaReader module to convert the file for you.
The module has a command-line tool dta2csv, which can "convert Stata 8 and Stata 10 .dta files to csv"
Bill's answer is correct, but it is shocking to see that among all the other answers no one points out the most significant aspect.
It has been said over and over again, that in an identifying relationship the child can not exist without the parent. (e.g. user287724). This is true, but completely misses the point. It would be enough for the foreign key to be non-null to achieve this. It does not need to be part of the primary key.
So here is the real reason:
The purpose of an identifying relationship is that the foreign key can NEVER CHANGE, because it is part of the primary key... therefore identifying!!!
easy!
if option == str(1):
numberA = int(raw_input("enter first number. "))
numberB= int(raw_input("enter second number. "))
print " "
print addition(numberA, numberB)
etc etc etc
var myObj = [];
myObj['Base'] = [];
myObj['Base']['Base.panel.panel_base'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
Align:'', AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
myObj['Base']['Base.panel.panel_top'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
Align:'',AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
myObj['SC1'] = [];
myObj['SC1']['Base.panel.panel_base'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
Align:'', AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
myObj['SC1']['Base.panel.panel_top'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
Align:'',AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
console.log(myObj);
if ('Base' in myObj) {
console.log('Base found');
if ('Base.panel.panel_base' in myObj['Base']) {
console.log('Base.panel.panel_base found');
console.log('old value: ' + myObj['Base']['Base.panel.panel_base'].Context);
myObj['Base']['Base.panel.panel_base'] = 'new Value';
console.log('new value: ' + myObj['Base']['Base.panel.panel_base']);
}
}
Output:
The array operation works. There is no problem.
Iteration:
Object.keys(myObj['Base']).forEach(function(key, index) {
var value = objcons['Base'][key];
}, myObj);
To use command support you should follow this steps:
Define Path in Environment Variables:
append variable value with the path to TortoiseProc.exe file, for example:
C:\Program Files\TortoiseSVN\bin
Since you have registered TortoiseProc, you can use it in according to TortoiseSVN documentation.
Examples:
TortoiseProc.exe /command:commit /path:"c:\svn_wc\file1.txt*c:\svn_wc\file2.txt" /logmsg:"test log message" /closeonend:0
TortoiseProc.exe /command:update /path:"c:\svn_wc\" /closeonend:0
TortoiseProc.exe /command:log /path:"c:\svn_wc\file1.txt" /startrev:50 /endrev:60 /closeonend:0
P.S. To use friendly name like 'svn' instead of 'TortoiseProc', place 'svn.bat' file in the directory of 'TortoiseProc.exe'. There is an example of svn.bat:
TortoiseProc.exe %1 %2 %3
You can use
try {
user.OtherFriend = row["US_OTHERFRIEND"].ToString();
}
catch (Exception ex)
{
// do something if you want
}
There is an attribute called android:weightSum.
You can set android:weightSum="2" in the parent linear_layout and android:weight="1" in the inner linear_layout.
Remember to set the inner linear_layout to fill_parent so weight attribute can work as expected.
Btw, I don't think its necesary to add a second view, altough I haven't tried. :)
<LinearLayout
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:weightSum="2">
<LinearLayout
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_weight="1">
</LinearLayout>
</LinearLayout>
please Press fn +ins key together
Disabled is a Boolean Attribute of the select element as stated by WHATWG, that means the RIGHT WAY TO DISABLE with jQuery would be
jQuery("#selectId").attr('disabled',true);
This would make this HTML
<select id="selectId" name="gender" disabled="disabled">
<option value="-1">--Select a Gender--</option>
<option value="0">Male</option>
<option value="1">Female</option>
</select>
This works for both XHTML and HTML (W3School reference)
Yet it also can be done using it as property
jQuery("#selectId").prop('disabled', 'disabled');
getting
<select id="selectId" name="gender" disabled>
Which only works for HTML and not XTML
NOTE: A disabled element will not be submitted with the form as answered in this question: The disabled form element is not submitted
NOTE2: A disabled element may be greyed out.
NOTE3:
A form control that is disabled must prevent any click events that are queued on the user interaction task source from being dispatched on the element.
<script>
var update_pizza = function () {
if ($("#pizza").is(":checked")) {
$('#pizza_kind').attr('disabled', false);
} else {
$('#pizza_kind').attr('disabled', true);
}
};
$(update_pizza);
$("#pizza").change(update_pizza);
</script>
I am using this function for describe table.
Use it after fill datatable
static public string DataTableToJSON(DataTable dataTable,bool readableformat=true)
{
string JSONString="[";
string JSONRow;
string colVal;
foreach(DataRow dataRow in dataTable.Rows)
{
if(JSONString!="[") { JSONString += ","; }
JSONRow = "";
if (readableformat) { JSONRow += "\r\n"; }
JSONRow += "{";
foreach (DataColumn col in dataTable.Columns)
{
colVal = dataRow[col].ToString();
colVal = colVal.Replace("\"", "\\\"");
colVal = colVal.Replace("'", "\\\'");
if(JSONRow!="{"&&JSONRow!="\r\n{") {
JSONRow += ",";
}
JSONRow += "\"" + col.ColumnName + "\":\"" + colVal + "\"";
}
JSONRow += "}";
JSONString += JSONRow;
}
JSONString += "\r\n]";
return JSONString;
}
MySQL Query: "DESCRIBE TableName;"; DataTableToJSON(dataTable) Example Output:
[
{"Field":"id","Type":"int(5)","Null":"NO","Key":"PRI","Default":"","Extra":"auto_increment"},
{"Field":"ad","Type":"int(11) unsigned","Null":"NO","Key":"MUL","Default":"","Extra":""},
{"Field":"soyad","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"ulke","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"alan","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"numara","Type":"varchar(20)","Null":"NO","Key":"","Default":"","Extra":""}
]
Tested With PHP:
$X='[
{"Field":"id","Type":"int(5)","Null":"NO","Key":"PRI","Default":"","Extra":"auto_increment"},
{"Field":"ad","Type":"int(11) unsigned","Null":"NO","Key":"MUL","Default":"","Extra":""},
{"Field":"soyad","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"ulke","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"alan","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"numara","Type":"varchar(20)","Null":"NO","Key":"","Default":"","Extra":""}
]';
$Y=json_decode($X,true);
echo $Y[0]["Field"];
var_dump($Y);
It is better if you don't kill a thread. A way could be to introduce a "try" block into the thread's cycle and to throw an exception when you want to stop the thread (for example a break/return/... that stops your for/while/...). I've used this on my app and it works...
Add .hide-text class to your span that has the text
.hide-text{
display:none;
}
or make the text transparent
.hide-text{
color:rgba(0,0,0,0);
}
use according to your use case.
this has been modified in codeigniter 2.2.1...usually not best practice to modify core files, I would always check for updates and 2.2.1 came out in Jan 2015
It's a link that links to nowhere essentially (it just adds "#" onto the URL). It's used for a number of different reasons. For instance, if you're using some sort of JavaScript/jQuery and don't want the actual HTML to link anywhere.
It's also used for page anchors, which is used to redirect to a different part of the page.
Yet another approach - just set a flag on an element signaling which type of event should be handled:
function setRangeValueChangeHandler(rangeElement, handler) {
rangeElement.oninput = (event) => {
handler(event);
// Save flag that we are using onInput in current browser
event.target.onInputHasBeenCalled = true;
};
rangeElement.onchange = (event) => {
// Call only if we are not using onInput in current browser
if (!event.target.onInputHasBeenCalled) {
handler(event);
}
};
}
In addition to CMS´ answer you may want to consider putting the style in an external stylesheet and assign the style to the id, like this:
#divCheckbox {
display: none;
}
Its because the .mdf
and .ldf
Files from the original Db
were locate at maybe c:\programFile\....
and this info is saved in the Backup!
If you create the same DB on a different SQL Server where the installation is on c:\program Files (x86)\ ....
you can not restore as usually. You need to relocate the path for .mdf
and .ldf
Files.
Therefore:
Create a empty DB on the new Server
Right click on the empty Db > Tasks > Restore > Database > click Device select your .bak
Files > Select Db to restore into
Done!
Hope it helps!
Dir has also shorter syntax to get an array of all files from directory:
Dir['dir/to/files/*'].each do |fname|
# do something with fname
end
Have you tried ALTER SYSTEM KILL SESSION? Get the SID and SERIAL# from V$SESSION for each session in the given schema, then do
ALTER SCHEMA KILL SESSION sid,serial#;
Not only for VS but nearly for all editors.
(function /* RegionName */ () { ... })();
Warning: has disadvantages such as scope.
Whenever this happens to me, I press Ctrl+Shift+R which refreshes intellisense
, close the query window (save if necessary), then start a new session which usually works quite well.
I wrote with parameters that are predefined
They are not "predefined" logically, somewhere inside your code. But as arguments of SP they have no default values and are required. To avoid passing those params explicitly you have to define default values in SP definition:
Alter Procedure [Test]
@StartDate AS varchar(6) = NULL,
@EndDate AS varchar(6) = NULL
AS
...
NULLs or empty strings or something more sensible - up to you. It does not matter since you are overwriting values of those arguments in the first lines of SP.
Now you can call it without passing any arguments e.g.
exec dbo.TEST
Another easy option to show Dialog is to use stacked_services package
_dialogService.showDialog(
title: "Title",
description: "Dialog message Tex",
);
});
Try this:
$('#click_advance').click(function(){
$('#display_advance').toggle('1000');
icon = $(this).find("i");
icon.hasClass("icon-circle-arrow-down"){
icon.addClass("icon-circle-arrow-up").removeClass("icon-circle-arrow-down");
}else{
icon.addClass("icon-circle-arrow-down").removeClass("icon-circle-arrow-up");
}
})
or even better, as Kevin said:
$('#click_advance').click(function(){
$('#display_advance').toggle('1000');
icon = $(this).find("i");
icon.toggleClass("icon-circle-arrow-up icon-circle-arrow-down")
})
This problem happens because you are calling fun.cpp
instead of fun.hpp
. So c++ compiler finds func.cpp definition twice and throws this error.
Change line 3 of your main.cpp
file, from #include "fun.cpp"
to #include "fun.hpp"
.
The problem is that they're all the same exact list in memory. When you use the [x]*n
syntax, what you get is a list of n
many x
objects, but they're all references to the same object. They're not distinct instances, rather, just n
references to the same instance.
To make a list of 3 different lists, do this:
x = [[] for i in range(3)]
This gives you 3 separate instances of []
, which is what you want
[[]]*n
is similar to
l = []
x = []
for i in range(n):
x.append(l)
While [[] for i in range(3)]
is similar to:
x = []
for i in range(n):
x.append([]) # appending a new list!
In [20]: x = [[]] * 4
In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object
In [22]: x=[[] for i in range(4)]
In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time
Provided that you are extending JFrame:
public void run() {
MyFrame myFrame = new MyFrame();
myFrame.setVisible(true);
myFrame.setExtendedState(myFrame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
}
You have to free()
the allocated memory in exact reverse order of how it was allocated using malloc()
.
Note that You should free the memory only after you are done with your usage of the allocated pointers.
memory allocation for 1D arrays:
buffer = malloc(num_items*sizeof(double));
memory deallocation for 1D arrays:
free(buffer);
memory allocation for 2D arrays:
double **cross_norm=(double**)malloc(150 * sizeof(double *));
for(i=0; i<150;i++)
{
cross_norm[i]=(double*)malloc(num_items*sizeof(double));
}
memory deallocation for 2D arrays:
for(i=0; i<150;i++)
{
free(cross_norm[i]);
}
free(cross_norm);
preffered using the object tag
<object data='http://website.com/nameoffolder/documentname.pdf#toolbar=1'
type='application/pdf'
width='100%'
height='700px'>
note that you can change the width and height to any value you please visit http://www.w3schools.com/tags/tag_object.asp
functional
function encodeData(data) {
return Object.keys(data).map(function(key) {
return [key, data[key]].map(encodeURIComponent).join("=");
}).join("&");
}
You can do this with a single statement - assuming you are calling it from a JDBC-like connector with in/out parameters functionality:
insert into batch(batchid, batchname)
values (batch_seq.nextval, 'new batch')
returning batchid into :l_batchid;
or, as a pl-sql script:
variable l_batchid number;
insert into batch(batchid, batchname)
values (batch_seq.nextval, 'new batch')
returning batchid into :l_batchid;
select :l_batchid from dual;
I've had this same error, without your whole code it is difficult to pinpoint exactly how to fix it but it is caused by not having a __set function.
The way that I have gotten around it in the past is I have done things like this:
$user = createUser();
$role = $user->role;
$role->rolename = 'Test';
now if you do this:
echo $user->role->rolename;
you should see 'Test'
Looks like you use %p: Print Pointers
You probably want to have LI rather than the UL have the background-color:
.selected li {
background-color: red;
}
Then you want to have a dynamic class for the UL:
<ul ng-repeat="vote in votes" ng-click="setSelected()" class="{{selected}}">
Now you need to update the $scope.selected when clicking the row:
$scope.setSelected = function() {
console.log("show", arguments, this);
this.selected = 'selected';
}
and then un-select the previously highlighted row:
$scope.setSelected = function() {
// console.log("show", arguments, this);
if ($scope.lastSelected) {
$scope.lastSelected.selected = '';
}
this.selected = 'selected';
$scope.lastSelected = this;
}
Working solution:
import UIKit
class RefreshControl: UIRefreshControl {
private weak var actionTarget: AnyObject?
private var actionSelector: Selector?
override init() { super.init() }
convenience init(actionTarget: AnyObject?, actionSelector: Selector) {
self.init()
self.actionTarget = actionTarget
self.actionSelector = actionSelector
addTarget()
}
private func addTarget() {
guard let actionTarget = actionTarget, let actionSelector = actionSelector else { return }
addTarget(actionTarget, action: actionSelector, for: .valueChanged)
}
required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
func endRefreshing(deadline: DispatchTime? = nil) {
guard let deadline = deadline else { endRefreshing(); return }
DispatchQueue.global(qos: .default).asyncAfter(deadline: deadline) { [weak self] in
DispatchQueue.main.async { self?.endRefreshing() }
}
}
func refreshActivityIndicatorView() {
guard let selector = actionSelector else { return }
let _isRefreshing = isRefreshing
removeTarget(actionTarget, action: selector, for: .valueChanged)
endRefreshing()
if _isRefreshing { beginRefreshing() }
addTarget()
}
func generateRefreshEvent() {
beginRefreshing()
sendActions(for: .valueChanged)
}
}
public extension UIScrollView {
private var _refreshControl: RefreshControl? { return refreshControl as? RefreshControl }
func addRefreshControll(actionTarget: AnyObject?, action: Selector, replaceIfExist: Bool = false) {
if !replaceIfExist && refreshControl != nil { return }
refreshControl = RefreshControl(actionTarget: actionTarget, actionSelector: action)
}
func scrollToTopAndShowRunningRefreshControl(changeContentOffsetWithAnimation: Bool = false) {
_refreshControl?.refreshActivityIndicatorView()
guard let refreshControl = refreshControl,
contentOffset.y != -refreshControl.frame.height else { return }
setContentOffset(CGPoint(x: 0, y: -refreshControl.frame.height), animated: changeContentOffsetWithAnimation)
}
private var canStartRefreshing: Bool {
guard let refreshControl = refreshControl, !refreshControl.isRefreshing else { return false }
return true
}
func startRefreshing() {
guard canStartRefreshing else { return }
_refreshControl?.generateRefreshEvent()
}
func pullAndRefresh() {
guard canStartRefreshing else { return }
scrollToTopAndShowRunningRefreshControl(changeContentOffsetWithAnimation: true)
_refreshControl?.generateRefreshEvent()
}
func endRefreshing(deadline: DispatchTime? = nil) { _refreshControl?.endRefreshing(deadline: deadline) }
}
// Add refresh control to UICollectionView / UITableView / UIScrollView
private func setupTableView() {
let tableView = UITableView()
// ...
tableView.addRefreshControll(actionTarget: self, action: #selector(refreshData))
}
@objc func refreshData(_ refreshControl: UIRefreshControl) {
tableView?.endRefreshing(deadline: .now() + .seconds(3))
}
// Stop refreshing in UICollectionView / UITableView / UIScrollView
tableView.endRefreshing()
// Simulate pull to refresh in UICollectionView / UITableView / UIScrollView
tableView.pullAndRefresh()
Do not forget to add the solution code here
import UIKit
class ViewController: UIViewController {
private weak var tableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
}
private func setupTableView() {
let tableView = UITableView()
view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
tableView.dataSource = self
tableView.delegate = self
tableView.addRefreshControll(actionTarget: self, action: #selector(refreshData))
self.tableView = tableView
}
}
extension ViewController {
@objc func refreshData(_ refreshControl: UIRefreshControl) {
print("refreshing")
tableView?.endRefreshing(deadline: .now() + .seconds(3))
}
}
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int { return 1 }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = "\(indexPath)"
return cell
}
}
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.pullAndRefresh()
}
}
wget is capable of doing what you are asking. Just try the following:
wget -p -k http://www.example.com/
The -p
will get you all the required elements to view the site correctly (css, images, etc).
The -k
will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.
From the Wget docs:
‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.
Each link will be changed in one of the two ways:
The links to files that have been downloaded by Wget will be changed to refer
to the file they point to as a relative link.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
downloaded, then the link in doc.html will be modified to point to
‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
combinations of directories.
The links to files that have not been downloaded by Wget will be changed to
include host name and absolute path of the location they point to.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
../bar/img.gif), then the link in doc.html will be modified to point to
http://hostname/bar/img.gif.
Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.
Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads.
I needed to trim the values in a primary key column that had first and last names, so I did not want to trim all white space as that would remove the space between the first and last name, which I needed to keep. What worked for me was...
UPDATE `TABLE` SET `FIELD`= TRIM(FIELD);
or
UPDATE 'TABLE' SET 'FIELD' = RTRIM(FIELD);
or
UPDATE 'TABLE' SET 'FIELD' = LTRIM(FIELD);
Note that the first instance of FIELD is in single quotes but the second is not in quotes at all. I had to do it this way or it gave me a syntax error saying it was a duplicate primary key when I had both in quotes.
You can use this way because id can not be sequential in all cases.
SELECT *
FROM `ht_news`
LIMIT 0 , 30
To check your MySQL version on your mac, navigate to the directory where you installed it (default is usr/local/mysql/bin) and issue this command:
./mysql --version
Alternatively, to avoid needing to navigate to that specific dir to run the command, add its location to your path ($PATH). There's more than one way to add a dir to your $PATH (with explanations on stackoverflow and other places on how to do so), such as adding it to your ./bash_profile.
After adding the mysql bin dir to your $PATH, verify it's there by executing:
echo $PATH
Thereafter you can check your mysql version from anywhere by running (note no "./"):
mysql --version
You can use the below query to identify the values. But please keep in mind that this will not give you the results from encrypted stored procedure.
SELECT DISTINCT OBJECT_NAME(comments.id) OBJECT_NAME
,objects.type_desc
FROM syscomments comments
,sys.objects objects
WHERE comments.id = objects.object_id
AND TEXT LIKE '%CreatedDate%'
ORDER BY 1
Runtime is a general term that refers to any library, framework, or platform that your code runs on.
The C and C++ runtimes are collections of functions.
The .NET runtime contains an intermediate language interpreter, a garbage collector, and more.
I had following Problem: Even if I set
xdebug.remote_enable=0
Xdebug-Error-Message-Decoration was shown.
My solution:
xdebug.default_enable=0
Only if I use this Flag, Xdebug was disabled.
I had been facing the same issue,
For Chrome and Firefox but everything was working how it should in internet explorer. I found that making the CSS file UTF-8 made it work for chrome.
Anwer is here How to dynamically add a style for text-align using jQuery
You can iterate over the row data
$('#button').click(function () {
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0]
});
console.log(ids)
alert(table.rows('.selected').data().length + ' row(s) selected');
});
Demo: Fiddle
Here's the query example to check the existence of multiple fields:
{
"query": {
"bool": {
"filter": [
{
"exists": {
"field": "field_1"
}
},
{
"exists": {
"field": "field_2"
}
},
{
"exists": {
"field": "field_n"
}
}
]
}
}
}
Symfony is smart and knows how to make the find()
by itself :
public function deleteGuestAction(Guest $guest)
{
if (!$guest) {
throw $this->createNotFoundException('No guest found');
}
$em = $this->getDoctrine()->getEntityManager();
$em->remove($guest);
$em->flush();
return $this->redirect($this->generateUrl('GuestBundle:Page:viewGuests.html.twig'));
}
To send the id in your controller, use {{ path('your_route', {'id': guest.id}) }}
This never gonna work, you can't stringify your FormData object.
You should do this:
this.uploadFileToUrl = function(file, title, text, uploadUrl){
var fd = new FormData();
fd.append('title', title);
fd.append('text', text);
fd.append('file', file);
$http.post(uploadUrl, obj, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
blockUI.stop();
})
.error(function(error){
toaster.pop('error', 'Errore', error);
});
}
I have written a quick example to demonstrate how to create a layout programmatically.
public class CodeLayout extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Creating a new RelativeLayout
RelativeLayout relativeLayout = new RelativeLayout(this);
// Defining the RelativeLayout layout parameters.
// In this case I want to fill its parent
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
// Creating a new TextView
TextView tv = new TextView(this);
tv.setText("Test");
// Defining the layout parameters of the TextView
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
// Setting the parameters on the TextView
tv.setLayoutParams(lp);
// Adding the TextView to the RelativeLayout as a child
relativeLayout.addView(tv);
// Setting the RelativeLayout as our content view
setContentView(relativeLayout, rlp);
}
}
In theory everything should be clear as it is commented. If you don't understand something just tell me.
You need to change your code to find the row relative to the button which was clicked. Try this:
$(".use-address").click(function() {
var id = $(this).closest("tr").find(".nr").text();
$("#resultas").append(id);
});
To prevent this, make sure every BEGIN TRANSACTION has COMMIT
The following will say successful but will leave uncommitted transactions:
BEGIN TRANSACTION
BEGIN TRANSACTION
<SQL_CODE?
COMMIT
Closing query windows with uncommitted transactions will prompt you to commit your transactions. This will generally resolve the Error 1222 message.
DEPLOYABLE SOLUTION (Alpine Linux)
To be able to fix this issue in our application environments, we have prepared Linux terminal commands as follows:
cd ~
Will generate cert file in home directory.
apk add openssl
This command installs openssl in alpine Linux. You can find proper commands for other Linux distributions.
openssl s_client -connect <host-dns-ssl-belongs> < /dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > public.crt
Generated the needed cert file.
sudo $JAVA_HOME/bin/keytool -import -alias server_name -keystore $JAVA_HOME/lib/security/cacerts -file public.crt -storepass changeit -noprompt
Applied the generated file to the JRE with the program 'keytool'.
Note: Please replace your DNS with <host-dns-ssl-belongs>
Note2: Please gently note that -noprompt
will not prompt the verification message (yes/no) and -storepass changeit
parameter will disable password prompt and provide the needed password (default is 'changeit'). These two properties will let you use those scripts in your application environments like building a Docker image.
Note3 If you are deploying your app via Docker, you can generate the secret file once and put it in your application project files. You won't need to generate it again and again.
int days = DateTime.DaysInMonth(int year,int month);
or
int days=System.Globalization.CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(int year,int month);
you have to pass year and month as int
then days in month will be return on currespoting year and month
This can be done by using the unbind function.
$('#myimage').unbind('click');
You can add multiple event handlers to the same object and event in jquery. This means adding a new one doesn't replace the old ones.
There are several strategies for changing event handlers, such as event namespaces. There are some pages about this in the online docs.
Look at this question (that's how I learned of unbind). There is some useful description of these strategies in the answers.
data.frame[row_number, column_number] = new_value
For example, if x
is your data.frame:
x[1, 4] = 5
In the other hand, there is some packages in AngularJS which are helpful (in AJAX WEB):
$('#dropdown_id').find('option').length
As discussed in the comments, this can be achieved by converting the entry into Date
format and extracting the year, for instance like this:
format(as.Date(df1$Date, format="%d/%m/%Y"),"%Y")
In my case, the reason was very low free space in disk (only 35 Mb). I did the following -
Delete redis dump file (if existing data not needed)
sudo rm /var/lib/redis/*
Delete all the keys of all the existing databases
sudo redis-cli flushall
That's why it's not working because you code something that is not right, that's why it always exit and the script executer will read it as not operable batch file that prevent it to exit and stop so it must be
tasklist /fi "IMAGENAME eq Notepad.exe" 2>NUL | find /I /N "Notepad.exe">NUL
if "%ERRORLEVEL%"=="0" (
msg * Program is running
goto Exit
)
else if "%ERRORLEVEL%"=="1" (
msg * Program is not running
goto Exit
)
rather than
@echo off
tasklist /fi "imagename eq notepad.exe" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"
exit
There's another use I have for git mv
not mentioned above.
Since discovering git add -p
(git add's patch mode; see http://git-scm.com/docs/git-add), I like to use it to review changes as I add them to the index. Thus my workflow becomes (1) work on code, (2) review and add to index, (3) commit.
How does git mv
fit in? If moving a file directly then using git rm
and git add
, all changes get added to the index, and using git diff to view changes is less easy (before committing). Using git mv
, however, adds the new path to the index but not changes made to the file, thus allowing git diff
and git add -p
to work as usual.
Greenlock handles certificate issuance and renewal (via Let's Encrypt) and http => https redirection, out-of-the box.
express-app.js
:
var express = require('express');
var app = express();
app.use('/', function (req, res) {
res.send({ msg: "Hello, Encrypted World!" })
});
// DO NOT DO app.listen()
// Instead export your app:
module.exports = app;
server.js
:
require('greenlock-express').create({
// Let's Encrypt v2 is ACME draft 11
version: 'draft-11'
, server: 'https://acme-v02.api.letsencrypt.org/directory'
// You MUST change these to valid email and domains
, email: '[email protected]'
, approveDomains: [ 'example.com', 'www.example.com' ]
, agreeTos: true
, configDir: "/path/to/project/acme/"
, app: require('./express-app.j')
, communityMember: true // Get notified of important updates
, telemetry: true // Contribute telemetry data to the project
}).listen(80, 443);
Watch the QuickStart demonstration: https://youtu.be/e8vaR4CEZ5s
Just answering this ahead-of-time because it's a common follow-up question:
You can't have SSL certificates on localhost. However, you can use something like Telebit which will allow you to run local apps as real ones.
You can also use private domains with Greenlock via DNS-01 challenges, which is mentioned in the README along with various plugins which support it.
Read the note above about localhost - you can't use non-standard ports with Let's Encrypt either.
However, you can expose your internal non-standard ports as external standard ports via port-forward, sni-route, or use something like Telebit that does SNI-routing and port-forwarding / relaying for you.
You can also use DNS-01 challenges in which case you won't need to expose ports at all and you can also secure domains on private networks this way.
Routes monitor the $location
service and respond to changes in URL (typically through the hash). To "activate" a route, you simply change the URL. The easiest way to do that is with anchor tags.
<a href="#/home">Go Home</a>
<a href="#/about">Go to About</a>
Nothing more complicated is needed. If, however, you must do this from code, the proper way is by using the $location
service:
$scope.go = function ( path ) {
$location.path( path );
};
Which, for example, a button could trigger:
<button ng-click="go('/home')"></button>
I found out that you need to add the pointer eg:
div{
cursor: url('cursorurl.png'), pointer;
}
Difference between Comparator and Comparable interfaces
Comparable
is used to compare itself by using with another object.
Comparator
is used to compare two datatypes are objects.
wxHexEditor is the only GUI disk editor for linux. to google "wxhexeditor site:archive.getdeb.net" and download the .deb file to install
See ?read.table
. Basically, when you use read.table
, you specify a number indicating the column:
##Row names in the first column
read.table(filname.txt, row.names=1)
Just a small correction to the first answer in this thread.
Even for Stack, you need to create new object with generics if you are using Stack from java util packages.
Right usage:
Stack<Integer> s = new Stack<Integer>();
Stack<String> s1 = new Stack<String>();
s.push(7);
s.push(50);
s1.push("string");
s1.push("stack");
if used otherwise, as mentioned in above post, which is:
/*
Stack myStack = new Stack();
// add any type of elements (String, int, etc..)
myStack.push("Hello");
myStack.push(1);
*/
Although this code works fine, has unsafe or unchecked operations which results in error.
Here is how to clear all trash & caches (without other private data in browsers) by a command line. This is a command line batch script that takes care of all trash (as of April 2014):
erase "%TEMP%\*.*" /f /s /q
for /D %%i in ("%TEMP%\*") do RD /S /Q "%%i"
erase "%TMP%\*.*" /f /s /q
for /D %%i in ("%TMP%\*") do RD /S /Q "%%i"
erase "%ALLUSERSPROFILE%\TEMP\*.*" /f /s /q
for /D %%i in ("%ALLUSERSPROFILE%\TEMP\*") do RD /S /Q "%%i"
erase "%SystemRoot%\TEMP\*.*" /f /s /q
for /D %%i in ("%SystemRoot%\TEMP\*") do RD /S /Q "%%i"
@rem Clear IE cache - (Deletes Temporary Internet Files Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
erase "%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*") do RD /S /Q "%%i"
@rem Clear Google Chrome cache
erase "%LOCALAPPDATA%\Google\Chrome\User Data\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Google\Chrome\User Data\*") do RD /S /Q "%%i"
@rem Clear Firefox cache
erase "%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*") do RD /S /Q "%%i"
pause
I am pretty sure it will run for some time when you first run it :) Enjoy!
to preserve the console output, that is, write to a file and also have it displayed on the console, you could use a class like:
public class TeePrintStream extends PrintStream {
private final PrintStream second;
public TeePrintStream(OutputStream main, PrintStream second) {
super(main);
this.second = second;
}
/**
* Closes the main stream.
* The second stream is just flushed but <b>not</b> closed.
* @see java.io.PrintStream#close()
*/
@Override
public void close() {
// just for documentation
super.close();
}
@Override
public void flush() {
super.flush();
second.flush();
}
@Override
public void write(byte[] buf, int off, int len) {
super.write(buf, off, len);
second.write(buf, off, len);
}
@Override
public void write(int b) {
super.write(b);
second.write(b);
}
@Override
public void write(byte[] b) throws IOException {
super.write(b);
second.write(b);
}
}
and used as in:
FileOutputStream file = new FileOutputStream("test.txt");
TeePrintStream tee = new TeePrintStream(file, System.out);
System.setOut(tee);
(just an idea, not complete)
Just import Android.app,then you can use:
<br/>Application.getProcessName()<br/>
Get the current Application Process Name without context, view, or activity.
Try below code
I will recommend to use error handler while using vlookup because error might occur when the lookup_value is not found.
Private Sub ComboBox1_Change()
On Error Resume Next
Ret = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
On Error GoTo 0
If Ret <> "" Then MsgBox Ret
End Sub
OR
On Error Resume Next
Result = Application.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
If Result = "Error 2042" Then
'nothing found
ElseIf cell <> Result Then
MsgBox cell.Value
End If
On Error GoTo 0
I don't think there is a way to ignore adding DEFINER
s to the dump. But there are ways to remove them after the dump file is created.
Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost
with an empty string ""
Edit the dump (or pipe the output) using perl
:
perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
You can kill a (SIGTERM) a windows process that was started from Java by calling the destroy method on the Process object. You can also kill any child Processes (since Java 9).
The following code starts a batch file, waits for ten seconds then kills all sub-processes and finally kills the batch process itself.
ProcessBuilder pb = new ProcessBuilder("cmd /c my_script.bat"));
Process p = pb.start();
p.waitFor(10, TimeUnit.SECONDS);
p.descendants().forEach(ph -> {
ph.destroy();
});
p.destroy();
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String cunvertCurrentDate="06/09/2015";
Date date = new Date();
date = df.parse(cunvertCurrentDate);
Just came across this myself.
Finally found my issue was with a .png file that I added that had a capital letter in it an caused exactly the same problem. Eclipse never flagged the file until I closed it and opened Eclipse back up.
You can use pd.to_datetime()
to convert to a datetime object. It takes a format parameter, but in your case I don't think you need it.
>>> import pandas as pd
>>> df = pd.DataFrame( {'Symbol':['A','A','A'] ,
'Date':['02/20/2015','01/15/2016','08/21/2015']})
>>> df
Date Symbol
0 02/20/2015 A
1 01/15/2016 A
2 08/21/2015 A
>>> df['Date'] =pd.to_datetime(df.Date)
>>> df.sort('Date') # This now sorts in date order
Date Symbol
0 2015-02-20 A
2 2015-08-21 A
1 2016-01-15 A
For future search, you can change the sort statement:
>>> df.sort_values(by='Date') # This now sorts in date order
Date Symbol
0 2015-02-20 A
2 2015-08-21 A
1 2016-01-15 A
#include?
should work, it works for general objects, not only strings. Your problem in example code is this test:
unless @suggested_horses.exists?(horse.id)
@suggested_horses<< horse
end
(even assuming using #include?
). You try to search for specific object, not for id. So it should be like this:
unless @suggested_horses.include?(horse)
@suggested_horses << horse
end
ActiveRecord has redefined comparision operator for objects to take a look only for its state (new/created) and id
> vec <- c(letters[1:3]) # vec <- c("a","b","c") ; or just empty vector: vec <- c()
> values<- c(1,2,3)
> for (i in 1:length(values)){
print(paste("length of vec", length(vec)));
vec[length(vec)+1] <- values[i] #Appends value at the end of vector
}
[1] "length of vec 3"
[1] "length of vec 4"
[1] "length of vec 5"
> vec
[1] "a" "b" "c" "1" "2" "3"
As your example is linking to an external domain, if you are using HTTPS then you should verify that the external domain is setup for SSL as well. Otherwise, your users may see SSL errors and/or 404 errors (e.g. older versions of Plesk store HTTP and HTTPS in separate folders). For CDNs, it shouldn't be an issue but for any other website it could be.
On a side note, tested while updated an old website and also works in the url= part of a META REFRESH.
I had this problem when I started using Entity Framework, it happened when I did not change the old SQL server connection to EntityFrameWork connection.
Solution: in the file where connection is made through web.config file "add name="Entities" connectionString=XYZ", make sure you are referring to the correct connection, in my case I had to do this
public static string MyEntityFrameworkConnection
{
get
{
return ConfigurationManager.ConnectionStrings["Entities"].ConnectionString;
}
}
call MyEntityFrameworkConnection whenever connection need to be established.
private string strConnection= Library.DataAccessLayer.DBfile.AdoSomething.MyEntityFrameworkConnection;
note: the connection in web.config file will be generated automatically when adding Entity model to the solution.
First just to answer a comment in the accepts answer.
"What does bind do? What if I have an interface and an implementation?"
It simply reads bind( implementation ).to( contract )
. You can alternative chain .in( scope )
. Default scope of PerLookup
. So if you want a singleton, you can
bind( implementation ).to( contract ).in( Singleton.class );
There's also a RequestScoped
available
Also, instead of bind(Class).to(Class)
, you can also bind(Instance).to(Class)
, which will be automatically be a singleton.
Adding to the accepted answer
For those trying to figure out how to register your AbstractBinder
implementation in your web.xml (i.e. you're not using a ResourceConfig
), it seems the binder won't be discovered through package scanning, i.e.
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>
your.packages.to.scan
</param-value>
</init-param>
Or this either
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>
com.foo.YourBinderImpl
</param-value>
</init-param>
To get it to work, I had to implement a Feature
:
import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.ext.Provider;
@Provider
public class Hk2Feature implements Feature {
@Override
public boolean configure(FeatureContext context) {
context.register(new AppBinder());
return true;
}
}
The @Provider
annotation should allow the Feature
to be picked up by the package scanning. Or without package scanning, you can explicitly register the Feature
in the web.xml
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>
com.foo.Hk2Feature
</param-value>
</init-param>
...
<load-on-startup>1</load-on-startup>
</servlet>
See Also:
and for general information from the Jersey documentation
Aside from the basic binding in the accepted answer, you also have factories, where you can have more complex creation logic, and also have access to request context information. For example
public class MyServiceFactory implements Factory<MyService> {
@Context
private HttpHeaders headers;
@Override
public MyService provide() {
return new MyService(headers.getHeaderString("X-Header"));
}
@Override
public void dispose(MyService service) { /* noop */ }
}
register(new AbstractBinder() {
@Override
public void configure() {
bindFactory(MyServiceFactory.class).to(MyService.class)
.in(RequestScoped.class);
}
});
Then you can inject MyService
into your resource class.
You could use IsEmpty()
function like this:
...
Set rRng = Sheet1.Range("A10")
If IsEmpty(rRng.Value) Then ...
you could also use following:
If ActiveCell.Value = vbNullString Then ...
HTML Code
<html>
<body>
<head>
<title></title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file"><span>Filename:</span></label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
//============================= DATABASE CONNECTIVITY d ====================
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else
//============================= DATABASE CONNECTIVITY u ====================
//============================= Retrieve data from DB d ====================
$sql = "SELECT name, size, type FROM videos";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc())
{
$path = "uploaded/" . $row["name"];
echo $path . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
//============================= Retrieve data from DB d ====================
?>
</body>
</html>
I didn't see any answers that show users where we can find a Global Temp table. You can view Local and Global temp tables in the same location when navigating within SSMS. Screenshot below taken from this link.
Databases --> System Databases --> tempdb --> Temporary Tables
All third=party tools mentioned below are 100% free.
I’ve used ApexSQL Search with good success for searching both objects and data in tables. It comes with several other features such as relationship diagrams and such…
I was a bit slow on large (40GB TFS Database) databases though…
Apart from this there is also SSMS Tools pack that offers a lot of other features that are quite useful even though these are not directly related to searching text.
I took Matt's LINQ example one step further for code cleanliness:
byte[] rv = a1.Concat(a2).Concat(a3).ToArray();
In my case, the arrays are small, so I'm not concerned about performance.
I know it is a very old question, but better update it with new information.
You can install service by using sc command:
InstallService.bat:
@echo OFF
echo Stopping old service version...
net stop "[YOUR SERVICE NAME]"
echo Uninstalling old service version...
sc delete "[YOUR SERVICE NAME]"
echo Installing service...
rem DO NOT remove the space after "binpath="!
sc create "[YOUR SERVICE NAME]" binpath= "[PATH_TO_YOUR_SERVICE_EXE]" start= auto
echo Starting server complete
pause
With SC, you can do a lot more things as well: uninstalling the old service (if you already installed it before), checking if service with same name exists... even set your service to autostart.
One of many references: creating a service with sc.exe; how to pass in context parameters
I have done by both this way & InstallUtil
. Personally I feel that using SC is cleaner and better for your health.
In angular 1.3, I think, they added a new function - $scope.$applyAsync()
. This function calls apply later on - they say about 10 ms later at least. It is not perfect, but it does at least eliminate the annoying error.
https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$applyAsync
This is an article that I always refer to when working with sockets..
It will show you how to reliably use 'select()' and contains some other useful links at the bottom for further info on sockets.
Use:
int Years(DateTime start, DateTime end)
{
return (end.Year - start.Year - 1) +
(((end.Month > start.Month) ||
((end.Month == start.Month) && (end.Day >= start.Day))) ? 1 : 0);
}
If your goal is to have
str = "Hello\nWorld";
and output what it contains in string literal form, you can use JSON.stringify
:
console.log(JSON.stringify(str)); // ""Hello\nWorld""
const str = "Hello\nWorld";_x000D_
const json = JSON.stringify(str);_x000D_
console.log(json); // ""Hello\nWorld""_x000D_
for (let i = 0; i < json.length; ++i) {_x000D_
console.log(`${i}: ${json.charAt(i)}`);_x000D_
}
_x000D_
.as-console-wrapper {_x000D_
max-height: 100% !important;_x000D_
}
_x000D_
console.log
adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal (yes, that's somewhat confusing).
JSON.stringify
takes what you give it (in this case, a string) and returns a string containing valid JSON for that value. So for the above, it returns an opening quote ("
), the word Hello
, a backslash (\
), the letter n
, the word World
, and the closing quote ("
). The linefeed in the string is escaped in the output as a \
and an n
because that's how you encode a linefeed in JSON. Other escape sequences are similarly encoded.
And if push --force
doesn't work you can do push --delete
. Look at 2nd line on this instance:
git reset --hard HEAD~3 # reset current branch to 3 commits ago
git push origin master --delete # do a very very bad bad thing
git push origin master # regular push
But beware...
In other words:
force
push on a public repository.pull
.reset
or rewrite
history in a repo someone might have already pulled.Of course there are exceptionally rare exceptions even to this rule, but in most cases it's not needed to do it and it will generate problems to everyone else.
And always be careful with what you push to a public repo. Reverting:
git revert -n HEAD~3..HEAD # prepare a new commit reverting last 3 commits
git commit -m "sorry - revert last 3 commits because I was not careful"
git push origin master # regular push
In effect, both origin HEADs (from the revert and from the evil reset) will contain the same files.
push --force
Another problem push --force
may bring is when someone push anything before you do, but after you've already fetched. If you push force your rebased version now you will replace work from others.
git push --force-with-lease
introduced in the git 1.8.5 (thanks to @VonC comment on the question) tries to address this specific issue. Basically, it will bring an error and not push if the remote was modified since your latest fetch.
This is good if you're really sure a push --force
is needed, but still want to prevent more problems. I'd go as far to say it should be the default push --force
behaviour. But it's still far from being an excuse to force a push
. People who fetched before your rebase will still have lots of troubles, which could be easily avoided if you had reverted instead.
And since we're talking about git --push
instances...
@linquize brought a good push force example on the comments: sensitive data. You've wrongly leaked data that shouldn't be pushed. If you're fast enough, you can "fix"*
it by forcing a push on top.
*
The data will still be on the remote unless you also do a garbage collect, or clean it somehow. There is also the obvious potential for it to be spread by others who'd fetched it already, but you get the idea.
The most straight-forward approach is to do a second if-test but with the condition inverted. This technique is shorter, easier on the eyes, and easier to get right than a choose-when-otherwise nested block:
<xsl:variable name="CreatedDate" select="@createDate"/>
<xsl:variable name="IDAppendedDate" select="2012-01-01" />
<b>date: <xsl:value-of select="$CreatedDate"/></b>
<xsl:if test="$CreatedDate > $IDAppendedDate">
<h2> mooooooooooooo </h2>
</xsl:if>
<xsl:if test="$CreatedDate <= $IDAppendedDate">
<h2> dooooooooooooo </h2>
</xsl:if>
Here's a real-world example of the technique being used in the style-sheet for a government website: http://w1.weather.gov/xml/current_obs/latest_ob.xsl
Export (or datapump if you have 10g/11g) is the way to do it. Why not ask how to fix your problems with that rather than trying to find another way to do it?
For me, I started the app from within windows explorer (by double clicking on it). Then it crashed immediately.
I then opened Event Viewer
of windows and viewed Application
and it displayed full stacktrace of error. The stacktrace showed relation with Bitmap or images. It was then turned out to be due to app icon not found
To get the IP address and host port of a container:
docker inspect containerId | awk '/IPAddress/ || /HostPort/'
Output:
"HostPort": "4200"
"HostPort": "4200"
"SecondaryIPAddresses": null,
"IPAddress": "172.17.0.2",
"IPAddress": "172.17.0.2",
for line in p.stdout:
...
always blocks until the next line-feed.
For "real-time" behaviour you have to do something like this:
while True:
inchar = p.stdout.read(1)
if inchar: #neither empty string nor None
print(str(inchar), end='') #or end=None to flush immediately
else:
print('') #flush for implicit line-buffering
break
The while-loop is left when the child process closes its stdout or exits.
read()/read(-1)
would block until the child process closed its stdout or exited.
If s is your string:
s.replace(/^[^(]*\(/, "") // trim everything before first parenthesis
.replace(/\)[^(]*$/, "") // trim everything after last parenthesis
.split(/\)[^(]*\(/); // split between parenthesis
Don't forget to add in app level gradle, apply plugin: 'kotlin-kapt'
Here is a locale independent solution (copy to a file named SetDateTimeComponents.cmd):
@echo off
REM This script taken from the following URL:
REM http://www.winnetmag.com/windowsscripting/article/articleid/9177/windowsscripting_9177.html
REM Create the date and time elements.
for /f "tokens=1-7 delims=:/-, " %%i in ('echo exit^|cmd /q /k"prompt $d $t"') do (
for /f "tokens=2-4 delims=/-,() skip=1" %%a in ('echo.^|date') do (
set dow=%%i
set %%a=%%j
set %%b=%%k
set %%c=%%l
set hh=%%m
set min=%%n
set ss=%%o
)
)
REM Let's see the result.
echo %dow% %yy%-%mm%-%dd% @ %hh%:%min%:%ss%
I put all my .cmd scripts into the same folder (%SCRIPTROOT%); any script that needs date/time values will call SetDateTimeComponents.cmd as in the following example:
setlocal
@echo Initializing...
set SCRIPTROOT=%~dp0
set ERRLOG=C:\Oopsies.err
:: Log start time
call "%SCRIPTROOT%\SetDateTimeComponents.cmd" >nul
@echo === %dow% %yy%-%mm%-%dd% @ %hh%:%min%:%ss% : Start === >> %ERRLOG%
:: Perform some long running action and log errors to ERRLOG.
:: Log end time
call "%SCRIPTROOT%\SetDateTimeComponents.cmd" >nul
@echo === %dow% %yy%-%mm%-%dd% @ %hh%:%min%:%ss% : End === >> %ERRLOG%
As the example shows, you can call SetDateTimeComponents.cmd whenever you need to update the date/time values. Hiding the time parsing script in it's own SetDateTimeComponents.cmd file is a nice way to hide the ugly details, and, more importantly, avoid typos.
You can try viewport units (CSS3):
canvas {
height: 100vh;
width: 100vw;
display: block;
}
next() is read until the space of the encounter, and the nextLine() is read to the end of the line.
Scanner scan = new Scanner(System.in);
String address = scan.next();
s += scan.nextLine();
This can never work.
The async
keyword allows await
to be used in a function marked as async
but it also converts that function into a promise generator. So a function marked with async
will return a promise. A constructor on the other hand returns the object it is constructing. Thus we have a situation where you want to both return an object and a promise: an impossible situation.
You can only use async/await where you can use promises because they are essentially syntax sugar for promises. You can't use promises in a constructor because a constructor must return the object to be constructed, not a promise.
There are two design patterns to overcome this, both invented before promises were around.
Use of an init()
function. This works a bit like jQuery's .ready()
. The object you create can only be used inside it's own init
or ready
function:
Usage:
var myObj = new myClass();
myObj.init(function() {
// inside here you can use myObj
});
Implementation:
class myClass {
constructor () {
}
init (callback) {
// do something async and call the callback:
callback.bind(this)();
}
}
Use a builder. I've not seen this used much in javascript but this is one of the more common work-arounds in Java when an object needs to be constructed asynchronously. Of course, the builder pattern is used when constructing an object that requires a lot of complicated parameters. Which is exactly the use-case for asynchronous builders. The difference is that an async builder does not return an object but a promise of that object:
Usage:
myClass.build().then(function(myObj) {
// myObj is returned by the promise,
// not by the constructor
// or builder
});
// with async/await:
async function foo () {
var myObj = await myClass.build();
}
Implementation:
class myClass {
constructor (async_param) {
if (typeof async_param === 'undefined') {
throw new Error('Cannot be called directly');
}
}
static build () {
return doSomeAsyncStuff()
.then(function(async_result){
return new myClass(async_result);
});
}
}
Implementation with async/await:
class myClass {
constructor (async_param) {
if (typeof async_param === 'undefined') {
throw new Error('Cannot be called directly');
}
}
static async build () {
var async_result = await doSomeAsyncStuff();
return new myClass(async_result);
}
}
Note: although in the examples above we use promises for the async builder they are not strictly speaking necessary. You can just as easily write a builder that accept a callback.
This has nothing whatsoever to do with async constructors but with what the keyword this
actually mean (which may be a bit surprising to people coming from languages that do auto-resolution of method names, that is, languages that don't need the this
keyword).
The this
keyword refers to the instantiated object. Not the class. Therefore you cannot normally use this
inside static functions since the static function is not bound to any object but is bound directly to the class.
That is to say, in the following code:
class A {
static foo () {}
}
You cannot do:
var a = new A();
a.foo() // NOPE!!
instead you need to call it as:
A.foo();
Therefore, the following code would result in an error:
class A {
static foo () {
this.bar(); // you are calling this as static
// so bar is undefinned
}
bar () {}
}
To fix it you can make bar
either a regular function or a static method:
function bar1 () {}
class A {
static foo () {
bar1(); // this is OK
A.bar2(); // this is OK
}
static bar2 () {}
}
I suggest that all events for Spinner are divided on two types:
User events (you meant as "click" event).
Program events.
I also suggest that when you want to catch user event you just want to get rid off "program events". So it's pretty simple:
private void setSelectionWithoutDispatch(Spinner spinner, int position) {
AdapterView.OnItemSelectedListener onItemSelectedListener = spinner.getOnItemSelectedListener();
spinner.setOnItemSelectedListener(null);
spinner.setSelection(position, false);
spinner.setOnItemSelectedListener(onItemSelectedListener);
}
There's a key moment: you need setSelection(position, false). "false" in animation parameter will fire event immediately. The default behaviour is to push event to event queue.
The difference is subtle but important. The MOV instruction is a 'MOVe' effectively a copy of the address that the TABLE-ADDR label stands for. The LEA instruction is a 'Load Effective Address' which is an indirected instruction, which means that TABLE-ADDR points to a memory location at which the address to load is found.
Effectively using LEA is equivalent to using pointers in languages such as C, as such it is a powerful instruction.
If you are on windows then below port related server settings are present in file nginx.conf at < nginx installation path >/conf folder.
server {
listen 80;
server_name localhost;
....
Change the port number and restart the instance.
Strip out tags, leave only alphanumeric characters and space:
$clear = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags($des));
Edit: all credit to DaveRandom for the perfect solution...
$clear = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags(html_entity_decode($des)));
Just a note for @"John Sansom" answer,
If the foreign key dependencies are sought, I think that the PT Where clause should be:
i1.CONSTRAINT_TYPE = 'FOREIGN KEY' -- instead of 'PRIMARY KEY'
and its the ON condition:
ON PT.TABLE_NAME = FK.TABLE_NAME – instead of PK.TABLE_NAME
As commonly is used the primary key of the foreign table, I think this issue has not been noticed before.
What about Date.today.to_time
?
You are apparently using Django.
You are probably better off just using models.IntegerField()
instead of models.TextField()
. Not only will it do the check for you, but it will give you the error message translated in several langs, and it will cast the value from it's type in the database to the type in your Python code transparently.
element.defaultValue
will give you the original value.
Please note that this only works on the initial value.
If you are needing this to persist the "old" value every time it changes, an expando property or similar method will meet your needs
Here is a solution that works with simple CSS and standard font awesome syntax, no need for unicode values, etc.
Create an <input>
tag followed by a standard <i>
tag with the icon you need.
Use relative positioning together with a higher layer order (z-index) and move the icon over and on top of the input field.
(Optional) You can make the icon active, to perhaps submit the data, via standard JS.
See the three code snippets below for the HTML / CSS / JS.
Or the same in JSFiddle here: Example: http://jsfiddle.net/ethanpil/ws1g27y3/
$('#filtersubmit').click(function() {_x000D_
alert('Searching for ' + $('#filter').val());_x000D_
});
_x000D_
#filtersubmit {_x000D_
position: relative;_x000D_
z-index: 1;_x000D_
left: -25px;_x000D_
top: 1px;_x000D_
color: #7B7B7B;_x000D_
cursor: pointer;_x000D_
width: 0;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input id="filter" type="text" placeholder="Search" />_x000D_
<i id="filtersubmit" class="fa fa-search"></i>
_x000D_
Today I was looking for this and Mr Brandon Rude gave an excellent answer. Unfortunately, AsyncTask
is now depricated, you can still use it, but it gives you a warning which is very annoying. So an alternative is to use Executors
like this way (in kotlin
):
val someRunnable = object : Runnable{
override fun run() {
// todo: do your background tasks
requireActivity().runOnUiThread{
// update views / ui if you are in a fragment
};
/*
runOnUiThread {
// update ui if you are in an activity
}
* */
}
};
Executors.newSingleThreadExecutor().execute(someRunnable);
And in java
it looks like this:
Runnable someRunnable = new Runnable() {
@Override
public void run() {
// todo: background tasks
runOnUiThread(new Runnable() {
@Override
public void run() {
// todo: update your ui / view in activity
}
});
/*
requireActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// todo: update your ui / view in Fragment
}
});*/
}
};
Executors.newSingleThreadExecutor().execute(someRunnable);
It can also be solved using the following query along with other answers.
WITH purchase_data AS (
SELECT address_id, purchased_at, product_id,
row_number() OVER (PARTITION BY address_id ORDER BY purchased_at DESC) AS row_number
FROM purchases
WHERE product_id = 1)
SELECT address_id, purchased_at, product_id
FROM purchase_data where row_number = 1
html link example:
<!-- boostrap button + fontawesome icon -->
<a class="btn btn-primary" id="BT_Download" target="_blank" href="DownloadDoc?Id=32">
<i class="icon-file-text icon-large"></i>
Download Document
</a>
use this in jQuery
$('#BT_Download').attr('disabled',true);
add this to css :
a[disabled="disabled"] {
pointer-events: none;
}
If you just need to await
to avoid nesting code:
let json;
await new Promise(done => $.getJSON('https://***', async function (data) {
json = data;
done();
}));
Grant required permission ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION after start service
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.location.LocationListener;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnCanceledListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import java.util.concurrent.TimeUnit;
/**
* Created by Ketan Ramani on 05/11/18.
*/
public class BackgroundLocationUpdateService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
/* Declare in manifest
<service android:name=".BackgroundLocationUpdateService"/>
*/
private final String TAG = "BackgroundLocationUpdateService";
private final String TAG_LOCATION = "TAG_LOCATION";
private Context context;
private boolean stopService = false;
/* For Google Fused API */
protected GoogleApiClient mGoogleApiClient;
protected LocationSettingsRequest mLocationSettingsRequest;
private String latitude = "0.0", longitude = "0.0";
private FusedLocationProviderClient mFusedLocationClient;
private SettingsClient mSettingsClient;
private LocationCallback mLocationCallback;
private LocationRequest mLocationRequest;
private Location mCurrentLocation;
/* For Google Fused API */
@Override
public void onCreate() {
super.onCreate();
context = this;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
StartForeground();
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
try {
if (!stopService) {
//Perform your task here
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (!stopService) {
handler.postDelayed(this, TimeUnit.SECONDS.toMillis(10));
}
}
}
};
handler.postDelayed(runnable, 2000);
buildGoogleApiClient();
return START_STICKY;
}
@Override
public void onDestroy() {
Log.e(TAG, "Service Stopped");
stopService = true;
if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
Log.e(TAG_LOCATION, "Location Update Callback Removed");
}
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void StartForeground() {
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);
String CHANNEL_ID = "channel_location";
String CHANNEL_NAME = "channel_location";
NotificationCompat.Builder builder = null;
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
notificationManager.createNotificationChannel(channel);
builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
builder.setChannelId(CHANNEL_ID);
builder.setBadgeIconType(NotificationCompat.BADGE_ICON_NONE);
} else {
builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
}
builder.setContentTitle("Your title");
builder.setContentText("You are now online");
Uri notificationSound = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(notificationSound);
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.ic_logo);
builder.setContentIntent(pendingIntent);
Notification notification = builder.build();
startForeground(101, notification);
}
@Override
public void onLocationChanged(Location location) {
Log.e(TAG_LOCATION, "Location Changed Latitude : " + location.getLatitude() + "\tLongitude : " + location.getLongitude());
latitude = String.valueOf(location.getLatitude());
longitude = String.valueOf(location.getLongitude());
if (latitude.equalsIgnoreCase("0.0") && longitude.equalsIgnoreCase("0.0")) {
requestLocationUpdate();
} else {
Log.e(TAG_LOCATION, "Latitude : " + location.getLatitude() + "\tLongitude : " + location.getLongitude());
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onConnected(@Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10 * 1000);
mLocationRequest.setFastestInterval(5 * 1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
mLocationSettingsRequest = builder.build();
mSettingsClient
.checkLocationSettings(mLocationSettingsRequest)
.addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
Log.e(TAG_LOCATION, "GPS Success");
requestLocationUpdate();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
int REQUEST_CHECK_SETTINGS = 214;
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult((AppCompatActivity) context, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sie) {
Log.e(TAG_LOCATION, "Unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.e(TAG_LOCATION, "Location settings are inadequate, and cannot be fixed here. Fix in Settings.");
}
}
}).addOnCanceledListener(new OnCanceledListener() {
@Override
public void onCanceled() {
Log.e(TAG_LOCATION, "checkLocationSettings -> onCanceled");
}
});
}
@Override
public void onConnectionSuspended(int i) {
connectGoogleClient();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
buildGoogleApiClient();
}
protected synchronized void buildGoogleApiClient() {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
mSettingsClient = LocationServices.getSettingsClient(context);
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
connectGoogleClient();
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
Log.e(TAG_LOCATION, "Location Received");
mCurrentLocation = locationResult.getLastLocation();
onLocationChanged(mCurrentLocation);
}
};
}
private void connectGoogleClient() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int resultCode = googleAPI.isGooglePlayServicesAvailable(context);
if (resultCode == ConnectionResult.SUCCESS) {
mGoogleApiClient.connect();
}
}
@SuppressLint("MissingPermission")
private void requestLocationUpdate() {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}
}
In Activity
Start Service : startService(new Intent(this, BackgroundLocationUpdateService.class));
Stop Service : stopService(new Intent(this, BackgroundLocationUpdateService.class));
In Fragment
Start Service : getActivity().startService(new Intent(getActivity().getBaseContext(), BackgroundLocationUpdateService.class));
Stop Service : getActivity().stopService(new Intent(getActivity(), BackgroundLocationUpdateService.class));
That's because req
and res
are two different objects.
You need to look for the property on the same object you added it to.
This matches everything up to ".txt" (without including it):
^.*(?=(\.txt))
The answer shared by Paul is the best one. To expand more,
There can be only one default export per file. Whereas there can be more than one const exports. The default variable can be imported with any name, whereas const variable can be imported with it's particular name.
var message2 = 'I am exported';
export default message2;
export const message = 'I am also exported'
At the imports side we need to import it like this:
import { message } from './test';
or
import message from './test';
With the first import, the const variable is imported whereas, with the second one, the default one will be imported.
Use ClassLoader#getResource()
instead if its URI represents a valid local disk file system path.
URL resource = classLoader.getResource("resource.ext");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);
// ...
If it doesn't (e.g. JAR), then your best bet is to copy it into a temporary file.
Path temp = Files.createTempFile("resource-", ".ext");
Files.copy(classLoader.getResourceAsStream("resource.ext"), temp, StandardCopyOption.REPLACE_EXISTING);
FileInputStream input = new FileInputStream(temp.toFile());
// ...
That said, I really don't see any benefit of doing so, or it must be required by a poor helper class/method which requires FileInputStream
instead of InputStream
. If you can, just fix the API to ask for an InputStream
instead. If it's a 3rd party one, by all means report it as a bug. I'd in this specific case also put question marks around the remainder of that API.
If you want it to start at 000001
and go to 999999
:
$num_str = sprintf("%06d", mt_rand(1, 999999));
Mind you, it's stored as a string.
In my case, I've just downloaded the missing file directly from here: https://gitlab.com/mailman/mailman-website/raw/a97d6b4c5b29594004e3855f1ab1222449d0c211/content/fonts/glyphicons-halflings-regular.woff2
Using these libraries:
Using this code:
List<Object[]> testNovedads = crudService.createNativeQuery(
"SELECT cantidad, id FROM NOVEDADES GROUP BY id ");
Gson gson = new Gson();
String json = gson.toJson(new TestNovedad());
JSONObject jsonObject = new JSONObject(json);
Collection<TestNovedad> novedads = new ArrayList<>();
for (Object[] object : testNovedads) {
Iterator<String> iterator = jsonObject.keys();
int pos = 0;
for (Iterator i = iterator; i.hasNext();) {
jsonObject.put((String) i.next(), object[pos++]);
}
novedads.add(gson.fromJson(jsonObject.toString(), TestNovedad.class));
}
for (TestNovedad testNovedad : novedads) {
System.out.println(testNovedad.toString());
}
/**
* Autores: Chalo Mejia
* Fecha: 01/10/2020
*/
package org.main;
import java.io.Serializable;
public class TestNovedad implements Serializable {
private static final long serialVersionUID = -6362794385792247263L;
private int id;
private int cantidad;
public TestNovedad() {
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
@Override
public String toString() {
return "TestNovedad [id=" + id + ", cantidad=" + cantidad + "]";
}
}
I landed here with the same issue, then figured it out on my own. This weird character was appearing with my HTML.
The issue is most likely your code editor. I use Espresso and sometimes run into issues like this.
To fix it, simply highlight the affected code, then go to the menu and click "convert to numeric entities". You'll see the numeric value of this character appear; simply delete it and it's gone forever.
Will the conditions be ORed or ANDed together?
Starts with: abc Ends with: xyz Contains: 123 Doesn't contain: 456
The OR version is fairly simple; as you said, it's mostly a matter of inserting pipes between individual conditions. The regex simply stops looking for a match as soon as one of the alternatives matches.
/^abc|xyz$|123|^(?:(?!456).)*$/
That fourth alternative may look bizarre, but that's how you express "doesn't contain" in a regex. By the way, the order of the alternatives doesn't matter; this is effectively the same regex:
/xyz$|^(?:(?!456).)*$|123|^abc/
The AND version is more complicated. After each individual regex matches, the match position has to be reset to zero so the next regex has access to the whole input. That means all of the conditions have to be expressed as lookaheads (technically, one of them doesn't have to be a lookahead, I think it expresses the intent more clearly this way). A final .*$
consummates the match.
/^(?=^abc)(?=.*xyz$)(?=.*123)(?=^(?:(?!456).)*$).*$/
And then there's the possibility of combined AND and OR conditions--that's where the real fun starts. :D
One can also use a test ApplicationContextInitializer to initialize a system property:
public class TestApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>
{
@Override
public void initialize(ConfigurableApplicationContext applicationContext)
{
System.setProperty("myproperty", "value");
}
}
and then configure it on the test class in addition to the Spring context config file locations:
@ContextConfiguration(initializers = TestApplicationContextInitializer.class, locations = "classpath:whereever/context.xml", ...)
@RunWith(SpringJUnit4ClassRunner.class)
public class SomeTest
{
...
}
This way code duplication can be avoided if a certain system property should be set for all the unit tests.
In conf directory of apache tomcat you can find context.xml file. In that edit tag as <Context reloadable="true">. this should solve the issue and you need not restart the server
Pseudo code, something like:
CASE
When CHARINDEX('lactulose', dbo.Table.Column) > 0 Then 'BP Medication'
ELSE ''
END AS 'Medication Type'
This does not care where the keyword is found in the list and avoids depending on formatting of spaces and commas.
You can either use
break;
or
foreach() if ($tmp++ < 2) {
}
(the second solution is even worse)
This is because you select not a theme of your project. Try to do next:
SELECT IDENT_CURRENT('databasename.dbo.tablename') AS your identity column;
In sonar.properties file in conf folder I had hardcoaded ip of my machine where sobarqube was installed in property sonar.web.host=10.9 235.22 I commented this and it started working for me.
I had the same issue, didn't want to mess with multiple typedefs in different files, so I resolved it with inheritance:
was:
class BurstBoss {
public:
typedef std::pair<Ogre::ParticleSystem*, bool> ParticleSystem; // removed this with...
did:
class ParticleSystem : public std::pair<Ogre::ParticleSystem*, bool>
{
public:
ParticleSystem(Ogre::ParticleSystem* system, bool enabled) : std::pair<Ogre::ParticleSystem*, bool>(system, enabled) {
};
};
Worked like a charm. Of course, I had to change any references from
BurstBoss::ParticleSystem
to simply
ParticleSystem
Without repeating the same thing in previous answers,
I'm writing this answer for the people who are looking to starting a new project and don't know which is the best framework to startup your project.
If you are a beginner to this framework the best thing I prefer is Use spring boot(with STS /Spring Tool Suite). Because it helps a lot. Its do all configurations on its own. Additionally, use Hibernate with spring-boot as a database framework. With this combination, your application will be the best. I can guarantee that with my experiences.
Even this is one of the best frameworks for JEE(in present) this is gonna die in the near future. There are lightweight alternatives coming up. So keep updated with your experience don't stick to one particular framework. The best thing is being fluent in concepts, not in the frameworks.
Change
$info=$_POST['id[]'];
to
$info=$_POST['id'];
by adding []
to the end of your form field names, PHP will automatically convert these variables into arrays.
As far that I know you only can get time with Date.
Date.now is the solution but is not available everywhere : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/now.
var currentTime = +new Date();
This gives you the current time in milliseconds.
For your jumps. If you compute interpolations correctly according to the delta frame time and you don't have some rounding number error, I bet for the garbage collector (GC).
If there is a lot of created temporary object in your loop, garbage collection has to lock the thread to make some cleanup and memory re-organization.
With Chrome you can see how much time the GC is spending in the Timeline panel.
EDIT: Since my answer, Date.now()
should be considered as the best option as it is supported everywhere and on IE >= 9.
If you want to fix vbs associations type
regsvr32 vbscript.dll
regsvr32 jscript.dll
regsvr32 wshext.dll
regsvr32 wshom.ocx
regsvr32 wshcon.dll
regsvr32 scrrun.dll
Also if you can't use vbs due to management then convert your script to a vb.net program which is designed to be easy, is easy, and takes 5 minutes.
Big difference is functions and subs are both called using brackets rather than just functions.
So the compilers are installed on all computers with .NET installed.
See this article here on how to make a .NET exe. Note the sample is for a scripting host. You can't use this, you have to put your vbs code in as .NET code.
With JPA 2.1 you should be able to do it.
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Index;
import javax.persistence.Table;
@Entity
@Table(name = "region",
indexes = {@Index(name = "my_index_name", columnList="iso_code", unique = true),
@Index(name = "my_index_name2", columnList="name", unique = false)})
public class Region{
@Column(name = "iso_code", nullable = false)
private String isoCode;
@Column(name = "name", nullable = false)
private String name;
}
Update: If you ever need to create and index with two or more columns you may use commas. For example:
@Entity
@Table(name = "company__activity",
indexes = {@Index(name = "i_company_activity", columnList = "activity_id,company_id")})
public class CompanyActivity{
Now it's also possible to reset the database through their web interface.
Go to dashboard.heroku.com select your app and then you'll find the database under the add-ons category, click on it and then you can reset the database.
Try this : (http://jsfiddle.net/TpqVx/)
.left-div {
float: left;
width: 100px;
/*height: 20px;*/
margin-right: 8px;
background-color: linen;
}
.right-div {
margin-left: 108px;
background-color: lime;
}??
<div class="left-div">
</div>
<div class="right-div">
My requirements are <b>[A]</b> Content in the two divs should line up at the top, <b>[B]</b> Long text in right-div should not wrap underneath left-div, and <b>[C]</b> I do not want to specify a width of right-div. I don't want to set the width of right-div because this markup needs to work within different widths.
</div>
<div style='clear:both;'> </div>
Hints :
float:left
in your left-most div only.height
, but anyway...<div 'clear:both'> </div>
after your last div.Your syntax is wrong:
string[] arr = new string[]{};
or
string[] arr = new string[0];
Just adding to Jason's answer, the .
selector is only for classes. If you want to select something other than the element, id, or class, you need to wrap it in square brackets.
e.g.
$('element[attr=val]')
Yes, just delete the branch by running git push origin :branchname
. To fix a new issue later, branch off from master again.
With the Android Studio default generated Activity superclass is ActionBarActivity
and then, none of solution in other responses works. To solve just change superclass:
public class xxxActivity extends ActionBarActivity{
to:
public class xxxActivity extends Activity {
If you want to do a horizontal centering, just put the form inside a DIV tag and apply align="center" attribute to it. So even if the form width is changed, your centering will remain the same.
<div align="center"><form id="form_login"><!--form content here--></form></div>
UPDATE
@G-Cyr is right. align="center"
attribute is now obsolete. You can use text-align
attribute for this as following.
<div style="text-align:center"><form id="form_login"><!--form content here--></form></div>
This will center all the content inside the parent DIV. An optional way is to use margin: auto
CSS attribute with predefined widths and heights. Please follow the following thread for more information.
How to horizontally center a in another ?
Vertical centering is little difficult than that. To do that, you can do the following stuff.
html
<body>
<div id="parent">
<form id="form_login">
<!--form content here-->
</form>
</div>
</body>
Css
#parent {
display: table;
width: 100%;
}
#form_login {
display: table-cell;
text-align: center;
vertical-align: middle;
}
I prefer to use both plural (/resources
) and singular (/resource/{id}
) because I think that it more clearly separates the logic between working on the collection of resources and working on a single resource.
As an important side-effect of this, it can also help to prevent somebody using the API wrongly. For example, consider the case where a user wrongly tries to get a resource by specifying the Id as a parameter like this:
GET /resources?Id=123
In this case, where we use the plural version, the server will most likely ignore the Id parameter and return the list of all resources. If the user is not careful, he will think that the call was successful and use the first resource in the list.
On the other hand, when using the singular form:
GET /resource?Id=123
the server will most likely return an error because the Id is not specified in the right way, and the user will have to realize that something is wrong.
You can find the command line tools at the downloads page under the "Command line tools only" section.
These are the links provided in the page as of now (version 26.1.1):
Windows no installer: https://dl.google.com/android/repository/sdk-tools-windows-4333796.zip
MacOSX: https://dl.google.com/android/repository/sdk-tools-darwin-4333796.zip
Linux: https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip
Be sure to have read and agreed with the terms of service before downloading any of the command line tools.
The installer version for windows doesn't seem to be available any longer, this is the link for version 24.4.1:
Your question How can I just get the file-names (with paths)
Your syntax example find . -iname "*php" -exec grep -H myString {} \;
My Command suggestion
sudo find /home -name *.php
The output from this command on my Linux OS:
compose-sample-3/html/mail/contact_me.php
As you require the filename with path, enjoy!
On macos Sierra this work for me, where python is managed by anaconda:
anaconda search -t conda mysql-python
anaconda show CEFCA/mysql-python
conda install --channel https://conda.anaconda.org/CEFCA mysql-python
The to use with SQLAlchemy:
Python 2.7.13 |Continuum Analytics, Inc.| (default, Dec 20 2016, 23:05:08) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. Anaconda is brought to you by Continuum Analytics. Please check out: http://continuum.io/thanks and https://anaconda.org
>>> from sqlalchemy import *
>>>dbengine = create_engine('mysql://....')
You have two syntax options:
Option 1
CREATE TABLE Table1 (
id int identity(1, 1) not null,
LongIntColumn1 int,
CurrencyColumn money
)
CREATE TABLE Table2 (
id int identity(1, 1) not null,
LongIntColumn2 int,
CurrencyColumn2 money
)
INSERT INTO Table1 VALUES(12, 12.00)
INSERT INTO Table1 VALUES(11, 13.00)
INSERT INTO Table2
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1
Option 2
CREATE TABLE Table1 (
id int identity(1, 1) not null,
LongIntColumn1 int,
CurrencyColumn money
)
INSERT INTO Table1 VALUES(12, 12.00)
INSERT INTO Table1 VALUES(11, 13.00)
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1
INTO Table2
FROM Table1
GROUP BY LongIntColumn1
Bear in mind that Option 2 will create a table with only the columns on the projection (those on the SELECT).
Additionally, if it's a folder to be removed and it's subsequent child folders or files, use:
git rm -r foldername
I tried @Mr. Stark answer. It didn't work. It failed to install the drive. I have Samsung S8 plus. I enabled the debugging mode on device then installed Android USB Driver for Windows from Samsung site, it works.
As pointed out in this comment How do you check in python whether a string contains only numbers? the isdigit()
method is not totally accurate for this use case, because it returns True for some digit-like characters:
>>> "\u2070".isdigit() # unicode escaped 'superscript zero'
True
If this needs to be avoided, the following simple function checks, if all characters in a string are a digit between "0" and "9":
import string
def contains_only_digits(s):
# True for "", "0", "123"
# False for "1.2", "1,2", "-1", "a", "a1"
for ch in s:
if not ch in string.digits:
return False
return True
Used in the example from the question:
if len(isbn) == 10 and contains_only_digits(isbn):
print ("Works")
If you have an Order
class, adding a property that references another class in your model, for instance Customer
should be enough to let EF know there's a relationship in there:
public class Order
{
public int ID { get; set; }
// Some other properties
// Foreign key to customer
public virtual Customer Customer { get; set; }
}
You can always set the FK
relation explicitly:
public class Order
{
public int ID { get; set; }
// Some other properties
// Foreign key to customer
[ForeignKey("Customer")]
public string CustomerID { get; set; }
public virtual Customer Customer { get; set; }
}
The ForeignKeyAttribute
constructor takes a string as a parameter: if you place it on a foreign key property it represents the name of the associated navigation property. If you place it on the navigation property it represents the name of the associated foreign key.
What this means is, if you where to place the ForeignKeyAttribute
on the Customer
property, the attribute would take CustomerID
in the constructor:
public string CustomerID { get; set; }
[ForeignKey("CustomerID")]
public virtual Customer Customer { get; set; }
EDIT based on Latest Code You get that error because of this line:
[ForeignKey("Parent")]
public Patient Patient { get; set; }
EF will look for a property called Parent
to use it as the Foreign Key enforcer. You can do 2 things:
1) Remove the ForeignKeyAttribute
and replace it with the RequiredAttribute
to mark the relation as required:
[Required]
public virtual Patient Patient { get; set; }
Decorating a property with the RequiredAttribute
also has a nice side effect: The relation in the database is created with ON DELETE CASCADE
.
I would also recommend making the property virtual
to enable Lazy Loading.
2) Create a property called Parent
that will serve as a Foreign Key. In that case it probably makes more sense to call it for instance ParentID
(you'll need to change the name in the ForeignKeyAttribute
as well):
public int ParentID { get; set; }
In my experience in this case though it works better to have it the other way around:
[ForeignKey("Patient")]
public int ParentID { get; set; }
public virtual Patient Patient { get; set; }
<table>
<tr>
<td>title</td>
<td>price</td>
<td>number</td>
</tr>
<? foreach ($shop as $row) : ?>
<tr>
<td><? echo $row[0]; ?></td>
<td><? echo $row[1]; ?></td>
<td><? echo $row[2]; ?></td>
</tr>
<? endforeach; ?>
</table>
There seem to be a number of steps here jumbled together. I'll put forward what I did from scratch.
Create the ErrorPage
controller
public class ErrorPageController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Oops(int id)
{
Response.StatusCode = id;
return View();
}
}
Add views for these two actions (right click -> Add View). These should appear in a folder called ErrorPage.
Inside App_Start
open up FilterConfig.cs
and comment out the error handling filter.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
// Remove this filter because we want to handle errors ourselves via the ErrorPage controller
//filters.Add(new HandleErrorAttribute());
}
Inside web.config add the following <customerErrors>
entries, under System.Web
<customErrors mode="On" defaultRedirect="~/ErrorPage/Oops">
<error redirect="~/ErrorPage/Oops/404" statusCode="404" />
<error redirect="~/ErrorPage/Oops/500" statusCode="500" />
</customErrors>
Test (of course). Throw an unhandled exception in your code and see it go to the page with id 500, and then use a URL to a page that does not exist to see 404.
You could get first rows of Spark DataFrame with head and then create Pandas DataFrame:
l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df_pandas = pd.DataFrame(df.head(3), columns=df.columns)
In [4]: df_pandas
Out[4]:
name age
0 Alice 1
1 Jim 2
2 Sandra 3
It means "a python object", i.e. not one of the builtin scalar types supported by numpy.
np.array([object()]).dtype
=> dtype('O')
Typecasting in Objective-C is easy as:
NSArray *threeViews = @[[UIView new], [UIView new], [UIView new]];
UIView *firstView = (UIView *)threeViews[0];
However, what happens if first object is not UIView
and you try to use it:
NSArray *threeViews = @[[NSNumber new], [UIView new], [UIView new]];
UIView *firstView = (UIView *)threeViews[0];
CGRect firstViewFrame = firstView.frame; // CRASH!
It will crash. And it's easy to find such crash for this case, but what if those lines are in different classes and the third line is executed only once in 100 cases. I bet your customers find this crash, not you! A plausible solution is to crash early, like this:
UIView *firstView = (UIView *)threeViews[0];
NSAssert([firstView isKindOfClass:[UIView class]], @"firstView is not UIView");
Those assertions doesn't look very nice, so we could improve them with this handy category:
@interface NSObject (TypecastWithAssertion)
+ (instancetype)typecastWithAssertion:(id)object;
@end
@implementation NSObject (TypecastWithAssertion)
+ (instancetype)typecastWithAssertion:(id)object {
if (object != nil)
NSAssert([object isKindOfClass:[self class]], @"Object %@ is not kind of class %@", object, NSStringFromClass([self class]));
return object;
}
@end
This is much better:
UIView *firstView = [UIView typecastWithAssertion:[threeViews[0]];
P.S. For collections type safety Xcode 7 have a much better than typecasting - generics
You can use : Query grouping allows you to create groups of WHERE clauses by enclosing them in parentheses. This will allow you to create queries with complex WHERE clauses. Nested groups are supported. Example:
$this->db->select('*')->from('my_table')
->group_start()
->where('a', 'a')
->or_group_start()
->where('b', 'b')
->where('c', 'c')
->group_end()
->group_end()
->where('d', 'd')
->get();
https://www.codeigniter.com/userguide3/database/query_builder.html#query-grouping
To answer the question of why http://127.0.0.1/cd_catalog.xml
works while
http://localhost/cd_catalog.xml
doesn't: Firefox is treating 127.0.0.1 and localhost as two different domains.
I came across this answer when I was trying to follow this guide for OSX. What worked for me was, after running python get-pip
, I had to ALSO easy_install pip
. That fixed the issue of not being able to run pip at all. I did have a bunch of old macport stuff installed. That may have conflicted.
Sadly, Python doesn't have a simple way to flatten lists. Try this:
def flatten(some_list):
for element in some_list:
if type(element) in (tuple, list):
for item in flatten(element):
yield item
else:
yield element
Which will recursively flatten a list; you can then do
result = []
[ result.extend(el) for el in x]
for el in flatten(result):
print el
As said before, you code will not work the way it is. A solution to that would be using a callback function, but if you think it would carry you to a 'Callback hell', you can search for "Promisses".
A possible solution using a callback function:
//DECLARE numberofDocs OUT OF FUNCTIONS
var numberofDocs;
userModel.count({}, setNumberofDocuments); //this search all DOcuments in a Collection
if you want to search the number of documents based on a query, you can do this:
userModel.count({yourQueryGoesHere}, setNumberofDocuments);
setNumberofDocuments is a separeted function :
var setNumberofDocuments = function(err, count){
if(err) return handleError(err);
numberofDocs = count;
};
Now you can get the number of Documents anywhere with a getFunction:
function getNumberofDocs(){
return numberofDocs;
}
var number = getNumberofDocs();
In addition , you use this asynchronous function inside a synchronous one by using a callback, example:
function calculateNumberOfDoc(someParameter, setNumberofDocuments){
userModel.count({}, setNumberofDocuments); //this search all DOcuments in a Collection
setNumberofDocuments(true);
}
Hope it can help others. :)
document.getElementById('tries').scrollIntoView()
works. This works better than window.location.hash
when you have fixed positioning.
For 2005 and later, these will both give what you're looking for.
SELECT name FROM sys.schemas
SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA
For 2000, this will give a list of the databases in the instance.
SELECT * FROM INFORMATION_SCHEMA.SCHEMATA
That's the "backward incompatability" noted in @Adrift's answer.
In SQL Server 2000 (and lower), there aren't really "schemas" as such, although you can use roles as namespaces in a similar way. In that case, this may be the closest equivalent.
SELECT * FROM sysusers WHERE gid <> 0
For images if your using Web Pages v2 use the WebImage Class
var webImage = new System.Web.Helpers.WebImage(Request.Files[0].InputStream);
byte[] imgByteArray = webImage.GetBytes();
You can use DefaultIfEmpty followed by First:
T customDefault = ...;
IEnumerable<T> mySequence = ...;
mySequence.DefaultIfEmpty(customDefault).First();
SELECT column1 FROM table WHERE ISNUMERIC(column1) = 1
Note, as Damien_The_Unbeliever has pointed out, this will include any valid numeric type.
To filter out columns containing non-digit characters (and empty strings), you could use
SELECT column1 FROM table WHERE column1 not like '%[^0-9]%' and column1 != ''
The snippet you're showing doesn't seem to be directly responsible for the error.
This is how you can CAUSE the error:
namespace MyNameSpace
{
int i; <-- THIS NEEDS TO BE INSIDE THE CLASS
class MyClass
{
...
}
}
If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }
.
You only need:
<add name="Access-Control-Allow-Origin" value="*" />
from your web.config.afterward, add this in the Application_BeginRequest
method of Global.asax:
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin","*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept");
HttpContext.Current.Response.End();
}
I hope this help. that work for me.
As per this the default is 2 MB for your <Connector>
.
maxPostSize = The maximum size in bytes of the POST which will be handled by the container FORM URL parameter parsing. The limit can be disabled by setting this attribute to a value less than or equal to 0. If not specified, this attribute is set to 2097152 (2 megabytes).
Edit Tomcat's server.xml. In the <Connector>
element, add an attribute maxPostSize
and set a larger value (in bytes) to increase the limit.
Having said that, if this is the issue, you should have got an exception on the lines of
Post data too big
in tomcat
There is no Windows 64-bit version of Oracle Express Edition. You'll have to go for Standard/Enterprise editions.
string _connString = "metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=DATABASE;persist security info=True;user id=sa;password=YourPassword;multipleactiveresultsets=True;App=EntityFramework"";
EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder(_connString);
ctx = new Entities(_connString);
You can get the connection string from the web.config, and just set that in the EntityConnectionStringBuilder constructor, and use the EntityConnectionStringBuilder as an argument in the constructor for the context.
Cache the connection string by username. Simple example using a couple of generic methods to handle adding/retrieving from cache.
private static readonly ObjectCache cache = MemoryCache.Default;
// add to cache
AddToCache<string>(username, value);
// get from cache
string value = GetFromCache<string>(username);
if (value != null)
{
// got item, do something with it.
}
else
{
// item does not exist in cache.
}
public void AddToCache<T>(string token, T item)
{
cache.Add(token, item, DateTime.Now.AddMinutes(1));
}
public T GetFromCache<T>(string cacheKey) where T : class
{
try
{
return (T)cache[cacheKey];
}
catch
{
return null;
}
}
I agree with Justin. To elaborate, overly long lines of code are harder to read by humans and some people might have console widths that only accommodate 80 characters per line.
The style recommendation is there to ensure that the code you write can be read by as many people as possible on as many platforms as possible and as comfortably as possible.
I used this code to show the dialog at the bottom of the screen:
Dialog dlg = <code to create custom dialog>;
Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();
wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);
This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about
private void showPictureialog() {
final Dialog dialog = new Dialog(this,
android.R.style.Theme_Translucent_NoTitleBar);
// Setting dialogview
Window window = dialog.getWindow();
window.setGravity(Gravity.CENTER);
window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
dialog.setTitle(null);
dialog.setContentView(R.layout.selectpic_dialog);
dialog.setCancelable(true);
dialog.show();
}
you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment