Test this
var selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
MessageBox.Show(selected);
If you have web services, check your URL pointing to the service. I had a simular issue which was fixed when I changed my web service URL.
for (int i = 0; i < clbIncludes.Items.Count; i++)
if (clbIncludes.GetItemChecked(i))
// Do selected stuff
else
// Do unselected stuff
If the the check is in indeterminate state, this will still return true. You may want to replace
if (clbIncludes.GetItemChecked(i))
with
if (clbIncludes.GetItemCheckState(i) == CheckState.Checked)
if you want to only include actually checked items.
cache.db
is being currently used by another process.I use SQLYog at home and work. It turns out they DO have a free open-source version, though sadly they've been trying to hide that fact for the last few years.
You can download the open-source version from https://github.com/webyog/sqlyog-community - just click the "Download SQLyog Community Version" link.
Try this (Note: I don't have right now Visual Studio ,so code is copy paste from my archive(I haven't test it) :
Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
Dim drv As DataRowView
If e.RowIndex >= 0 Then
If e.RowIndex <= ds.Tables("Products").Rows.Count - 1 Then
drv = ds.Tables("Products").DefaultView.Item(e.RowIndex)
Dim c As Color
If drv.Item("Quantity").Value < 5 Then
c = Color.LightBlue
Else
c = Color.Pink
End If
e.CellStyle.BackColor = c
End If
End If
End Sub
Mutable default arguments don't generally do what you want. Instead, try this:
class Node:
def __init__(self, wordList=None, adjacencyList=None):
if wordList is None:
self.wordList = []
else:
self.wordList = wordList
if adjacencyList is None:
self.adjacencyList = []
else:
self.adjacencyList = adjacencyList
from command line
python -c help('modules')
can be used to view all modules, and for specific modules
python -c help('os')
For Linux below will work
python -c "help('os')"
The sh
solution by Brian Campbell
, while noble and well executed, has a few problems, so I thought I'd provide my own bash
solution.
The problems with the sh
one:
~/foo
doesn't expand to your homedirectory inside heredocs. And neither when it's read by the read
statement or quoted in the rm
statement. Which means you'll get No such file or directory
errors.grep
and such for basic operations is daft. Especially when you're using a crappy shell to avoid the "heavy" weight of bash.echo
.sh
can cope with them - which is why I almost always prefer bash
, it's far more bulletproof & harder to exploit when used well).While, yes, using /bin/sh
for your hashbang means you must avoid bash
isms at all costs, you can use all the bash
isms you like, even on Ubuntu or whatnot when you're honest and put #!/bin/bash
at the top.
So, here's a bash
solution that's smaller, cleaner, more transparent, probably "faster", and more bulletproof.
[[ -d $1 && $1 != *[^0-9]* ]] || { echo "Invalid input." >&2; exit 1; }
rm -rf ~/foo/"$1"/bar ...
$1
in the rm
statement!-d
check will also fail if $1
is empty, so that's two checks in one.=~
in bash, you should be putting the regular expression in a variable. In any case, globs like mine are always preferable and supported in far more bash versions.Using your code:
console.log(arr[1]); // prints: abc
console.log(arr[0]); // prints: format_abc
Edit: Safari 3, if it matters.
Delegate
is just the base class so you can't use it like that. You could do something like this though:
public void DoRequest(string request, Action<string> callback)
{
// do stuff....
callback("asdf");
}
ASP.NET Core 2.0 with Angular
Make sure to use type of authentication filter
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
To clear of all the overlays including polys, markers, etc...
simply use:
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);}
Here is a function that I wrote to do it form me on a map application:
function clear_Map() {
directionsDisplay = new google.maps.DirectionsRenderer();
//var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var myOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: HamptonRoads
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}
// wrap it in jQuery, now it's a collection
var $elements = $(someHTML);
// append to the DOM
$("#myDiv").append($elements);
// do stuff, using the initial reference
$elements.effects("highlight", {}, 2000);
I know this is old, but Google sent me here so I guess others will come too like me.
The answer on 2018 is the selected one here: Pycharm: "unresolved reference" error on the IDE when opening a working project
Just be aware that you can only add one Content Root
but you can add several Source Folders
. No need to touch __init__.py
files.
You could try posting multipart content from the client like this:
using (var httpClient = new HttpClient())
{
var uri = new Uri("http://example.com/api/controller"));
using (var formData = new MultipartFormDataContent())
{
//add content to form data
formData.Add(new StringContent(JsonConvert.SerializeObject(content)), "Content");
//add config to form data
formData.Add(new StringContent(JsonConvert.SerializeObject(config)), "Config");
var response = httpClient.PostAsync(uri, formData);
response.Wait();
if (!response.Result.IsSuccessStatusCode)
{
//error handling code goes here
}
}
}
On the server side you could read the the content like this:
public async Task<HttpResponseMessage> Post()
{
//make sure the post we have contains multi-part data
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
//read data
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
//declare backup file summary and file data vars
var content = new Content();
var config = new Config();
//iterate over contents to get Content and Config
foreach (var requestContents in provider.Contents)
{
if (requestContents.Headers.ContentDisposition.Name == "Content")
{
content = JsonConvert.DeserializeObject<Content>(requestContents.ReadAsStringAsync().Result);
}
else if (requestContents.Headers.ContentDisposition.Name == "Config")
{
config = JsonConvert.DeserializeObject<Config>(requestContents.ReadAsStringAsync().Result);
}
}
//do something here with the content and config and set success flag
var success = true;
//indicate to caller if this was successful
HttpResponseMessage result = Request.CreateResponse(success ? HttpStatusCode.OK : HttpStatusCode.InternalServerError, success);
return result;
}
}
this may be handy
add this to your manifest
android:theme="@android:style/Theme.Light.NoTitleBar"
cheers
A quick and easy solution for interactive work is to copy-and-paste the text by loading the data from the clipboard.
Select the content of the string with your mouse:
In the Python shell use read_clipboard()
>>> pd.read_clipboard()
col1;col2;col3
0 1;4.4;99
1 2;4.5;200
2 3;4.7;65
3 4;3.2;140
Use the appropriate separator:
>>> pd.read_clipboard(sep=';')
col1 col2 col3
0 1 4.4 99
1 2 4.5 200
2 3 4.7 65
3 4 3.2 140
>>> df = pd.read_clipboard(sep=';') # save to dataframe
For a long time I have used the alternative:
('netscape' in window) && / rv:/.test(navigator.userAgent)
because I don't trust user agent strings. Some bugs are not detectable using feature detection, so detecting the browser is required for some workarounds.
Also if you are working around a bug in Gecko, then the bug is probably also in derivatives of Firefox, and this code should work with derivatives too (Do Waterfox and Pale Moon have 'Firefox' in the user agent string?).
You should use django methods, like exists. Its there for you to use it.
if qs.exists():
return qs[0]
return None
The three most used and well supported jQuery grid plugins today are SlickGrid, jqGrid and DataTables. See http://wiki.jqueryui.com/Grid-OtherGrids for more info.
I liked @KyleMit's answer on how to make an unstyled input group, but in my case, I only wanted the right side unstyled - I still wanted to use an input-group-addon on the left side and have it look like normal bootstrap. So, I did this:
css
.input-group.input-group-unstyled-right input.form-control {
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
.input-group-unstyled-right .input-group-addon.input-group-addon-unstyled {
border-radius: 4px;
border: 0px;
background-color: transparent;
}
html
<div class="input-group input-group-unstyled-right">
<span class="input-group-addon">
<i class="fa fa-envelope-o"></i>
</span>
<input type="text" class="form-control">
<span class="input-group-addon input-group-addon-unstyled">
<i class="fa fa-check"></i>
</span>
</div>
@Henry-Neo's method was close, it just needed more strict Regex rules.
<form name="emailForm">
Email: <input type="email" name="email1" ng-model="emailReg">
Repeat Email: <input type="email" name="email2" ng-model="emailReg2" ng-pattern="(emailReg)">
</form>
By including the regex rule inside parentheses, it will match the entire string of emailReg
to emailReg2
and will cause the form validation to fail because it doesn't match.
You can then drill into the elements to find out which part is failing.
<p ng-show="emailForm.$valid">Form Valid</p>
<p ng-show="emailForm.email1.$error">Email not valid</p>
<p ng-show="emailForm.email1.$valid && emailForm.email1.$error.pattern">
Emails Do Not Match
</p>
Faced with the same situation playing with Javascript webworkers. Unfortunately Chrome doesn't allow to access javascript workers stored in a local file.
One kind of workaround below using a local storage is to running Chrome with --allow-file-access-from-files
(with s
at the end), but only one instance of Chrome is allowed, which is not too convenient for me. For this reason i'm using Chrome Canary, with file access allowed.
BTW in Firefox there is no such an issue.
This isn't possible with ruby currently. You can't pass 'empty' attributes to methods. The closest you can get is to pass nil:
ldap_get(base_dn, filter, nil, X)
However, this will set the scope to nil, not LDAP::LDAP_SCOPE_SUBTREE.
What you can do is set the default value within your method:
def ldap_get(base_dn, filter, scope = nil, attrs = nil)
scope ||= LDAP::LDAP_SCOPE_SUBTREE
... do something ...
end
Now if you call the method as above, the behaviour will be as you expect.
Yes. Only comments and the end tag for the html element are allowed after the end tag for the body.
Browsers may perform error recovery, but you should never depend on that.
While I agree with the previous answers, it's important to note how to access the code of those external libraries.
For example to access a class in the external library, you will want to use the import keyword followed by the external library's name, continued with dot notation until the desired class is reached.
Look at the image below to see how I import CodeGenerationException class from the quickfixj library.
Switch statements with String
cases have been implemented in Java SE 7, at least 16 years after they were first requested. A clear reason for the delay was not provided, but it likely had to do with performance.
The feature has now been implemented in javac
with a "de-sugaring" process; a clean, high-level syntax using String
constants in case
declarations is expanded at compile-time into more complex code following a pattern. The resulting code uses JVM instructions that have always existed.
A switch
with String
cases is translated into two switches during compilation. The first maps each string to a unique integer—its position in the original switch. This is done by first switching on the hash code of the label. The corresponding case is an if
statement that tests string equality; if there are collisions on the hash, the test is a cascading if-else-if
. The second switch mirrors that in the original source code, but substitutes the case labels with their corresponding positions. This two-step process makes it easy to preserve the flow control of the original switch.
For more technical depth on switch
, you can refer to the JVM Specification, where the compilation of switch statements is described. In a nutshell, there are two different JVM instructions that can be used for a switch, depending on the sparsity of the constants used by the cases. Both depend on using integer constants for each case to execute efficiently.
If the constants are dense, they are used as an index (after subtracting the lowest value) into a table of instruction pointers—the tableswitch
instruction.
If the constants are sparse, a binary search for the correct case is performed—the lookupswitch
instruction.
In de-sugaring a switch
on String
objects, both instructions are likely to be used. The lookupswitch
is suitable for the first switch on hash codes to find the original position of the case. The resulting ordinal is a natural fit for a tableswitch
.
Both instructions require the integer constants assigned to each case to be sorted at compile time. At runtime, while the O(1)
performance of tableswitch
generally appears better than the O(log(n))
performance of lookupswitch
, it requires some analysis to determine whether the table is dense enough to justify the space–time tradeoff. Bill Venners wrote a great article that covers this in more detail, along with an under-the-hood look at other Java flow control instructions.
Prior to JDK 7, enum
could approximate a String
-based switch. This uses the static valueOf
method generated by the compiler on every enum
type. For example:
Pill p = Pill.valueOf(str);
switch(p) {
case RED: pop(); break;
case BLUE: push(); break;
}
Doubles don't have decimal places - they're not based on decimal digits to start with. You could get "the closest double to the current value when truncated to three decimal digits", but it still wouldn't be exactly the same. You'd be better off using decimal
.
Having said that, if it's only the way that rounding happens that's a problem, you can use Math.Truncate(value * 1000) / 1000;
which may do what you want. (You don't want rounding at all, by the sounds of it.) It's still potentially "dodgy" though, as the result still won't really just have three decimal places. If you did the same thing with a decimal value, however, it would work:
decimal m = 12.878999m;
m = Math.Truncate(m * 1000m) / 1000m;
Console.WriteLine(m); // 12.878
EDIT: As LBushkin pointed out, you should be clear between truncating for display purposes (which can usually be done in a format specifier) and truncating for further calculations (in which case the above should work).
I had a similar problem.
I would also look at this answer: Is there a high resolution (microsecond, nanosecond) DateTime object available for the CLR?.
About half-way down is an answer by "Robert P" with some extension functions I found useful.
Here's a solution, based on jQuery and a mouse event listener (which is far better than a regular polling) on the body:
$("body").mousemove(function(e) {
document.Form1.posx.value = e.pageX;
document.Form1.posy.value = e.pageY;
})
You can use pgrep
as long as you include the -f
options. That makes pgrep
match keywords in the whole command (including arguments) instead of just the process name.
pgrep -f keyword
From the man page:
-f
The pattern is normally only matched against the process name. When-f
is set, the full command line is used.
If you really want to avoid pgrep, try:
ps -ef | awk '/[k]eyword/{print $2}'
Note the []
around the first letter of the keyword. That's a useful trick to avoid matching the awk
command itself.
All the answers above about reload()
or imp.reload()
are deprecated.
reload()
is no longer a builtin function in python 3 and imp.reload()
is marked deprecated (see help(imp)
).
It's better to use importlib.reload()
instead.
I know this post is really old but, to get the contents of an element in reference to its ID, this is what I would do:
window.onclick = e => {
console.log(e.target);
console.log(e.target.id, ' -->', e.target.innerHTML);
}
It is not a question of preference. /base
and /base/
have different semantics. In many cases, the difference is unimportant. But it is important when there are relative URLs.
child
relative to /base/
is /base/child
.child
relative to /base
is (perhaps surprisingly) /child
.Sometime this happened due to not fond any source like if i want to set a text into a textview from adapter then i should use
textView.setText(""+name);
If you write something like
textView.setText(name);
this will not work and sometime we don't find the resource from the string.xml file then this type of error occur.
I found this code at jwt.io and it works well.
//this is used to parse base64
function url_base64_decode(str) {
var output = str.replace(/-/g, '+').replace(/_/g, '/');
switch (output.length % 4) {
case 0:
break;
case 2:
output += '==';
break;
case 3:
output += '=';
break;
default:
throw 'Illegal base64url string!';
}
var result = window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
try{
return decodeURIComponent(escape(result));
} catch (err) {
return result;
}
}
In some cases(certain development platforms),
the best answer(for now) faces a problem of invalid base64 length.
So, I needed a more stable way.
I hope it would help you.
JS Code:
<script type="text/javascript">
function ShowCurrentTime(name) {
PageMethods.GetCurrentTime(name, OnSuccess);
}
function OnSuccess(response, userContext, methodName) {
alert(response);
}
</script>
HTML Code:
<asp:ImageButton ID="IMGBTN001" runat="server" ImageUrl="Images/ico/labaniat.png"
class="img-responsive em-img-lazy" OnClientClick="ShowCurrentTime('01')" />
Code Behind C#
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
Python is very sensitive to indentation, with the code below I got the same error:
except IntegrityError as e:
if 'unique constraint' in e.args:
return render(request, "calender.html")
The correct indentation is:
except IntegrityError as e:
if 'unique constraint' in e.args:
return render(request, "calender.html")
Depends on your use case.
If you want to do some animation of children blending in, use the react animation add-on: https://facebook.github.io/react/docs/animation.html Otherwise, make the rendering of the children dependent on props and add the props after some delay.
I wouldn't delay in the component, because it will probably haunt you during testing. And ideally, components should be pure.
I did a log file which prints data into text file using "Winston" log. The source code is here below,
const { createLogger, format, transports } = require('winston');
var fs = require('fs')
var logger = fs.createWriteStream('Data Log.txt', {`
flags: 'a'
})
const os = require('os');
var sleep = require('system-sleep');
var endOfLine = require('os').EOL;
var t = ' ';var s = ' ';var q = ' ';
var array1=[];
var array2=[];
var array3=[];
var array4=[];
array1[0] = 78;`
array1[1] = 56;
array1[2] = 24;
array1[3] = 34;
for (var n=0;n<4;n++)
{
array2[n]=array1[n].toString();
}
for (var k=0;k<4;k++)
{
array3[k]=Buffer.from(' ');
}
for (var a=0;a<4;a++)
{
array4[a]=Buffer.from(array2[a]);
}
for (m=0;m<4;m++)
{
array4[m].copy(array3[m],0);
}
logger.write('Date'+q);
logger.write('Time'+(q+' '))
logger.write('Data 01'+t);
logger.write('Data 02'+t);
logger.write('Data 03'+t);
logger.write('Data 04'+t)
logger.write(endOfLine);
logger.write(endOfLine);
enter code here`enter code here`
}
function mydata() //user defined function
{
logger.write(datechar+s);
logger.write(timechar+s);
for ( n = 0; n < 4; n++)
{
logger.write(array3[n]);
}
logger.write(endOfLine);
}
for (;;)
}
var now = new Date();
var dateFormat = require('dateformat');
var date = dateFormat(now,"isoDate");
var time = dateFormat(now, "h:MM:ss TT ");
var datechar = date.toString();
var timechar = time.toString();
mydata();
sleep(5*1000);
}
Just modified @ClickUpvote's answer:
You can use IIFE (Immediately Invoked Function Expression) and recursion to make it a little bit more easier:
var i = 5; //set the countdown
(function timer(){
if (--i < 0) return;
setTimeout(function(){
console.log(i + ' secs'); //do stuff here
timer();
}, 1000);
})();
var i = 5;_x000D_
(function timer(){_x000D_
if (--i < 0) return;_x000D_
setTimeout(function(){_x000D_
document.getElementsByTagName('h1')[0].innerHTML = i + ' secs';_x000D_
timer();_x000D_
}, 1000);_x000D_
})();
_x000D_
<h1>5 secs</h1>
_x000D_
try to show popup like this
new Handler().postDelayed(new Runnable(){
public void run() {
popupWindow.showAtLocation(context.getWindow().getDecorView(), Gravity.CENTER,0,0);
}
}, 200L);
In my case, i'm using Postgresql 9.2.24 and solution was this (pg_hba.conf):
host all all 0.0.0.0/0 trust
For remote connections use trust. Combined with (as mentioned above)
listen_addresses = '*'
Set<YourPropertyType> set = new HashSet<>();
list
.stream()
.filter(it -> set.add(it.getYourProperty()))
.forEach(it -> ...);
Have a max int and set it to the first value in the array. Then in a for loop iterate through the whole array and see if the max int is larger than the int at the current index.
int max = array.get(0);
for (int i = 1; i < array.length; i++) {
if (array.get(i) > max) {
max = array.get(i);
}
}
Official Notice: success and error have been deprecated, please use the standard then method instead.
Deprecation Notice: The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.
link: https://code.angularjs.org/1.5.7/docs/api/ng/service/$http
I know its a long time since Jon's original answer, but I had a similar requirement to the OP.
By way of extending Jon's solution I came up with the following, which will take one or more path segments takes as many path segments that you can throw at it.
Usage
Path.combine("/Users/beardtwizzle/");
Path.combine("/", "Users", "beardtwizzle");
Path.combine(new String[] { "/", "Users", "beardtwizzle", "arrayUsage" });
Code here for others with a similar problem
public class Path {
public static String combine(String... paths)
{
File file = new File(paths[0]);
for (int i = 1; i < paths.length ; i++) {
file = new File(file, paths[i]);
}
return file.getPath();
}
}
Try Jedi! There's a Vim plugin at https://github.com/davidhalter/jedi-vim.
It works just much better than anything else for Python in Vim. It even has support for renaming, goto, etc. The best part is probably that it really tries to understand your code (decorators, generators, etc. Just look at the feature list).
There's several things you can improve upon here. To start, there's no reason to use an <a>
(anchor) tag since you don't have a link.
Every element can be bound to click and hover events... divs, spans, labels, inputs, etc.
I can't really identify what it is you're trying to do, though. You're mixing the goal with your own implementation and, from what I've seen so far, you're not really sure how to do it. Could you better illustrate what it is you're trying to accomplish?
== EDIT ==
The requirements are still very vague. I've implemented a very quick version of what I'm imagining you're saying ... or something close that illustrates how you might be able to do it. Left me know if I'm on the right track.
My column names is as below
colnames(t)
[1] "Class" "Sex" "Age" "Survived" "Freq"
I want to change column name of Class and Sex
colnames(t)=c("STD","Gender","AGE","SURVIVED","FREQ")
The stash command will stash any changes you have made since your last commit. In your case there is no reason to stash if you are gonna continue working on it the next day. I would only use stash to undo changes that you don't want to commit.
The answer to this is very needed today because not everyone wants to use cURL to consume web services. Also PHP does allow for this using the following code
function get_info()
{
$post_data = array(
'test' => 'foobar',
'okay' => 'yes',
'number' => 2
);
// Send a request to example.com
$result = $this->post_request('http://www.example.com/', $post_data);
if ($result['status'] == 'ok'){
// Print headers
echo $result['header'];
echo '<hr />';
// print the result of the whole request:
echo $result['content'];
}
else {
echo 'A error occured: ' . $result['error'];
}
}
function post_request($url, $data, $referer='') {
// Convert the data array into URL Parameters like a=b&foo=bar etc.
$data = http_build_query($data);
// parse the given URL
$url = parse_url($url);
if ($url['scheme'] != 'http') {
die('Error: Only HTTP request are supported !');
}
// extract host and path:
$host = $url['host'];
$path = $url['path'];
// open a socket connection on port 80 - timeout: 30 sec
$fp = fsockopen($host, 80, $errno, $errstr, 30);
if ($fp){
// send the request headers:
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
if ($referer != '')
fputs($fp, "Referer: $referer\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ". strlen($data) ."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data);
$result = '';
while(!feof($fp)) {
// receive the results of the request
$result .= fgets($fp, 128);
}
}
else {
return array(
'status' => 'err',
'error' => "$errstr ($errno)"
);
}
// close the socket connection:
fclose($fp);
// split the result header from the content
$result = explode("\r\n\r\n", $result, 2);
$header = isset($result[0]) ? $result[0] : '';
$content = isset($result[1]) ? $result[1] : '';
// return as structured array:
return array(
'status' => 'ok',
'header' => $header,
'content' => $content);
}
I had similar problem with IntelliJ when tried to run some Groovy scripts. Here is how I solved it.
Go to "Project Structure"-> "Project" -> "Project language level" and select "SDK default". This should use the same SDK for all project modules.
This usually happens to me when I forget to change the company to match mine.
When you create a new app, it usually says, "com.yourcompany". Change it to whatever you registered with, in my case com.DavidKanarek
For installing standard toolboxes: Just insert your CD/DVD of MATLAB and start installing, when you see typical/Custom, choose custom and check the toolboxes you want to install and uncheck the others which are installed already.
>>> dict(zip(keys, values))
{0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
My solution was to switch my Mac keyboard from Unicode to U.S. English.
I my case, I was using syncthing. It created a duplicate that I was not aware of and my compilation was failing.
Unfortunately you can't.
If you really want them in that order you'll have to create a new table with the columns in that order and copy data. Or rename columns etc. There is no easy way.
You should rather use ViewPropertyAnimator. This animates the view to its future position and you don't need to force any layout params on the view after the animation ends. And it's rather simple.
myView.animate().x(50f).y(100f);
myView.animate().translateX(pixelInScreen)
Note: This pixel is not relative to the view. This pixel is the pixel position in the screen.
The popular library Humanizer has a Truncate method. To install with NuGet:
Install-Package Humanizer
If you are developing spring boot application add "SpringBootServletInitializer" as shown in following code to your main file. Because without SpringBootServletInitializer Tomcat will consider it as normal application it will not consider as Spring boot application
@SpringBootApplication
public class DemoApplication extends *SpringBootServletInitializer*{
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(DemoApplication .class);
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication .class, args);
}
}
You can also evaluate your output as a sub-process, by surrounding everything with back ticks or with putting it inside $():
`ps aux | grep -ie amarok | awk '{print "kill -9 " $2}'`
$(ps aux | grep -ie amarok | awk '{print "kill -9 " $2}')
pullFiles.sh
:#!/bin/bash
HOST_DIR=<pull-to>
DEVICE_DIR=/sdcard/<pull-from>
EXTENSION=".jpg"
for file in $(adb shell ls $DEVICE_DIR | grep $EXTENSION'$')
do
file=$(echo -e $file | tr -d "\r\n"); # EOL fix
adb pull $DEVICE_DIR/$file $HOST_DIR/$file;
done
Make it executable: chmod +x pullFiles.sh
Run it: ./pullFiles.sh
Post::where('id',3)->update(['title'=>'Updated title']);
The notion of complex numbers was introduced in mathematics, from the need of calculating negative quadratic roots. Complex number concept was taken by a variety of engineering fields.
Today that complex numbers are widely used in advanced engineering domains such as physics, electronics, mechanics, astronomy, etc...
Real and imaginary part, of a negative square root example:
#include <stdio.h>
#include <complex.h>
int main()
{
int negNum;
printf("Calculate negative square roots:\n"
"Enter negative number:");
scanf("%d", &negNum);
double complex negSqrt = csqrt(negNum);
double pReal = creal(negSqrt);
double pImag = cimag(negSqrt);
printf("\nReal part %f, imaginary part %f"
", for negative square root.(%d)",
pReal, pImag, negNum);
return 0;
}
As an addition to @ANisus' answer...
below is some information from the "Go in action" book, which I think is worth mentioning:
nil
& empty
slicesIf we think of a slice like this:
[pointer] [length] [capacity]
then:
nil slice: [nil][0][0]
empty slice: [addr][0][0] // points to an address
nil slice
They’re useful when you want to represent a slice that doesn’t exist, such as when an exception occurs in a function that returns a slice.
// Create a nil slice of integers. var slice []int
empty slice
Empty slices are useful when you want to represent an empty collection, such as when a database query returns zero results.
// Use make to create an empty slice of integers. slice := make([]int, 0) // Use a slice literal to create an empty slice of integers. slice := []int{}
Regardless of whether you’re using a nil slice or an empty slice, the built-in functions
append
,len
, andcap
work the same.
package main
import (
"fmt"
)
func main() {
var nil_slice []int
var empty_slice = []int{}
fmt.Println(nil_slice == nil, len(nil_slice), cap(nil_slice))
fmt.Println(empty_slice == nil, len(empty_slice), cap(empty_slice))
}
prints:
true 0 0
false 0 0
According to docker docs,
Both CMD and ENTRYPOINT instructions define what command gets executed when running a container. There are few rules that describe their co-operation.
- Dockerfile should specify at least one of
CMD
orENTRYPOINT
commands.ENTRYPOINT
should be defined when using the container as an executable.CMD
should be used as a way of defining default arguments for anENTRYPOINT
command or for executing an ad-hoc command in a container.CMD
will be overridden when running the container with alternative arguments.
The tables below shows what command is executed for different ENTRYPOINT
/ CMD
combinations:
-- No ENTRYPOINT
+----------------------------------------------------------+
¦ No CMD ¦ error, not allowed ¦
¦----------------------------+-----------------------------¦
¦ CMD ["exec_cmd", "p1_cmd"] ¦ exec_cmd p1_cmd ¦
¦----------------------------+-----------------------------¦
¦ CMD ["p1_cmd", "p2_cmd"] ¦ p1_cmd p2_cmd ¦
¦----------------------------+-----------------------------¦
¦ CMD exec_cmd p1_cmd ¦ /bin/sh -c exec_cmd p1_cmd ¦
+----------------------------------------------------------+
-- ENTRYPOINT exec_entry p1_entry
+---------------------------------------------------------------+
¦ No CMD ¦ /bin/sh -c exec_entry p1_entry ¦
¦----------------------------+----------------------------------¦
¦ CMD ["exec_cmd", "p1_cmd"] ¦ /bin/sh -c exec_entry p1_entry ¦
¦----------------------------+----------------------------------¦
¦ CMD ["p1_cmd", "p2_cmd"] ¦ /bin/sh -c exec_entry p1_entry ¦
¦----------------------------+----------------------------------¦
¦ CMD exec_cmd p1_cmd ¦ /bin/sh -c exec_entry p1_entry ¦
+---------------------------------------------------------------+
-- ENTRYPOINT ["exec_entry", "p1_entry"]
+------------------------------------------------------------------------------+
¦ No CMD ¦ exec_entry p1_entry ¦
¦----------------------------+-------------------------------------------------¦
¦ CMD ["exec_cmd", "p1_cmd"] ¦ exec_entry p1_entry exec_cmd p1_cmd ¦
¦----------------------------+-------------------------------------------------¦
¦ CMD ["p1_cmd", "p2_cmd"] ¦ exec_entry p1_entry p1_cmd p2_cmd ¦
¦----------------------------+-------------------------------------------------¦
¦ CMD exec_cmd p1_cmd ¦ exec_entry p1_entry /bin/sh -c exec_cmd p1_cmd ¦
+------------------------------------------------------------------------------+
In my case, the crti.o error was entailed by the execution path configuration from Matlab. For instance, you cannot perform a file if you have not set the path of your execution directory earlier. To do this: File > setPath, add your directory and save.
Working jsbin: http://jsbin.com/ANAYeDU/4/edit
Main bit:
function answers()
{
var element = document.getElementById("mySelect");
var elementValue = element.value;
if(elementValue == "To measure time"){
alert("Thats correct");
}
}
You will have to use the fluent API to do this.
Try adding the following to your DbContext
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasOptional(a => a.UserDetail)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
}
preg_replace('/^[^:\/?]+:\/\//','',$url);
some results:
input: http://php.net/preg_replace output: php.net/preg_replace input: https://www.php.net/preg_replace output: www.php.net/preg_replace input: ftp://www.php.net/preg_replace output: www.php.net/preg_replace input: https://php.net/preg_replace?url=http://whatever.com output: php.net/preg_replace?url=http://whatever.com input: php.net/preg_replace?url=http://whatever.com output: php.net/preg_replace?url=http://whatever.com input: php.net?site=http://whatever.com output: php.net?site=http://whatever.com
The name of the key 'key_name' is key_name, therefore print 'key_name'
or whatever variable you have representing it.
In my case my request object inherited from base object. Without knowingly I added a property with int? in my request object and my base object also has same property ( same name ) with int datatype. I noticed this and deleted the property which I added in request object and after that it worked fine.
if (rs == null || !rs.first()) { //empty } else { //not empty }
Note that after this method call, if the resultset is not empty, it is at the beginning.
In certain circumstances you may want to only pass down the environment variables your subprocess needs, but I think you've got the right idea in general (that's how I do it too).
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
private const string strconneciton = "Data Source=.;Initial Catalog=Employees;Integrated Security=True";
SqlConnection con = new SqlConnection(strconneciton);
private void button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into EmployeeData (Name,S/O,Address,Phone,CellNo,CNICNO,LicenseNo,LicenseDistrict,LicenseValidPhoto,ReferenceName,ReferenceContactNo) values ( '" + textName.Text + "','" + textSO.Text + "','" + textAddress.Text + "','" + textPhone.Text + "','" + textCell.Text + "','" + textCNIC.Text + "','" + textLicenseNo.Text + "','" + textLicenseDistrict.Text + "','" + textLicensePhoto.Text + "','" + textReferenceName.Text + "','" + textContact.Text + "' )", con);
cmd.ExecuteNonQuery();
con.Close();
}
See the relevant documentation in general and specifically
from matplotlib.ticker import FormatStrFormatter
fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
The framework class has been modified to require a flag to inform fromHtml()
how to process line breaks. This was added in Nougat, and only touches on the challenge of incompatibilities of this class across versions of Android.
I've published a compatibility library to standardize and backport the class and include more callbacks for elements and styling:
While it is similar to the framework's Html class, some signature changes were required to allow more callbacks. Here's the sample from the GitHub page:
Spanned fromHtml = HtmlCompat.fromHtml(context, source, 0);
// You may want to provide an ImageGetter, TagHandler and SpanCallback:
//Spanned fromHtml = HtmlCompat.fromHtml(context, source, 0,
// imageGetter, tagHandler, spanCallback);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(fromHtml);
try this:
ls -ltraR |egrep -v '\.$|\.\.|\.:|\.\/|total' |sed '/^$/d'
What the other answers suggest will work for the program in question, but it has the potential to cause breakage in other programs and unknown dependence elsewhere. It's better to make a tiny wrapper script:
#!/bin/sh
export LD_LIBRARY_PATH=/usr/local/lib64:$LD_LIBRARY_PATH
program_needing_different_run_time_library_path
This mostly avoids the problem described in Why LD_LIBRARY_PATH is bad by confining the effects to the program which needs them.
Note that despite the names LD_RUN_PATH works at link-time and is non-evil, while LD_LIBRARY_PATH works at both link and run time (and is evil :).
Use the Maven debug option, ie mvn -X
:
Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...
In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml
.
I simply declared as below in web.xml file and Its working for me :
<welcome-file-list>
<welcome-file>/WEB-INF/jsps/index.jsp</welcome-file>
</welcome-file-list>
And NO html/jsp pages present in public directory except static resources(css, js, images). Now I can access my index page with URL like : http://localhost:8080/app/ Its calling /WEB-INF/jsps/index.jsp page. When hosted live in production the final URL looks like https://eisdigital.com/
You must enable php! Check the folder mods-enabled
in the Apache directory (default: /etc/apache2/
) to see if you find a file named php
. I don't remember the extension but I think it's .so
.
Also check in /var/log/apache2/error.log
to see if you have any other errors.
Are you sure you can't alter the HTML in the popup window?
If you can, add a <script>
tag at the end of the popup's HTML, and call window.print()
inside it. Then it won't be called until the HTML has loaded.
After jQuery 1.6, using promise seems like a better option.
var $div1 = $('#div1');
var fadeOutDone = $div1.fadeOut().promise();
// do your logic here, e.g.fetch your 2nd image url
$.get('secondimageinfo.json').done(function(data){
fadeoOutDone.then(function(){
$div1.html('<img src="' + data.secondImgUrl + '" alt="'data.secondImgAlt'">');
$div1.fadeIn();
});
});
Old post, but I thought I'd weigh in, with a DataTable extension that can convert a single column at a time, to a given type:
public static class DataTableExt
{
public static void ConvertColumnType(this DataTable dt, string columnName, Type newType)
{
using (DataColumn dc = new DataColumn(columnName + "_new", newType))
{
// Add the new column which has the new type, and move it to the ordinal of the old column
int ordinal = dt.Columns[columnName].Ordinal;
dt.Columns.Add(dc);
dc.SetOrdinal(ordinal);
// Get and convert the values of the old column, and insert them into the new
foreach (DataRow dr in dt.Rows)
dr[dc.ColumnName] = Convert.ChangeType(dr[columnName], newType);
// Remove the old column
dt.Columns.Remove(columnName);
// Give the new column the old column's name
dc.ColumnName = columnName;
}
}
}
It can then be called like this:
MyTable.ConvertColumnType("MyColumnName", typeof(int));
Of course using whatever type you desire, as long as each value in the column can actually be converted to the new type.
I got in the habit of using it liberally in Visual C++ since doing so would trigger IntelliSense ones I hit the '>' key, and I'm lazy. (and prone to typos)
But I've continued to use it, since I find it handy to see that I'm calling a member function rather than a global function.
By the power of Google I found a blogpost from 2007 which gives the following regex that matches string which don't contains a certain substring:
^((?!my string).)*$
It works as follows: it looks for zero or more (*) characters (.) which do not begin (?! - negative lookahead) your string and it stipulates that the entire string must be made up of such characters (by using the ^ and $ anchors). Or to put it an other way:
The entire string must be made up of characters which do not begin a given string, which means that the string doesn't contain the given substring.
If you CAST
your data as a VARCHAR()
instead of explicitly CONVERT
ing your data you can simply
SELECT REPLACE(CAST(CreatedDate AS VARCHAR(20)),'Jan 1 1900 12:00AM','')
The CAST
will automatically return your Date then as Jun 18 2020 12:46PM
fix length strings formats which you can additionally SUBSTRING()
SELECT SUBSTRING(REPLACE(CAST(CreatedDate AS VARCHAR(20)),'Jan 1 1900 12:00AM',''),1,11)
Output
Jun 18 2020
No, but you can detect what mouse button was used in the "onmousedown" event... and from there determine if it was a "right-click".
Well,
Just worked it out. While having both installations we have two ORACLE_HOME directories and both have SQAORA32.dll files. While looking up for ORACLE_HOMe my app was getting confused..I just removed the Client oracle home entry as oracle client is by default present in oracle DB Now its working...Thanks!!
The only surefire option to find the current session.save_path
value is always to check with phpinfo()
in exactly the environment where you want to find out the session storage directory.
Reason: there can be all sorts of things that change session.save_path
, either by overriding the php.ini
value or by setting it at runtime with ini_set('session.save_path','/path/to/folder');
. For example, web server management panels like ISPConfig, Plesk etc. often adapt this to give each website its own directory with session files.
Len is what you want.
word = "habit"
length = Len(word)
Below is an example of the correct way I think. At least it is what I use. You need to do Response.Clear to get rid of any headers that are already populated. You need to pass the correct ContentType of text/xml. That is the way you serve xml. In general you want to serve it as charset UTF-8 as that is what most parsers are expecting. But I don't think it has to be that. But if you change it make sure to change your xml document declaration and indicate the charset in there. You need to use the XmlWriter so you can actually write in UTF-8 and not whatever charset is the default. And to have it properly encode your xml data in UTF-8.
' -----------------------------------------------------------------------------
' OutputDataSetAsXML
'
' Description: outputs the given dataset as xml to the response object
'
' Arguments:
' dsSource - source data set
'
' Dependencies:
'
' History
' 2006-05-02 - WSR : created
'
Private Sub OutputDataSetAsXML(ByRef dsSource As System.Data.DataSet)
Dim xmlDoc As System.Xml.XmlDataDocument
Dim xmlDec As System.Xml.XmlDeclaration
Dim xmlWriter As System.Xml.XmlWriter
' setup response
Me.Response.Clear()
Me.Response.ContentType = "text/xml"
Me.Response.Charset = "utf-8"
xmlWriter = New System.Xml.XmlTextWriter(Me.Response.OutputStream, System.Text.Encoding.UTF8)
' create xml data document with xml declaration
xmlDoc = New System.Xml.XmlDataDocument(dsSource)
xmlDoc.DataSet.EnforceConstraints = False
xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", Nothing)
xmlDoc.PrependChild(xmlDec)
' write xml document to response
xmlDoc.WriteTo(xmlWriter)
xmlWriter.Flush()
xmlWriter.Close()
Response.End()
End Sub
' -----------------------------------------------------------------------------
It might be the easiest way to input a string and find its length.
// Finding length of a string in C++
#include<iostream>
#include<string>
using namespace std;
int count(string);
int main()
{
string str;
cout << "Enter a string: ";
getline(cin,str);
cout << "\nString: " << str << endl;
cout << count(str) << endl;
return 0;
}
int count(string s){
if(s == "")
return 0;
if(s.length() == 1)
return 1;
else
return (s.length());
}
Dijkstra's algorithm assumes paths can only become 'heavier', so that if you have a path from A to B with a weight of 3, and a path from A to C with a weight of 3, there's no way you can add an edge and get from A to B through C with a weight of less than 3.
This assumption makes the algorithm faster than algorithms that have to take negative weights into account.
Maybe check that the header has the same line-ending as the actual data rows (as specified in ROWTERMINATOR
)?
Update: from MSDN:
The FIRSTROW attribute is not intended to skip column headers. Skipping headers is not supported by the BULK INSERT statement. When skipping rows, the SQL Server Database Engine looks only at the field terminators, and does not validate the data in the fields of skipped rows.
I don't endorse this solution in any way, shape or form. But if you add a variable to the __builtin__
module, it will be accessible as if a global from any other module that includes __builtin__
-- which is all of them, by default.
a.py contains
print foo
b.py contains
import __builtin__
__builtin__.foo = 1
import a
The result is that "1" is printed.
Edit: The __builtin__
module is available as the local symbol __builtins__
-- that's the reason for the discrepancy between two of these answers. Also note that __builtin__
has been renamed to builtins
in python3.
Thanx @krd, I am using your error catch process, but had to update the print and except statements. I am using Python 2.7.6 on Linux Mint 17.2.
Also, it was unclear where the output string was coming from. My update:
import subprocess
# Output returned in error handler
try:
print("Ping stdout output on success:\n" +
subprocess.check_output(["ping", "-c", "2", "-w", "2", "1.1.1.1"]))
except subprocess.CalledProcessError as e:
print("Ping stdout output on error:\n" + e.output)
# Output returned normally
try:
print("Ping stdout output on success:\n" +
subprocess.check_output(["ping", "-c", "2", "-w", "2", "8.8.8.8"]))
except subprocess.CalledProcessError as e:
print("Ping stdout output on error:\n" + e.output)
I see an output like this:
Ping stdout output on error:
PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.
--- 1.1.1.1 ping statistics ---
2 packets transmitted, 0 received, 100% packet loss, time 1007ms
Ping stdout output on success:
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=59 time=37.8 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=59 time=38.8 ms
--- 8.8.8.8 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 37.840/38.321/38.802/0.481 ms
For website developers, another option you have is to follow a working Facebook Graph API tutorial such as this one.
But if you need a quick solution where you can customize and embed a Facebook page feed instantly, you should use website plugins such as this one.
Here's a step by step guide:
Visit the tutorial link to see a live demo there as well.
I found the answer here: Is it possible to pass query parameters via Django's {% url %} template tag?
Simply add them to the end:
<a href="{% url myview %}?office=foobar">
For Django 1.5+
<a href="{% url 'myview' %}?office=foobar">
[there is nothing else to improve but I'm getting a stupid error when I fix the code ticks]
This is not an easy one. I've come up with a Script solution. (I don't think this can be done using pure CSS)
the HTML stays the same as you posted, the CSS changes a little bit, JQuery code added.
Working Fiddle Tested on: IE10, IE9, IE8, FF, Chrome
BTW: if you have unique elements, why don't you use id's instead of classes? I think it gives a better selector performance.
Explanation of how it works:
inner-container
will span the entire space of the outer-container
(so basically, he's not needed) but I left him there, so you wont need to change you DOM.
the table-header
is relatively positioned, without a scroll (overflow: hidden
), we will handle his scroll later.
the table-body
have to span the rest of the inner-container
height, so I used a script to determine what height to fix him. (it changes dynamically when you re-size the window)
without a fixed height, the scroll wont appear, because the div will just grow large instead..
notice that this part can be done without script, if you fix the header height and use CSS3 (as shown in the end of the answer)
now it's just a matter of moving the header along with the body each time we scroll.
this is done by a function assigned to the scroll
event.
CSS (some of it was copied from your style)
*
{
padding: 0;
margin: 0;
}
body
{
height: 100%;
width: 100%;
}
table
{
border-collapse: collapse; /* make simple 1px lines borders if border defined */
}
.outer-container
{
background-color: #ccc;
position: absolute;
top:0;
left: 0;
right: 300px;
bottom: 40px;
}
.inner-container
{
height: 100%;
overflow: hidden;
}
.table-header
{
position: relative;
}
.table-body
{
overflow: auto;
}
.header-cell
{
background-color: yellow;
text-align: left;
height: 40px;
}
.body-cell
{
background-color: blue;
text-align: left;
}
.col1, .col3, .col4, .col5
{
width:120px;
min-width: 120px;
}
.col2
{
min-width: 300px;
}
JQuery
$(document).ready(function () {
setTableBody();
$(window).resize(setTableBody);
$(".table-body").scroll(function ()
{
$(".table-header").offset({ left: -1*this.scrollLeft });
});
});
function setTableBody()
{
$(".table-body").height($(".inner-container").height() - $(".table-header").height());
}
If you don't care about fixing the header height (I saw that you fixed the cell's height in your CSS), some of the Script can be skiped if you use CSS3 :Shorter Fiddle (this will not work on IE8)
You may want to check out GCCXML.
Running GCCXML on your sample code produces:
<GCC_XML>
<Namespace id="_1" name="::" members="_3 " mangled="_Z2::"/>
<Namespace id="_2" name="std" context="_1" members="" mangled="_Z3std"/>
<Enumeration id="_3" name="MyEnum" context="_1" location="f0:1" file="f0" line="1">
<EnumValue name="FOO" init="0"/>
<EnumValue name="BAR" init="80"/>
</Enumeration>
<File id="f0" name="my_enum.h"/>
</GCC_XML>
You could use any language you prefer to pull out the Enumeration and EnumValue tags and generate your desired code.
You can loop through all the Animals using foreach and put it into NewAnimals.
I just put the content in the question in a file called test.php
and ran php test.php
.
(In the folder where the test.php
is.)
$ php foo.php
15
In general you add all prerequisite steps to setUp and all clean-up steps to tearDown.
You can read more with examples here.
When a setUp() method is defined, the test runner will run that method prior to each test. Likewise, if a tearDown() method is defined, the test runner will invoke that method after each test.
For example you have a test that requires items to exist, or certain state - so you put these actions(creating object instances, initializing db, preparing rules and so on) into the setUp.
Also as you know each test should stop in the place where it was started - this means that we have to restore app state to it's initial state - e.g close files, connections, removing newly created items, calling transactions callback and so on - all these steps are to be included into the tearDown.
So the idea is that test itself should contain only actions that to be performed on the test object to get the result, while setUp and tearDown are the methods to help you to leave your test code clean and flexible.
You can create a setUp and tearDown for a bunch of tests and define them in a parent class - so it would be easy for you to support such tests and update common preparations and clean ups.
If you are looking for an easy example please use the following link with example
So you want to:
Inspired by this answer, here's the adapted version of your script:
#!/usr/bin/env bash
different_user=deploy
useradd -m -s /bin/bash "$different_user"
echo "Current user: $(whoami)"
echo "Current directory: $(pwd)"
echo
echo "Switching user to $different_user"
sudo -u "$different_user" -i /bin/bash - <<-'EOF'
echo "Current user: $(id)"
echo "Current directory: $(pwd)"
EOF
echo
echo "Switched back to $(whoami)"
different_user_home="$(eval echo ~"$different_user")"
echo "$different_user home directory: $different_user_home"
When you run it, you should get the following:
Current user: root
Current directory: /root
Switching user to deploy
Current user: uid=1003(deploy) gid=1003(deploy) groups=1003(deploy)
Current directory: /home/deploy
Switched back to root
deploy home directory: /home/deploy
I would think you should add it to ~/.bash_profile
instead of .bashrc
, (creating .bash_profile
if it doesn't exist.) Then you don't have to add the extra step of checking for ~/.bashrc
in your .bash_profile
Are you comfortable working and editing in a terminal? Just in case, ~/
means your home directory, so if you open a new terminal window that is where you will be "located". And the dot at the front makes the file invisible to normal ls
command, unless you put -a
or specify the file name.
Check this answer for more detail.
Use SSL only and instead of encrypting the HTTP_USER_AGENT in the session id and verifying it on every request, just store the HTTP_USER_AGENT string in your session db as well.
Now you only have a simple server based string compare with the ENV'HTTP_USER_AGENT'.
Or you can add a certain variation in your string compare to be more robust against browser version updates. And you could reject certain HTTP_USER_AGENT id's. (empty ones i.e.) Does not resolve the problem completley, but it adds at least a bit more complexity.
Another method could be using more sophisticated browser fingerprinting techniques and combine theyse values with the HTTP_USER_AGENT and send these values from time to time in a separate header values. But than you should encrypt the data in the session id itself.
But that makes it far more complex and raises the CPU usage for decryption on every request.
See the Android documentation on controlling the emulator; it's Ctrl + F11 / Ctrl + F12.
On ThinkPad running Ubuntu, you may try CTRL + Left Arrow Key or Right Arrow Key
Pass re.IGNORECASE
to the flags
param of search
, match
, or sub
:
re.search('test', 'TeSt', re.IGNORECASE)
re.match('test', 'TeSt', re.IGNORECASE)
re.sub('test', 'xxxx', 'Testing', flags=re.IGNORECASE)
The "Leader key" is a way of extending the power of VIM's shortcuts by using sequences of keys to perform a command. The default leader key is backslash. Therefore, if you have a map of <Leader>Q, you can perform that action by typing \Q.
What if you need to access two elements of the list simultaneously?
for i in range(len(a[0:-1])):
something_new[i] = a[i] * a[i+1]
You can use this, but it's probably less clear:
for i, _ in enumerate(a[0:-1]):
something_new[i] = a[i] * a[i+1]
Personally I'm not 100% happy with either!
Check if node_modules
directory exists. After a fresh clone, there will very likely be no node_modules
(since these are .gitignore
'd).
run npm install
to ensure all deps are downloaded.
If node_modules
exists, remove it with rm -rf node_modules
and then run npm install
.
While I agree with the most voted answer, here is another way to keep all rows except the first:
dat <- tail(dat, -1)
This can also be accomplished using Hadley Wickham's dplyr
package.
dat <- dat %>% slice(-1)
In my case it was failing as the IP of my source server was not whitelisted in the target server.
For e.g. I was trying to access https://prodcat.ref.test.co.uk from application running on my source server. On source server find IP by ifconfig
This IP should be whitelisted in the target Server's apache config file. If its not then get it whitelist.
Steps to add a IP for whitelisting (if you control the target server as well) ssh to the apache server sudo su - cd /usr/local/apache/conf/extra (actual directories can be different based on your config)
Find the config file for the target application for e.g. prodcat-443.conf
RewriteCond %{REMOTE_ADDR} <YOUR Server's IP>
for e.g.
RewriteCond %{REMOTE_ADDR} !^192\.68\.2\.98
Hope this helps someone
Because apt-cache policy
will list all the matches available, even if not installed, I would suggest using this command for a more manageable shortlist of GTK-related packages installed on your system:
apt list --installed libgtk*
Then all you have to do is subtract that from total document height
jQuery(function () {
var documentHeight = jQuery(document).height();
var element = jQuery('#you-element');
var distanceFromBottom = documentHeight - (element.position().top + element.outerHeight(true));
alert(distanceFromBottom)
});
This works like charm I did it for Ubuntu 16.04. Full credit to below link as I got it from there. [https://coderwall.com/p/j9btlg/reset-the-mysql-5-7-root-password-in-ubuntu-16-04-lts][1]
Stop MySQL
sudo service mysql stop
Make MySQL service directory. sudo mkdir /var/run/mysqld
Give MySQL user permission to write to the service directory.
sudo chown mysql: /var/run/mysqld
Start MySQL manually, without permission checks or networking.
sudo mysqld_safe --skip-grant-tables --skip-networking &
Log in without a password.
mysql -uroot mysql
Update the password for the root user. make sure at atleast root account gets updated by the below query. make some selection and check the existing values if you like
UPDATE mysql.user SET
authentication_string=PASSWORD('YOURNEWPASSWORD'),
plugin='mysql_native_password' WHERE User='root';
EXIT;
Turn off MySQL.
sudo mysqladmin -S /var/run/mysqld/mysqld.sock shutdown
Start the MySQL service normally.
sudo service mysql start
The for-each loop was introduced in Java 1.5 and is used with collections (and to be pedantic, arrays, and anything implementing the Iterable<E>
interface ... which the article notes):
http://download.oracle.com/javase/1,5.0/docs/guide/language/foreach.html
The Old Way: UIActionSheet
let actionSheet = UIActionSheet(title: "Takes the appearance of the bottom bar if specified; otherwise, same as UIActionSheetStyleDefault.", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: "Destroy", otherButtonTitles: "OK")
actionSheet.actionSheetStyle = .Default
actionSheet.showInView(self.view)
// MARK: UIActionSheetDelegate
func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
switch buttonIndex {
...
}
}
The New Way: UIAlertController
let alertController = UIAlertController(title: nil, message: "Takes the appearance of the bottom bar if specified; otherwise, same as UIActionSheetStyleDefault.", preferredStyle: .ActionSheet)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
// ...
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
// ...
}
alertController.addAction(OKAction)
let destroyAction = UIAlertAction(title: "Destroy", style: .Destructive) { (action) in
println(action)
}
alertController.addAction(destroyAction)
self.presentViewController(alertController, animated: true) {
// ...
}
The previous answers will work installing a new version of Node.js (probably the best option), but if you have a dependency on a specific Node.js version then the following will work: "npm install npm -g". Verify by running npm -v before and after the command.
If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.
EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character
Ensure the database's backup mode is set to Simple (see here for an overview of the different modes). This will avoid SQL Server waiting for a transaction log backup before reusing space.
Use dbcc shrinkfile
or Management Studio to shrink the log files.
Step #2 will do nothing until the backup mode is set.
I made some changes in above code to look for a location fix by both GPS and Network for about 5sec and give me the best known location out of it.
public class LocationService implements LocationListener {
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
final static long MIN_TIME_INTERVAL = 60 * 1000L;
Location location;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute
protected LocationManager locationManager;
private CountDownTimer timer = new CountDownTimer(5 * 1000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
stopUsingGPS();
}
};
public LocationService() {
super(R.id.gps_service_id);
}
public void start() {
if (Utils.isNetworkAvailable(context)) {
try {
timer.start();
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
Location tempLocation = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (tempLocation != null
&& isBetterLocation(tempLocation,
location))
location = tempLocation;
}
}
if (isGPSEnabled) {
locationManager.requestSingleUpdate(
LocationManager.GPS_PROVIDER, this, null);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
Location tempLocation = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (tempLocation != null
&& isBetterLocation(tempLocation,
location))
location = tempLocation;
}
}
} catch (Exception e) {
onTaskError(e.getMessage());
e.printStackTrace();
}
} else {
onOfflineResponse(requestData);
}
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(LocationService.this);
}
}
public boolean canGetLocation() {
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
return isGPSEnabled || isNetworkEnabled;
}
@Override
public void onLocationChanged(Location location) {
if (location != null
&& isBetterLocation(location, this.location)) {
this.location = location;
}
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public Object getResponseObject(Object location) {
return location;
}
public static boolean isBetterLocation(Location location,
Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > MIN_TIME_INTERVAL;
boolean isSignificantlyOlder = timeDelta < -MIN_TIME_INTERVAL;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location,
// use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true;
// If the new location is more than two minutes older, it must
// be worse
} else if (isSignificantlyOlder) {
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation
.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and
// accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate
&& isFromSameProvider) {
return true;
}
return false;
}
}
In the above class, I am registering a location listener for both GPS and network, so an onLocationChanged
call back can be called by either or both of them multiple times and we just compare the new location fix with the one we already have and keep the best one.
Try the Join-Path cmdlet:
Get-ChildItem c:\code\*\bin\* -Filter *.dll | Foreach-Object {
Join-Path -Path $_.DirectoryName -ChildPath "$buildconfig\$($_.Name)"
}
Array(10).fill('a').join('')
Although the most voted answer is a bit more compact, with this approach you don't have to add an extra array item.
string name = System.Environment.MachineName;
To insert a VARCHAR2
into a BLOB
column you can rely on the function utl_raw.cast_to_raw
as next:
insert into mytable(id, myblob) values (1, utl_raw.cast_to_raw('some magic here'));
It will cast your input VARCHAR2
into RAW
datatype without modifying its content, then it will insert the result into your BLOB
column.
More details about the function utl_raw.cast_to_raw
Simple but works..
listen.owner = nginx
listen.group = nginx
chown nginx:nginx /var/run/php-fpm/php-fpm.sock
Alternatively to information_schema
it is possible to use pg_tables
:
select * from pg_tables where schemaname='public';
Microsoft's GUID
's textual representation can be in the form of a UUID being surrounded by two curly braces {}
.
Ok Check and Add to Watch:
Now you can see a list of all SubKey with its validation state at end of value.
So search for the Invalid value.
This code is work perfect for me
Bitmap tempbg = BitmapFactory.decodeResource(getResources(),R.drawable.b1); //Load a background.
Bitmap final_Bitmap = BlurImage(tempbg);
@SuppressLint("NewApi")
Bitmap BlurImage (Bitmap input)
{
try
{
RenderScript rsScript = RenderScript.create(getApplicationContext());
Allocation alloc = Allocation.createFromBitmap(rsScript, input);
ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(rsScript, Element.U8_4(rsScript));
blur.setRadius(21);
blur.setInput(alloc);
Bitmap result = Bitmap.createBitmap(input.getWidth(), input.getHeight(), Bitmap.Config.ARGB_8888);
Allocation outAlloc = Allocation.createFromBitmap(rsScript, result);
blur.forEach(outAlloc);
outAlloc.copyTo(result);
rsScript.destroy();
return result;
}
catch (Exception e) {
// TODO: handle exception
return input;
}
}
Different types of variable:
DECLARE is permitted only inside a BEGIN ... END compound statement and must be at its start, before any other statements.
Therefore, if you are defining a stored program and actually do want a "local variable", you will need to drop the @ character and ensure that your DECLARE statement is at the start of your program block. Otherwise, to use a "user variable", drop the DECLARE statement.
Furthermore, you will either need to surround your query in parentheses in order to execute it as a subquery:
SET @countTotal = (SELECT COUNT(*) FROM nGrams);
Or else, you could use SELECT ... INTO:
SELECT COUNT(*) INTO @countTotal FROM nGrams;
Use Chrome browser and with the Web Server for Chrome extension, set a default folder and put your linked html/js files in there, browse to 127.0.0.1:8887 (0r whatever the port is set at) in Chrome and open the developers panel & console. You can then interact with your html/js scripts in the console.
You can always use Request.QueryString
collection like Web forms, but you can also make MVC handle them and pass them as parameters. This is the suggested way as it's easier and it will validate input data type automatically.
Make use of onResume method... both on the fragment activity and the activity holding the fragment.
I had a similar problem in a MS-Access query, and I solved it by changing my equivalent fName
to an "Expression" (as opposed to "Group By" or "Sum"). So long as all of my fields were "Expression", the Access query builder did not require any Group By
clause at the end.
You might find this link helpful:
http://tldp.org/LDP/abs/html/string-manipulation.html
In general,
To replace the first match of $substring with $replacement:
${string/substring/replacement}
To replace all matches of $substring with $replacement:
${string//substring/replacement}
EDIT: Note that this applies to a variable named $string.
Sometime your code syntax has error, like you use " in ", it must be " ...'...." For help you quickly detect problems, you click Design button, vs try to render, and it will show the line of error
Use below css to align Label with Checkbox
.chkbox label
{
position: relative;
top: -2px;
}
<div class="chkbox">
<asp:CheckBox ID="Ckbox" runat="server" Text="Check Box Alignment"/>
</div>
Yes. Use WindowBuilder Pro (provided by Google). It supports SWT and Swing as well with multiple layouts (Group layout, MiGLayout etc.) It's integrated out of the box with Eclipse Indigo, but you can install plugin on previous versions (3.4/3.5/3.6):
None of the other answers worked for me.
Make sure both unzipped files are in same folder, but also right click on setup.exe, select properties, compatibility, and then put a checkmark in "Run this program in compatibility mode for..." and select Windows 7.
I successfully launched the installer without the error message on Windows 10 for the 32-bit version of Oracle 11g release 2.
From: http://www-01.ibm.com/support/docview.wss?uid=swg21960606
I was able to apply a background below the Scaffold
(and even it's AppBar
) by putting the Scaffold
under a Stack
and setting a Container
in the first "layer" with the background image set and fit: BoxFit.cover
property.
Both the Scaffold
and AppBar
has to have the backgroundColor
set as Color.transparent
and the elevation
of AppBar
has to be 0 (zero).
Voilà! Now you have a nice background below the whole Scaffold and AppBar! :)
import 'package:flutter/material.dart';
import 'package:mynamespace/ui/shared/colors.dart';
import 'package:mynamespace/ui/shared/textstyle.dart';
import 'package:mynamespace/ui/shared/ui_helpers.dart';
import 'package:mynamespace/ui/widgets/custom_text_form_field_widget.dart';
class SignUpView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Stack( // <-- STACK AS THE SCAFFOLD PARENT
children: [
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/bg.png"), // <-- BACKGROUND IMAGE
fit: BoxFit.cover,
),
),
),
Scaffold(
backgroundColor: Colors.transparent, // <-- SCAFFOLD WITH TRANSPARENT BG
appBar: AppBar(
title: Text('NEW USER'),
backgroundColor: Colors.transparent, // <-- APPBAR WITH TRANSPARENT BG
elevation: 0, // <-- ELEVATION ZEROED
),
body: Padding(
padding: EdgeInsets.all(spaceXS),
child: Column(
children: [
CustomTextFormFieldWidget(labelText: 'Email', hintText: 'Type your Email'),
UIHelper.verticalSpaceSM,
SizedBox(
width: double.maxFinite,
child: RaisedButton(
color: regularCyan,
child: Text('Finish Registration', style: TextStyle(color: white)),
onPressed: () => {},
),
),
],
),
),
),
],
);
}
}
My approach would be:
/// <summary>
/// Appends CSS Class seprated by a space character
/// </summary>
/// <param name="control">Target control</param>
/// <param name="cssClass">CSS class name to append</param>
public static void AppendCss(HtmlGenericControl control, string cssClass)
{
// Ensure CSS class is definied
if (string.IsNullOrEmpty(cssClass)) return;
// Append CSS class
if (string.IsNullOrEmpty(control.Attributes["class"]))
{
// Set our CSS Class as only one
control.Attributes["class"] = cssClass;
}
else
{
// Append new CSS class with space as seprator
control.Attributes["class"] += (" " + cssClass);
}
}
First of all you missed ScriptService attribute to add in webservice.
[ScriptService]
After then try following method to call webservice via JSON.
var webAddr = "http://Domain/VBRService.asmx/callJson"; var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr); httpWebRequest.ContentType = "application/json; charset=utf-8"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = "{\"x\":\"true\"}"; streamWriter.Write(json); streamWriter.Flush(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); return result; }
Using jquery:
<form action="upload" enctype="multipart/form-data" method="post">
Upload image:
<input id="image-file" type="file" name="file" />
<input type="submit" value="Upload" />
<script type="text/javascript">
$('#image-file').bind('change', function() {
alert('This file size is: ' + this.files[0].size/1024/1024 + "MiB");
});
</script>
</form>
You can make a symbolic link of your module to the standard path, so depmod will see it and you'll be able load it as any other module.
sudo ln -s /path/to/module.ko /lib/modules/`uname -r`
sudo depmod -a
sudo modprobe module
If you add the module name to /etc/modules it will be loaded any time you boot.
Anyway I think that the proper configuration is to copy the module to the standard paths.
First of all, there're two kinds of keystores.
Individual and General
The application will use the one indicated in the startup or the default of the system.
It will be a different folder if JRE or JDK is running, or if you check the personal or the "global" one.
They are encrypted too
In short, the path will be like:
$JAVA_HOME/lib/security/cacerts
for the "general one", who has all the CA for the Authorities and is quite important.
You can use a binding adapter(Kotlin) to achieve this. Create a binding adapter class named ChangeShapeColor like below
@BindingAdapter("shapeColor")
// Method to load shape and set its color
fun loadShape(textView: TextView, color: String) {
// first get the drawable that you created for the shape
val mDrawable = ContextCompat.getDrawable(textView.context,
R.drawable.language_image_bg)
val shape = mDrawable as (GradientDrawable)
// use parse color method to parse #34444 to the int
shape.setColor(Color.parseColor(color))
}
Create a drawable shape in res/drawable folder. I have created a circle
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<solid android:color="#anyColorCode"/>
<size
android:width="@dimen/dp_16"
android:height="@dimen/dp_16"/>
</shape>
Finally refer it to your view
<TextView>
.........
app:shapeColor="@{modelName.colorString}"
</Textview>
There might two issues
1) $blogs may be a stdObject
or
2) The properties of the array might be the stdObject
Try using var_dump($blogs) and see the actual problem if the properties of array have stdObject try like this
$blog->id;
$blog->content;
$blog->title;
I ran into similar problems, you might be able to get it to work using a similar method.
First, try this with your current configuration, exclude httpclient
from httpmime
:
dependencies {
compile 'com.google.android.gms:play-services:+'
compile ('org.apache.httpcomponents:httpmime:4.2.6'){
exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient:4.2.6'
}
In my case, I fixed it by using the following jars :
Then, in the build.gradle, excluding httpclient
from httpmime
:
dependencies {
compile 'com.google.android.gms:play-services:+'
compile('org.apache.httpcomponents:httpmime:4.3.5') {
exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
}
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementsByClassName('featured-heading')[0].setAttribute('style', 'background-color: green')");
I could add an attribute using the above code in java
Take a look at Traverse. It will recursively walk an object tree for you and at every node you have a number of different objects you can access - key of current node, value of current node, parent of current node, full key path of current node, etc. https://github.com/substack/js-traverse. I've used it to good effect on objects that I wanted to scrub circular references to and when I need to do a deep clone while transforming various data bits. Here's some code pulled form their samples to give you a flavor of what it can do.
var id = 54;
var callbacks = {};
var obj = { moo : function () {}, foo : [2,3,4, function () {}] };
var scrubbed = traverse(obj).map(function (x) {
if (typeof x === 'function') {
callbacks[id] = { id : id, f : x, path : this.path };
this.update('[Function]');
id++;
}
});
console.dir(scrubbed);
console.dir(callbacks);
A practical explanation: By default, <p> </p>
will add line breaks before and after the enclosed text (so it creates a paragraph). <span>
does not do this, that is why it is called inline.
Bitmap d = new Bitmap(c.Width, c.Height);
for (int i = 0; i < c.Width; i++)
{
for (int x = 0; x < c.Height; x++)
{
Color oc = c.GetPixel(i, x);
int grayScale = (int)((oc.R * 0.3) + (oc.G * 0.59) + (oc.B * 0.11));
Color nc = Color.FromArgb(oc.A, grayScale, grayScale, grayScale);
d.SetPixel(i, x, nc);
}
}
This way it also keeps the alpha channel.
Enjoy.
You are to use something like this:
start /d C:\Windows\System32\calc.exe
start /d "C:\Program Files\Mozilla
Firefox" firefox.exe start /d
"C:\Program Files\Microsoft
Office\Office12" EXCEL.EXE
Also I advice you to use special batch files editor - Dr.Batcher
When inserting the generated ID is saved into the instance of the object being saved (see below):
protected void btnInsertProductCategory_Click(object sender, EventArgs e)
{
ProductCategory productCategory = new ProductCategory();
productCategory.Name = “Sample Category”;
productCategory.ModifiedDate = DateTime.Now;
productCategory.rowguid = Guid.NewGuid();
int id = InsertProductCategory(productCategory);
lblResult.Text = id.ToString();
}
//Insert a new product category and return the generated ID (identity value)
private int InsertProductCategory(ProductCategory productCategory)
{
ctx.ProductCategories.InsertOnSubmit(productCategory);
ctx.SubmitChanges();
return productCategory.ProductCategoryID;
}
reference: http://blog.jemm.net/articles/databases/how-to-common-data-patterns-with-linq-to-sql/#4
My advice is to stick to rule 0 and not redo what standard libraries already do, if this is enough. Look at math.h (cmath in standard C++) and functions frexp, frexpf, frexpl, that break a floating point value (double, float, or long double) in its significand and exponent part. To extract the sign from the significand you can use signbit, also in math.h / cmath, or copysign (only C++11). Some alternatives, with slighter different semantics, are modf and ilogb/scalbn, available in C++11; http://en.cppreference.com/w/cpp/numeric/math/logb compares them, but I didn't find in the documentation how all these functions behave with +/-inf and NaNs. Finally, if you really want to use bitmasks (e.g., you desperately need to know the exact bits, and your program may have different NaNs with different representations, and you don't trust the above functions), at least make everything platform-independent by using the macros in float.h/cfloat.
Open httpd.conf file in your text editor. Find this line:
Listen 80
and change it
Listen 8079
After change, save it and restart apache.
curl
sends POST requests with the default content type of application/x-www-form-urlencoded
. If you want to send a JSON request, you will have to specify the correct content type header:
$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"
But that will only work if the server accepts json input. The .json
at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.
The reason you get a 401
and not some other error is probably because the server can't extract the auth_token
from your request.
From the javadoc
@param the sole object to be stored in the returned list.
@return an immutable list containing only the specified object.
example
import java.util.*;
public class HelloWorld {
public static void main(String args[]) {
// create an array of string objs
String initList[] = { "One", "Two", "Four", "One",};
// create one list
List list = new ArrayList(Arrays.asList(initList));
System.out.println("List value before: "+list);
// create singleton list
list = Collections.singletonList("OnlyOneElement");
list.add("five"); //throws UnsupportedOperationException
System.out.println("List value after: "+list);
}
}
Use it when code expects a read-only list, but you only want to pass one element in it. singletonList
is (thread-)safe and fast.
Below gives me opposite of what you have. (Notice Group column)
SELECT
*
FROM
myTable
GROUP BY
Group_value,
ID
ORDER BY
count(Group_value)
Let me know if this is fine with you...
I am trying to get what you want too...
Here is how you set the date and time:
update user set expiry_date=TO_DATE('31/DEC/2017 12:59:59', 'dd/mm/yyyy hh24:mi:ss') where id=123;
go to your project folder via cmd. run the following command
composer update
it will install the missing vendor folder and files in your project.
but in some cases, it gives an error like "Your configuration does not allow connection to ....." in cmd.
for that go to your composer.json file,
change "secure-http": true
to "secure-http": false
but in some cases (as was in my case) you may not find such line in your file. for that do the following action:
change "config": {
"preferred-install": "dist"
}
to
"config": {
"preferred-install": "dist",
"secure-http": false
}
and run again composer update
command.
hope this will solve problem.
for k, m in self.materials.items():
example:
miles_dict = {'Monday':1, 'Tuesday':2.3, 'Wednesday':3.5, 'Thursday':0.9}
for k, v in miles_dict.items():
print("%s: %s" % (k, v))
One of the best use case for me to use enum's with interface is Predicate filters. It's very elegant way to remedy lack of typness of apache collections (If other libraries mayn't be used).
import java.util.ArrayList;
import java.util.Collection;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
public class Test {
public final static String DEFAULT_COMPONENT = "Default";
enum FilterTest implements Predicate {
Active(false) {
@Override
boolean eval(Test test) {
return test.active;
}
},
DefaultComponent(true) {
@Override
boolean eval(Test test) {
return DEFAULT_COMPONENT.equals(test.component);
}
}
;
private boolean defaultValue;
private FilterTest(boolean defautValue) {
this.defaultValue = defautValue;
}
abstract boolean eval(Test test);
public boolean evaluate(Object o) {
if (o instanceof Test) {
return eval((Test)o);
}
return defaultValue;
}
}
private boolean active = true;
private String component = DEFAULT_COMPONENT;
public static void main(String[] args) {
Collection<Test> tests = new ArrayList<Test>();
tests.add(new Test());
CollectionUtils.filter(tests, FilterTest.Active);
}
}
One way to fix up your python2 code is:
import sys
if sys.version_info >= (3, 0):
def xrange(*args, **kwargs):
return iter(range(*args, **kwargs))
Since API Level 21 (Lollipop) Android provides a PdfRenderer class:
// create a new renderer
PdfRenderer renderer = new PdfRenderer(getSeekableFileDescriptor());
// let us just render all pages
final int pageCount = renderer.getPageCount();
for (int i = 0; i < pageCount; i++) {
Page page = renderer.openPage(i);
// say we render for showing on the screen
page.render(mBitmap, null, null, Page.RENDER_MODE_FOR_DISPLAY);
// do stuff with the bitmap
// close the page
page.close();
}
// close the renderer
renderer.close();
For more information see the sample app.
For older APIs I recommend Android PdfViewer library, it is very fast and easy to use, licensed under Apache License 2.0:
pdfView.fromAsset(String)
.pages(0, 2, 1, 3, 3, 3) // all pages are displayed by default
.enableSwipe(true)
.swipeHorizontal(false)
.enableDoubletap(true)
.defaultPage(0)
.onDraw(onDrawListener)
.onLoad(onLoadCompleteListener)
.onPageChange(onPageChangeListener)
.onPageScroll(onPageScrollListener)
.onError(onErrorListener)
.enableAnnotationRendering(false)
.password(null)
.scrollHandle(null)
.load();
you can use the following Bootstrap class with
<tr class="w-25">
</tr>
for more details check the following page https://getbootstrap.com/docs/4.1/utilities/sizing/
I found this an easy way of cleaning in a shape between the desired row and column. I am not sure if this is what you are looking for. Hope it helps.
Sub sbClearCellsOnlyData()
Range("A1:C10").ClearContents
End Sub
from os import listdir
def find_csv_filenames( path_to_dir, suffix=".csv" ):
filenames = listdir(path_to_dir)
return [ filename for filename in filenames if filename.endswith( suffix ) ]
The function find_csv_filenames()
returns a list of filenames as strings, that reside in the directory path_to_dir
with the given suffix (by default, ".csv").
Addendum
How to print the filenames:
filenames = find_csv_filenames("my/directory")
for name in filenames:
print name
You can invoke dll function from user32.dll i think Something like
Rundll32.exe user32.dll, MessageBox (0, "text", "titleText", {extra flags for like topmost messagebox e.t.c})
Typing it from my Phone, don't judge me... otherwise i would link the extra flags.
For security reasons, Firefox doesn't allow you to place text on the clipboard. However, there is a work-around available using Flash.
function copyIntoClipboard(text) {
var flashId = 'flashId-HKxmj5';
/* Replace this with your clipboard.swf location */
var clipboardSWF = 'http://appengine.bravo9.com/copy-into-clipboard/clipboard.swf';
if(!document.getElementById(flashId)) {
var div = document.createElement('div');
div.id = flashId;
document.body.appendChild(div);
}
document.getElementById(flashId).innerHTML = '';
var content = '<embed src="' +
clipboardSWF +
'" FlashVars="clipboard=' + encodeURIComponent(text) +
'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
document.getElementById(flashId).innerHTML = content;
}
The only disadvantage is that this requires Flash to be enabled.
source is currently dead: http://bravo9.com/journal/copying-text-into-the-clipboard-with-javascript-in-firefox-safari-ie-opera-292559a2-cc6c-4ebf-9724-d23e8bc5ad8a/ (and so is it's Google cache)
You've got a couple of issues here.
Firstly, you're defining your code within an anonymous function. This construct:
(function() {
...
)();
does two things. It defines an anonymous function and calls it. There are scope reasons to do this but I'm not sure it's what you actually want.
You're passing in a code block to setTimeout()
. The problem is that update()
is not within scope when executed like that. It however if you pass in a function pointer instead so this works:
(function() {
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout(update, 1000); }
}
)();
because the function pointer update
is within scope of that block.
But like I said, there is no need for the anonymous function so you can rewrite it like this:
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout(update, 1000); }
}
or
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout('update()', 1000); }
}
and both of these work. The second works because the update()
within the code block is within scope now.
I also prefer the $(function() { ... }
shortened block form and rather than calling setTimeout()
within update()
you can just use setInterval()
instead:
$(function() {
setInterval(update, 1000);
});
function update() {
$("#board").append(".");
}
Hope that clears that up.
When you use float without width, there remains some space in that row. To block this space you can use clear:both;
in next element.
IntVar = int("".join(filter(str.isdigit, StringVar)))
From JavaEE docs ServletResponse#setContentType
Sets the content type of the response being sent to the client, if the response has not been committed yet.
The given content type may include a character encoding specification, for example,
response.setContentType("text/html;charset=UTF-8");
The response's character encoding is only set from the given content type if this method is called before getWriter
is called.
This method may be called repeatedly to change content type and character encoding.
This method has no effect if called after the response has been committed. It does not set the response's character encoding if it is called after getWriter
has been called or after the response has been committed.
Containers must communicate the content type and the character encoding used for the servlet response's writer to the client if the protocol provides a way for doing so. In the case of HTTP, the Content-Type header is used.
With image class name:
$('.img_class').hide(); // to hide image
$('.img_class').show(); // to show image
With image Id :
$('#img_id').hide(); // to hide image
$('#img_id').show(); // to show image
1) Ensure that the enable32BitAppOnWin64 setting for the "SharePoint Central Administration" app pool is set to False, and the same for the "SharePoint Web Services Root" app pool
2) Edit applicationHost.config:
bitness64 being the magic word here
Simplest is to wrap the image in a center tag, like so ...
<center>![Alt test](http://upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png)</center>
Anything to do with Markdown can be tested here - http://daringfireball.net/projects/markdown/dingus
Sure, <center>
may be deprecated, but it's simple and it works!
This will be helpful for some people:
From MySQL command line:
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
Sadly, at this point newuser has no permissions to do anything with the databases. In fact, if newuser even tries to login (with the password, password), they will not be able to reach the MySQL shell.
Therefore, the first thing to do is to provide the user with access to the information they will need.
GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';
The asterisks in this command refer to the database and table (respectively) that they can access—this specific command allows to the user to read, edit, execute and perform all tasks across all the databases and tables.
Once you have finalized the permissions that you want to set up for your new users, always be sure to reload all the privileges.
FLUSH PRIVILEGES;
Your changes will now be in effect.
For more information: http://dev.mysql.com/doc/refman/5.6/en/grant.html
If you are not comfortable with the command line then you can use a client like MySQL workbench, Navicat or SQLyog
You can get a graphical view of the project history with tools like gitk
. Just run:
gitk --all
If you want to checkout a specific branch:
git checkout <branch name>
For a specific commit, use the SHA1 hash instead of the branch name. (See Treeishes in the Git Community Book, which is a good read, to see other options for navigating your tree.)
git log
has a whole set of options to display detailed or summary history too.
I don't know of an easy way to move forward in a commit history. Projects with a linear history are probably not all that common. The idea of a "revision" like you'd have with SVN or CVS doesn't map all that well in Git.
In Python 3, urllib.quote
has been moved to urllib.parse.quote
and it does handle unicode by default.
>>> from urllib.parse import quote
>>> quote('/test')
'/test'
>>> quote('/test', safe='')
'%2Ftest'
>>> quote('/El Niño/')
'/El%20Ni%C3%B1o/'
You could also do this:
#!/usr/bin/perl
use strict;
use warnings;
$^I = '.bak'; # create a backup copy
while (<>) {
s/<PREF>/ABCD/g; # do the replacement
print; # print to the modified file
}
Invoke the script with by
./script.pl input_file
You will get a file named input_file
, containing your changes, and a file named input_file.bak
, which is simply a copy of the original file.
numpy.append
always copies the array before appending the new values. Your code is equivalent to the following:
import numpy as np
result = np.zeros((2,0))
new_result = np.append([result[0]],[1,2])
result[0] = new_result # ERROR: has shape (2,0), new_result has shape (2,)
Perhaps you mean to do this?
import numpy as np
result = np.zeros((2,0))
result = np.append([result[0]],[1,2])
You can't call something on the entire viewModel, but on an individual observable you can call myObservable.valueHasMutated()
to notify subscribers that they should re-evaluate. This is generally not necessary in KO, as you mentioned.
For completeness, write_csv()
from the readr
package is faster and never writes row names
# install.packages('readr', dependencies = TRUE)
library(readr)
write_csv(t, "t.csv")
If you need to write big data out, use fwrite()
from the data.table
package. It's much faster than both write.csv
and write_csv
# install.packages('data.table')
library(data.table)
fwrite(t, "t.csv")
Below is a benchmark that Edouard published on his site
microbenchmark(write.csv(data, "baseR_file.csv", row.names = F),
write_csv(data, "readr_file.csv"),
fwrite(data, "datatable_file.csv"),
times = 10, unit = "s")
## Unit: seconds
## expr min lq mean median uq max neval
## write.csv(data, "baseR_file.csv", row.names = F) 13.8066424 13.8248250 13.9118324 13.8776993 13.9269675 14.3241311 10
## write_csv(data, "readr_file.csv") 3.6742610 3.7999409 3.8572456 3.8690681 3.8991995 4.0637453 10
## fwrite(data, "datatable_file.csv") 0.3976728 0.4014872 0.4097876 0.4061506 0.4159007 0.4355469 10
This post helped me today, but I had to experiment to do what I needed. Here is what I found.
Should you want to add more complex time periods, for example 1 year and 15 days, you can use
UPDATE tablename SET datefieldname = curdate() + INTERVAL 15 DAY + INTERVAL 1 YEAR;
I found that using DATE_ADD
doesn't allow for adding more than one interval. And there is no YEAR_DAYS interval keyword, though there are others that combine time periods. If you are adding times, use now()
rather than curdate()
.
Personally, I would define it this way:
function isVowel( chr ){ return 'aeiou'.indexOf( chr[0].toLowerCase() ) !== -1 }
You could also use ['a','e','i','o','u']
and skip the length test, but then you are creating an array each time you call the function. (There are ways of mimicking this via closures, but those are a bit obscure to read)
To answer your question, update_attribute
skips pre save "validations" but it still runs any other callbacks like after_save
etc. So if you really want to "just update the column and skip any AR cruft" then you need to use (apparently)
Model.update_all(...)
see https://stackoverflow.com/a/7243777/32453
Example:
import React from 'react';
import PropTypes from 'prop-types';
class MenuItem extends React.Component {
render() {
return (
<li>
<a href={this.props.href}>{this.props.children}</a>
</li>
);
}
}
MenuItem.defaultProps = {
href: "/",
children: "Main page"
};
MenuItem.propTypes = {
href: PropTypes.string.isRequired,
children: PropTypes.string.isRequired
};
export default MenuItem;
Picture: Shows you error in console if the expected type is different
Try:
try
{
int cnt= m.getSmartPhoneCount("HTC",true);
System.out.println("total count of HTC="+cnt);
}
catch (NoSuchBrandSmartPhoneAvailableException e)
{
// TODO Auto-generated catch
e.printStackTrace();
}
To select all anchors with the data attribute data-customerID==22
, you should include the a
to limit the scope of the search to only that element type. Doing data attribute searches in a large loop or at high frequency when there are many elements on the page can cause performance issues.
$('a[data-customerID="22"]');
Add the jar files to your library(if using netbeans) and modify your manifest's file classpath
as follows:
Class-Path: lib/derby.jar lib/derbyclient.jar lib/derbynet.jar lib/derbytools.jar
a similar answer exists here
A SIMPLE TABLE SORT PHP CODE:
(the simple table for several values processing and sorting, using this sortable.js script )
<html><head>
<script src="sorttable.js"></script>
<style>
tbody tr td {color:green;border-right:1px solid;width:200px;}
</style>
</head><body>
<?php
$First = array('a', 'b', 'c', 'd');
$Second = array('1', '2', '3', '4');
if (!empty($_POST['myFirstvalues']))
{ $First = explode("\r\n",$_POST['myFirstvalues']); $Second = explode("\r\n",$_POST['mySecondvalues']);}
?>
</br>Hi User. PUT your values</br></br>
<form action="" method="POST">
projectX</br>
<textarea cols="20" rows="20" name="myFirstvalues" style="width:200px;background:url(untitled.PNG);position:relative;top:19px;Float:left;">
<?php foreach($First as $vv) {echo $vv."\r\n";}?>
</textarea>
The due amount</br>
<textarea cols="20" rows="20" name="mySecondvalues" style="width:200px;background:url(untitled.PNG);Float:left;">
<?php foreach($Second as $vv) {echo $vv."\r\n";}?>
</textarea>
<input type="submit">
</form>
<table class="sortable" style="padding:100px 0 0 300px;">
<thead style="background-color:#999999; color:red; font-weight: bold; cursor: default; position:relative;">
<tr><th>ProjectX</th><th>Due amount</th></tr>
</thead>
<tbody>
<?php
foreach($First as $indx => $value) {
echo '<tr><td>'.$First[$indx].'</td><td>'.$Second[$indx].'</td></tr>';
}
?>
</tbody>
<tfoot><tr><td>TOTAL = <b>111111111</b></td><td>Still to spend = <b>5555555</b></td></tr></tfoot></br></br>
</table>
</body>
</html>
source: php sortable table
Here is the official documentation of ArrayList.get().
Anyway it is very simple, for example
ArrayList list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
String str = (String) list.get(0); // here you get "1" in str
Every time a new device is opened par() will reset, so another option is simply do dev.off()
and continue.