Based on the answer @ellemayo gave, I came up with the following solution that allows for disabling of the hash tag if desired:
function updateQueryString(key, value, options) {
if (!options) options = {};
var url = options.url || location.href;
var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"), hash;
hash = url.split('#');
url = hash[0];
if (re.test(url)) {
if (typeof value !== 'undefined' && value !== null) {
url = url.replace(re, '$1' + key + "=" + value + '$2$3');
} else {
url = url.replace(re, '$1$3').replace(/(&|\?)$/, '');
}
} else if (typeof value !== 'undefined' && value !== null) {
var separator = url.indexOf('?') !== -1 ? '&' : '?';
url = url + separator + key + '=' + value;
}
if ((typeof options.hash === 'undefined' || options.hash) &&
typeof hash[1] !== 'undefined' && hash[1] !== null)
url += '#' + hash[1];
return url;
}
Call it like this:
updateQueryString('foo', 'bar', {
url: 'http://my.example.com#hash',
hash: false
});
Results in:
http://my.example.com?foo=bar
check the speling and Upper/Lower case of term ""
when ever we write @RenderSection("name", required: false) make sure that the razor view Contains a section @section name{} so check the speling and Upper/Lower case of term "" Correct in this case is "Scripts"
In SQL Server 2012 and higher, this will format a number with commas:
select format([Number], 'N0')
You can also change 0
to the number of decimal places you want.
This answer is for people who see cloning a function as the answer to their desired usage, but who many not actually need to clone a function, because what they really want is simply to be able to attach different properties to the same function, but only declare that function one time.
Do this by creating a function-creating function:
function createFunction(param1, param2) {
function doSomething() {
console.log('in the function!');
}
// Assign properties to `doSomething` if desired, perhaps based
// on the arguments passed into `param1` and `param2`. Or,
// even return a different function from among a group of them.
return doSomething;
};
let a = createFunction();
a.something = 1;
let b = createFunction();
b.something = 2; // does not overwrite a.something
console.log(a.something);
a();
b();
This is not exactly the same as you have outlined, however, it depends on how you want to use the function you're wishing to clone. This also uses more memory because it actually creates multiple copies of the function, once per invocation. However, this technique may solve some people's use case without the need for a complicated clone
function.
These detailed explanations are great, but the OP's (and my) confusion could be resolved with one sentence: "Direct DNS to your GitHub username or organization, ignoring the specific project, and add the appropriate CNAME files in your project repositories: GitHub will send the right DNS to the right project based on files in the respository."
I made this short example which also works.
#include <iostream>
#include <type_traits>
class foo;
class bar;
template<class T>
struct is_bar
{
template<class Q = T>
typename std::enable_if<std::is_same<Q, bar>::value, bool>::type check()
{
return true;
}
template<class Q = T>
typename std::enable_if<!std::is_same<Q, bar>::value, bool>::type check()
{
return false;
}
};
int main()
{
is_bar<foo> foo_is_bar;
is_bar<bar> bar_is_bar;
if (!foo_is_bar.check() && bar_is_bar.check())
std::cout << "It works!" << std::endl;
return 0;
}
Comment if you want me to elaborate. I think the code is more or less self-explanatory, but then again I made it so I might be wrong :)
You can see it in action here.
You can use the include?
method:
my_string = "abcdefg"
if my_string.include? "cde"
puts "String includes 'cde'"
end
If all of the above fails, try to convert to UNIX Line Endings, or do:
brew install dos2unix
sudo dos2unix -c mac /private/etc/hosts
Maybe the hosts encoding is wrong.
hope this helps
I found this https://typescriptbcl.codeplex.com/SourceControl/latest
here is the Guid version they have in case the link does not work later.
module System {
export class Guid {
constructor (public guid: string) {
this._guid = guid;
}
private _guid: string;
public ToString(): string {
return this.guid;
}
// Static member
static MakeNew(): Guid {
var result: string;
var i: string;
var j: number;
result = "";
for (j = 0; j < 32; j++) {
if (j == 8 || j == 12 || j == 16 || j == 20)
result = result + '-';
i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
result = result + i;
}
return new Guid(result);
}
}
}
May I suggest a more accurate simple answer to the original question below
SELECT
KEYS.table_schema, KEYS.table_name, KEYS.column_name, KEYS.ORDINAL_POSITION
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE keys
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS CONS
ON cons.TABLE_SCHEMA = keys.TABLE_SCHEMA
AND cons.TABLE_NAME = keys.TABLE_NAME
AND cons.CONSTRAINT_NAME = keys.CONSTRAINT_NAME
WHERE cons.CONSTRAINT_TYPE = 'PRIMARY KEY'
Notes:
if (file.split(".")[1] == "mp3"):
print "its mp3"
elif (file.split(".")[1] == "flac"):
print "its flac"
else:
print "not compat"
Case 1 : Yes, this works fine.
Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.
Share and enjoy.
That's HTML Encoding. There's no native javascript function to do that, but you can google and get some nicely done up ones.
E.g. http://sanzon.wordpress.com/2008/05/01/neat-little-html-encoding-trick-in-javascript/
EDIT:
This is what I've tested:
var div = document.createElement('div');
var text = document.createTextNode('<htmltag/>');
div.appendChild(text);
console.log(div.innerHTML);
Output: <htmltag/>
public static class AsyncHelper
{
private static readonly TaskFactory _taskFactory = new
TaskFactory(CancellationToken.None,
TaskCreationOptions.None,
TaskContinuationOptions.None,
TaskScheduler.Default);
public static TResult RunSync<TResult>(Func<Task<TResult>> func)
=> _taskFactory
.StartNew(func)
.Unwrap()
.GetAwaiter()
.GetResult();
public static void RunSync(Func<Task> func)
=> _taskFactory
.StartNew(func)
.Unwrap()
.GetAwaiter()
.GetResult();
}
Then
AsyncHelper.RunSync(() => DoAsyncStuff());
if you use that class pass your async method as parameter you can call the async methods from sync methods in a safe way.
it's explained here : https://cpratt.co/async-tips-tricks/
Keep in mind that a PDOStatement
is Traversable
. Given a query:
$query = $dbh->query('
SELECT
*
FROM
test
');
It can be iterated over:
$it = new IteratorIterator($query);
echo '<p>', iterator_count($it), ' items</p>';
// Have to run the query again unfortunately
$query->execute();
foreach ($query as $row) {
echo '<p>', $row['title'], '</p>';
}
Or you can do something like this:
$it = new IteratorIterator($query);
$it->rewind();
if ($it->valid()) {
do {
$row = $it->current();
echo '<p>', $row['title'], '</p>';
$it->next();
} while ($it->valid());
} else {
echo '<p>No results</p>';
}
You may get the following error while creating an optimized production build when using query-string module.
Failed to minify the code from this file: ./node_modules/query-string/index.js:8
To overcome this, kindly use the alternative module called stringquery which does the same process well without any issues while running the build.
import querySearch from "stringquery";
var query = querySearch(this.props.location.search);
I spent multiple days on this issue. I finally got it resolved with the following combination of suggestions from this post.
bin\
instead of bin\x64\Debug
. I had tried this several times already before I changed the platform target. It never made a difference other than getting an error that it failed to load the assembly because of an invalid format. To be clear, I had to do both of these before it started working. I had tried them individually multiple times but it never fixed it until I did both.
If I change either one of these settings back to the original, I get the same error again, despite having run Clean Solution, and manually deleting everything in the bin
directory.
To parse a Date from a String you can choose which format you would like it to have. For example:
public Date StringToDate(String s){
Date result = null;
try{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
result = dateFormat.parse(s);
}
catch(ParseException e){
e.printStackTrace();
}
return result ;
}
If you would like to use this method now, you will have to use something like this
Date date = StringToDate("2015-12-06 17:03:00");
For more explanation you should check out http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
the easiest way is using command line. Just type in directory of your .xsd file:
xjc myFile.xsd.
So, the java will generate all Pojos.
In each html template I just add the following meta tags at the top:
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
In my understanding each template is free standing therefore it does not inherit meta no caching rules setup in the index.html file.
String phoneNumber = "0123456789";
String message = "Hello World!";
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
Include the following permission in your AndroidManifest.xml file
<uses-permission android:name="android.permission.SEND_SMS" />
<script type="text/javascript">
var i=0;
function increase()
{
i++;
return false;
}</script><input type="button" onclick="increase();">
If, like me, you've come to this topic via Razor components as you're learning Blazor, then you'll find you need to think a little more outside of the box to solve this problem. It's a bit of a minefield if (also like me) Blazor is your first forray into the MVC-type world, as the documentation isn't as helpful for such 'menial' tasks.
So, at the time of writing, you cannot achieve this using vanilla Blazor/Razor without embedding an MVC controller to handle the file download part an example of which is as below:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;
[Route("api/[controller]")]
[ApiController]
public class FileHandlingController : ControllerBase
{
[HttpGet]
public FileContentResult Download(int attachmentId)
{
TaskAttachment taskFile = null;
if (attachmentId > 0)
{
// taskFile = <your code to get the file>
// which assumes it's an object with relevant properties as required below
if (taskFile != null)
{
var cd = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileNameStar = taskFile.Filename
};
Response.Headers.Add(HeaderNames.ContentDisposition, cd.ToString());
}
}
return new FileContentResult(taskFile?.FileData, taskFile?.FileContentType);
}
}
Next, make sure your application startup (Startup.cs) is configured to correctly use MVC and has the following line present (add it if not):
services.AddMvc();
.. and then finally modify your component to link to the controller, for example (iterative based example using a custom class):
<tbody>
@foreach (var attachment in yourAttachments)
{
<tr>
<td><a href="api/[email protected]" target="_blank">@attachment.Filename</a> </td>
<td>@attachment.CreatedUser</td>
<td>@attachment.Created?.ToString("dd MMM yyyy")</td>
<td><ul><li class="oi oi-circle-x delete-attachment"></li></ul></td>
</tr>
}
</tbody>
Hopefully this helps anyone who struggled (like me!) to get an appropriate answer to this seemingly simple question in the realms of Blazor…!
We can use the IIFE to swap two value without extra parameter
var a = 5, b =8;_x000D_
b = (function(a){ _x000D_
return a _x000D_
}(a, a=b));_x000D_
_x000D_
document.write("a: " + a+ " b: "+ b);
_x000D_
I hope this saves someone some hours of pain.
Install jquery with npm
npm install jquery --save
Add typings
npm install --save-dev @types/jquery
Add scripts to angular-cli.json
"apps": [{
...
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
],
...
}]
Build project and serve
ng build
Hope this helps! Enjoy coding
This works for me :
$scope.array1 = $scope.array1.concat(array2)
In your case it would be :
$scope.actions.data = $scope.actions.data.concat(data)
In my case, I was getting the error because I upgraded from Laravel Mix Version 2 to 5.
In Laravel Mix Version 2, you import vue components as follows:
Vue.component(
'example-component',
require('./components/ExampleComponent.vue')
);
In Laravel Mix Version 5, you have to import your components as follows:
import ExampleComponent from './components/ExampleComponent.vue';
Vue.component('example-component', ExampleComponent);
Here is the documentation: https://laravel-mix.com/docs/5.0/upgrade
Better, to improve performance of your app, you can lazy load your components as follows:
Vue.component("ExampleComponent", () => import("./components/ExampleComponent"));
Use Measure-Command
Example
Measure-Command { <your command here> | Out-Host }
The pipe to Out-Host
allows you to see the output of the command, which is
otherwise consumed by Measure-Command
.
time1
is the key of the most outer dictionary, eg, feb2012
. So then you're trying to index the string, but you can only do this with integers. I think what you wanted was:
for info in courses[time1][course]:
As you're going through each dictionary, you must add another nest.
This is so simple to do on a PC: Windows OS: Send the os a command to change the text: import os
os.system('color a') #green text
print 'I like green'
raw_input('do you?')
im
is "image process name"
example /f /im notepad.exe
is specified to kill image process name (program) notepad.exe
In your controller, you are using an http
scheme, but I think you should be using a ws
scheme, as you are using websockets. Try to use ws://localhost:3000
in your connect function.
You have to close that application first. There is no way to delete it, if it's used by some application.
UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.
There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.
Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.
Newest Python 3.8.4 or higher should able to support https protocol out of box. If you still have old python installation on your pc - either download & install python3 manually, or using Chocolatey:
If you don't have Chocolatey, install it - from here: https://chocolatey.org/docs/installation
You can just copy paste one command line liner and execute it from command prompt with elevated priviledges.
choco install python3
if you don't have python3 installed, or you you have it installed - then:
choco upgrade python3
Notice also that you can use also anaconda distribution, as it has built-in python with https support, but this rather ancient instructions, no need to follow them anymore.
Install anaconda, using command line:
choco install anaconda3
Set environment variables:
set PATH=C:\tools\Anaconda3\Scripts;C:\tools\Anaconda3;C:\tools\Anaconda3\Library\bin;%PATH%
and then run command which failed. In my case it was:
pip install conan
Anaconda uses separate python installation, and pip is also anaconda specific.
to make it simple, just add a class="form-inline"
before the input.
example:
<div class="col-md-4 form-inline"> //add the class here...
<label>Lot Size:</label>
<input type="text" value="" name="" class="form-control" >
</div>
Half a decade later we have a built-in way for it! For modern browsers I would use:
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;_x000D_
console.log(tz);
_x000D_
This returns a IANA timezone string, but not the offset. Learn more at the MDN reference.
Compatibility table - as of March 2019, works for 90% of the browsers in use globally. Doesn't work on Internet Explorer.
This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.
In standard SQL one would write:
SELECT t0.foo, t1.bar
FROM FIRST_TABLE t0
RIGHT OUTER JOIN SECOND_TABLE t1;
Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :
Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]
Super late here and I still couldn't uninstall using sudo
as the other answers suggest. What did it for me was checking where cordova
was installed by running
which cordova
it will output something like this
/usr/local/bin/
then removing by
rm -rf /usr/local/bin/cordova
You should always return the same type on all case condition:
In the first one you have an character and on the else you have an int.
You can use:
Select convert(varchar(11),isnull(totalamount,0))
or if you want with your solution:
Case when total_amount = 0 then '0'
else convert(varchar(11),isnull(total_amount, 0))
end as total_amount
process.cwd()
returns directory where command has been executed (not directory of the node package) if it's has not been changed by 'process.chdir' inside of application.__filename
returns absolute path to file where it is placed.__dirname
returns absolute path to directory of __filename
.If you need to load files from your module directory you need to use relative paths.
require('../lib/test');
instead of
var lib = path.join(path.dirname(fs.realpathSync(__filename)), '../lib');
require(lib + '/test');
It's always relative to file where it called from and don't depend on current work dir.
Using EntityManager em;
public User getUserById(Long id) {
return em.getReference(User.class, id);
}
if((pswd.length<6 || pswd.length>12) || pswd == ""){
document.getElementById("passwordloc").innerHTML="character should be between 6-12 characters"; status=false;
}
else {
if(pswd != pswdcnf) {
document.getElementById("passwordconfirm").innerHTML="password doesnt matched"; status=true;
} else {
document.getElementById("passwordconfirm").innerHTML="password matche";
document.getElementById("passwordloc").innerHTML = '';
}
}
The <ul>
is by default a block element, make it inline-block
instead:
.navigation-bar ul {
padding: 0px;
margin: 0px;
text-align: center;
display:inline-block;
vertical-align:top;
}
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>
the code behind for the window:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModelBase();
}
}
The ViewModel:
public class ViewModelBase
{
private ICommand _clickCommand;
public ICommand ClickCommand
{
get
{
return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
}
}
public bool CanExecute
{
get
{
// check if executing is allowed, i.e., validate, check if a process is running, etc.
return true/false;
}
}
public void MyAction()
{
}
}
Command Handler:
public class CommandHandler : ICommand
{
private Action _action;
private Func<bool> _canExecute;
/// <summary>
/// Creates instance of the command handler
/// </summary>
/// <param name="action">Action to be executed by the command</param>
/// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
public CommandHandler(Action action, Func<bool> canExecute)
{
_action = action;
_canExecute = canExecute;
}
/// <summary>
/// Wires CanExecuteChanged event
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Forcess checking if execute is allowed
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return _canExecute.Invoke();
}
public void Execute(object parameter)
{
_action();
}
}
I hope this will give you the idea.
In Django
1 : we have default field with name "id" which is auto increment.
2 : You can define a auto increment field using AutoField
field.
class Order(models.Model): auto_increment_id = models.AutoField(primary_key=True) #you use primary_key = True if you do not want to use default field "id" given by django to your model
+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ | core_order | CREATE TABLE `core_order` ( `auto_increment_id` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`auto_increment_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 | +------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.01 sec)
class Order(models.Model): dd_date = models.DateTimeField(auto_now_add=True)
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+ | core_order | CREATE TABLE `core_order` ( `id` int(11) NOT NULL AUTO_INCREMENT, `dd_date` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 | +-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
Collections.synchronizedMap()
guarantees that each atomic operation you want to run on the map will be synchronized.
Running two (or more) operations on the map however, must be synchronized in a block. So yes - you are synchronizing correctly.
When I downloaded chromedriver.exe I just move it in PATH folder C:\Windows\System32\chromedriver.exe and had exact same problem.
For me solution was to just change folder in PATH, so I just moved it at Pycharm Community bin folder that was also in PATH. ex:
For generate Model , controller with resources and migration best command is:
php artisan make:model ModelName -m -cr
The best way is to add the directory to the load path and then require
the basename of each file. This is because you want to avoid accidentally requiring the same file twice -- often not the intended behavior. Whether a file will be loaded or not is dependent on whether require
has seen the path passed to it before. For example, this simple irb session shows that you can mistakenly require and load the same file twice.
$ irb
irb(main):001:0> require 'test'
=> true
irb(main):002:0> require './test'
=> true
irb(main):003:0> require './test.rb'
=> false
irb(main):004:0> require 'test'
=> false
Note that the first two lines return true
meaning the same file was loaded both times. When paths are used, even if the paths point to the same location, require
doesn't know that the file was already required.
Here instead, we add a directory to the load path and then require the basename of each *.rb file within.
dir = "/path/to/directory"
$LOAD_PATH.unshift(dir)
Dir[File.join(dir, "*.rb")].each {|file| require File.basename(file) }
If you don't care about the file being required more than once, or your intention is just to load the contents of the file, perhaps load
should be used instead of require
. Use load in this case, because it better expresses what you're trying to accomplish. For example:
Dir["/path/to/directory/*.rb"].each {|file| load file }
The proposed solution is just to much work for something that can be done like this:
Get-Alias -Definition Write*
For python2 and python3 compatibility, you can use:
# Python 2 and 3
from imp import reload
reload(mymodule)
Something to be aware of, the $_SESSION
variables are still set in the same page after calling session_destroy()
where as this is not the case when using unset($_SESSION)
or $_SESSION = array()
. Also, unset($_SESSION)
blows away the $_SESSION
superglobal so only do this when you're destroying a session.
With all that said, it's best to do like the PHP docs has it in the first example for session_destroy()
.
Yes it is true.
If you create two instance of your class
Test t1 = new Test();
Test t2 = new Test();
Then t1.foo and t2.foo both synchronize on the same static object and hence block each other.
As it is being mentioned in pir's comment - the .apply(lambda el: scale.fit_transform(el))
method will produce the following warning:
DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
Converting your columns to numpy arrays should do the job (I prefer StandardScaler):
from sklearn.preprocessing import StandardScaler
scale = StandardScaler()
dfTest[['A','B','C']] = scale.fit_transform(dfTest[['A','B','C']].as_matrix())
-- Edit Nov 2018 (Tested for pandas 0.23.4)--
As Rob Murray mentions in the comments, in the current (v0.23.4) version of pandas .as_matrix()
returns FutureWarning
. Therefore, it should be replaced by .values
:
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit_transform(dfTest[['A','B']].values)
-- Edit May 2019 (Tested for pandas 0.24.2)--
As joelostblom mentions in the comments, "Since 0.24.0
, it is recommended to use .to_numpy()
instead of .values
."
Updated example:
import pandas as pd
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
dfTest = pd.DataFrame({
'A':[14.00,90.20,90.95,96.27,91.21],
'B':[103.02,107.26,110.35,114.23,114.68],
'C':['big','small','big','small','small']
})
dfTest[['A', 'B']] = scaler.fit_transform(dfTest[['A','B']].to_numpy())
dfTest
A B C
0 -1.995290 -1.571117 big
1 0.436356 -0.603995 small
2 0.460289 0.100818 big
3 0.630058 0.985826 small
4 0.468586 1.088469 small
Do you want the JDK or the JRE? Anyways, I had this problem too, a few weeks ago. I followed the instructions here and it worked:
http://www.backtrack-linux.org/wiki/index.php/Java_Install
root@bt:~# killall -9 /opt/firefox/firefox-bin
root@bt:~# mkdir /opt/java
root@bt:~# mv -f jre1.7.0_05/ /opt/java/
root@bt:~# update-alternatives --install /usr/bin/java java /opt/java/jre1.7.0_05/bin/java 1
root@bt:~# update-alternatives --set java /opt/java/jre1.7.0_05/bin/java
root@bt:~# export JAVA_HOME="/opt/java/jre1.7.0_05"
For Java 7 (32 bit)
root@bt:~# ln -sf $JAVA_HOME/lib/i386/libnpjp2.so /usr/lib/mozilla/plugins/
For Java 8 (64 bit)
root@bt:~# ln -sf $JAVA_HOME/jre/lib/amd64/libnpjp2.so /usr/lib/mozilla/plugins/
root@bt:~# firefox http://java.com/en/download/testjava.jsp
You can pull the .apks from any of them:
adb pull /mnt/asec
When not told otherwise commands take over the foreground. You only have one "foreground" process running in a single shell session. The & symbol instructs commands to run in a background process and immediately returns to the command line for additional commands.
sh my_script.sh &
A background process will not stay alive after the shell session is closed. SIGHUP terminates all running processes. By default anyway. If your command is long-running or runs indefinitely (ie: microservice) you need to pr-pend it with nohup so it remains running after you disconnect from the session:
nohup sh my_script.sh &
EDIT: There does appear to be a gray area regarding the closing of background processes when & is used. Just be aware that the shell may close your process depending on your OS and local configurations (particularly on CENTOS/RHEL): https://serverfault.com/a/117157.
when you start in cygwin, you are in your $HOME, like in unix generally, which maps to c:/cygwin/home/$YOURNAME by default. So you could put everything there.
You can also access the c: drive from cygwin through /cygdrive/c/ (e.g. /cygdrive/c/Documents anb Settings/yourname/Desktop).
Here are the steps to do it correctly:
First of all, declare an instance of TextView in your MainActivity.java as follows:
TextView mTextView;
Set some text DYNAMICALLY(if you want) as follows:
mTextView.setText("some_text");
Now, to set the background color, you need to define your own color in the res->values->colors.xml file as follows:
<resources>
<color name="my_color">#000000</color>
</resources>
You can now use "my_color" color in your java file to set the background dynamically as follows:
mTextView.setBackgroundResource(R.color.my_color);
Change appBase
in server.xml
If you want to keep both previous webapps and a new one, you can use another Host instance with another port defined in tomcat.
You can call ViewController this way, If you want with NavigationController
1.In current Screen : Load new screen
VerifyExpViewController *addProjectViewController = [[VerifyExpViewController alloc] init];
[self.navigationController pushViewController:addProjectViewController animated:YES];
2.1 In Loaded View : add below in .h file
@interface VerifyExpViewController : UIViewController <UINavigationControllerDelegate>
2.2 In Loaded View : add below in .m file
@implementation VerifyExpViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationController.delegate = self;
[self setNavigationBar];
}
-(void)setNavigationBar
{
self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
self.navigationController.navigationBar.translucent = YES;
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"B_topbar.png"] forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor]};
self.navigationItem.hidesBackButton = YES;
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Btn_topback.png"] style:UIBarButtonItemStylePlain target:self action:@selector(onBackButtonTap:)];
self.navigationItem.leftBarButtonItem.tintColor = [UIColor lightGrayColor];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Save.png"] style:UIBarButtonItemStylePlain target:self action:@selector(onSaveButtonTap:)];
self.navigationItem.rightBarButtonItem.tintColor = [UIColor lightGrayColor];
}
-(void)onBackButtonTap:(id)sender
{
[self.navigationController popViewControllerAnimated:YES];
}
-(IBAction)onSaveButtonTap:(id)sender
{
//todo for save button
}
@end
Hope this will be useful for someone there :)
Update:
As of Xcode 7.1, you don't need to manually enter the NSAppTransportSecurity
Dictionary in the info.plist
.
It will now autocomplete for you, realize it's a dictionary, and then autocomplete the Allows Arbitrary
Loads as well.
info.plist screenshot
StringBuilder b = new StringBuilder();
Scanner s = new Scanner(System.in);
String n = s.nextLine();
for(int i = 0; i < n.length(); i++) {
char c = n.charAt(i);
if(Character.isLowerCase(c) == true) {
b.append(String.valueOf(c).toUpperCase());
}
else {
b.append(String.valueOf(c).toLowerCase());
}
}
System.out.println(b);
AppCompatActivity
At the time of this writing (check the link to confirm it is still true), the Android Documentation recommends using AppCompatActivity
if you are using an App Bar.
This is the rational given:
Beginning with Android 3.0 (API level 11), all activities that use the default theme have an ActionBar as an app bar. However, app bar features have gradually been added to the native ActionBar over various Android releases. As a result, the native ActionBar behaves differently depending on what version of the Android system a device may be using. By contrast, the most recent features are added to the support library's version of Toolbar, and they are available on any device that can use the support library.
For this reason, you should use the support library's Toolbar class to implement your activities' app bars. Using the support library's toolbar helps ensure that your app will have consistent behavior across the widest range of devices. For example, the Toolbar widget provides a material design experience on devices running Android 2.1 (API level 7) or later, but the native action bar doesn't support material design unless the device is running Android 5.0 (API level 21) or later.
The general directions for adding a ToolBar are
AppCompatActivity
NoActionBar
.ToolBar
to each activity's xml layout.ToolBar
in each activity's onCreate
.See the documentation directions for more details. They are quite clear and helpful.
Please check that you have <?PHP
at the top of your code. If you forget it, this error will appear.
If I need only to highlight the first word as a command, I often use properties
:
```properties
npm run build
```
I obtain something like:
npm run build
var y = $(window).scrollTop(); //your current y position on the page
$(window).scrollTop(y+150);
If you have <deployment retail="true"/>
in your .NET Framework's machine.config, you won't see detailed error messages. Make sure that setting is false, or not present.
Here is my Code which runs with O(1). Here I used vector pair which contain the value which pushed and also contain the minimum value up to this pushed value.
Here is my version of C++ implementation.
vector<pair<int,int> >A;
int sz=0; // to keep track of the size of vector
class MinStack
{
public:
MinStack()
{
A.clear();
sz=0;
}
void push(int x)
{
int mn=(sz==0)?x: min(A[sz-1].second,x); //find the minimum value upto this pushed value
A.push_back(make_pair(x,mn));
sz++; // increment the size
}
void pop()
{
if(sz==0) return;
A.pop_back(); // pop the last inserted element
sz--; // decrement size
}
int top()
{
if(sz==0) return -1; // if stack empty return -1
return A[sz-1].first; // return the top element
}
int getMin()
{
if(sz==0) return -1;
return A[sz-1].second; // return the minimum value at sz-1
}
};
Heres a solution.
Setup a boolean sitiation using blur and focus
//see if our window is active
window.isActive = true;
$(window).focus(function() { this.isActive = true; });
$(window).blur(function() { this.isActive = false; });
Bind your link with a jquery click handler that calls something like this.
function startMyApp(){
document.location = 'fb://';
setTimeout( function(){
if (window.isActive) {
document.location = 'http://facebook.com';
}
}, 1000);
}
if the app opens, we'll lose focus on the window and the timer ends. otherwise we get nothing and we load the usual facebook url.
[f,x]=hist(data)
The area for each individual bar is height*width. Since MATLAB will choose equidistant points for the bars, so the width is:
delta_x = x(2) - x(1)
Now if we sum up all the individual bars the total area will come out as
A=sum(f)*delta_x
So the correctly scaled plot is obtained by
bar(x, f/sum(f)/(x(2)-x(1)))
Do:
con.query('SET GLOBAL connect_timeout=28800')
con.query('SET GLOBAL interactive_timeout=28800')
con.query('SET GLOBAL wait_timeout=28800')
Parameter meaning (taken from MySQL Workbench in Navigator: Instance > Options File > Tab "Networking" > Section "Timeout Settings")
BTW: 28800 seconds are 8 hours, so for a 10 hour execution time these values should be actually higher.
I know this is a very old question but feel this adds a valuable alternative of how to deal with the console issue. Place the following code before any call to console.* (so your very first script).
// Avoid `console` errors in browsers that lack a console.
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
Reference:
https://github.com/h5bp/html5-boilerplate/blob/v5.0.0/dist/js/plugins.js
elem.classList.add("first");
elem.classList.add("second");
elem.classList.add("third");
is equal
elem.classList.add("first","second","third");
You can use a simple, low-cost USB port reader like this test connects directly to your Android device; it has a utility app and an SDK you can use for app development: https://www.atlasrfidstore.com/sls-rfid-smartmicro-android-micro-usb-reader/
If you have Response Like This:
{
"registeration_method": "email",
"is_stucked": true,
"individual": {
"id": 24099,
"first_name": "ahmad",
"last_name": "zozoz",
"email": null,
"mobile_number": null,
"confirmed": false,
"avatar": "http://abc-abc-xyz.amazonaws.com/images/placeholder-profile.png",
"doctor_request_status": 0
},
"max_number_of_confirmation_trials": 4,
"max_number_of_invalid_confirmation_trials": 12
}
and you want to check for value is_stucked
which will be read as AnyObject, all you have to do is this
if let isStucked = response["is_stucked"] as? Bool{
if isStucked{
print("is Stucked")
}
else{
print("Not Stucked")
}
}
Seems based on benchmarks at JSPerf that using +=
is the fastest method, though not necessarily in every browser.
For building strings in the DOM, it seems to be better to concatenate the string first and then add to the DOM, rather then iteratively add it to the dom. You should benchmark your own case though.
(Thanks @zAlbee for correction)
Add System.IO.Compression.ZipFile as nuget reference it is working
This fixed it for me: Open maven projects tab on the right. Add the pom if not yet present, then click refresh on the top left of the tab.
Basically I solved it by NOT-ing the isReplyFormOpen
value whenever it is clicked:
<a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>
<div ng-init="isReplyFormOpen = false" ng-show="isReplyFormOpen" id="replyForm">
<!-- Form -->
</div>
Two ways to implement a Caesar Cipher:
Option 1: Change chars to ASCII numbers, then you can increase the value, then revert it back to the new character.
Option 2: Use a Map map each letter to a digit like this.
A - 0
B - 1
C - 2
etc...
With a map you don't have to re-calculate the shift every time. Then you can change to and from plaintext to encrypted by following map.
If you are using postgres use text wherever you can, unless you have a size constraint since there is no performance penalty for text vs varchar
There is no performance difference among these three types, apart from increased storage space when using the blank-padded type, and a few extra CPU cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, there is no such advantage in PostgreSQL; in fact character(n) is usually the slowest of the three because of its additional storage costs. In most situations text or character varying should be used instead
This will do it:
wc -c filename
If you want only the count without the filename being repeated in the output:
wc -c < filename
Edit:
Use -m
to count character instead of bytes (as shown in Sébastien's answer).
If you're fetching JSON, use $.getJSON() so it automatically converts the JSON to a JS Object.
run this: conda install python-graphviz
You can use SUBSTRING
and CONVERT
:
SELECT stuff
FROM table
WHERE conditions
ORDER BY CONVERT(SUBSTRING(name_column, 6), SIGNED INTEGER);
Where name_column
is the column with the "name-" values. The SUBSTRING
removes everything up before the sixth character (i.e. the "name-" prefix) and then the CONVERT
converts the left over to a real integer.
UPDATE: Given the changing circumstances in the comments (i.e. the prefix can be anything), you'll have to throw a LOCATE
in the mix:
ORDER BY CONVERT(SUBSTRING(name_column, LOCATE('-', name_column) + 1), SIGNED INTEGER);
This of course assumes that the non-numeric prefix doesn't have any hyphens in it but the relevant comment says that:
name
can be any sequence of letters
so that should be a safe assumption.
nohup some_command &> nohup2.out &
and voila.
Older syntax for Bash version < 4:
nohup some_command > nohup2.out 2>&1 &
Some compilers support compound literals as an extention, allowing this construct:
Customer customerRecords[2];
customerRecords[0] = (Customer){25, "Bob Jones"};
customerRecords[1] = (Customer){26, "Jim Smith"};
But it's rather unportable.
The precise meaning of these terms is going to depend a lot on what language/system/universe you are talking about.
In HTML/XML, an attribute is the part of a tag with an equals sign and a value, and property doesn't mean anything, for example.
So we need more information about what domain you're discussing.
In the numpy README.txt file, it says
After installation, tests can be run with:
python -c 'import numpy; numpy.test()'
This should be a sufficient test for proper installation.
Tables displaying the issue:
and ==
Moral of the story use ===
table generation credit: https://github.com/dorey/JavaScript-Equality-Table
Changing your passwords is a good idea, but for the process of removing password's from your repo's history, I recommend the BFG Repo-Cleaner, a faster, simpler alternative to git-filter-branch
explicitly designed for removing private data from Git repos.
Create a private.txt
file listing the passwords, etc, that you want to remove (one entry per line) and then run this command:
$ java -jar bfg.jar --replace-text private.txt my-repo.git
All files under a threshold size (1MB by default) in your repo's history will be scanned, and any matching string (that isn't in your latest commit) will be replaced with the string "***REMOVED***". You can then use git gc
to clean away the dead data:
$ git gc --prune=now --aggressive
The BFG is typically 10-50x faster than running git-filter-branch
and the options are simplified and tailored around these two common use-cases:
Full disclosure: I'm the author of the BFG Repo-Cleaner.
After you changed a Mac which are not the origin one who created the disitribution certificate, you will missing the private key.Just delete the origin certificate and recreate a new one, that works for me~
ihave followed the instruction of heroku logs img https://devcenter.heroku.com/articles/buildpacks#detection-failure ( use cmd: heroku logs -> show your error) then do the cmd: "heroku buildpacks:clear". finally, it worked for me!
task :invoke_another_task do
# some code
Rake::Task["another:task"].invoke
end
The key difference: NSMutableDictionary can be modified in place, NSDictionary cannot. This is true for all the other NSMutable* classes in Cocoa. NSMutableDictionary is a subclass of NSDictionary, so everything you can do with NSDictionary you can do with both. However, NSMutableDictionary also adds complementary methods to modify things in place, such as the method setObject:forKey:
.
You can convert between the two like this:
NSMutableDictionary *mutable = [[dict mutableCopy] autorelease];
NSDictionary *dict = [[mutable copy] autorelease];
Presumably you want to store data by writing it to a file. NSDictionary has a method to do this (which also works with NSMutableDictionary):
BOOL success = [dict writeToFile:@"/file/path" atomically:YES];
To read a dictionary from a file, there's a corresponding method:
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"/file/path"];
If you want to read the file as an NSMutableDictionary, simply use:
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/file/path"];
Hemant and Vikram's answers didn't quite work for me outright in Chrome. The event.preventDefault(); script prevented the the page from submitting regardless of passing or failing the validation. Instead, I had to move the event.preventDefault(); into the if statement as follows:
if(check if your conditions are not satisfying)
{
event.preventDefault();
alert("validation failed false");
returnToPreviousPage();
return false;
}
alert("validations passed");
return true;
}
Thanks to Hemant and Vikram for putting me on the right track.
To add on to KaZ answer, Whenever I am making a QML application I tend to add this to the main c++
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QStandardPaths>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
// get the applications dir path and expose it to QML
QUrl appPath(QString("%1").arg(app.applicationDirPath()));
engine.rootContext()->setContextProperty("appPath", appPath);
// Get the QStandardPaths home location and expose it to QML
QUrl userPath;
const QStringList usersLocation = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
if (usersLocation.isEmpty())
userPath = appPath.resolved(QUrl("/home/"));
else
userPath = QString("%1").arg(usersLocation.first());
engine.rootContext()->setContextProperty("userPath", userPath);
QUrl imagePath;
const QStringList picturesLocation = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation);
if (picturesLocation.isEmpty())
imagePath = appPath.resolved(QUrl("images"));
else
imagePath = QString("%1").arg(picturesLocation.first());
engine.rootContext()->setContextProperty("imagePath", imagePath);
QUrl videoPath;
const QStringList moviesLocation = QStandardPaths::standardLocations(QStandardPaths::MoviesLocation);
if (moviesLocation.isEmpty())
videoPath = appPath.resolved(QUrl("./"));
else
videoPath = QString("%1").arg(moviesLocation.first());
engine.rootContext()->setContextProperty("videoPath", videoPath);
QUrl homePath;
const QStringList homesLocation = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
if (homesLocation.isEmpty())
homePath = appPath.resolved(QUrl("/"));
else
homePath = QString("%1").arg(homesLocation.first());
engine.rootContext()->setContextProperty("homePath", homePath);
QUrl desktopPath;
const QStringList desktopsLocation = QStandardPaths::standardLocations(QStandardPaths::DesktopLocation);
if (desktopsLocation.isEmpty())
desktopPath = appPath.resolved(QUrl("/"));
else
desktopPath = QString("%1").arg(desktopsLocation.first());
engine.rootContext()->setContextProperty("desktopPath", desktopPath);
QUrl docPath;
const QStringList docsLocation = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation);
if (docsLocation.isEmpty())
docPath = appPath.resolved(QUrl("/"));
else
docPath = QString("%1").arg(docsLocation.first());
engine.rootContext()->setContextProperty("docPath", docPath);
QUrl tempPath;
const QStringList tempsLocation = QStandardPaths::standardLocations(QStandardPaths::TempLocation);
if (tempsLocation.isEmpty())
tempPath = appPath.resolved(QUrl("/"));
else
tempPath = QString("%1").arg(tempsLocation.first());
engine.rootContext()->setContextProperty("tempPath", tempPath);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
Using it in QML
....
........
............
Text{
text:"This is the applications path: " + appPath
+ "\nThis is the users home directory: " + homePath
+ "\nThis is the Desktop path: " desktopPath;
}
If I use exit()
in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing.
See here
But sys.exit()
is better in this case. It closes the program and doesn't create any dialogue box.
Why not cp
to location 1, then mv
to location 2. This takes care of "removing" the original.
And no, it's not the correct syntax. |
is used to "pipe" output from one program and turn it into input for the next program. What you want is ;
, which seperates multiple commands.
cp file1 file2 ; cp file1 file3 ; rm file1
If you require that the individual commands MUST succeed before the next can be started, then you'd use &&
instead:
cp file1 file2 && cp file1 file3 && rm file1
That way, if either of the cp
commands fails, the rm
will not run.
This can be done without the use of hidden field. You have to take benefit of the JQuerys ability to make custom attributes on run time.
('#selector').autocomplete({
source: url,
select: function (event, ui) {
$("#txtAllowSearch").val(ui.item.label); // display the selected text
$("#txtAllowSearch").attr('item_id',ui.item.value); // save selected id to hidden input
}
});
$('#button').click(function() {
alert($("#txtAllowSearch").attr('item_id')); // get the id from the hidden input
});
I was facing the same issue, and it drove me up the wall. The issue ended up to be that the .idea folder was ALREADY commited into the repo previously, and so they were being tracked by git regardless of whether you ignored them or not. I would recommend the following, after closing RubyMine/IntelliJ or whatever IDE you are using:
mv .idea ../.idea_backup
rm .idea # in case you forgot to close your IDE
git rm -r .idea
git commit -m "Remove .idea from repo"
mv ../.idea_backup .idea
After than make sure to ignore .idea in your .gitignore
Although it is sufficient to ignore it in the repository's .gitignore, I would suggest that you ignore your IDE's dotfiles globally.
Otherwise you will have to add it to every .gitgnore for every project you work on. Also, if you collaborate with other people, then its best practice not to pollute the project's .gitignore with private configuation that are not specific to the source-code of the project.
hope this help you or Ctrl + Alt + Shift + S => select Dependencies tab and find what you need ( see my image)
Define one Enum Type as
public enum Colors {
BLUE, SILVER, MAGENTA, RED
}
Change data type of color
from String
to Colors
Change return type and argument type of getter and setter method of color to Colors
Define comparator type as follows
static class ColorComparator implements Comparator<CarSort>
{
public int compare(CarSort c1, CarSort c2)
{
return c1.getColor().compareTo(c2.getColor());
}
}
after adding elements to List, call sort method of Collection by passing list and comparator objects as arguments
i.e, Collections.sort(carList, new ColorComparator());
then print using ListIterator
.
full class implementation is as follows:
package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.ListIterator;
public class CarSort implements Comparable<CarSort>{
String name;
Colors color;
public CarSort(String name, Colors color){
this.name = name;
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Colors getColor() {
return color;
}
public void setColor(Colors color) {
this.color = color;
}
//Implement the natural order for this class
public int compareTo(CarSort c)
{
return getName().compareTo(c.getName());
}
static class ColorComparator implements Comparator<CarSort>
{
public int compare(CarSort c1, CarSort c2)
{
return c1.getColor().compareTo(c2.getColor());
}
}
public enum Colors {
BLUE, SILVER, MAGENTA, RED
}
public static void main(String[] args)
{
List<CarSort> carList = new ArrayList<CarSort>();
List<String> sortOrder = new ArrayList<String>();
carList.add(new CarSort("Ford Figo",Colors.SILVER));
carList.add(new CarSort("Santro",Colors.BLUE));
carList.add(new CarSort("Honda Jazz",Colors.MAGENTA));
carList.add(new CarSort("Indigo V2",Colors.RED));
Collections.sort(carList, new ColorComparator());
ListIterator<CarSort> itr=carList.listIterator();
while (itr.hasNext()) {
CarSort carSort = (CarSort) itr.next();
System.out.println("Car colors: "+carSort.getColor());
}
}
}
If you are interested in a more compact stack trace with more information (package detail) that looks like:
java.net.SocketTimeoutException:Receive timed out
at j.n.PlainDatagramSocketImpl.receive0(Native Method)[na:1.8.0_151]
at j.n.AbstractPlainDatagramSocketImpl.receive(AbstractPlainDatagramSocketImpl.java:143)[^]
at j.n.DatagramSocket.receive(DatagramSocket.java:812)[^]
at o.s.n.SntpClient.requestTime(SntpClient.java:213)[classes/]
at o.s.n.SntpClient$1.call(^:145)[^]
at ^.call(^:134)[^]
at o.s.f.SyncRetryExecutor.call(SyncRetryExecutor.java:124)[^]
at o.s.f.RetryPolicy.call(RetryPolicy.java:105)[^]
at o.s.f.SyncRetryExecutor.call(SyncRetryExecutor.java:59)[^]
at o.s.n.SntpClient.requestTimeHA(SntpClient.java:134)[^]
at ^.requestTimeHA(^:122)[^]
at o.s.n.SntpClientTest.test2h(SntpClientTest.java:89)[test-classes/]
at s.r.NativeMethodAccessorImpl.invoke0(Native Method)[na:1.8.0_151]
you can try to use Throwables.writeTo from the spf4j lib.
Once you are quite good in Java SE (lets say you are able to pass SCJP), I'd suggest you get junior Java programmer job and improve yourself on real world problems
Here is some code that might help you out. Strings can be treated as an array of characters
string numbers = "12345";
int[] intArray = new int[numbers.Length];
for (int i=0; i < numbers.Length; i++)
{
intArray[i] = int.Parse(numbers[i]);
}
Try like this
var results = db.costumers.Where(X=>X.FullName.Contains(FirstName)&&(X=>X.FullName.EndsWith(LastName))
.Select(X=>X);
Run hive in debug mode
hive -hiveconf hive.root.logger=DEBUG,console
and then execute
show tables
can find the actual problem
You can also use UUID class from java.util package, which returns random uuid of 32bit characters String.
java.util.UUID.randomUUID().toString()
TLDR; (semi-related to an EF editor bug in EF6/VS2012U5) if you generate the model from DB and you cannot see the attributed m:m table: Delete the two related tables -> Save .edmx -> Generate/add from database -> Save.
For those who came here wondering how to get a many-to-many relationship with attribute columns to show in the EF .edmx file (as it would currently not show and be treated as a set of navigational properties), AND you generated these classes from your database table (or database-first in MS lingo, I believe.)
Delete the 2 tables in question (to take the OP example, Member and Comment) in your .edmx and add them again through 'Generate model from database'. (i.e. do not attempt to let Visual Studio update them - delete, save, add, save)
It will then create a 3rd table in line with what is suggested here.
This is relevant in cases where a pure many-to-many relationship is added at first, and the attributes are designed in the DB later.
This was not immediately clear from this thread/Googling. So just putting it out there as this is link #1 on Google looking for the issue but coming from the DB side first.
I just ran into this problem myself.
First, modify your code slightly:
var download = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+"<"+this.gamesave.tagName+">"
+this.xml.firstChild.innerHTML
+"</"+this.gamesave.tagName+">";
this.loader.src = "data:application/x-forcedownload;base64,"+
btoa(download);
Then use your favorite web inspector, put a breakpoint on the line of code that assigns this.loader.src, then execute this code:
for (var i = 0; i < download.length; i++) {
if (download[i].charCodeAt(0) > 255) {
console.warn('found character ' + download[i].charCodeAt(0) + ' "' + download[i] + '" at position ' + i);
}
}
Depending on your application, replacing the characters that are out of range may or may not work, since you'll be modifying the data. See the note on MDN about unicode characters with the btoa method:
https://developer.mozilla.org/en-US/docs/Web/API/window.btoa
My solution is similar.
// In destination class:
var AddressString:String = String()
// In segue:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "seguetobiddetailpagefromleadbidder")
{
let secondViewController = segue.destinationViewController as! BidDetailPage
secondViewController.AddressString = pr.address as String
}
}
If $AccountNumber
or $Balance
is a node-set, then this behavior could easily happen. It's not because and
is being treated as or
.
For example, if $AccountNumber
referred to nodes with the values 12345
and 66
and $Balance
referred to nodes with the values 55
and 0
, then
$AccountNumber != '12345'
would be true (because 66
is not equal to 12345
) and $Balance != '0'
would be true (because 55
is not equal to 0
).
I'd suggest trying this instead:
<xsl:when test="not($AccountNumber = '12345' or $Balance = '0')">
$AccountNumber = '12345' or $Balance = '0'
will be true any time there is an $AccountNumber
with the value 12345
or there is a $Balance
with the value 0
, and if you apply not()
to that, you will get a false result.
It turns out the answer was ridiculously simple, but mystifying as to why it was necessary.
In the IIS Manager on the server, I set the application pool for my web application to not allow 32-bit assemblies.
It seems it assumes, on a 64-bit system, that you must want the 32 bit assembly. Bizarre.
This is the reply I received from Github when I asked them to delete a pull request:
"Thanks for getting in touch! Pull requests can't be deleted through the UI at the moment and we'll only delete pull requests when they contain sensitive information like passwords or other credentials."
If a class is declared as static then the variables and methods need to be declared as static.
A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
->The main features of a static class are:
Example
static class CollegeRegistration
{
//All static member variables
static int nCollegeId; //College Id will be same for all the students studying
static string sCollegeName; //Name will be same
static string sColegeAddress; //Address of the college will also same
//Member functions
public static int GetCollegeId()
{
nCollegeId = 100;
return (nCollegeID);
}
//similarly implementation of others also.
} //class end
public class student
{
int nRollNo;
string sName;
public GetRollNo()
{
nRollNo += 1;
return (nRollNo);
}
//similarly ....
public static void Main()
{
//Not required.
//CollegeRegistration objCollReg= new CollegeRegistration();
//<ClassName>.<MethodName>
int cid= CollegeRegistration.GetCollegeId();
string sname= CollegeRegistration.GetCollegeName();
} //Main end
}
Swift version to get Bool?
NSUserDefaults.standardUserDefaults().objectForKey(DefaultsIsGiver) as? Bool
You should write a kind of template into the @RequestMapping
:
http://localhost:8080/userGrid?_search=${search}&nd=${nd}&rows=${rows}&page=${page}&sidx=${sidx}&sord=${sord}
Now define your business method like following:
@RequestMapping("/userGrid?_search=${search}&nd=${nd}&rows=${rows}&page=${page}&sidx=${sidx}&sord=${sord}")
public @ResponseBody GridModel getUsersForGrid(
@RequestParam(value = "search") String search,
@RequestParam(value = "nd") int nd,
@RequestParam(value = "rows") int rows,
@RequestParam(value = "page") int page,
@RequestParam(value = "sidx") int sidx,
@RequestParam(value = "sort") Sort sort) {
...............
}
So, framework will map ${foo}
to appropriate @RequestParam
.
Since sort may be either asc or desc I'd define it as a enum:
public enum Sort {
asc, desc
}
Spring deals with enums very well.
This should help:
if(screen.width<1026){//get the screen width
//get element form document
elem.style.display == 'none'//toggle visibility
}
768 px should be enough as well
IMHO there are three reasons to use OpenGL ES in a game:
Drawing text is always a problem in game design, because you are drawing things, so you cannot have the look and feel of a common activity, with widgets and so on.
You can use a framework to generate Bitmap fonts from TrueType fonts and render them. All the frameworks I've seen operate the same way: generate the vertex and texture coordinates for the text in draw time. This is not the most efficient use of OpenGL.
The best way is to allocate remote buffers (vertex buffer objects - VBOs) for the vertices and textures early in code, avoiding the lazy memory transfer operations in draw time.
Keep in mind that game players don't like to read text, so you won't write a long dynamically generated text. For labels, you can use static textures, leaving dynamic text for time and score, and both are numeric with a few characters long.
So, my solution is simple:
Draw operations are fast, if you use remote static buffers.
I create an XML file with screen positions (based on screen's diagonal percentage) and textures (static and characters), and then I load this XML before rendering.
To get a high FPS rate, you should avoid generating VBOs at draw time.
You can change the default location of .m2 directory in m2.conf file. It resides in your maven installation directory.
add modify this line in
m2.conf
set maven.home C:\Users\me\.m2
You can vertically align a div in another div. See this example on JSFiddle or consider the example below.
HTML
<div class="outerDiv">
<div class="innerDiv"> My Vertical Div </div>
</div>
CSS
.outerDiv {
display: inline-flex; // <-- This is responsible for vertical alignment
height: 400px;
background-color: red;
color: white;
}
.innerDiv {
margin: auto 5px; // <-- This is responsible for vertical alignment
background-color: green;
}
The .innerDiv
's margin must be in this format: margin: auto *px;
[Where, *
is your desired value.]
display: inline-flex
is supported in the latest (updated/current version) browsers with HTML5 support.
It may not work in Internet Explorer :P :)
Always try to define a height for any vertically aligned div (i.e. innerDiv) to counter compatibility issues.
to get all tables in a database:
select * from INFORMATION_SCHEMA.TABLES
to get all columns in a database:
select * from INFORMATION_SCHEMA.columns
to get all views in a db:
select * from INFORMATION_SCHEMA.TABLES where table_type = 'view'
I had this problem and I solved it when I understood that it was looking for the Windows Registry specified in the brackets.
Since the error was happening only in one computer, what I had to do was export the registry from the computer that it was working and install it on the computer that was missing it.
If I'm reading your question right, you want to run a script in the post build actions part of the build.
I myself use PostBuildScript Plugin for running git clean -fxd
after the build has archived artifacts and published test results. My Jenkins slaves have SSD disks, so I do not have the room keep generated files in the workspace.
Ok the issue it seems to come from this line:
https://github.com/angular-ui/ui-date/blob/master/src/date.js#L106.
Actually this line it's the binding with jQuery UI which it should be the place to inject the data format.
As you can see in var opts
there is no property dateFormat
with the value from ng-date-format as you could espect.
Anyway the directive has a constant called uiDateConfig
to add properties to opts
.
The flexible solution (recommended):
From here you can see you can insert some options injecting in the directive a controller variable with the jquery ui options.
<input ui-date="dateOptions" ui-date-format="mm/dd/yyyy" ng-model="valueofdate" />
myAppModule.controller('MyController', function($scope) {
$scope.dateOptions = {
dateFormat: "dd-M-yy"
};
});
The hardcoded solution:
If you don't want to repeat this procedure all the time change the value of uiDateConfig
in date.js to:
.constant('uiDateConfig', { dateFormat: "dd-M-yy" })
You're missing *
s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2
as an attempt to call a function named 0.207
...
For example:
> 1 + 2*(3)
[1] 7
> 1 + 2 (3)
Error: attempt to apply non-function
Your (unreproducible) expression should read:
censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) +
0.207* (log(DIAM93))^2 -
0.0281*(log(DIAM93))^3)
Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...
If you want to select the columns from First Table "which are also present in Second table, then in this case you can also use EXCEPT
. In this case, column names can be different as well but data type should be same.
Example:
select ID, FName
from FirstTable
EXCEPT
select ID, SName
from SecondTable
The operation you defined is a "merge" and you cannot do that with cp
. However, if you are not looking for merging and ok to lose the folder bar
then you can simply rm -rf bar
to delete the folder and then mv foo bar
to rename it. This will not take any time as both operations are done by file pointers, not file contents.
There are a lot of questions already about this, so I will refer you to those.
One thing you want to make sure to prevent the need for uninstallation, is that you use the same upgrade code on every release, but change the product code. These values are located in the Installshield project properties.
Some references:
Just a slight modification for the code written by Roel Van de Paar, as all credit goes to him. I am using this in Windows and it is working perfectly, both for setting and adding cookies:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('chromedriver.exe',options=chrome_options)
driver.get('https://web.whatsapp.com') # Already authenticated
time.sleep(30)
Just create the header.php file, and where you want to use it do:
<?php
include('header.php');
?>
Same with the footer. You don't need php tags in these files if you just have html.
See more about include here:
This worked for me:
<video src="file.mp4" controls style="max-width:100%; height:auto"></video>
If you need to increase MySQL Connections without MySQL restart do like below, also if you don't know configuration file, below use the mysqlworkbench or phpmyadmin or command prompt to run below queries.
mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 151 |
+-----------------+-------+
1 row in set (0.00 sec)
mysql> SET GLOBAL max_connections = 250;
Query OK, 0 rows affected (0.00 sec)
mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 250 |
+-----------------+-------+
1 row in set (0.00 sec)
These settings will change at MySQL Restart.
For permanent changes add below line in my.cnf and restart MySQL.
max_connections = 151
Just make sure to write the docker name correctly!
In my case, I wrote (notice the extra 'u'):
FROM ubunutu:16.04
The correct docker name is:
FROM ubuntu:16.04
Docker images are pretty minimal, But you can install ping
in your official ubuntu docker image via:
apt-get update
apt-get install iputils-ping
Chances are you dont need ping
your image, and just want to use it for testing purposes. Above example will help you out.
But if you need ping to exist on your image, you can create a Dockerfile
or commit
the container you ran the above commands in to a new image.
Commit:
docker commit -m "Installed iputils-ping" --author "Your Name <[email protected]>" ContainerNameOrId yourrepository/imagename:tag
Dockerfile:
FROM ubuntu
RUN apt-get update && apt-get install -y iputils-ping
CMD bash
Please note there are best practices on creating docker images, Like clearing apt cache files after and etc.
The problem is that you're trying to bind a temporary to the reference, which C++ doesn't allow unless the reference is const
.
So you can do one of either the following:
void myfunc(string*& val)
{
// Do stuff to the string pointer
}
void myfunc2(string* const& val)
{
// Do stuff to the string pointer
}
int main()
// sometime later
{
// ...
string s;
string* ps = &s;
myfunc( ps); // OK because ps is not a temporary
myfunc2( &s); // OK because the parameter is a const&
// ...
return 0;
}
If your working tree is dirty, you can compare it to a stash by first committing the dirty working tree, and then comparing it to the stash. Afterwards, you may undo the commit with the dirty working tree (since you might not want to have that dirty commit in your commit log).
You can also use the following approach to compare two stashes with each other (in which case you just pop one of the stashes at first).
Commit your dirty working tree:
git add .
git commit -m "Dirty commit"
Diff the stash with that commit:
git diff HEAD stash@{0}
Then, afterwards, you may revert the commit, and put it back in the working dir:
git reset --soft HEAD~1
git reset .
Now you've diffed the dirty working tree with your stash, and are back to where you were initially.
Initializer block is just like any bits of code; it's not "attached" to any field/method preceding it. To assign values to fields, you have to explicitly use the field as the lhs of an assignment statement.
private int lineCount; {
try{
lineCount = LineCounter.countLines(sFileName);
/*^^^^^^^*/
}
catch(IOException ex){
System.out.println (ex.toString());
System.out.println("Could not find file " + sFileName);
}
}
Also, your countLines
can be made simpler:
public static int countLines(String filename) throws IOException {
LineNumberReader reader = new LineNumberReader(new FileReader(filename));
while (reader.readLine() != null) {}
reader.close();
return reader.getLineNumber();
}
Based on my test, it looks like you can getLineNumber()
after close()
.
I had the same problem. I solved it by running these 2 commands:
brew uninstall vapor
brew install vapor/tap/vapor
It worked.
and also if you will try to create Navigation Bar
manually this code will help you
func setNavBarToTheView() {
let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 64.0))
self.view.addSubview(navBar);
let navItem = UINavigationItem(title: "Camera");
let doneItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: self, action: #selector(CameraViewController.onClickBack));
navItem.leftBarButtonItem = doneItem;
navBar.setItems([navItem], animated: true);
}
To add up to Louis answer:
Alternatively you can use the attribute ToolVersion="12.0"
if you are using Visual Studio 2013 instead of using the ToolPath
Attribute. Details visit http://msdn.microsoft.com/en-us/library/dd647548.aspx
So you are not forced to use absolute path.
If your data has the names grouped as shown then you can use this formula in D2 copied down to get a total against the last entry for each name
=IF((A2=A3)*(B2=B3),"",SUM(C$2:C2)-SUM(D$1:D1))
See screenshot
>>> string="abc&def#ghi"
>>> for ch in ['&','#']:
... if ch in string:
... string=string.replace(ch,"\\"+ch)
...
>>> print string
abc\&def\#ghi
Try out something like this:
<style>
#divMain { width: 500px; }
#left-div { width: 100px; float: left; background-color: #fcc; }
#middle-div { margin-left: 100px; margin-right: 100px; background-color: #cfc; }
#right-div { width: 100px; float: right; background-color: #ccf; }
</style>
<div id="divMain">
<div id="left-div">
left div
</div>
<div id="right-div">
right div
</div>
<div id="middle-div">
middle div<br />bit taller
</div>
</div>
divs will naturally take up 100% width of their container, there is no need to explicitly set this width. By adding a left/right margin the same as the two side divs, it's own contents is forced to sit between them.
Note that the "middle div" goes after the "right div" in the HTML
Joshua Bloch has a talk about API design that covers how bad ones make boilerplate code necessary. (Minute 46 for reference to boilerplate, listening to this today)
Use the Java 8 way of converting a Map<String, Object>
to Map<String, String>
. This solution handles null
values.
Map<String, String> keysValuesStrings = keysValues.entrySet().stream()
.filter(entry -> entry.getValue() != null)
.collect(Collectors.toMap(Entry::getKey, entry -> entry.getValue().toString()));
I was successful using tidy
command line utility. On linux I installed it quickly with apt-get install tidy
. Then the command:
tidy -q -asxml --numeric-entities yes source.html >file.xml
gave an xml file, which I was able to process with xslt processor. However I needed to set up xhtml1 dtds correctly.
This is their homepage: html-tidy.org (and the legacy one: HTML Tidy)
Happened to me because i was running a virtual machine at the same time, the ram was already allocated to that so android studio couldn't take up any ram, switching off virtual box and restarting did the trick for me.
No.
If the user is sophisticated or determined enough to:
then they are probably sophisticated or determined enough to:
So what's on this hidden sheet? Proprietary information like price formulas, or client names, or employee salaries? Putting that info in even an hidden tab probably isn't the greatest idea to begin with.
You may run into such problem while dealing with scraped data stored as Pandas DataFrame.
This solution works like charm if the list of values is present as text.
def textToList(hashtags):
return hashtags.strip('[]').replace('\'', '').replace(' ', '').split(',')
hashtags = "[ 'A','B','C' , ' D']"
hashtags = textToList(hashtags)
Output: ['A', 'B', 'C', 'D']
No external library required.
Extract numbers from any string at beginning position.
x <- gregexpr("^[0-9]+", years) # Numbers with any number of digits
x2 <- as.numeric(unlist(regmatches(years, x)))
Extract numbers from any string INDEPENDENT of position.
x <- gregexpr("[0-9]+", years) # Numbers with any number of digits
x2 <- as.numeric(unlist(regmatches(years, x)))
I'm using @foreach
when I send an entity that contains a list of entities ( for example to display 2 grids in 1 view )
For example if I'm sending as model the entity Foo that contains Foo1(List<Foo1>)
and Foo2(List<Foo2>)
I can refer to the first List with:
@foreach (var item in Model.Foo.Foo1)
{
@Html.DisplayFor(modelItem=> item.fooName)
}
When i analyzed your code. I have also faced the same problem but my problem is if i give value for both first and last name means it is working fine. but when i give only one value means it says 400. anyway use the .andDo(print()) method to find out the error
public void testGetUserByName() throws Exception {
String firstName = "Jack";
String lastName = "s";
this.userClientObject = client.createClient();
mockMvc.perform(get("/byName")
.sessionAttr("userClientObject", this.userClientObject)
.param("firstName", firstName)
.param("lastName", lastName)
).andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andExpect(jsonPath("$[0].id").exists())
.andExpect(jsonPath("$[0].fn").value("Marge"));
}
If your problem is org.springframework.web.bind.missingservletrequestparameterexception
you have to change your code to
@RequestMapping(value = "/byName", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public
@ResponseBody
String getUserByName(
@RequestParam( value="firstName",required = false) String firstName,
@RequestParam(value="lastName",required = false) String lastName,
@ModelAttribute("userClientObject") UserClient userClient)
{
return client.getUserByName(userClient, firstName, lastName);
}
The facade is another Request class, access it with the full path:
$input = \Request::all();
From laravel 5 you can also access it through the request()
function:
$input = request()->all();
I have a helper method for this in my System.Web.UI.Page class
protected T FindControlFromMaster<T>(string name) where T : Control
{
MasterPage master = this.Master;
while (master != null)
{
T control = master.FindControl(name) as T;
if (control != null)
return control;
master = master.Master;
}
return null;
}
then you can access using below code.
Label lblStatus = FindControlFromMaster<Label>("lblStatus");
if(lblStatus!=null)
lblStatus.Text = "something";
Just add the document ready function, this way it waits until the DOM has been loaded, also by using the :visible
pseudo you can write a simple show and hide function.
$(document).ready(function(){
$( '.expand' ).click(function() {
if($( '.img_display_content' ).is(":visible")){
$( '.img_display_content' ).hide();
} else{
$( '.img_display_content' ).show();
}
});
});
In general, you can create strings using:
stringExample = "someString " + str(someNumber)
print(stringExample)
plot.savefig(stringExample)
Add this to the stylesheet:
table {
border-collapse: collapse;
}
The reason why it behaves this way is actually described pretty well in the specification:
There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.
... and later, for collapse
setting:
In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.
I am not aware of any libraries to do this (but I am sure there are many that can) but if you can already create HTML from the crystal report why not use XSLT to clean up the markup?
//String appending
#include <iostream>
using namespace std;
void stringconcat(char *str1, char *str2){
while (*str1 != '\0'){
str1++;
}
while(*str2 != '\0'){
*str1 = *str2;
str1++;
str2++;
}
}
int main() {
char str1[100];
cin.getline(str1, 100);
char str2[100];
cin.getline(str2, 100);
stringconcat(str1, str2);
cout<<str1;
getchar();
return 0;
}
Do not use primitives in your Entity classes, use instead their respective wrappers. That will fix this problem.
Out of your Entity classes you can use the != null validation for the rest of your code flow.
in php
echo '<a href="' . $folder_path . '">Link text</a>';
or
<a href="<?=$folder_path?>">Link text</a>;
or
<a href="<?php echo $folder_path ?>">Link text</a>;
When the directory already exist:
mkdir -m 777 /path/to/your/dir
When the directory does not exist and you want to create the parent directories:
mkdir -m 777 -p /parent/dirs/to/create/your/dir
If you need to do many append operations to build a large string, you can use StringIO or cStringIO. The interface is like a file. ie: you write
to append text to it.
If you're just appending two strings then just use +
.
You can try this:
create procedure [dbo].[get_user_names]
@user_id_list varchar(2000), -- You can use any max length
@username varchar (30) output
as
select last_name+', '+first_name
from user_mstr
where user_id in (Select ID from dbo.SplitString( @user_id_list, ',') )
And here is the user defined function for SplitString:
Create FUNCTION [dbo].[SplitString]
(
@Input NVARCHAR(MAX),
@Character CHAR(1)
)
RETURNS @Output TABLE (
Item NVARCHAR(1000)
)
AS
BEGIN
DECLARE @StartIndex INT, @EndIndex INT
SET @StartIndex = 1
IF SUBSTRING(@Input, LEN(@Input) - 1, LEN(@Input)) <> @Character
BEGIN
SET @Input = @Input + @Character
END
WHILE CHARINDEX(@Character, @Input) > 0
BEGIN
SET @EndIndex = CHARINDEX(@Character, @Input)
INSERT INTO @Output(Item)
SELECT SUBSTRING(@Input, @StartIndex, @EndIndex - 1)
SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))
END
RETURN
END
Keep it simple:
try:
from . import mymodule # "myapp" case
except:
import mymodule # "__main__" case
Use AsyncTaskLoader to keep your data safe even if the activity changes, instead of using AsyncTask that is a better way to build apps than preventing screen rotation.
The second argument Title does not mean Title of the page - It is more of a definition/information for the state of that page
But we can still change the title using onpopstate event, and passing the title name not from the second argument, but as an attribute from the first parameter passed as object
Reference: http://spoiledmilk.com/blog/html5-changing-the-browser-url-without-refreshing-page/
document.getElementById('myDiv').style.height = 500;
This is the very basic JS code required to adjust the height of your object dynamically. I just did this very thing where I had some auto height property, but when I add some content via XMLHttpRequest
I needed to resize my parent div and this offsetheight property did the trick in IE6/7 and FF3
Native DOM elements that are inputs also have a form
attribute that points to the form they belong to:
var form = element.form;
alert($(form).attr('name'));
According to w3schools, the .form
property of input fields is supported by IE 4.0+, Firefox 1.0+, Opera 9.0+, which is even more browsers that jQuery guarantees, so you should stick to this.
If this were a different type of element (not an <input>
), you could find the closest parent with closest
:
var $form = $(element).closest('form');
alert($form.attr('name'));
Also, see this MDN link on the form
property of HTMLInputElement
:
Simple way of solving this issue is save the both entity. first save the child entity and then save the parent entity. Because parent entity is depend on child entity for the foreign key value.
Below simple exam of one to one relationship
insert into Department (name, numOfemp, Depno) values (?, ?, ?)
Hibernate: insert into Employee (SSN, dep_Depno, firstName, lastName, middleName, empno) values (?, ?, ?, ?, ?, ?)
Session session=sf.openSession();
session.beginTransaction();
session.save(dep);
session.save(emp);
I was parsing JSON from a REST API call and got this error. It turns out the API had become "fussier" (eg about order of parameters etc) and so was returning malformed results. Check that you are getting what you expect :)
I've approached this in a different way. I've created a function which simply returns true or false.. Usage:
If FieldContains("A;B;C",MyFieldVariable,True|False) then
.. Do Something
End If
Public Function FieldContains(Searchfor As String, SearchField As String, AllowNulls As Boolean) As Boolean
If AllowNulls And Len(SearchField) = 0 Then Return True
For Each strSearchFor As String In Searchfor.Split(";")
If UCase(SearchField) = UCase(strSearchFor) Then
Return True
End If
Next
Return False
End Function
Simple way, use the Exception.ToString()
function, it will return the line after the exception description.
You can also check the program debug database as it contains debug info/logs about the whole application.
If you want to stay within the standard library, you can subclass urllib2.Request
:
import urllib2
class RequestWithMethod(urllib2.Request):
def __init__(self, *args, **kwargs):
self._method = kwargs.pop('method', None)
urllib2.Request.__init__(self, *args, **kwargs)
def get_method(self):
return self._method if self._method else super(RequestWithMethod, self).get_method()
def put_request(url, data):
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = RequestWithMethod(url, method='PUT', data=data)
return opener.open(request)
Many of the solutions so far posted use type assertions and therefor do not throw compilation errors if required interface properties are omitted in the implementation.
For those interested in some other robust, compact solutions:
Option 1: Instantiate an anonymous class which implements the interface:
new class implements MyInterface {
nameFirst = 'John';
nameFamily = 'Smith';
}();
Option 2: Create a utility function:
export function impl<I>(i: I) { return i; }
impl<MyInterface>({
nameFirst: 'John';
nameFamily: 'Smith';
})
The error you get is due to the CORS standard, which sets some restrictions on how JavaScript can perform ajax requests.
The CORS standard is a client-side standard, implemented in the browser. So it is the browser which prevent the call from completing and generates the error message - not the server.
Postman does not implement the CORS restrictions, which is why you don't see the same error when making the same call from Postman.
They are both correct. Personally I prefer your approach better for its verbosity but it's really down to personal preference.
Off hand, running if($_POST) would not throw an error - the $_POST array exists regardless if the request was sent with POST headers. An empty array is cast to false in a boolean check.
Another nice way to put your logic in data is something like this:
# Initialization.
CAR_TYPES = {
foo_type: ['honda', 'acura', 'mercedes'],
bar_type: ['toyota', 'lexus']
# More...
}
@type_for_name = {}
CAR_TYPES.each { |type, names| names.each { |name| @type_for_name[type] = name } }
case @type_for_name[car]
when :foo_type
# do foo things
when :bar_type
# do bar things
end
It helps not to focus on the strong
or weak
part of the discussion. Instead focus on the cycle part.
A retain cycle is a loop that happens when Object A retains Object B, and Object B retains Object A. In that situation, if either object is released:
Thus, those two objects will just hang around in memory for the life of the program even though they should, if everything were working properly, be deallocated.
So, what we're worried about is retain cycles, and there's nothing about blocks in and of themselves that create these cycles. This isn't a problem, for example:
[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
[self doSomethingWithObject:obj];
}];
The block retains self
, but self
doesn't retain the block. If one or the other is released, no cycle is created and everything gets deallocated as it should.
Where you get into trouble is something like:
//In the interface:
@property (strong) void(^myBlock)(id obj, NSUInteger idx, BOOL *stop);
//In the implementation:
[self setMyBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[self doSomethingWithObj:obj];
}];
Now, your object (self
) has an explicit strong
reference to the block. And the block has an implicit strong reference to self
. That's a cycle, and now neither object will be deallocated properly.
Because, in a situation like this, self
by definition already has a strong
reference to the block, it's usually easiest to resolve by making an explicitly weak reference to self
for the block to use:
__weak MyObject *weakSelf = self;
[self setMyBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[weakSelf doSomethingWithObj:obj];
}];
But this should not be the default pattern you follow when dealing with blocks that call self
! This should only be used to break what would otherwise be a retain cycle between self and the block. If you were to adopt this pattern everywhere, you'd run the risk of passing a block to something that got executed after self
was deallocated.
//SUSPICIOUS EXAMPLE:
__weak MyObject *weakSelf = self;
[[SomeOtherObject alloc] initWithCompletion:^{
//By the time this gets called, "weakSelf" might be nil because it's not retained!
[weakSelf doSomething];
}];
This question is quite dated yet I wanted to leave an answer that leverages the current version of the language. Unfortunately static classes still don't exist in TypeScript however you can write a class that behaves similar with only a small overhead using a private constructor which prevents instantiation of classes from outside.
class MyStaticClass {
public static readonly property: number = 42;
public static myMethod(): void { /* ... */ }
private constructor() { /* noop */ }
}
This snippet will allow you to use "static" classes similar to the C# counterpart with the only downside that it is still possible to instantiate them from inside. Fortunately though you cannot extend classes with private constructors.
In your application android manifest file, under the application tag you can try several of these themes.
Replace
<application
android:theme="@style/AppTheme" >
with different themes defined by the android system. They can be like:-
android:theme="@android:style/Theme.Black"
android:theme="@android:style/Theme.DeviceDefault"
android:theme="@android:style/Theme.DeviceDefault.Dialog"
android:theme="@android:style/Theme.Holo"
android:theme="@android:style/Theme.Translucent"
Each of these themes will have a different effect on your application like the DeviceDefault.Dialog will make your application look like a dialog box. You should try more of these. You can have a look from the android sdk or simply use auto complete in Eclipse IDE to explore the various available options.
A correct way to define your own theme would be to edit the styles.xml
file present in the resources folder of your application.
If you are still looking for further more customization,
Check out the following library: https://lokesh-coder.github.io/pretty-checkbox/
Thanks
Late to the party, but the top voted answers all seemed like hacks to me.
All I did was remove the following from my app.config in the test project. Worked.
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
document.location.href="/";
or
window.location.href = "/";
According to the W3C, they are the same. In reality, for cross browser safety, you should use window.location
rather than document.location
.
See: http://www.w3.org/TR/Window/#window-location
(Note: I copied the difference explanation above, from this question.)
That is not useful for just one update/delete/insert.
Possibly adds performance if several operators after if condition.
In last case better write
update a set .. where ..
if @@rowcount > 0
begin
..
end
public boolean checkForEmail() {
Context c;
EditText mEtEmail=(EditText)findViewById(R.id.etEmail);
String mStrEmail = mEtEmail.getText().toString();
if (android.util.Patterns.EMAIL_ADDRESS.matcher(mStrEmail).matches()) {
return true;
}
Toast.makeText(this,"Email is not valid", Toast.LENGTH_LONG).show();
return false;
}
public boolean checkForMobile() {
Context c;
EditText mEtMobile=(EditText)findViewById(R.id.etMobile);
String mStrMobile = mEtMobile.getText().toString();
if (android.util.Patterns.PHONE.matcher(mStrMobile).matches()) {
return true;
}
Toast.makeText(this,"Phone No is not valid", Toast.LENGTH_LONG).show();
return false;
}
Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.
You need to extract the number from the string, and pass it into the Date constructor
:
var x = [{
"id": 1,
"start": "\/Date(1238540400000)\/"
}, {
"id": 2,
"start": "\/Date(1238626800000)\/"
}];
var myDate = new Date(x[0].start.match(/\d+/)[0] * 1);
The parts are:
x[0].start - get the string from the JSON
x[0].start.match(/\d+/)[0] - extract the numeric part
x[0].start.match(/\d+/)[0] * 1 - convert it to a numeric type
new Date(x[0].start.match(/\d+/)[0] * 1)) - Create a date object
The second is almost correct:
{
"foos" : [{
"prop1":"value1",
"prop2":"value2"
}, {
"prop1":"value3",
"prop2":"value4"
}]
}
Scanner sc = new Scanner(System.in);
//do stuff with sc
sc.close();//write at end of code.
I suggest using concat()
if you are using nodeJS. In all other cases, I have found that slice(0)
works fine.
I opened this thread looking for a quick solution to a simple question, but I found that the answers here were either not helpful or overly complicated. The best way to get the last 5 chars of a string is, in fact, to use the Right() method. Here is a simple example:
Dim sMyString, sLast5 As String
sMyString = "I will be going to school in 2011!"
sLast5 = Right(sMyString, - 5)
MsgBox("sLast5 = " & sLast5)
If you're getting an error then there is probably something wrong with your syntax. Also, with the Right() method you don't need to worry much about going over or under the string length. In my example you could type in 10000 instead of 5 and it would just MsgBox the whole string, or if sMyString was NULL or "", the message box would just pop up with nothing.
It is possible for the TCP socket to be "closing" and your code to not have yet been notified.
Here is a animation for the life cycle. http://tcp.cs.st-andrews.ac.uk/index.shtml?page=connection_lifecycle
Basically, the connection was closed by the client. You already have throws IOException
and SocketException
extends IOException
. This is working just fine. You just need to properly handle IOException
because it is a normal part of the api.
EDIT: The RST
packet occurs when a packet is received on a socket which does not exist or was closed. There is no difference to your application. Depending on the implementation the reset
state may stick and closed
will never officially occur.
There is a new method what came with Angular 7.2.0
https://angular.io/api/router/NavigationExtras#state
Send:
this.router.navigate(['action-selection'], { state: { example: 'bar' } });
Receive:
constructor(private router: Router) {
console.log(this.router.getCurrentNavigation().extras.state.example); // should log out 'bar'
}
You can find some additional info here:
https://github.com/angular/angular/pull/27198
The link above contains this example which can be useful: https://stackblitz.com/edit/angular-bupuzn