I wrote a Clump extension method several years ago. Works great, and is the fastest implementation here. :P
/// <summary>
/// Clumps items into same size lots.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">The source list of items.</param>
/// <param name="size">The maximum size of the clumps to make.</param>
/// <returns>A list of list of items, where each list of items is no bigger than the size given.</returns>
public static IEnumerable<IEnumerable<T>> Clump<T>(this IEnumerable<T> source, int size)
{
if (source == null)
throw new ArgumentNullException("source");
if (size < 1)
throw new ArgumentOutOfRangeException("size", "size must be greater than 0");
return ClumpIterator<T>(source, size);
}
private static IEnumerable<IEnumerable<T>> ClumpIterator<T>(IEnumerable<T> source, int size)
{
Debug.Assert(source != null, "source is null.");
T[] items = new T[size];
int count = 0;
foreach (var item in source)
{
items[count] = item;
count++;
if (count == size)
{
yield return items;
items = new T[size];
count = 0;
}
}
if (count > 0)
{
if (count == size)
yield return items;
else
{
T[] tempItems = new T[count];
Array.Copy(items, tempItems, count);
yield return tempItems;
}
}
}
Starting from Rob's answer, I am currently using the following syntax.Since the question has received a lot of attention,I decided to share it with you :
var requrl = '@Url.Action("Action", "Controller", null, Request.Url.Scheme, null)';
$.ajax({
type: "POST",
url: requrl,
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.d.toString());
}
});
Nothing beats a nice example
For people looking for a clean coding example of an one-to-many/many-to-one associations between the 3 participating classes to store extra attributes in the relation check this site out:
nice example of one-to-many/many-to-one associations between the 3 participating classes
Think about your primary keys
Also think about your primary key. You can often use composite keys for relationships like this. Doctrine natively supports this. You can make your referenced entities into ids. Check the documentation on composite keys here
Add "name" attribute and keep the name same for all the radio buttons in a form.
i.e.,
<input type="radio" name="test" value="value1"> Value 1
<input type="radio" name="test" value="value2"> Value 2
<input type="radio" name="test" value="value3"> Value 3
Hope that would help.
Install redis on your system first -
brew install redis
then start the redis server -
redis-server
Best answer is to use the from dateutil import parser
.
usage:
from dateutil import parser
datetime_obj = parser.parse('2018-02-06T13:12:18.1278015Z')
print datetime_obj
# output: datetime.datetime(2018, 2, 6, 13, 12, 18, 127801, tzinfo=tzutc())
You should not think about Hive as a regular RDBMS, Hive is better suited for batch processing over very large sets of immutable data.
The following applies to versions prior to Hive 0.14, see the answer by ashtonium for later versions.
There is no operation supported for deletion or update of a particular record or particular set of records, and to me this is more a sign of a poor schema.
Here is what you can find in the official documentation:
Hadoop is a batch processing system and Hadoop jobs tend to have high latency and
incur substantial overheads in job submission and scheduling. As a result -
latency for Hive queries is generally very high (minutes) even when data sets
involved are very small (say a few hundred megabytes). As a result it cannot be
compared with systems such as Oracle where analyses are conducted on a
significantly smaller amount of data but the analyses proceed much more
iteratively with the response times between iterations being less than a few
minutes. Hive aims to provide acceptable (but not optimal) latency for
interactive data browsing, queries over small data sets or test queries.
Hive is not designed for online transaction processing and does not offer
real-time queries and row level updates. It is best used for batch jobs over
large sets of immutable data (like web logs).
A way to work around this limitation is to use partitions: I don't know what you id corresponds to, but if you're getting different batches of ids separately, you could redesign your table so that it is partitioned by id, and then you would be able to easily drop partitions for the ids you want to get rid of.
The solution seems to be to add multiple @font-face
rules, for example:
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans.ttf");
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-Bold.ttf");
font-weight: bold;
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-Oblique.ttf");
font-style: italic, oblique;
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-BoldOblique.ttf");
font-weight: bold;
font-style: italic, oblique;
}
By the way, it would seem Google Chrome doesn't know about the format("ttf")
argument, so you might want to skip that.
(This answer was correct for the CSS 2 specification. CSS3 only allows for one font-style rather than a comma-separated list.)
I have just tested the following pipeline and it works
parallel firstBranch: {
stage ('Starting Test')
{
build job: 'test1', parameters: [string(name: 'Environment', value: "$env.Environment")]
}
}, secondBranch: {
stage ('Starting Test2')
{
build job: 'test2', parameters: [string(name: 'Environment', value: "$env.Environment")]
}
}
This Job named 'trigger-test' accepts one parameter named 'Environment'
Job 'test1' and 'test2' are simple jobs:
Example for 'test1'
On execution, I am able to see both stages running in the same time
Check an ASCII table.
It stands for CR
, or Carriage Return, AKA the Return key.
I created an alternate colors library for bootstrap 2.3.2 it's available and simple to use for anyone interested in more colors for the old glyphicons library.
You go into your router configuration and forward port 80 to the LAN IP of the computer running the web server.
Then anyone outside your network (but not you inside the network) can access your site using your WAN IP address (whatismyipcom).
I had the same problem where I wanted to use python3 for most work but IDA pro required python2. SO, here's what I did.
I first created 3 variables in the user environment variable as follows:
Now I added
%PYTHON_ACTIVE%
to PATH variable. So, basically saying that whatever this "PYTHON_ACTIVE" contains is the active python. We programmatically change the contains of "PYTHON_ACTIVE" to switch python version.
Here is the example script:
:: This batch file is used to switch between python 2 and 3.
@ECHO OFF
set /p choice= "Please enter '27' for python 2.7 , '38' for python 3.8 : "
IF %choice%==27 (
setx PYTHON_ACTIVE %HOME_PYTHON27%
)
IF %choice%==38 (
setx PYTHON_ACTIVE %HOME_PYTHON38%
)
PAUSE
This script takes python version as input and accordingly copies HOME_PYTHON27 or HOME_PYTHON38 to PYTHON_ACTIVE. Thus changing the global Python version.
Use dict.setdefault()
:
dic.setdefault(key,[]).append(value)
help(dict.setdefault):
setdefault(...)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
You are using the beta version of angular CLI you can do this way.
npm uninstall -g @angular/cli
npm uninstall -g angular/cli
Then type,
npm cache clean
Then go to the AppData folder which is hidden in your users and go to roaming folder which is inside AppData then go to npm folder and delete angular files in there and also go to npm-cache folder and delete angular components in there.After that restart your PC and type
npm install -g @angular/cli@latest
This worked for me ??
You should consider have other php files included if you're going to derive a website from it. Instead of doing all the css/etc in that file, you can do
<head>
<?php include_once('C:\Users\George\Documents\HTML\style.css'); ?>
<title>Title</title>
</hea>
Then you can have a separate CSS file that is just being pulled into your php file. It provides some "neater" coding.
varbinary(max)
is the way to go (introduced in SQL Server 2005)
This did the trick for me; full example:
HTML:
<a href="/my-popup.php" class="import">Click for my popup on same domain</a>
Javascript:
(function(){
var doc = document;
jQuery('.import').click(function(e){
e.preventDefault();
window.popup = window.open(jQuery(this).attr('href'), 'importwindow', 'width=500, height=200, top=100, left=200, toolbar=1');
window.popup.onload = function() {
window.popup.onbeforeunload = function(){
doc.location.reload(true); //will refresh page after popup close
}
}
});
})();
If you want to run a Python subprocess under the virtualenv, you can do that by running the script using the Python interpreter that lives inside virtualenv's /bin/ directory:
import subprocess
# Path to a Python interpreter that runs any Python script
# under the virtualenv /path/to/virtualenv/
python_bin = "/path/to/virtualenv/bin/python"
# Path to the script that must run under the virtualenv
script_file = "must/run/under/virtualenv/script.py"
subprocess.Popen([python_bin, script_file])
However, if you want to activate the virtualenv under the current Python interpreter instead of a subprocess, you can use the activate_this.py
script:
# Doing execfile() on this file will alter the current interpreter's
# environment so you can import libraries in the virtualenv
activate_this_file = "/path/to/virtualenv/bin/activate_this.py"
execfile(activate_this_file, dict(__file__=activate_this_file))
just use
$memcachedConfig = array();
before
print $memcachedConfig['host'];
print $memcachedConfig['port'];
Warning: Illegal string offset 'host' in ....
Warning: Illegal string offset 'port' in ....
this is because you never define what is $memcachedConfig, so by default are treated by string not arrays..
A callback lets you pass executable code as an argument to other code. In C and C++ this is implemented as a function pointer. In .NET you would use a delegate to manage function pointers.
A few uses include error signaling and controlling whether a function acts or not.
It's because the iterable is
(x > 0 for x in list)
Note that x > 0
returns either True
or False
and thus you have an iterable of booleans.
Set the html tag, too. This way no weird position hacks are required.
html, body {height: 100%}
As @high6 and @erik-p-hansen pointed out in the answer given by @high6, this can be overcome by importing the target for the module where the PrimeNumberModel class is, which is probably the same name as your project in a simple project.
While looking at this, I came across the article Write your first Unit Test in Swift on swiftcast.tv by Clayton McIlrath. It discusses access modifiers, shows an example of the same problem you are having (but for a ViewController rather than a model file) and shows how to both import the target and solve the access modifier problem by including the destination file in the target, meaning you don't have to make the class you are trying to test public unless you actually want to do so.
<?php
list($year) = explode("-", "2068-06-15");
echo $year;
?>
Get comfortable with zip
. It comes in handy when dealing with column data.
df['new_col'] = list(zip(df.lat, df.long))
It's less complicated and faster than using apply
or map
. Something like np.dstack
is twice as fast as zip
, but wouldn't give you tuples.
sudo find / -Bmin 60
From the man
page:
-Bmin n
True if the difference between the time of a file's inode creation and the time
find
was started, rounded up to the next full minute, is n minutes.
Obviously, you may want to set up a bit differently, but this primary seems the best solution for searching for any file created in the last N minutes.
OK - what you're missing is that its designed to be more industrial and serve many sites, so the config you want is probably:
/etc/apache2/sites-available/default
which on my system is linked to from /etc/apache2/sites-enabled/
if you want to have different sites with different options, copy the file and then change those...
Below is code which reads excel file by opening dialog and then uses async and wait to run asynchronous the code which reads one by one line from excel and binds to grid
namespace EmailBillingRates
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
lblProcessing.Text = "";
}
private async void btnReadExcel_Click(object sender, EventArgs e)
{
string filename = OpenFileDialog();
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(filename);
Microsoft.Office.Interop.Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Microsoft.Office.Interop.Excel.Range xlRange = xlWorksheet.UsedRange;
try
{
Task<int> longRunningTask = BindGrid(xlRange);
int result = await longRunningTask;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
//cleanup
// GC.Collect();
//GC.WaitForPendingFinalizers();
//rule of thumb for releasing com objects:
// never use two dots, all COM objects must be referenced and released individually
// ex: [somthing].[something].[something] is bad
//release com objects to fully kill excel process from running in the background
Marshal.ReleaseComObject(xlRange);
Marshal.ReleaseComObject(xlWorksheet);
//close and release
xlWorkbook.Close();
Marshal.ReleaseComObject(xlWorkbook);
//quit and release
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
}
}
private void btnSendEmail_Click(object sender, EventArgs e)
{
}
private string OpenFileDialog()
{
string filename = "";
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "Excel File Dialog";
fdlg.InitialDirectory = @"c:\";
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
fdlg.FilterIndex = 2;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
filename = fdlg.FileName;
}
return filename;
}
private async Task<int> BindGrid(Microsoft.Office.Interop.Excel.Range xlRange)
{
lblProcessing.Text = "Processing File.. Please wait";
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
// dt.Column = colCount;
dataGridView1.ColumnCount = colCount;
dataGridView1.RowCount = rowCount;
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
//write the value to the Grid
if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
{
await Task.Delay(1);
dataGridView1.Rows[i - 1].Cells[j - 1].Value = xlRange.Cells[i, j].Value2.ToString();
}
}
}
lblProcessing.Text = "";
return 0;
}
}
internal class async
{
}
}
And this is if copying a single property to another list is needed:
targetList.AddRange(sourceList.Select(i => i.NeededProperty));
The language standard simply doesn't allow for it. Labels can only be followed by statements, and declarations do not count as statements in C. The easiest way to get around this is by inserting an empty statement after your label, which relieves you from keeping track of the scope the way you would need to inside a block.
#include <stdio.h>
int main ()
{
printf("Hello ");
goto Cleanup;
Cleanup: ; //This is an empty statement.
char *str = "World\n";
printf("%s\n", str);
}
Yes, to increase the threads number you need to increase the virtual memory or decrease the stack size. In Raspberry Pi I didn’t find a way to increase the virtual memory, if a decrease the stack size from default 8MB to 1MB It is possibly get more than 1000 threads per process but decrease the stack size with the “ulimit -s” command make this for all threads. So, my solution was use “pthread_t” instance “thread class” because the pthread_t let me set the stack size per each thread. Finally, I am available to archive more than 1000 threads per process in Raspberry Pi each one with 1MB of stack.
Here is simple solution for Windows 7 and Nexus 5 on Android 5.
Original: http://www.android.gs/download-and-install-google-nexus-5-usb-drivers-adb-fastboot/
Note: do not forget to enable USB debugging on your device :)
Trying to access an undefined variable will throw you a ReferenceError
.
A solution to this is to use typeof
:
if (typeof window === "undefined") {
console.log("Oops, `window` is not defined")
}
or a try catch:
try { window } catch (err) {
console.log("Oops, `window` is not defined")
}
While typeof window
is probably the cleanest of the two, the try catch can still be useful in some cases.
As of Spring 5.1 you can use HttpHeaders.setBasicAuth
Create Basic Authorization header:
String username = "willie";
String password = ":p@ssword";
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(username, password);
...other headers goes here...
Pass the headers to the RestTemplate:
HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<Account> response = restTemplate.exchange(url, HttpMethod.GET, request, Account.class);
Account account = response.getBody();
Try to put android:gravity="center_vertical|right"
inside parent LinearLayout else as you are inside RelativeLayout you can put android:layout_centerInParent="true"
inside your scrollView
.
In my case settings.gradle contained invalid configuration.
I changed:
include ':app' rootProject.name='<somthing else>'
To:
include ':app'
Error is gone. So maybe check your settings.gradle for potential errors. If this won't work try to remove cache and other tips.
Give Safe User Permission To Use Port 80
Remember, we do NOT want to run your applications as the root user, but there is a hitch: your safe user does not have permission to use the default HTTP port (80). You goal is to be able to publish a website that visitors can use by navigating to an easy to use URL like http://ip:port/
Unfortunately, unless you sign on as root, you’ll normally have to use a URL like http://ip:port
- where port number > 1024.
A lot of people get stuck here, but the solution is easy. There a few options but this is the one I like. Type the following commands:
sudo apt-get install libcap2-bin
sudo setcap cap_net_bind_service=+ep `readlink -f \`which node\``
Now, when you tell a Node application that you want it to run on port 80, it will not complain.
Check this reference link
Did you see ExpandoObject class?
Directly from MSDN description: "Represents an object whose members can be dynamically added and removed at run time."
With it you can write code like this:
dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
((IDictionary<String, Object>)employee).Remove("Name");
It seems to work fine in Google Chrome. Which browser are you using? Here the proof http://jsfiddle.net/CN8XL/
Anyhow you can also access to the input value parameter through the document.FormName.checkyear.value
. You have to wrap in the input in a <form>
tag like with the proper name
attribute, like shown below:
<form name="FormName">
<input type="hidden" name="checkyear" id="checkyear" value="">
</form>
Have you considered using the jQuery Library? Here are the docs for .val()
function.
There's no easy way to do this, but something like this will work:
SELECT ET.TrainingID,
ET.CompletedDate,
ET.Notes
FROM
HR_EmployeeTrainings ET
inner join
(
select TrainingID, Max(CompletedDate) as CompletedDate
FROM HR_EmployeeTrainings
WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID)
GROUP BY AvantiRecID, TrainingID
) ET2
on ET.TrainingID = ET2.TrainingID
and ET.CompletedDate = ET2.CompletedDate
If you're looking for arbitrary strings, and not just characters, you can use an overload of IndexOfAny which takes string arguments from the new project NLib:
if (s.IndexOfAny("aaa", "bbb", "ccc", StringComparison.Ordinal) >= 0)
In addition to backticks `command`
, command substitution can be done with $(command)
or "$(command)"
, which I find easier to read, and allows for nesting.
OUTPUT=$(ls -1)
echo "${OUTPUT}"
MULTILINE=$(ls \
-1)
echo "${MULTILINE}"
Quoting ("
) does matter to preserve multi-line variable values; it is optional on the right-hand side of an assignment, as word splitting is not performed, so OUTPUT=$(ls -1)
would work fine.
My way on Windows 8
Add a directory with ssh-keygen to the system PATH variable, usually C:\Program Files (x86)\Git\bin
Open CMD, go to C:\Users\Me\
Generate SSH key ssh-keygen -t rsa
Enter file in which to save the key (//.ssh/id_rsa): .ssh/id_rsa (change a default incorrect path to .ssh/somegoodname_rsa)
Add the key to Heroku heroku keys:add
Select a created key from a list
Go to your app directory, write some beautiful code
Init a git repo git init
git add .
git commit -m 'chore(release): v0.0.1
Create Heroku application heroku create
Deploy your app git push heroku master
Open your app heroku open
some comments says that it works and some say it doesn't
It works only for your form
background not any other controls
behind
For me - here is a less confusing way of doing the socket.setTimeout
var request=require('https').get(
url
,function(response){
var r='';
response.on('data',function(chunk){
r+=chunk;
});
response.on('end',function(){
console.dir(r); //end up here if everything is good!
});
}).on('error',function(e){
console.dir(e.message); //end up here if the result returns an error
});
request.on('error',function(e){
console.dir(e); //end up here if a timeout
});
request.on('socket',function(socket){
socket.setTimeout(1000,function(){
request.abort(); //causes error event ?
});
});
Here's a rather unconventional way of doing it:
#inputcontainer
{
display:table-cell; //display like a <td> to make the vertical-align work
text-align:center; //centre the input horizontally
vertical-align:middle; //centre the input vertically
width:200px; //widen the div for demo purposes
height:200px; //make the div taller for demo purposes
background:green; //change the background of the div for demo purposes
}
It might not be the best way to do it, and margin? won't work, but it does the job. If you need to use margin, then you could wrap the div that displays as a table cell in another 'normal' div.
JSFiddle: http://jsfiddle.net/qw4QW/
There's one in scipy.stats:
>>> import scipy.stats
>>> scipy.stats.norm(0, 1)
<scipy.stats.distributions.rv_frozen object at 0x928352c>
>>> scipy.stats.norm(0, 1).pdf(0)
0.3989422804014327
>>> scipy.stats.norm(0, 1).cdf(0)
0.5
>>> scipy.stats.norm(100, 12)
<scipy.stats.distributions.rv_frozen object at 0x928352c>
>>> scipy.stats.norm(100, 12).pdf(98)
0.032786643008494994
>>> scipy.stats.norm(100, 12).cdf(98)
0.43381616738909634
>>> scipy.stats.norm(100, 12).cdf(100)
0.5
[One thing to beware of -- just a tip -- is that the parameter passing is a little broad. Because of the way the code is set up, if you accidentally write scipy.stats.norm(mean=100, std=12)
instead of scipy.stats.norm(100, 12)
or scipy.stats.norm(loc=100, scale=12)
, then it'll accept it, but silently discard those extra keyword arguments and give you the default (0,1).]
Maybe you can use float:right;:
.one {_x000D_
padding-left: 1em;_x000D_
text-color: white;_x000D_
display:inline; _x000D_
}_x000D_
.two {_x000D_
background-color: #00ffff;_x000D_
}_x000D_
.pull-right{_x000D_
float:right;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div class="row">_x000D_
<h3 class="one">Text</h3>_x000D_
<button class="btn btn-secondary pull-right">Button</button>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
To put it on one line:
currentLoad = IIf(IsNumeric(oXLSheet2.Cells(4, 6).Value), CInt(oXLSheet2.Cells(4, 6).Value), 0)
According to the HTML5 Spec:
A valid browsing context name is any string with at least one character that does not start with a U+005F LOW LINE character. (Names starting with an underscore are reserved for special keywords.)
A valid browsing context name or keyword is any string that is either a valid browsing context name or that is an ASCII case-insensitive match for one of: _blank, _self, _parent, or _top." - Source
That means that there is no such keyword as _new
in HTML5, and not in HTML4 (and consequently XHTML) either. That means, that there will be no consistent behavior whatsoever if you use this as a value for the target attribute.
As Daniel and Michael have pointed out in the comments, when using target _blank
pointing to an untrusted website, you should, in addition, set rel="noopener"
. This prevents the opening site to mess with the opener via JavaScript. See this post for more information.
I know this is very old and possibly talking about an older version of Visual studio and so this might not have been an option before but anyway, my way would be when at a breakpoint use the locals window to see all current variable values ( Debug >> Windows >> Locals )
I always do input prompts, like this:
<input style="color: #C0C0C0;" value="[email protected]"
onfocus="this.value=''; this.style.color='#000000'">
Of course, if your user fills in the field, changes focus and comes back to the field, the field will once again be cleared. If you do it like that, be sure that's what you want. You can make it a one time thing by setting a semaphore, like this:
<script language = "text/Javascript">
cleared[0] = cleared[1] = cleared[2] = 0; //set a cleared flag for each field
function clearField(t){ //declaring the array outside of the
if(! cleared[t.id]){ // function makes it static and global
cleared[t.id] = 1; // you could use true and false, but that's more typing
t.value=''; // with more chance of typos
t.style.color='#000000';
}
}
</script>
Your <input> field then looks like this:
<input id = 0; style="color: #C0C0C0;" value="[email protected]"
onfocus=clearField(this)>
The error is:
Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])
In JSON, platforms
look like this:
"platforms": [
{
"platform": "iphone"
},
{
"platform": "ipad"
},
{
"platform": "android_phone"
},
{
"platform": "android_tablet"
}
]
So try change your pojo to something like this:
private List platforms;
public List getPlatforms(){
return this.platforms;
}
public void setPlatforms(List platforms){
this.platforms = platforms;
}
EDIT: you will need change mobile_networks
too. Will look like this:
private List mobile_networks;
public List getMobile_networks() {
return mobile_networks;
}
public void setMobile_networks(List mobile_networks) {
this.mobile_networks = mobile_networks;
}
In general, no. However, a struct declared as file-scope or static in a function /will/ be initialized to 0 (just like all other variables of those scopes):
int x; // 0
int y = 42; // 42
struct { int a, b; } foo; // 0, 0
void foo() {
struct { int a, b; } bar; // undefined
static struct { int c, d; } quux; // 0, 0
}
After speaking with an LDAP expert, it's not possible this way. One query can't search more than one DC or OU.
Your options are:
- Run more then 1 query and parse the result.
- Use a filter to find the desired users/objects based off a different attribute like an AD group or by name.
Another modification:
function update() {
$.get("response.php", function(data) {
$("#some_div").html(data);
window.setTimeout(update, 10000);
});
}
The difference with this is that it waits 10 seconds AFTER the ajax call is one. So really the time between refreshes is 10 seconds + length of ajax call. The benefit of this is if your server takes longer than 10 seconds to respond, you don't get two (and eventually, many) simultaneous AJAX calls happening.
Also, if the server fails to respond, it won't keep trying.
I've used a similar method in the past using .ajax to handle even more complex behaviour:
function update() {
$("#notice_div").html('Loading..');
$.ajax({
type: 'GET',
url: 'response.php',
timeout: 2000,
success: function(data) {
$("#some_div").html(data);
$("#notice_div").html('');
window.setTimeout(update, 10000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#notice_div").html('Timeout contacting server..');
window.setTimeout(update, 60000);
}
}
This shows a loading message while loading (put an animated gif in there for typical "web 2.0" style). If the server times out (in this case takes longer than 2s) or any other kind of error happens, it shows an error, and it waits for 60 seconds before contacting the server again.
This can be especially beneficial when doing fast updates with a larger number of users, where you don't want everyone to suddenly cripple a lagging server with requests that are all just timing out anyways.
JavaScript will be required, but the amount of code can be kept to a minimum by using an intermediary <output>
element and an oninput
form handler to perform the comparison (patterns and validation could augment this solution, but aren't shown here for sake of simplicity):
<form oninput="result.value=!!p2.value&&(p1.value==p2.value)?'Match!':'Nope!'">
<input type="password" name="p1" value="" required />
<input type="password" name="p2" value="" required />
<output name="result"></output>
</form>
Report from the future: April 2018.
I wanted to normalize my local repos on my Mac and my Windows, which had ended up in different local folders.
The Windows 10 client made me go through the "Can't Find" > "Locate" routine, tedious but not terrible. Also need to update the local "Clone path" in Options for future use.
When I consolidated the mac folders, the Github client just found them again - I had to do nothing!
In Java 8, you can do it in a simpler and clean way :
if ("POST".equalsIgnoreCase(request.getMethod()))
{
test = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
}
format
supports a percentage floating point precision type:
>>> print "{0:.0%}".format(1./3)
33%
If you don't want integer division, you can import Python3's division from __future__
:
>>> from __future__ import division
>>> 1 / 3
0.3333333333333333
# The above 33% example would could now be written without the explicit
# float conversion:
>>> print "{0:.0f}%".format(1/3 * 100)
33%
# Or even shorter using the format mini language:
>>> print "{:.0%}".format(1/3)
33%
The C++ String Toolkit Library (StrTk) has the following solution:
static const std::size_t digit_table_symbol_count = 256;
static const unsigned char digit_table[digit_table_symbol_count] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xFF - 0x07
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x08 - 0x0F
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x10 - 0x17
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x18 - 0x1F
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x20 - 0x27
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x28 - 0x2F
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // 0x30 - 0x37
0x08, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x38 - 0x3F
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x40 - 0x47
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x48 - 0x4F
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x50 - 0x57
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x58 - 0x5F
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x60 - 0x67
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x68 - 0x6F
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x70 - 0x77
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x78 - 0x7F
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x80 - 0x87
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x88 - 0x8F
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x90 - 0x97
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x98 - 0x9F
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xA0 - 0xA7
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xA8 - 0xAF
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xB0 - 0xB7
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xB8 - 0xBF
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xC0 - 0xC7
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xC8 - 0xCF
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xD0 - 0xD7
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xD8 - 0xDF
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xE0 - 0xE7
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xE8 - 0xEF
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xF0 - 0xF7
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF // 0xF8 - 0xFF
};
template<typename InputIterator, typename T>
inline bool string_to_signed_type_converter_impl_itr(InputIterator begin, InputIterator end, T& v)
{
if (0 == std::distance(begin,end))
return false;
v = 0;
InputIterator it = begin;
bool negative = false;
if ('+' == *it)
++it;
else if ('-' == *it)
{
++it;
negative = true;
}
if (end == it)
return false;
while(end != it)
{
const T digit = static_cast<T>(digit_table[static_cast<unsigned int>(*it++)]);
if (0xFF == digit)
return false;
v = (10 * v) + digit;
}
if (negative)
v *= -1;
return true;
}
The InputIterator can be of either unsigned char*, char* or std::string iterators, and T is expected to be a signed int, such as signed int, int, or long
Here i have done complete bins for above query. below is demo link, i think it may help you
Demo: http://codebins.com/bin/4ldqp9b/1
HTML:
<div id="edge">
<div class="box" style="top:20; background:#f8a2a4;">
</div>
<div class="box" style="top:70; background:#a2f8a4;">
</div>
<div class="box" style="top:120; background:#5599fd;">
</div>
</div>
<br/>
<input type="button" id="btnAnimate" name="btnAnimate" value="Animate" />
CSS:
body{
background:#ffffef;
}
#edge{
width:500px;
height:200px;
border:1px solid #3377af;
padding:5px;
}
.box{
position:absolute;
left:10;
width:40px;
height:40px;
border:1px solid #a82244;
}
JQuery:
$(function() {
$("#btnAnimate").click(function() {
var move = "";
if ($(".box:eq(0)").css('left') == "10px") {
move = "+=" + ($("#edge").width() - 35);
} else {
move = "-=" + ($("#edge").width() - 35);
}
$(".box").animate({
left: move
}, 500, function() {
if ($(".box:eq(0)").css('left') == "475px") {
$(this).css('background', '#afa799');
} else {
$(".box:eq(0)").css('background', '#f8a2a4');
$(".box:eq(1)").css('background', '#a2f8a4');
$(".box:eq(2)").css('background', '#5599fd');
}
});
});
});
The same happened to me. But the scenario was a little different, I had master branch, and I carved out release_1 (say) out of it. Made some changes in release_1 branch and merged it into origin. then I did ssh and on the remote server I again checkout out release_1 using the command git checkout -b release_1 - which actually carves out a new branch release_! from the master rather than checking out the already existing branch release_1 from origin. Solved the problem by removing "-b" switch
Thank you Phil for your solution; in case someone ever gets in the same situation as me, here is a (more complex) variant:
---
# this is just to avoid a call to |default on each iteration
- set_fact:
postconf_d: {}
- name: 'get postfix default configuration'
command: 'postconf -d'
register: command
# the answer of the command give a list of lines such as:
# "key = value" or "key =" when the value is null
- name: 'set postfix default configuration as fact'
set_fact:
postconf_d: >
{{
postconf_d |
combine(
dict([ item.partition('=')[::2]|map('trim') ])
)
with_items: command.stdout_lines
This will give the following output (stripped for the example):
"postconf_d": {
"alias_database": "hash:/etc/aliases",
"alias_maps": "hash:/etc/aliases, nis:mail.aliases",
"allow_min_user": "no",
"allow_percent_hack": "yes"
}
Going even further, parse the lists in the 'value':
- name: 'set postfix default configuration as fact'
set_fact:
postconf_d: >-
{% set key, val = item.partition('=')[::2]|map('trim') -%}
{% if ',' in val -%}
{% set val = val.split(',')|map('trim')|list -%}
{% endif -%}
{{ postfix_default_main_cf | combine({key: val}) }}
with_items: command.stdout_lines
...
"postconf_d": {
"alias_database": "hash:/etc/aliases",
"alias_maps": [
"hash:/etc/aliases",
"nis:mail.aliases"
],
"allow_min_user": "no",
"allow_percent_hack": "yes"
}
A few things to notice:
in this case it's needed to "trim" everything (using the >-
in YAML and -%}
in Jinja), otherwise you'll get an error like:
FAILED! => {"failed": true, "msg": "|combine expects dictionaries, got u\" {u'...
obviously the {% if ..
is far from bullet-proof
in the postfix case, val.split(',')|map('trim')|list
could have been simplified to val.split(', ')
, but I wanted to point out the fact you will need to |list
otherwise you'll get an error like:
"|combine expects dictionaries, got u\"{u'...': <generator object do_map at ...
Hope this can help.
try this
In your controller use
> $scope.onMapOverlayCompleted = onMapOverlayCompleted;
>
> function onMapOverlayCompleted(e) {
>
> e.overlay.getPath().getArray().forEach(function (position) {
> console.log('lat', position.lat());
> console.log('lng', position.lng());
> });
>
> }
**In Your html page , include drawning manaer**
<ng-map id="geofence-map" zoom="8" center="current" default-style="true" class="map-layout map-area"
tilt="45"
heading="90">
<drawing-manager
on-overlaycomplete="onMapOverlayCompleted()"
drawing-control-options="{position: 'TOP_CENTER',drawingModes:['polygon','circle']}"
drawingControl="true"
drawingMode="null"
markerOptions="{icon:'www.example.com/icon'}"
rectangleOptions="{fillColor:'#B43115'}"
circleOptions="{fillColor: '#F05635',fillOpacity: 0.50,strokeWeight: 5,clickable: false,zIndex: 1,editable: true}">
</drawing-manager>
</ng-map>
You have to write this code instead of return View(); :
return RedirectToAction("ActionName", "ControllerName");
If you really want constants, not just variables looking like constants, the standard way to do it is to use immutable dictionaries. Unfortunately it's not built-in yet, so you have to use third party recipes (like this one or that one).
You need to close the input element with />
at the end. In React, we have to close every element. Your code should be:
<input id="icon_prefix" type="text" class="validate/">
I believe the main (only?) different is inheritance:
class T < S
end
p T.k
=> 23
S.k = 24
p T.k
=> 24
p T.s
=> nil
Class variables are shared by all "class instances" (i.e. subclasses), whereas class instance variables are specific to only that class. But if you never intend to extend your class, the difference is purely academic.
You can treat a submodule exactly like an ordinary repository. To propagate your changes upstream just commit and push as you would normally within that directory.
In options object you have used "=" sign to assign value to port but we have to use ":" to assign values to properties in object when using object literal to create an object i.e."{}" ,these curly brackets. Even when you use function expression or create an object inside object you have to use ":" sign. for e.g.:
var rishabh = {
class:"final year",
roll:123,
percent: function(marks1, marks2, marks3){
total = marks1 + marks2 + marks3;
this.percentage = total/3 }
};
john.percent(85,89,95);
console.log(rishabh.percentage);
here we have to use commas "," after each property. but you can use another style to create and initialize an object.
var john = new Object():
john.father = "raja"; //1st way to assign using dot operator
john["mother"] = "rani";// 2nd way to assign using brackets and key must be string
I'll take a stab at it:
/^[a-z](?:_?[a-z0-9]+)*$/i
Explained:
/
^ # match beginning of string
[a-z] # match a letter for the first char
(?: # start non-capture group
_? # match 0 or 1 '_'
[a-z0-9]+ # match a letter or number, 1 or more times
)* # end non-capture group, match whole group 0 or more times
$ # match end of string
/i # case insensitive flag
The non-capture group takes care of a) not allowing two _
's (it forces at least one letter or number per group) and b) only allowing the last char to be a letter or number.
Some test strings:
"a": match
"_": fail
"zz": match
"a0": match
"A_": fail
"a0_b": match
"a__b": fail
"a_1_c": match
Slicing of arrays is done with [first:last+1]
.
One trick I tend to use a lot of is to indicate extra information with ellipses. So, if your field is one hundred characters, I would use:
if len(s) <= 100:
print s
else:
print "%s..."%(s[:97])
And yes, I know ()
is superfluous in this case for the %
formatting operator, it's just my style.
The below query takes the first date for each work order (in a table of showing all status changes):
SELECT
WORKORDERNUM,
MIN(DATE)
FROM
WORKORDERS
WHERE
DATE >= to_date('2015-01-01','YYYY-MM-DD')
GROUP BY
WORKORDERNUM
I was having this exact issue and this was because I was returning images from a server into component that is 1 step down the path. This what I mean. See file arrangement
*projectfolder/phpfiles/component.php*
Now my images folder was located here projectfolder/images/
Now I fixed it by adding ../ so that it could skip 1 step backwards
Goodluck
Your and
should be a &&
in the where
clause.
where epl.DepartAirportAfter > sd.UTCDepartureTime
and epl.ArriveAirportBy > sd.UTCArrivalTime
should be
where epl.DepartAirportAfter > sd.UTCDepartureTime
&& epl.ArriveAirportBy > sd.UTCArrivalTime
Before clear space (trim)
Then replace with RegEx .replace("/\xEF\xBB\xBF/", "")
I'm working on Javascript, I did with JavaScript.
To resize the image proportionally using CSS:
img.resize {
width:540px; /* you can use % */
height: auto;
}
statmodels graphics also gives a nice view of correlation matrix
import statsmodels.api as sm
import matplotlib.pyplot as plt
corr = dataframe.corr()
sm.graphics.plot_corr(corr, xnames=list(corr.columns))
plt.show()
If you want to turn off logging programmatically then use
List<Logger> loggers = Collections.<Logger>list(LogManager.getCurrentLoggers());
loggers.add(LogManager.getRootLogger());
for ( Logger logger : loggers ) {
logger.setLevel(Level.OFF);
}
Have you considered using this.props.navigation.replace( "HomeScreen" )
instead of this.props.navigation.navigate( "HomeScreen" )
.
This way you are not adding anything to the stack. so HomeScreen won't wave anything to go back to if back button pressed in Android or screen swiped to the right in IOS.
More informations check the Documentation.
And of course you can hide the back button by setting headerLeft: null
in navigationOptions
A jar file is a zip archive. You can extract it using 7zip (a great simple tool to open archives). You can also change its extension to zip and use whatever to unzip the file.
Now you have your class file. There is no easy way to edit class file, because class files are binaries (you won't find source code in there. maybe some strings, but not java code). To edit your class file you can use a tool like classeditor.
You have all the strings your class is using hard-coded in the class file. So if the only thing you would like to change is some strings you can do it without using classeditor.
Based on the answer from @Ryan Ahearn
, following is what I did on Ubuntu
16.04 to create a user front
that only has permission for nginx's web dir /var/www/html
.
Steps:
* pre-steps: * basic prepare of server, * create user 'dev' which will be the owner of "/var/www/html", * * install nginx, * * * create user 'front' sudo useradd -d /home/front -s /bin/bash front sudo passwd front # create home folder, if not exists yet, sudo mkdir /home/front # set owner of new home folder, sudo chown -R front:front /home/front # switch to user, su - front # copy .bashrc, if not exists yet, cp /etc/skel/.bashrc ~front/ cp /etc/skel/.profile ~front/ # enable color, vi ~front/.bashrc # uncomment the line start with "force_color_prompt", # exit user exit * * add to group 'dev', sudo usermod -a -G dev front * change owner of web dir, sudo chown -R dev:dev /var/www * change permission of web dir, chmod 775 $(find /var/www/html -type d) chmod 664 $(find /var/www/html -type f) * * re-login as 'front' to make group take effect, * * test * * ok *
Another way is to use constant pattern matching:
if (nullableBool is true) {}
if (nullableBool is false) {}
if (nullableBool is null) {}
Unlike the operator ==
, when reading the code, this will distinguish the nullable type check from ordinary "code with a smell".
Statically typed languages type-check at compile time and the type can NOT change. (Don't get cute with type-casting comments, a new variable/reference is created).
Dynamically typed languages type-check at run-time and the type of an variable CAN be changed at run-time.
Here's another way
Sub testborder()
Dim rRng As Range
Set rRng = Sheet1.Range("B2:D5")
'Clear existing
rRng.Borders.LineStyle = xlNone
'Apply new borders
rRng.BorderAround xlContinuous
rRng.Borders(xlInsideHorizontal).LineStyle = xlContinuous
rRng.Borders(xlInsideVertical).LineStyle = xlContinuous
End Sub
Add it to the session, not to the request.
HttpSession session = request.getSession();
session.setAttribute("object", object);
Also, don't use scriptlets in the JSP. Use EL instead; to access object
all you need is ${object}
.
A primary feature of JSP technology version 2.0 is its support for an expression language (EL). An expression language makes it possible to easily access application data stored in JavaBeans components. For example, the JSP expression language allows a page author to access a bean using simple syntax such as
${name}
for a simple variable or${name.foo.bar}
for a nested property.
It seems that your question is quite answered, but i have an approach that may simplify you case:
I had a similar issue trying to return string data from mysql, even configuring both database and php to return strings formatted to utf-8. The only way i got the error was actually returning them from the database.
Finally, sailing through the web i found a really easy way to deal with it:
Giving that you can save all those types of string data in your mysql in different formats and collations, what you only need to do is, right at your php connection file, set the collation to utf-8, like this:
$connection = new mysqli($server, $user, $pass, $db);
$connection->set_charset("utf8");
Wich means that first you save the data in any format or collation and you convert it only at the return to your php file.
Hope it was helpful!
parentElement
is new to Firefox 9 and to DOM4, but it has been present in all other major browsers for ages.
In most cases, it is the same as parentNode
. The only difference comes when a node's parentNode
is not an element. If so, parentElement
is null
.
As an example:
document.body.parentNode; // the <html> element
document.body.parentElement; // the <html> element
document.documentElement.parentNode; // the document node
document.documentElement.parentElement; // null
(document.documentElement.parentNode === document); // true
(document.documentElement.parentElement === document); // false
Since the <html>
element (document.documentElement
) doesn't have a parent that is an element, parentElement
is null
. (There are other, more unlikely, cases where parentElement
could be null
, but you'll probably never come across them.)
Are you just looking to verify that the file is of a given extension? You can simplify what you are trying to do with something like this:
(.*?)\.(jpg|gif|doc|pdf)$
Then, when you call IsMatch() make sure to pass RegexOptions.IgnoreCase as your second parameter. There is no reason to have to list out the variations for casing.
Edit: As Dario mentions, this is not going to work for the RegularExpressionValidator, as it does not support casing options.
You need to have the System.Linq
namespace included in your view since Select is an extension method. You have a couple of options on how to do this:
Add @using System.Linq
to the top of your cshtml file.
If you find that you will be using this namespace often in many of your views, you can do this for all views by modifying the web.config inside of your Views folder (not the one at the root). You should see a pages/namespace XML element, create a new add
child that adds System.Linq. Here is an example:
<configuration>
<system.web.webPages.razor>
<pages>
<namespaces>
<add namespace="System.Linq" />
</namespaces>
</pages>
</system.web.webPages.razor>
</configuration>
I am having the same problem and tried many ways but at last, I have got to know that I don't have sufficient permissions to push or pull on this repo and one more way to check if you are having the permissions or not is you were not able to see settings option in that repo and if you were having permissions then you will be able to see settings option
Thanks! this is what I observed
Reference to http://developer.android.com/training/basics/activity-lifecycle/starting.html
onResume()
Called just before the activity starts interacting with the user. At this point the activity is at the top of the activity stack, with user input going to it.
Always followed by onPause()
.
onPause()
Called when the system is about to start resuming another activity. This method is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, and so on. It should do whatever it does very quickly, because the next activity will not be resumed until it returns.
Followed either by onResume()
if the activity returns back to the front, or by onStop()
if it becomes invisible to the user.
Just use -p1
: you will need to use -p0
in the --no-prefix
case anyway, so you can just leave out the --no-prefix
and use -p1
:
$ git diff > save.patch
$ patch -p1 < save.patch
$ git diff --no-prefix > save.patch
$ patch -p0 < save.patch
Remove obj
and just do this inside your for loop:
arr.push(i);
Also, the i < yearEnd
condition will not include the final year, so change it to i <= yearEnd
.
class a(object):
def my_hello(self):
print "hello ravi"
class b(a):
def my_hello(self):
super(b,self).my_hello()
print "hi"
obj = b()
obj.my_hello()
I think if you try:
Sub Macro3()
a = ActiveSheet.UsedRange.Columns.Count - 3
End Sub
with a watch on a
you will see it does make a difference.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/recycler_view"/>
</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="46dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:text="TextView"
android:textSize="16dp" />
</LinearLayout>
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private List<String> data;
public CustomAdapter (List<String> data){
this.data = data;
}
@Override
public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_view, parent, false);
return new ViewHolder(rowItem);
}
@Override
public void onBindViewHolder(CustomAdapter.ViewHolder holder, int position) {
holder.textView.setText(this.data.get(position));
}
@Override
public int getItemCount() {
return this.data.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView textView;
public ViewHolder(View view) {
super(view);
view.setOnClickListener(this);
this.textView = view.findViewById(R.id.textview);
}
@Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "position : " + getLayoutPosition() + " text : " + this.textView.getText(), Toast.LENGTH_SHORT).show();
}
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new CustomAdapter(generateData()));
recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
}
private List<String> generateData() {
List<String> data = new ArrayList<>();
for (int i = 0; i < 100; i++) {
data.add(String.valueOf(i) + "th Element");
}
return data;
}
}
My case was that I had a typo on the referred column:
MariaDB [blog]> alter table t_user add FOREIGN KEY ( country_code ) REFERENCES t_country ( coutry_code );
ERROR 1005 (HY000): Can't create table `blog`.`t_user` (errno: 150 "Foreign key constraint is incorrectly formed")
The error message is quite cryptic and I've tried everything - verifying the types of the columns, collations, engines, etc.
It took me awhile to note the typo and after fixing it all worked fine:
MariaDB [blog]> alter table t_user add FOREIGN KEY ( country_code ) REFERENCES t_country ( country_code );
Query OK, 2 rows affected (0.039 sec)
Records: 2 Duplicates: 0 Warnings: 0
An alternative to services is to use the value store.
In the base of my app I added this
var agentApp = angular.module('rbAgent', ['ui.router', 'rbApp.tryGoal', 'rbApp.tryGoal.service', 'ui.bootstrap']);
agentApp.value('agentMemory',
{
contextId: '',
sessionId: ''
}
);
...
And then in my controller I just reference the value store. I don't think it holds thing if the user closes the browser.
angular.module('rbAgent')
.controller('AgentGoalListController', ['agentMemory', '$scope', '$rootScope', 'config', '$state', function(agentMemory, $scope, $rootScope, config, $state){
$scope.config = config;
$scope.contextId = agentMemory.contextId;
...
This error is actually the result of you not including bootstrap's javascript before calling the modal
function. Modal is defined in bootstrap.js not jQuery. It's also important to note that bootstrap actually needs jQuery to define the modal
function, so it's vital that you include jQuery before including bootstrap's javascript. To avoid the error just be sure to include jQuery then bootstrap's javascript before you call the modal
function. I usually do the following in my header tag:
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/path/to/bootstrap/js/bootstrap.min.js"></script>
</header>
// loading bytes from a file is very easy in C#. The built in System.IO.File.ReadAll* methods take care of making sure every byte is read properly.
// note that for Linux, you will not need the c: part
// just swap out the example folder here with your actual full file path
string pdfFilePath = "c:/pdfdocuments/myfile.pdf";
byte[] bytes = System.IO.File.ReadAllBytes(pdfFilePath);
// munge bytes with whatever pdf software you want, i.e. http://sourceforge.net/projects/itextsharp/
// bytes = MungePdfBytes(bytes); // MungePdfBytes is your custom method to change the PDF data
// ...
// make sure to cleanup after yourself
// and save back - System.IO.File.WriteAll* makes sure all bytes are written properly - this will overwrite the file, if you don't want that, change the path here to something else
System.IO.File.WriteAllBytes(pdfFilePath, bytes);
Here's a sample code on how to read a file properly inside a jar file (in this case, the current executing jar file)
Just change executable with the path of your jar file if it is not the current running one.
Then change the filePath to the path of the file you want to use inside the jar file. I.E. if your file is in
someJar.jar\img\test.gif
. Set the filePath to "img\test.gif"
File executable = new File(BrowserViewControl.class.getProtectionDomain().getCodeSource().getLocation().toURI());
JarFile jar = new JarFile(executable);
InputStream fileInputStreamReader = jar.getInputStream(jar.getJarEntry(filePath));
byte[] bytes = new byte[fileInputStreamReader.available()];
int sizeOrig = fileInputStreamReader.available();
int size = fileInputStreamReader.available();
int offset = 0;
while (size != 0){
fileInputStreamReader.read(bytes, offset, size);
offset = sizeOrig - fileInputStreamReader.available();
size = fileInputStreamReader.available();
}
Both approaches call a constructor, they just call different ones. This code:
var albumData = new Album
{
Name = "Albumius",
Artist = "Artistus",
Year = 2013
};
is syntactic shorthand for this equivalent code:
var albumData = new Album();
albumData.Name = "Albumius";
albumData.Artist = "Artistus";
albumData.Year = 2013;
The two are almost identical after compilation (close enough for nearly all intents and purposes). So if the parameterless constructor wasn't public:
public Album() { }
then you wouldn't be able to use the object initializer at all anyway. So the main question isn't which to use when initializing the object, but which constructor(s) the object exposes in the first place. If the object exposes two constructors (like the one in your example), then one can assume that both ways are equally valid for constructing an object.
Sometimes objects don't expose parameterless constructors because they require certain values for construction. Though in cases like that you can still use the initializer syntax for other values. For example, suppose you have these constructors on your object:
private Album() { }
public Album(string name)
{
this.Name = name;
}
Since the parameterless constructor is private, you can't use that. But you can use the other one and still make use of the initializer syntax:
var albumData = new Album("Albumius")
{
Artist = "Artistus",
Year = 2013
};
The post-compilation result would then be identical to:
var albumData = new Album("Albumius");
albumData.Artist = "Artistus";
albumData.Year = 2013;
git rebase -i
will do it.
First, start with a clean working directory: git status
should show no pending modifications, deletions, or additions.
Now, you have to decide which commit(s) you want to split.
To split apart your most recent commit, first:
$ git reset HEAD~
Now commit the pieces individually in the usual way, producing as many commits as you need.
This requires rebasing, that is, rewriting history. To find the correct commit, you have several choices:
If it was three commits back, then
$ git rebase -i HEAD~3
where 3
is how many commits back it is.
If it was farther back in the tree than you want to count, then
$ git rebase -i 123abcd~
where 123abcd
is the SHA1 of the commit you want to split up.
If you are on a different branch (e.g., a feature branch) that you plan to merge into master:
$ git rebase -i master
When you get the rebase edit screen, find the commit you want to break apart. At the beginning of that line, replace pick
with edit
(e
for short). Save the buffer and exit. Rebase will now stop just after the commit you want to edit. Then:
$ git reset HEAD~
Commit the pieces individually in the usual way, producing as many commits as you need, then
$ git rebase --continue
Public Function LastData(rCol As Range) As Range
Set LastData = rCol.Find("*", rCol.Cells(1), , , , xlPrevious)
End Function
Usage: ?lastdata(activecell.EntireColumn).Address
Like Jaanus told:
Calling this (-selectRowAtIndexPath:animated:scrollPosition:) method does not cause the delegate to receive a tableView:willSelectRowAtIndexPath: or tableView:didSelectRowAtIndexPath: message, nor will it send UITableViewSelectionDidChangeNotification notifications to observers.
So you just have to call the delegate
method yourself.
For example:
Swift 3 version:
let indexPath = IndexPath(row: 0, section: 0);
self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableViewScrollPosition.none)
self.tableView(self.tableView, didSelectRowAt: indexPath)
ObjectiveC version:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView selectRowAtIndexPath:indexPath
animated:YES
scrollPosition:UITableViewScrollPositionNone];
[self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
Swift 2.3 version:
let indexPath = NSIndexPath(forRow: 0, inSection: 0);
self.tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.None)
self.tableView(self.tableView, didSelectRowAtIndexPath: indexPath)
The syntax is changed in new 3.x releases rather than old 2.x releases: for example in python 2.x you can write: print "Hi new world" but in the new 3.x release you need to use the new syntax and write it like this: print("Hi new world")
check the documentation: http://docs.python.org/3.3/library/functions.html?highlight=print#print
Create a Pivot Table. It has these features and many more.
If you are dead-set on doing this yourself then you could add shapes to the worksheet and use VBA to hide and unhide rows and columns on clicking the shapes.
not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
The native lib is expected in one of the following locations
/usr/java/packages/lib/amd64
/usr/lib64
/lib64
/lib
/usr/lib
and not in
tomcat/lib
The files in tomcat/lib
are all jar
file and are added by tomcat to the classpath
so that they are available to your application.
The native lib is needed by tomcat to perform better on the platform it is installed on and thus cannot be a jar
, for linux it could be a .so
file, for windows it could be a .dll
file.
Just download the native library for your platform and place it in the one of the locations tomcat is expecting it to be.
Note that you are not required to have this lib for development/test purposes. Tomcat runs just fine without it.
org.apache.catalina.startup.Catalina start INFO: Server startup in 2882 ms
EDIT
The output you are getting is very normal, it's just some logging outputs from tomcat, the line right above indicates that the server correctly started and is ready for operating.
If you are troubling with running your servlet then after the run on sever
command eclipse opens a browser window (embeded (default) or external, depends on your config). If nothing shows on the browser, then check the url bar of the browser to see whether your servlet was requested or not.
It should be something like that
http://localhost:8080/<your-context-name>/<your-servlet-name>
EDIT 2
Try to call your servlet using the following url
http://localhost:8080/com.filecounter/FileCounter
Also each web project has a web.xml, you can find it in your project under WebContent\WEB-INF
.
It is better to configure your servlets there using servlet-name
servlet-class
and url-mapping
. It could look like that:
<servlet>
<description></description>
<display-name>File counter - My first servlet</display-name>
<servlet-name>file_counter</servlet-name>
<servlet-class>com.filecounter.FileCounter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>file_counter</servlet-name>
<url-pattern>/FileFounter</url-pattern>
</servlet-mapping>
In eclipse dynamic web project the default context name is the same as your project name.
http://localhost:8080/<your-context-name>/FileCounter
will work too.
A good example is Javascript. You want this to be at the bottom of the page that is rendered in the browser because this is best practice.
How would you do this from a View based on a Layout/Masterpage where you can only access the middle of the page?
You do this by declaring a Scripts section at the bottom of the Layout page. Then you can add content, in this case Javascript includes (I hope!), from your View page to the bottom of your layout page.
I really don't like the fact that, because of the "promise" way of doing things, the consumer of the service that uses $http has to "know" about how to unpack the response.
I just want to call something and get the data out, similar to the old $scope.items = Data.getData();
way, which is now deprecated.
I tried for a while and didn't come up with a perfect solution, but here's my best shot (Plunker). It may be useful to someone.
app.factory('myService', function($http) {
var _data; // cache data rather than promise
var myService = {};
myService.getData = function(obj) {
if(!_data) {
$http.get('test.json').then(function(result){
_data = result.data;
console.log(_data); // prove that it executes once
angular.extend(obj, _data);
});
} else {
angular.extend(obj, _data);
}
};
return myService;
});
Then controller:
app.controller('MainCtrl', function( myService,$scope) {
$scope.clearData = function() {
$scope.data = Object.create(null);
};
$scope.getData = function() {
$scope.clearData(); // also important: need to prepare input to getData as an object
myService.getData($scope.data); // **important bit** pass in object you want to augment
};
});
Flaws I can already spot are
getData
can only accept the obj
parameter in the form of an object (although it could also accept an array), which won't be a problem for many applications, but it's a sore limitation$scope.data
with = {}
to make it an object (essentially what $scope.clearData()
does above), or = []
for an array, or it won't work (we're already having to assume something about what data is coming). I tried to do this preparation step IN getData
, but no luck.Nevertheless, it provides a pattern which removes controller "promise unwrap" boilerplate, and might be useful in cases when you want to use certain data obtained from $http in more than one place while keeping it DRY.
It used to be a required part of a package (old, pre-3.3 "regular package", not newer 3.3+ "namespace package").
Python defines two types of packages, regular packages and namespace packages. Regular packages are traditional packages as they existed in Python 3.2 and earlier. A regular package is typically implemented as a directory containing an
__init__.py
file. When a regular package is imported, this__init__.py
file is implicitly executed, and the objects it defines are bound to names in the package’s namespace. The__init__.py
file can contain the same Python code that any other module can contain, and Python will add some additional attributes to the module when it is imported.
But just click the link, it contains an example, more information, and an explanation of namespace packages, the kind of packages without __init__.py
.
You could use the following code where indentation doesn't matter:
>>> def fun():
return ('{0} Here is a really long'
' sentence with {1}').format(3, 5)
You just need to enclose string in the parentheses.
I had a similar problem accessing a LDAP-Server from a docker container. I set a fixed IP for the container and added a firewall rule.
docker-compose.yml:
version: '2'
services:
containerName:
image: dockerImageName:latest
extra_hosts:
- "dockerhost:192.168.50.1"
networks:
my_net:
ipv4_address: 192.168.50.2
networks:
my_net:
ipam:
config:
- subnet: 192.168.50.0/24
iptables rule:
iptables -A INPUT -j ACCEPT -p tcp -s 192.168.50.2 -d $192.168.50.1 --dport portnumberOnHost
Inside the container access dockerhost:portnumberOnHost
I know this is a pretty old thread, but to keep things up to date and more relevant, you can use the more accurate performance.now()
functionality to get finer grain timing in javascript.
window.performance = window.performance || {};
performance.now = (function() {
return performance.now ||
performance.mozNow ||
performance.msNow ||
performance.oNow ||
performance.webkitNow ||
Date.now /*none found - fallback to browser default */
})();
Using the START
command to run each program should get you what you need:
START "title" [/D path] [options] "command" [parameters]
Every START
invocation runs the command given in its parameter and returns immediately, unless executed with a /WAIT
switch.
That applies to command-line apps. Apps without command line return immediately anyway, so to be sure, if you want to run all asynchronously, use START
.
When reading the strtok documentation, I see you need to pass in a NULL pointer after the first "initializing" call. Maybe you didn't do that. Just a guess of course.
Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-
We are doing AND operation in this example. There are also other masking operators- OR, XOR.
Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-
1 1 1 0 1 1 0 1 [input] (&) 0 0 1 1 1 1 0 0 [mask] ------------------------------ 0 0 1 0 1 1 0 0 [output]
So, only the middle 4 bits (as these bits are 1
in this mask) remain.
Lets see this with XOR-
1 1 1 0 1 1 0 1 [input] (^) 0 0 1 1 1 1 0 0 [mask] ------------------------------ 1 1 0 1 0 0 0 1 [output]
Now, the middle 4 bits are flipped (1
became 0
, 0
became 1
).
So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-
bool isOdd(int i) {
return i%2;
}
This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-
bool isOdd(int i) {
return i&1;
}
Short Explanation: If the least significant bit of a binary number is 1
then it is odd; for 0
it will be even. So, by doing AND with 1
we are removing all other bits except for the least significant bit i.e.:
55 -> 0 0 1 1 0 1 1 1 [input] (&) 1 -> 0 0 0 0 0 0 0 1 [mask] --------------------------------------- 1 <- 0 0 0 0 0 0 0 1 [output]
Judging from the error message the value of i was the empty string when you executed it, not 0.
List<T>
equality does not check them element-by-element. You can use LINQ's SequenceEqual
method for that:
var a = ints1.SequenceEqual(ints2);
To ignore order, use SetEquals
:
var a = new HashSet<int>(ints1).SetEquals(ints2);
This should work, because you are comparing sequences of IDs, which do not contain duplicates. If it does, and you need to take duplicates into account, the way to do it in linear time is to compose a hash-based dictionary of counts, add one for each element of the first sequence, subtract one for each element of the second sequence, and check if the resultant counts are all zeros:
var counts = ints1
.GroupBy(v => v)
.ToDictionary(g => g.Key, g => g.Count());
var ok = true;
foreach (var n in ints2) {
int c;
if (counts.TryGetValue(n, out c)) {
counts[n] = c-1;
} else {
ok = false;
break;
}
}
var res = ok && counts.Values.All(c => c == 0);
Finally, if you are fine with an O(N*LogN)
solution, you can sort the two sequences, and compare them for equality using SequenceEqual
.
You can use this solution. (Use nuget package) The source code is available on : Github: https://github.com/michelcedric/UserImpersonation
More detail https://michelcedric.wordpress.com/2015/09/03/usurpation-didentite-dun-user-c-user-impersonation/
You can do this using jQuery:
This method gets a list of its children then counts the length of that list, as simple as that.
$("ul").find("*").length;
The find() method traverses DOM downwards along descendants, all the way down to the last descendant.
Note: children() method traverses a single level down the DOM tree.
In a system I am developing, the string to be replaced by sed is input text from a user which is stored in a variable and passed to sed.
As noted earlier on this post, if the string contained within the sed command block contains the actual delimiter used by sed - then sed terminates on syntax error. Consider the following example:
This works:
$ VALUE=12345
$ echo "MyVar=%DEF_VALUE%" | sed -e s/%DEF_VALUE%/${VALUE}/g
MyVar=12345
This breaks:
$ VALUE=12345/6
$ echo "MyVar=%DEF_VALUE%" | sed -e s/%DEF_VALUE%/${VALUE}/g
sed: -e expression #1, char 21: unknown option to `s'
Replacing the default delimiter is not a robust solution in my case as I did not want to limit the user from entering specific characters used by sed as the delimiter (e.g. "/").
However, escaping any occurrences of the delimiter in the input string would solve the problem. Consider the below solution of systematically escaping the delimiter character in the input string before having it parsed by sed. Such escaping can be implemented as a replacement using sed itself, this replacement is safe even if the input string contains the delimiter - this is since the input string is not part of the sed command block:
$ VALUE=$(echo ${VALUE} | sed -e "s#/#\\\/#g")
$ echo "MyVar=%DEF_VALUE%" | sed -e s/%DEF_VALUE%/${VALUE}/g
MyVar=12345/6
I have converted this to a function to be used by various scripts:
escapeForwardSlashes() {
# Validate parameters
if [ -z "$1" ]
then
echo -e "Error - no parameter specified!"
return 1
fi
# Perform replacement
echo ${1} | sed -e "s#/#\\\/#g"
return 0
}
// Make option have a "selected" attribute using jQuery
var yourValue = "Gateway 2";
$("#gate").find('option').each(function( i, opt ) {
if( opt.value === yourValue )
$(opt).attr('selected', 'selected');
});
/* Try this in FF30+ Covers up the arrow, turns off the background */
/* still lets you style the border around the image and allows selection on the arrow */
@-moz-document url-prefix() {
.yourClass select {
text-overflow: '';
text-indent: -1px;
-moz-appearance: none;
background: none;
}
/*fix for popup in FF30 */
.yourClass:after {
position: absolute;
margin-left: -27px;
height: 22px;
border-top-right-radius: 6px;
border-bottom-right-radius: 6px;
content: url('../images/yourArrow.svg');
pointer-events: none;
overflow: hidden;
border-right: 1px solid #yourBorderColour;
border-top: 1px solid #yourBorderColour;
border-bottom: 1px solid #yourBorderColour;
}
}
I had the same error. I know this thread is pretty much dead already but I want to set another option besides "anonymous procedure".
I solved it like this:
Check if the stored procedure exist:
IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='my_procedure') BEGIN
print 'exists' -- or watever you want
END ELSE BEGIN
print 'doesn''texists' -- or watever you want
END
However the "CREATE/ALTER PROCEDURE' must be the first statement in a query batch"
is still there. I solved it like this:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE -- view procedure function or anything you want ...
I end up with this code:
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('my_procedure'))
BEGIN
DROP PROCEDURE my_procedure
END
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].my_procedure ...
This is actually really easy:
one of best solution enjoyed it ;)
public DataTable GetContentAsDataTable(bool IgnoreHideColumns=false)
{
try
{
if (dgv.ColumnCount == 0) return null;
DataTable dtSource = new DataTable();
foreach (DataGridViewColumn col in dgv.Columns)
{
if (IgnoreHideColumns & !col.Visible) continue;
if (col.Name == string.Empty) continue;
dtSource.Columns.Add(col.Name, col.ValueType);
dtSource.Columns[col.Name].Caption = col.HeaderText;
}
if (dtSource.Columns.Count == 0) return null;
foreach (DataGridViewRow row in dgv.Rows)
{
DataRow drNewRow = dtSource.NewRow();
foreach (DataColumn col in dtSource .Columns)
{
drNewRow[col.ColumnName] = row.Cells[col.ColumnName].Value;
}
dtSource.Rows.Add(drNewRow);
}
return dtSource;
}
catch { return null; }
}
img {_x000D_
max-width: 80px; /* Also works with percentage value like 100% */_x000D_
height: auto;_x000D_
}
_x000D_
<p>This image is originally 400x400 pixels, but should get resized by the CSS:</p>_x000D_
<img width="400" height="400" src="https://i.stack.imgur.com/aEEkn.png">_x000D_
_x000D_
<p>Let's say the author of the HTML deliberately wants_x000D_
the height to be half the value of the width,_x000D_
this CSS will ignore the HTML author's wishes, which may or may not be what you want:_x000D_
</p>_x000D_
<img width="400" height="200" src="https://i.stack.imgur.com/aEEkn.png">
_x000D_
You may try these
int selectedIndex = myComboBox.getSelectedIndex();
-or-
Object selectedObject = myComboBox.getSelectedItem();
-or-
String selectedValue = myComboBox.getSelectedValue().toString();
You can see the log info in the console view of your IDE if you are not using any log4j properties to generate log file. You can define log4j.properties in your project so that those properties would be used to generate log file. A quick sample is listed below.
# Global logging configuration
log4j.rootLogger=DEBUG, stdout, R
# SQL Map logging configuration...
log4j.logger.com.ibatis=INFO
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=INFO
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=INFO
log4j.logger.com.ibatis.SQLMap.engine.impl.SQL MapClientDelegate=INFO
log4j.logger.java.sql.Connection=INFO
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache.http=ERROR
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=MyLog.log
log4j.appender.R.MaxFileSize=50000KB
log4j.appender.R.Encoding=UTF-8
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d %5p [%t] (%F\:%L) - %m%n
Try this
myDataTable.Select("[Name] is NULL OR [Name] <> 'n/a'" )
Edit: Relevant sources:
It appears that IntelliJ 11 has changed the method, and the checked answer no longer works for me. In case anyone else arrives here via a search engine, here's how I solved it in IntelliJ 11:
Note that step 5 seems to be the key difference. If you select "jar directory" it will look exactly the same in the IDE but won't include the path at runtime. There appears to be no way to determine whether you've previously selected "classes" or "jar directory" after the fact.
If you want it to run on specific days of the month, like the 1st, 4th, 7th, etc... then you can just have a conditional in your script that checks for the current day of the month.
I thought all you needed for this was instead of */3 which means every three days, use 1/3 which means every three days starting on the 1st of the month. so 7/3 would mean every three days starting on the 7th of the month, etc.
Playing with the tsconfig.json You can also targeting es5 like this :
{
"compilerOptions": {
"experimentalDecorators": true,
"module": "commonjs",
"target": "es5"
}
...
You can follow these tutorials to get started
Tutorials
Hello World Web Server (paid)
Node JS Processing Model – Single Threaded Model with Event Loop Architecture
Developer Sites
Videos
Screencasts
Books
Courses
Blogs
Podcasts
JavaScript resources
Node.js Modules
Other
The issue arises when the image is not present on the cluster and k8s engine is going to pull the respective registry. k8s Engine enables 3 types of ImagePullPolicy mentioned :
Best Practices : It is always recommended to tag the new image in both docker file as well as k8s deployment file. So That it can pull the new image in container.
I know its Too late But I hope it will work new comers Try This Its Working ... :D
select
case
when isnumeric(my_NvarcharColumn) = 1 then
cast(my_NvarcharColumn AS int)
else
NULL
end
AS 'my_NvarcharColumnmitter'
from A
DIV
does not fire a resize
event, so you won't be able to do exactly what you've coded, but you could look into monitoring DOM properties.
If you are actually working with something like resizables, and that is the only way for a div to change in size, then your resize plugin will probably be implementing a callback of its own.
It appears that the functionality previously present in the react-cookie
npm package has been moved to universal-cookie
. The relevant example from the universal-cookie repository now is:
import Cookies from 'universal-cookie';
const cookies = new Cookies();
cookies.set('myCat', 'Pacman', { path: '/' });
console.log(cookies.get('myCat')); // Pacman
this native-base there is solution:
<Button
block
disabled={!learnedWordsByUser.length}
style={{ marginTop: 10 }}
onPress={learnedWordsByUser.length && () => {
onFlipCardsGenerateNewWords(learnedWordsByUser)
onFlipCardsBtnPress()
}}
>
<Text>Let's Review</Text>
</Button>
Is there a name to describe this idiom?
In UML it is called aggregation. It differs from composition in that the member object is not owned by the referring class. In C++ you can implement aggregation in two different ways, through references or pointers.
I am assuming it is to prevent the possibly large overhead of copying a big complex object?
No, that would be a really bad reason to use this. The main reason for aggregation is that the contained object is not owned by the containing object and thus their lifetimes are not bound. In particular the referenced object lifetime must outlive the referring one. It might have been created much earlier and might live beyond the end of the lifetime of the container. Besides that, the state of the referenced object is not controlled by the class, but can change externally. If the reference is not const
, then the class can change the state of an object that lives outside of it.
Is this generally good practice? Are there any pitfalls to this approach?
It is a design tool. In some cases it will be a good idea, in some it won't. The most common pitfall is that the lifetime of the object holding the reference must never exceed the lifetime of the referenced object. If the enclosing object uses the reference after the referenced object was destroyed, you will have undefined behavior. In general it is better to prefer composition to aggregation, but if you need it, it is as good a tool as any other.
Get the real path to your script
if [ -L $0 ] ; then
ME=$(readlink $0)
else
ME=$0
fi
DIR=$(dirname $ME)
(This is answer to the same my question here: Get the name of the directory where a script is executed)
try out like this
body {
background: #fff url("!--MIZO-PRO--!") no-repeat center 15px top 15px/100px;
}
/* 100px is the background size */
POSIX compatible:
command -v <the_command>
Example use:
if ! command -v COMMAND &> /dev/null
then
echo "COMMAND could not be found"
exit
fi
For Bash specific environments:
hash <the_command> # For regular commands. Or...
type <the_command> # To check built-ins and keywords
Avoid which
. Not only is it an external process you're launching for doing very little (meaning builtins like hash
, type
or command
are way cheaper), you can also rely on the builtins to actually do what you want, while the effects of external commands can easily vary from system to system.
Why care?
which
that doesn't even set an exit status, meaning the if which foo
won't even work there and will always report that foo
exists, even if it doesn't (note that some POSIX shells appear to do this for hash
too).which
do custom and evil stuff like change the output or even hook into the package manager.So, don't use which
. Instead use one of these:
$ command -v foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
$ type foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
$ hash foo 2>/dev/null || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
(Minor side-note: some will suggest 2>&-
is the same 2>/dev/null
but shorter – this is untrue. 2>&-
closes FD 2 which causes an error in the program when it tries to write to stderr, which is very different from successfully writing to it and discarding the output (and dangerous!))
If your hash bang is /bin/sh
then you should care about what POSIX says. type
and hash
's exit codes aren't terribly well defined by POSIX, and hash
is seen to exit successfully when the command doesn't exist (haven't seen this with type
yet). command
's exit status is well defined by POSIX, so that one is probably the safest to use.
If your script uses bash
though, POSIX rules don't really matter anymore and both type
and hash
become perfectly safe to use. type
now has a -P
to search just the PATH
and hash
has the side-effect that the command's location will be hashed (for faster lookup next time you use it), which is usually a good thing since you probably check for its existence in order to actually use it.
As a simple example, here's a function that runs gdate
if it exists, otherwise date
:
gnudate() {
if hash gdate 2>/dev/null; then
gdate "$@"
else
date "$@"
fi
}
You can use scripts-common to reach your need.
To check if something is installed, you can do:
checkBin <the_command> || errorMessage "This tool requires <the_command>. Install it please, and then run this tool again."
Your particular string won't work as typed because of the escape characters at the end \", won't allow it to close on the quotation.
Maybe I'm just wrong on that one because I'm still very new to python so if so please correct me but, changing it slightly to adjust for that, the repr() function will do the job of reproducing any string stored in a variable as a raw string.
You can do it two ways:
>>>print("C:\\Windows\Users\alexb\\")
C:\Windows\Users\alexb\
>>>print(r"C:\\Windows\Users\alexb\\")
C:\\Windows\Users\alexb\\
Store it in a variable:
test = "C:\\Windows\Users\alexb\\"
Use repr():
>>>print(repr(test))
'C:\\Windows\Users\alexb\\'
or string replacement with %r
print("%r" %test)
'C:\\Windows\Users\alexb\\'
The string will be reproduced with single quotes though so you would need to strip those off afterwards.
Choose which DI to inject stuff into Jersey:
Spring 4:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring4</artifactId>
</dependency>
Spring 3:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
</dependency>
HK2:
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
</dependency>
Specifically, I got this issue when attempting to retrieve the default (no-args) InitialContext
within an embedded Tomcat7 instance, in SpringBoot.
The solution for me, was to tell Tomcat to enableNaming
.
i.e.
@Bean
public TomcatEmbeddedServletContainerFactory tomcatFactory() {
return new TomcatEmbeddedServletContainerFactory() {
@Override
protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(
Tomcat tomcat) {
tomcat.enableNaming();
return super.getTomcatEmbeddedServletContainer(tomcat);
}
};
}
Recently WhatsApp updated on its official website that we need to use this HTML tag in order to make it shareable to mobile sites:
<a href="whatsapp://send?text=Hello%20World!">Hello, world!</a>
_x000D_
You can replace text=
to have your link or any text content
Previous answers got you list of torch.Size Here is how to get list of ints
listofints = [int(x) for x in tensor.shape]
See CNCopyCurrentNetworkInfo in CaptiveNetwork: http://developer.apple.com/library/ios/#documentation/SystemConfiguration/Reference/CaptiveNetworkRef/Reference/reference.html.
Mockito also provides the option of stubbing methods, matching arguments (like anyInt() and anyString()), verifying the number of invocations (times(3), atLeastOnce(), never()), and more.
I've also found that Mockito is simple and clean.
One thing I don't like about Mockito is that you can't stub static methods.
you can do this with css3, this blurs the whole element
div (or whatever element) {
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);
}
Fiddle: http://jsfiddle.net/H4DU4/
You can easily increase your VM's RAM by modifying the memory property of config.vm.provider section in your vagrant file.
config.vm.provider "virtualbox" do |vb|
vb.memory = "4096"
end
This allocates about 4GB of RAM to your VM. You can change this according to your requirement. For example, following setting would allocate 2GB of RAM to your VM.
config.vm.provider "virtualbox" do |vb|
vb.memory = "2048"
end
Try removing the config.vm.customize ["modifyvm", :id, "--memory", 1024]
in your file, and adding the above code.
For the network configuration, try modifying the config.vm.network :hostonly, "199.188.44.20"
in your file toconfig.vm.network "private_network", ip: "199.188.44.20"
You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).
For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.
Function ExtractSDI(ByVal text As String) As String
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)
If allMatches.count <> 0 Then
result = allMatches.Item(0).submatches.Item(0)
End If
ExtractSDI = result
End Function
If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:
Ex) =RegexExtract(A1, "(sdi \d+)", ", ")
Here is:
Function RegexExtract(ByVal text As String, _
ByVal extract_what As String, _
Optional seperator As String = "") As String
Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)
For i = 0 To allMatches.count - 1
For j = 0 To allMatches.Item(i).submatches.count - 1
result = result & seperator & allMatches.Item(i).submatches.Item(j)
Next
Next
If Len(result) <> 0 Then
result = Right(result, Len(result) - Len(seperator))
End If
RegexExtract = result
End Function
*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.
Yes, the way you are doing it is perfectly legitimate. To access that data on the client side, edit your success function to accept a parameter: data.
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
doSomething(data);
}
});
Late to the party, but for anyone tasked with creating their own or wants to see how this would work, here's the function with an added bonus of rearranging the start-stop values based on the desired increment:
def RANGE(start, stop=None, increment=1):
if stop is None:
stop = start
start = 1
value_list = sorted([start, stop])
if increment == 0:
print('Error! Please enter nonzero increment value!')
else:
value_list = sorted([start, stop])
if increment < 0:
start = value_list[1]
stop = value_list[0]
while start >= stop:
worker = start
start += increment
yield worker
else:
start = value_list[0]
stop = value_list[1]
while start < stop:
worker = start
start += increment
yield worker
Negative increment:
for i in RANGE(1, 10, -1):
print(i)
Or, with start-stop reversed:
for i in RANGE(10, 1, -1):
print(i)
Output:
10
9
8
7
6
5
4
3
2
1
Regular increment:
for i in RANGE(1, 10):
print(i)
Output:
1
2
3
4
5
6
7
8
9
Zero increment:
for i in RANGE(1, 10, 0):
print(i)
Output:
'Error! Please enter nonzero increment value!'
A filter argument with a trailing * can be evaluated almost instantaneously via an index lookup. A leading * implies a sequential search through the index, so it is O(N). It will take ages.
I suggest you reconsider the requirement.
If you don't want use connection pool (you sure, that your app has only one connection), you can do this - if connection falls you must establish new one - call method .openSession() instead .getCurrentSession()
For example:
SessionFactory sf = null;
// get session factory
// ...
//
Session session = null;
try {
session = sessionFactory.getCurrentSession();
} catch (HibernateException ex) {
session = sessionFactory.openSession();
}
If you use Mysql, you can set autoReconnect property:
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1/database?autoReconnect=true</property>
I hope this helps.
Replace void *disconnectFunc;
with void (*disconnectFunc)();
to declare function pointer type variable. Or even better use a typedef
:
typedef void (*func_t)(); // pointer to function with no args and void return
...
func_t fptr; // variable of pointer to function
...
void D::setDisconnectFunc( func_t func )
{
fptr = func;
}
void D::disconnected()
{
fptr();
connected = false;
}
The ist and 2nd answer are good but if anybody is looking for having a script or If you want dynamic i.e (db/username/password in variable) then here:
#!/bin/bash
DB="mydb"
USER="user1"
PASS="pass_bla"
mysql -uroot -prootpassword -e "CREATE DATABASE $DB CHARACTER SET utf8 COLLATE utf8_general_ci";
mysql -uroot -prootpassword -e "CREATE USER $USER@'127.0.0.1' IDENTIFIED BY '$PASS'";
mysql -uroot -prootpassword -e "GRANT SELECT, INSERT, UPDATE ON $DB.* TO '$USER'@'127.0.0.1'";
I compared all possibilities with a long test sheet:
0,140625 sec for
lastrow = calcws.Cells.Find("*", [A1], , , xlByColumns, xlPrevious).row
0 sec for
iLastRow = calcws.Cells(rows.count, "a").End(xlUp).row
and
numofrows = calcws.Cells.SpecialCells(xlLastCell).row
0,0078125 sec for
lastrow = calcws.UsedRange.rows.count
Do While 1
If calcws.Cells(lastrow, 1).Value = "" Then
lastrow = lastrow - 1
Else
Exit Do
End If
Loop
I think the favourites are obvious...
When I've got several faux-links, I prefer to give them a class of 'no-link'.
Then in jQuery, I add the following code:
$(function(){
$('.no-link').click(function(e){
e.preventDefault();
});
});
And for the HTML, the link is simply
<a href="/" class="no-link">Faux-Link</a>
I don't like using Hash-Tags unless they're used for anchors, and I only do the above when I've got more than two faux-links, otherwise I go with javascript:void(0).
<a href="javascript:void(0)" class="no-link">Faux-Link</a>
Typically, I like to just avoid using a link at all and just wrap something around in a span and use that as a way to active some JavaScript code, like a pop-up or a content-reveal.
The default behaviour of Newtonsoft.Json is going to find the public
constructors. If your default constructor is only used in containing class or the same assembly, you can reduce the access level to protected
or internal
so that Newtonsoft.Json will pick your desired public
constructor.
Admittedly, this solution is rather very limited to specific cases.
internal Result() { }
public Result(int? code, string format, Dictionary<string, string> details = null)
{
Code = code ?? ERROR_CODE;
Format = format;
if (details == null)
Details = new Dictionary<string, string>();
else
Details = details;
}
WARNING: You should understand the security risks of this method before you consider it. John's summary of the risk:
By giving the container access to
/var/run/docker.sock
, it is [trivially easy] to break out of the containment provided by docker and gain access to the host machine. Obviously this is potentially dangerous.
Inside the container, the dockerId is your hostname. So, you could:
--volume
/var/run/docker.sock:/var/run/docker.sock --privileged
docker inspect $(hostname)
inside the containerAvoid this. Only do it if you understand the risks and have a clear mitigation for the risks.
My understanding is that this question is better answered over in this post.
But briefly, the answer to the OP with this method is simply:
s1 = pd.merge(df1, df2, how='inner', on=['user_id'])
Which gives s1 with 5 columns: user_id and the other two columns from each of df1 and df2.
Like this:
Dim rng as Range
Set rng = ActiveCell.Resize(numRows, numCols)
then read the contents of that range to an array:
Dim arr As Variant
arr = rng.Value
'arr is now a two-dimensional array of size (numRows, numCols)
or, select the range (I don't think that's what you really want, but you ask for this in the question).
rng.Select
You can also return all selected checkboxes value in comma separated string. This will also make it easier for you when you send it as a parameter to SQL
Here is a sample that return all selected checkboxes values that have the name "chkboxName" in comma separate string
And here is the javascript
function showSelectedValues()
{
alert($("input[name=chkboxName]:checked").map(function () {
return this.value;
}).get().join(","));
}
Here is the HTML sample
<html>
<head>
</head>
<body>
<div>
<input name="chkboxName" type="checkbox" value="one_name" checked>
<input name="chkboxName" type="checkbox" value="one_name1">
<input name="chkboxName" type="checkbox" value="one_name2">
</div>
</body>
</html>
To answer your question, let's assume that you are interested in a specific angular version and NOT in a specific angular-cli version (angular-cli is just a tool after all).
A reasonnable move is to keep your angular-cli version alligned with your angular version, otherwise you risk to stumble into incompatibilities issues. So getting the correct angular-cli version will lead you to getting the desired angular version.
From that assumption, your question is not about angular-cli, but about npm.
Here is the way to go:
[STEP 0 - OPTIONAL] If you're not sure of the angular-cli version installed in your environment, uninstall it.
npm uninstall -g @angular/cli
Then, run (--force flag might be required)
npm cache clean
or, if you're using npm > 5.
npm cache verify
[STEP 1] Install an angular-cli specific version
npm install -g @angular/[email protected]
[STEP 2] Create a project
ng new you-app-name
The resulting white app will be created in the desired angular version.
NOTE: I have not found any page displaying the compatibility matrix of angular and angular-cli. So I guess the only way to know what angular-cli version should be installed is to try various versions, create a new project and checkout the package.json
to see which angular version is used.
angular versions changelog Here is the changelog from github reposition, where you can check available versions and the differences.
Hope it helps
One word: Don't.
OK obviously that isn't a real answer. But still SOAP should be avoided at all costs. ;-) Is it possible to add a proxy server between the iPhone and the web service? Perhaps something that converts REST into SOAP for you?
You could try CSOAP, a SOAP library that depends on libxml2 (which is included in the iPhone SDK).
I've written my own SOAP framework for OSX. However it is not actively maintained and will require some time to port to the iPhone (you'll need to replace NSXML with TouchXML for a start)
WHERE column_name LIKE '%save 50[%] off!%'
I can think of 2 options
background-color
for the column on the container <div/>
instead (<div class="separator"/>
) with repeat-y
Building on Alpar's answer, here's a more generalised way to split a single list of items into multiple containers (rows, columns, buckets, whatever):
<div class="row" ng-repeat="row in [0,1,2]">
<div class="col" ng-repeat="item in $ctrl.items" ng-if="$index % 3 == row">
<span>{{item.name}}</span>
</div>
</div>
for a list of 10 items, generates:
<div class="row">
<div class="col"><span>Item 1</span></div>
<div class="col"><span>Item 4</span></div>
<div class="col"><span>Item 7</span></div>
<div class="col"><span>Item 10</span></div>
</div>
<div class="row">
<div class="col"><span>Item 2</span></div>
<div class="col"><span>Item 5</span></div>
<div class="col"><span>Item 8</span></div>
</div>
<div class="row">
<div class="col"><span>Item 3</span></div>
<div class="col"><span>Item 6</span></div>
<div class="col"><span>Item 9</span></div>
</div>
The number of containers can be quickly coded into a controller function:
JS (ES6)
$scope.rowList = function(rows) {
return Array(rows).fill().map((x,i)=>i);
}
$scope.rows = 2;
HTML
<div class="row" ng-repeat="row in rowList(rows)">
<div ng-repeat="item in $ctrl.items" ng-if="$index % rows == row">
...
This approach avoids duplicating the item markup (<span>{{item.name}}</span>
in this case) in the source template - not a huge win for a simple span, but for a more complex DOM structure (which I had) this helps keep the template DRY.
var ctrlKeyDown = false;
$(document).ready(function(){
$(document).on("keydown", keydown);
$(document).on("keyup", keyup);
});
function keydown(e) {
if ((e.which || e.keyCode) == 116 || ((e.which || e.keyCode) == 82 && ctrlKeyDown)) {
// Pressing F5 or Ctrl+R
e.preventDefault();
} else if ((e.which || e.keyCode) == 17) {
// Pressing only Ctrl
ctrlKeyDown = true;
}
};
function keyup(e){
// Key up Ctrl
if ((e.which || e.keyCode) == 17)
ctrlKeyDown = false;
};
Why use a <a href>
? I solve it like this:
<span class='a'>fake link</span>
And style it with:
.a {text-decoration:underline; cursor:pointer;}
You can easily access it with jQuery:
$(".a").click();
Simple example...
Let's say the child view controller has a UISlider
and we want to pass the value of the slider back to the parent via a delegate.
In the child view controller's header file, declare the delegate type and its methods:
ChildViewController.h
#import <UIKit/UIKit.h>
// 1. Forward declaration of ChildViewControllerDelegate - this just declares
// that a ChildViewControllerDelegate type exists so that we can use it
// later.
@protocol ChildViewControllerDelegate;
// 2. Declaration of the view controller class, as usual
@interface ChildViewController : UIViewController
// Delegate properties should always be weak references
// See http://stackoverflow.com/a/4796131/263871 for the rationale
// (Tip: If you're not using ARC, use `assign` instead of `weak`)
@property (nonatomic, weak) id<ChildViewControllerDelegate> delegate;
// A simple IBAction method that I'll associate with a close button in
// the UI. We'll call the delegate's childViewController:didChooseValue:
// method inside this handler.
- (IBAction)handleCloseButton:(id)sender;
@end
// 3. Definition of the delegate's interface
@protocol ChildViewControllerDelegate <NSObject>
- (void)childViewController:(ChildViewController*)viewController
didChooseValue:(CGFloat)value;
@end
In the child view controller's implementation, call the delegate methods as required.
ChildViewController.m
#import "ChildViewController.h"
@implementation ChildViewController
- (void)handleCloseButton:(id)sender {
// Xcode will complain if we access a weak property more than
// once here, since it could in theory be nilled between accesses
// leading to unpredictable results. So we'll start by taking
// a local, strong reference to the delegate.
id<ChildViewControllerDelegate> strongDelegate = self.delegate;
// Our delegate method is optional, so we should
// check that the delegate implements it
if ([strongDelegate respondsToSelector:@selector(childViewController:didChooseValue:)]) {
[strongDelegate childViewController:self didChooseValue:self.slider.value];
}
}
@end
In the parent view controller's header file, declare that it implements the ChildViewControllerDelegate
protocol.
RootViewController.h
#import <UIKit/UIKit.h>
#import "ChildViewController.h"
@interface RootViewController : UITableViewController <ChildViewControllerDelegate>
@end
In the parent view controller's implementation, implement the delegate methods appropriately.
RootViewController.m
#import "RootViewController.h"
@implementation RootViewController
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
ChildViewController *detailViewController = [[ChildViewController alloc] init];
// Assign self as the delegate for the child view controller
detailViewController.delegate = self;
[self.navigationController pushViewController:detailViewController animated:YES];
}
// Implement the delegate methods for ChildViewControllerDelegate
- (void)childViewController:(ChildViewController *)viewController didChooseValue:(CGFloat)value {
// Do something with value...
// ...then dismiss the child view controller
[self.navigationController popViewControllerAnimated:YES];
}
@end
Hope this helps!
paste your .html file in assets folder of your project folder. and create an xml file in layout folder with the fol code: my.xml:
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
add fol code in activity
setContentView(R.layout.my);
WebView mWebView = null;
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("file:///android_asset/new.html"); //new.html is html file name.
1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,
2) AbstractTableModel should be useful, where is in the JTable
required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel
,
3) consider using DefaultTableModel
, (if you are not sure about how to works) instead of AbstractTableModel
,
could be generated from simple code:
import javax.swing.*;
import javax.swing.table.*;
public class TableCheckBox extends JFrame {
private static final long serialVersionUID = 1L;
private JTable table;
public TableCheckBox() {
Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
Object[][] data = {
{"Buy", "IBM", new Integer(1000), new Double(80.50), false},
{"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
{"Sell", "Apple", new Integer(3000), new Double(7.35), true},
{"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model) {
private static final long serialVersionUID = 1L;
/*@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}*/
@Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Integer.class;
case 3:
return Double.class;
default:
return Boolean.class;
}
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TableCheckBox frame = new TableCheckBox();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
});
}
}
Be careful with your tests. If you in your form you put the same email as the email address which must receive it will be directly in spam :)
I may be wrong, but I think the accepted answer by @amit has a bug.
from pandas import DataFrame as df
x = [1,2,3]
y = [7,8,9,10]
# this gives me a syntax error at 'for' (Python 3.7)
d1 = df[[a, "A", b, "B"] for a in x for b in y]
# this works
d2 = df([a, "A", b, "B"] for a in x for b in y)
# and if you want to add the column names on the fly
# note the additional parentheses
d3 = df(([a, "A", b, "B"] for a in x for b in y), columns = ("l","m","n","o"))
Most of the answers show how to best handle HttpContext
from the documentation, which is also what I went with.
I did want to mention that you'll want to check you project settings when debugging, the default is Enable Anonymous Authentication = true
.
EDIT: the following is wrong, because Cell("width") returns the width of the last modified cell.
Cell("width")
returns the width of the current cell, so you don't need a reference to the current cell. If you need one, though, cell("address")
returns the address of the current cell, so if you need a reference to the current cell, use indirect(cell("address"))
. See the documentation: http://www.techonthenet.com/excel/formulas/cell.php
This error may be shown if you use fake assemblies. Removing fakes leads to successful build of the project.
Use StringUtils, in case you need string result:
String last = StringUtils.right(number.toString(), 1);
For Official information:
https://vuejs.org/v2/guide/migration.html#v-el-and-v-ref-replaced
A simple Example:
On any Element you have to add an attribute ref
with a unique value
<input ref="foo" type="text" >
To target that elemet use this.$refs.foo
this.$refs.foo.focus(); // it will focus the input having ref="foo"
Quicksort has O(n2) worst-case runtime and O(nlogn) average case runtime. However, it’s superior to merge sort in many scenarios because many factors influence an algorithm’s runtime, and, when taking them all together, quicksort wins out.
In particular, the often-quoted runtime of sorting algorithms refers to the number of comparisons or the number of swaps necessary to perform to sort the data. This is indeed a good measure of performance, especially since it’s independent of the underlying hardware design. However, other things – such as locality of reference (i.e. do we read lots of elements which are probably in cache?) – also play an important role on current hardware. Quicksort in particular requires little additional space and exhibits good cache locality, and this makes it faster than merge sort in many cases.
In addition, it’s very easy to avoid quicksort’s worst-case run time of O(n2) almost entirely by using an appropriate choice of the pivot – such as picking it at random (this is an excellent strategy).
In practice, many modern implementations of quicksort (in particular libstdc++’s std::sort
) are actually introsort, whose theoretical worst-case is O(nlogn), same as merge sort. It achieves this by limiting the recursion depth, and switching to a different algorithm (heapsort) once it exceeds logn.
Replacing ng-model with ng-checked works for me.
In response to
Don't hardcode /sdcard/
Sometimes we HAVE TO hardcode it as in some phone models the API method returns the internal phone memory.
Known types: HTC One X and Samsung S3.
Environment.getExternalStorageDirectory().getAbsolutePath() gives a different path - Android
Ok I found out the answer myself. Much like npm cache clean
, Yarn also has its own
yarn cache clean
For those who want to just copy and paste the fastest implementation of shift, there is a benchmark and conclusion(see the end). In addition, I introduce fill_value parameter and fix some bugs.
import numpy as np
import timeit
# enhanced from IronManMark20 version
def shift1(arr, num, fill_value=np.nan):
arr = np.roll(arr,num)
if num < 0:
arr[num:] = fill_value
elif num > 0:
arr[:num] = fill_value
return arr
# use np.roll and np.put by IronManMark20
def shift2(arr,num):
arr=np.roll(arr,num)
if num<0:
np.put(arr,range(len(arr)+num,len(arr)),np.nan)
elif num > 0:
np.put(arr,range(num),np.nan)
return arr
# use np.pad and slice by me.
def shift3(arr, num, fill_value=np.nan):
l = len(arr)
if num < 0:
arr = np.pad(arr, (0, abs(num)), mode='constant', constant_values=(fill_value,))[:-num]
elif num > 0:
arr = np.pad(arr, (num, 0), mode='constant', constant_values=(fill_value,))[:-num]
return arr
# use np.concatenate and np.full by chrisaycock
def shift4(arr, num, fill_value=np.nan):
if num >= 0:
return np.concatenate((np.full(num, fill_value), arr[:-num]))
else:
return np.concatenate((arr[-num:], np.full(-num, fill_value)))
# preallocate empty array and assign slice by chrisaycock
def shift5(arr, num, fill_value=np.nan):
result = np.empty_like(arr)
if num > 0:
result[:num] = fill_value
result[num:] = arr[:-num]
elif num < 0:
result[num:] = fill_value
result[:num] = arr[-num:]
else:
result[:] = arr
return result
arr = np.arange(2000).astype(float)
def benchmark_shift1():
shift1(arr, 3)
def benchmark_shift2():
shift2(arr, 3)
def benchmark_shift3():
shift3(arr, 3)
def benchmark_shift4():
shift4(arr, 3)
def benchmark_shift5():
shift5(arr, 3)
benchmark_set = ['benchmark_shift1', 'benchmark_shift2', 'benchmark_shift3', 'benchmark_shift4', 'benchmark_shift5']
for x in benchmark_set:
number = 10000
t = timeit.timeit('%s()' % x, 'from __main__ import %s' % x, number=number)
print '%s time: %f' % (x, t)
benchmark result:
benchmark_shift1 time: 0.265238
benchmark_shift2 time: 0.285175
benchmark_shift3 time: 0.473890
benchmark_shift4 time: 0.099049
benchmark_shift5 time: 0.052836
shift5 is winner! It's OP's third solution.
all the major javascript libraries like jscript, prototype, YUI have support for loading script files. For example, in YUI, after loading the core you can do the following to load the calendar control
var loader = new YAHOO.util.YUILoader({
require: ['calendar'], // what components?
base: '../../build/',//where do they live?
//filter: "DEBUG", //use debug versions (or apply some
//some other filter?
//loadOptional: true, //load all optional dependencies?
//onSuccess is the function that YUI Loader
//should call when all components are successfully loaded.
onSuccess: function() {
//Once the YUI Calendar Control and dependencies are on
//the page, we'll verify that our target container is
//available in the DOM and then instantiate a default
//calendar into it:
YAHOO.util.Event.onAvailable("calendar_container", function() {
var myCal = new YAHOO.widget.Calendar("mycal_id", "calendar_container");
myCal.render();
})
},
// should a failure occur, the onFailure function will be executed
onFailure: function(o) {
alert("error: " + YAHOO.lang.dump(o));
}
});
// Calculate the dependency and insert the required scripts and css resources
// into the document
loader.insert();
what you are trying to do is more a segmentedbutton than an imagebutton list.
here http://blog.bookworm.at/2010/10/segmented-controls-in-android.html is an example on how to do so. The basic idea is to customize RadioButton instead of ImageButton, since the RadioButton will have the checked state you need
A bit late to the party, but Krux has created a script for this, called Postscribe. We were able to use this to get past this issue.
This may be what you are looking for:
body>div {_x000D_
background: #aaa;_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
body>div>div {_x000D_
flex-grow: 1;_x000D_
width: 33%;_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
body>div>div:nth-child(even) {_x000D_
background: #23a;_x000D_
}_x000D_
_x000D_
body>div>div:nth-child(odd) {_x000D_
background: #49b;_x000D_
}
_x000D_
<div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
</div>
_x000D_