Here's another step I had to go through, after receiving an error on completing Step 9:
ImportError: dlopen(/Users/rick/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib
sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
Reference: Thanks! http://ageekstory.blogspot.com/2011_04_01_archive.html
To pull a copy of the branch and force overwrite of local files from the origin use:
git reset --hard origin/current_branch
All current work will be lost and it will then be the same as the origin branch
/[\W\S_]/
This creates a character class removing the word characters, space characters, and adding back the underscore character (as underscore is a "word" character). All that is left is the special characters. Capital letters represent the negation of their lowercase counterparts.
\W
will select all non "word" characters equivalent to [^a-zA-Z0-9_]
\S
will select all non "whitespace" characters equivalent to [ \t\n\r\f\v]
_
will select "_" because we negate it when using the \W
and need to add it back in
Thanks to AddRange
:
Example:
public class Person
{
private string Name;
private string FirstName;
public Person(string name, string firstname) => (Name, FirstName) = (name, firstname);
}
To add multiple Person
to a List<>
:
List<Person> listofPersons = new List<Person>();
listofPersons.AddRange(new List<Person>
{
new Person("John1", "Doe" ),
new Person("John2", "Doe" ),
new Person("John3", "Doe" ),
});
For adding compression to the resulting zip file, check out this link.
You need to change:
zip = zipfile.ZipFile('Python.zip', 'w')
to
zip = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED)
This works for me:
import Cookies from 'universal-cookie';
const cookies = new Cookies();
function headers(set_cookie=false) {
let headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
};
if (set_cookie) {
headers['Authorization'] = "Bearer " + cookies.get('remember_user_token');
}
return headers;
}
Then build your call:
export function fetchTests(user_id) {
return function (dispatch) {
let data = {
method: 'POST',
credentials: 'same-origin',
mode: 'same-origin',
body: JSON.stringify({
user_id: user_id
}),
headers: headers(true)
};
return fetch('/api/v1/tests/listing/', data)
.then(response => response.json())
.then(json => dispatch(receiveTests(json)));
};
}
It depends on the needs of the specific situation. For example, the dictionary approach would be quite good assuming:
If the above are not true for your situation, just use the method Any()
:
Item wonderIfItsPresent = ...
bool containsItem = myList.Any(item => item.UniqueProperty == wonderIfItsPresent.UniqueProperty);
This will enumerate through the list until it finds a match, or until it reaches the end.
Well, you want to process the string representing the number, iterating over the digits, not the number itself (which is an abstract entity that could be written differently, like "CX" in Roman numerals or "0x6e" hexadecimal (both for 110) or whatever).
Therefore:
inp = input('Enter a number:')
n = 0
for digit in inp:
n = n + int(digit)
print(n)
Note that the n = 0
is required (someplace before entry into the loop). You can't take the value of a variable which doesn't exist (and the right hand side of n = n + int(digit)
takes the value of n
). And if n
does exist at that point, it might hold something completely unrelated to your present needs, leading to unexpected behaviour; you need to guard against that.
This solution makes no attempt to ensure that the input provided by the user is actually a number. I'll leave this problem for you to think about (hint: all that you need is there in the Python tutorial).
public TreeNode findKthElement(TreeNode root, int k){
if((k==numberElement(root.left)+1)){
return root;
}
else if(k>numberElement(root.left)+1){
findKthElement(root.right,k-numberElement(root.left)-1);
}
else{
findKthElement(root.left, k);
}
}
public int numberElement(TreeNode node){
if(node==null){
return 0;
}
else{
return numberElement(node.left) + numberElement(node.right) + 1;
}
}
Also note that if your using the git flow system and your feature branch might be called
feature/mobile_additions
and with a git remote called stagingtwo, then the command to push to heroku would be
git push stagingtwo feature/mobile_additions:master
you must check is user loggined ?
Auth::check() ? Auth::user()->id : null
It seems that when you change to the latest SDK (2.2) building no longer generates an R.java file. Or at least not in the way we're used to. To solve this delete the package underneath the gen folder and clean without building. This solves the issue for me.
Have you tried int 21h
service 2? DL
is the character to print.
mov dl,'A' ; print 'A'
mov ah,2
int 21h
To print the integer value, you'll have to write a loop to decompose the integer to individual characters. If you're okay with printing the value in hex, this is pretty trivial.
If you can't rely on DOS services, you might also be able to use the BIOS int 10h
with AL
set to 0Eh
or 0Ah
.
Change your subplot settings to:
plt.subplot(1, 2, 1)
...
plt.subplot(1, 2, 2)
The parameters for subplot
are: number of rows, number of columns, and which subplot you're currently on. So 1, 2, 1
means "a 1-row, 2-column figure: go to the first subplot." Then 1, 2, 2
means "a 1-row, 2-column figure: go to the second subplot."
You currently are asking for a 2-row, 1-column (that is, one atop the other) layout. You need to ask for a 1-row, 2-column layout instead. When you do, the result will be:
In order to minimize the overlap of subplots, you might want to kick in a:
plt.tight_layout()
before the show. Yielding:
In Python, the name of the class refers to the class instance. Consider:
class A: pass
class B: pass
class C: pass
lst = [A, B, C]
# instantiate second class
b_instance = lst[1]()
print b_instance
I was attempting to find strings with numbers ONLY, no punctuation or anything else. I finally found an answer that would work here.
Using PATINDEX('%[^0-9]%', some_column) = 0 allowed me to filter out everything but actual number strings.
The declaration of your event object has to be inside your new css function. Otherwise the event can only be fired once.
(function() {
orig = $.fn.css;
$.fn.css = function() {
var ev = new $.Event('style');
orig.apply(this, arguments);
$(this).trigger(ev);
}
})();
In at least in ubuntu 16.10, the default python3
is python3.5
. As such, all of the python3-X
packages will be installed for python3.5 and not for python3.6.
You can verify this by checking the shebang of pip3
:
$ head -n1 $(which pip3)
#!/usr/bin/python3
Fortunately, the pip installed by the python3-pip
package is installed into the "shared" /usr/lib/python3/dist-packages
such that python3.6 can also take advantage of it.
You can install packages for python3.6 by doing:
python3.6 -m pip install ...
For example:
$ python3.6 -m pip install requests
$ python3.6 -c 'import requests; print(requests.__file__)'
/usr/local/lib/python3.6/dist-packages/requests/__init__.py
Just a small modification that might actually solve the problem:
window.onload = function() {
if (window.jQuery) {
// jQuery is loaded
alert("Yeah!");
} else {
location.reload();
}
}
Instead of $(document).Ready(function()
use window.onload = function()
.
Answer: You need CSS for “current” link here is tut.
Description of jQuery menu nav
Sample : One of meny solution
Its working for me
JaredPar is right in that you can't know if the process is running. You can only know if the process was running at the moment you checked. It might have died in the mean time.
You also have to be aware the PIDs can be recycled pretty quickly. So just because there's a process out there with your PID, it doesn't mean that it's your process.
Have the processes share a GUID. (Process 1 could generate the GUID and pass it to Process 2 on the command line.) Process 2 should create a named mutex with that GUID. When Process 1 wants to check, it can do a WaitForSingleObject
on the mutex with a 0 timeout. If Process 2 is gone, the return code will tell you that the mutex was abandoned, otherwise you'll get a timeout.
As I can see: http://itsolutionstuff.com/post/laravel-5-clear-cache-from-route-view-config-and-all-cache-data-from-applicationexample.html
is it possible to use the code below with the new clear cache commands:
//Clear Cache facade value:
Route::get('/clear-cache', function() {
$exitCode = Artisan::call('cache:clear');
return '<h1>Cache facade value cleared</h1>';
});
//Reoptimized class loader:
Route::get('/optimize', function() {
$exitCode = Artisan::call('optimize');
return '<h1>Reoptimized class loader</h1>';
});
//Route cache:
Route::get('/route-cache', function() {
$exitCode = Artisan::call('route:cache');
return '<h1>Routes cached</h1>';
});
//Clear Route cache:
Route::get('/route-clear', function() {
$exitCode = Artisan::call('route:clear');
return '<h1>Route cache cleared</h1>';
});
//Clear View cache:
Route::get('/view-clear', function() {
$exitCode = Artisan::call('view:clear');
return '<h1>View cache cleared</h1>';
});
//Clear Config cache:
Route::get('/config-cache', function() {
$exitCode = Artisan::call('config:cache');
return '<h1>Clear Config cleared</h1>';
});
It's not necessary to give the possibility to clear the caches to everyone, especially in a production enviroment, so I suggest to comment that routes and, when it's needed, to de-comment the code and run the routes.
I think thats impossible, sorry.
Thats why whenever running a delete or update you should always use BEGIN TRANSACTION
, then COMMIT
if successful or ROLLBACK
if not.
Try this:
window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=\''+elemA+'\'&lon=\''+elemB+'\'&setLatLon=Set";
Before you set your routes, add the code:
app.all('*', function(req, res, next) {
setTimeout(function() {
next();
}, 120000); // 120 seconds
});
A solution that is viable for both Linux and Windows is to just get used to using console ffmpeg in your code. I stack up threads, write a simple thread controller class, then you can easily make use of what ever functionality of ffmpeg you want to use.
As an example, this contains sections use ffmpeg to create a thumbnail from a time that I specify.
In the thread controller you have something like
List<ThrdFfmpeg> threads = new List<ThrdFfmpeg>();
Which is the list of threads that you are running, I make use of a timer to Pole these threads, you can also set up an event if Pole'ing is not suitable for your application. In this case thw class Thrdffmpeg contains,
public class ThrdFfmpeg
{
public FfmpegStuff ffm { get; set; }
public Thread thrd { get; set; }
}
FFmpegStuff contains the various ffmpeg functionality, thrd is obviously the thread.
A property in FfmpegStuff is the class FilesToProcess, which is used to pass information to the called process, and receive information once the thread has stopped.
public class FileToProcess
{
public int videoID { get; set; }
public string fname { get; set; }
public int durationSeconds { get; set; }
public List<string> imgFiles { get; set; }
}
VideoID (I use a database) tells the threaded process which video to use taken from the database. fname is used in other parts of my functions that use FilesToProcess, but not used here. durationSeconds - is filled in by the threads that just collect video duration. imgFiles is used to return any thumbnails that were created.
I do not want to get bogged down in my code when the purpose of this is to encourage the use of ffmpeg in easily controlled threads.
Now we have our pieces we can add to our threads list, so in our controller we do something like,
AddThread()
{
ThrdFfmpeg thrd;
FileToProcess ftp;
foreach(FileToProcess ff in `dbhelper.GetFileNames(txtCategory.Text))`
{
//make a thread for each
ftp = new FileToProcess();
ftp = ff;
ftp.imgFiles = new List<string>();
thrd = new ThrdFfmpeg();
thrd.ffm = new FfmpegStuff();
thrd.ffm.filetoprocess = ftp;
thrd.thrd = new `System.Threading.Thread(thrd.ffm.CollectVideoLength);`
threads.Add(thrd);
}
if(timerNotStarted)
StartThreadTimer();
}
Now Pole'ing our threads becomes a simple task,
private void timerThreads_Tick(object sender, EventArgs e)
{
int runningCount = 0;
int finishedThreads = 0;
foreach(ThrdFfmpeg thrd in threads)
{
switch (thrd.thrd.ThreadState)
{
case System.Threading.ThreadState.Running:
++runningCount;
//Note that you can still view data progress here,
//but remember that you must use your safety checks
//here more than anywhere else in your code, make sure the data
//is readable and of the right sort, before you read it.
break;
case System.Threading.ThreadState.StopRequested:
break;
case System.Threading.ThreadState.SuspendRequested:
break;
case System.Threading.ThreadState.Background:
break;
case System.Threading.ThreadState.Unstarted:
//Any threads that have been added but not yet started, start now
thrd.thrd.Start();
++runningCount;
break;
case System.Threading.ThreadState.Stopped:
++finishedThreads;
//You can now safely read the results, in this case the
//data contained in FilesToProcess
//Such as
ThumbnailsReadyEvent( thrd.ffm );
break;
case System.Threading.ThreadState.WaitSleepJoin:
break;
case System.Threading.ThreadState.Suspended:
break;
case System.Threading.ThreadState.AbortRequested:
break;
case System.Threading.ThreadState.Aborted:
break;
default:
break;
}
}
if(flash)
{//just a simple indicator so that I can see
//that at least one thread is still running
lbThreadStatus.BackColor = Color.White;
flash = false;
}
else
{
lbThreadStatus.BackColor = this.BackColor;
flash = true;
}
if(finishedThreads >= threads.Count())
{
StopThreadTimer();
ShowSample();
MakeJoinedThumb();
}
}
Putting your own events onto into the controller class works well, but in video work, when my own code is not actually doing any of the video file processing, poling then invoking an event in the controlling class works just as well.
Using this method I have slowly built up just about every video and stills function I think I will ever use, all contained in the one class, and that class as a text file is useable on the Lunux and Windows version, with just a small number of pre-process directives.
This is what helped me to understand the entire issue:
And in the following another example of a problematic query.
Problematic:
SELECT COUNT(*) as attempts, SUM(elapsed) as elapsedtotal, userid, timestamp, questionid, answerid, SUM(correct) as correct, elapsed, ipaddress FROM `gameplay`
WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 1 DAY)
AND cookieid = #
Solved by adding this to the end:
GROUP BY timestamp, userid, cookieid, questionid, answerid, elapsed, ipaddress
Note: See the error message in PHP, it tells you where the problem lies.
Example:
MySQL query error 1140: In aggregated query without GROUP BY, expression #4 of SELECT list contains nonaggregated column 'db.gameplay.timestamp'; this is incompatible with sql_mode=only_full_group_by - Query: SELECT COUNT(*) as attempts, SUM(elapsed) as elapsedtotal, userid, timestamp, questionid, answerid, SUM(correct) as correct, elapsed, ipaddress FROM gameplay WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 1 DAY) AND userid = 1
In this case, expression #4 was missing in the GROUP BY.
grid.newpage() ## If you're using ggplot
grid() ## If you just want to activate the device.
Solution for me was to use:
from flask_sqlalchemy import SQLAlchemy
instead of
from flask.ext.sqlalchemy import SQLAlchemy
Intent intent=new Intent(String) is defined for parameter task, whereas you are passing parameter componentname into this, use instead:
Intent i = new Intent(Settings.this, com.scytec.datamobile.vd.gui.android.AppPreferenceActivity.class);
startActivity(i);
In this statement replace ActivityName by Name of Class of Activity, this code resides in.
Solution #1
Since the original question only wants a simplified solution (and not a faster one), here is a one-line solution:
public boolean contains(int[] array, int key) {
return Arrays.toString(array).matches(".*[\\[ ]" + key + "[\\],].*");
}
Explanation: Javadoc of Arrays.toString()
states the result is enclosed in square brackets and adjacent elements are separated by the characters ", " (a comma followed by a space). So we can count on this. First we convert array
to a string, and then we check if key
is contained in this string. Of course we cannot accept "sub-numbers" (e.g. "1234" contains "23"), so we have to look for patterns where the key
is preceded with an opening bracket or a space, and followed by a closing bracket or a comma.
Note: The used regexp pattern also handles negative numbers properly (whose string representation starts with a minus sign).
Solution #2
This solution is already posted but it contains mistakes, so I post the correct solution:
public boolean contains(int[] array, int key) {
Arrays.sort(array);
return Arrays.binarySearch(array, key) >= 0;
}
Also this solution has a side effect: it modifies the array
(sorts it).
I'm new to flutter. I found that one can also achieve it this way.
tabs: [
for (var title in movieTitles) Tab(text: title)
]
Note: It requires dart sdk version to be >= 2.3.0, see here
in priciple it's the same idea as @Landeeyos. anyhow, expanding on that response: a bit late to the party but here are my two cents:
scenario:
I have a unique case of adding some (roughly 28 text files) predefined, template files with my WPF application. So, the idea is that everytime this app is to be installed, these template, text files will be readily available for usage. anyhow, what I did was that made a seperate library to hold the files by adding a resource.resx. Then I added all those files to this resource file (if you double click a .resx file, its designer gets opened in visual studio). I had set the Access Modifier to public for all. Also, each file was marked as an embedded resource via the Build Action of each text file (you can get that by looking at its properties). let's call this bibliothek1.dll i referenced this above library (bibliothek1.dll) in another library (call it bibliothek2.dll) and then consumed this second library in mf wpf app.
actual fun:
// embedded resource file name <i>with out extension</i>(this is vital!)
string fileWithoutExt = Path.GetFileNameWithoutExtension(fileName);
// is required in the next step
// without specifying the culture
string wildFile = IamAResourceFile.ResourceManager.GetString(fileWithoutExt);
Console.Write(wildFile);
// with culture
string culturedFile = IamAResourceFile.ResourceManager.GetString(fileWithoutExt, CultureInfo.InvariantCulture);
Console.Write(culturedFile);
sample: checkout 'testingresourcefilesusage' @ https://github.com/Natsikap/samples.git
I hope it helps someone, some day, somewhere!
In the XML: use literal line-breaks, nothing else needed there.
The newlines will be preserved for Javascript to read them [1]. Note that any indentation-spaces and preceding or trailing line-breaks are preserved too (the reason you weren't seeing them is that HTML/CSS collapses whitespace into single space-characters by default).
Then the easiest way is: In the HTML: do nothing, just use CSS to preserve the line-breaks
.msg_body {
white-space: pre-line;
}
But this also preserves your extra lines from the XML document, and doesn't work in IE 6 or 7 [2].
So clean up the whitespace yourself; this is one way to do it (linebreaks for clarity - Javascript is happy with or without them [3]) [4]
[get lyric...].nodeValue
.replace(/^[\r\n\t ]+|[\r\n\t ]+$/g, '')
.replace(/[ \t]+/g, ' ')
.replace(/ ?([\r\n]) ?/g, '$1')
and then preserve those line-breaks with
.msg_body {
white-space: pre; // for IE 6 and 7
white-space: pre-wrap; // or pre-line
}
or, instead of that CSS, add a .replace(/\r?\n/g, '<br />')
after the other JavaScript .replace
s.
(Side note: Using document.write() like that is also not ideal and sometimes vulnerable to cross-site scripting attacks, but that's another subject. In relation to this answer, if you wanted to use the variation that replaces with <br>
, you'd have to escape <
,&
(,>
,"
,'
) before generating the <br>
s.)
--
[1] reference: sections "Element White Space Handling" and "XML Schema White Space Control" http://www.usingxml.com/Basics/XmlSpace#ElementWhiteSpaceHandling
[2] http://www.quirksmode.org/css/whitespace.html
[3] except for a few places in Javascript's syntax where its semicolon insertion is particularly annoying.
[4] I wrote it and tested these regexps in Linux Node.js (which uses the same Javascript engine as Chrome, "V8"). There's a small risk some browser executes regexps differently. (My test string (in javascript syntax) "\n\nfoo bar baz\n\n\tmore lyrics \nare good\n\n"
)
Well actually your only need $.each to get all values, it will help you jsfiddle.net/NdQbw/5
<div class="divright">
<select id="drp_Books_Ill_Illustrations" class="leaderMultiSelctdropdown Books_Illustrations" name="drp_Books_Ill_Illustrations" multiple="">
<option value=" ">No illustrations</option>
<option value="a" selected>Illustrations</option>
<option value="b">Maps</option>
<option value="c" selected>selectedPortraits</option>
</select>
</div>
<div class="divright">
<select id="drp_Books_Ill_Illustrations1" class=" Books_Illustrations" name="drp_Books_Ill_Illustrations" multiple="">
<option value=" ">No illustrations</option>
<option value="a">Illustrations</option>
<option value="b">Maps</option>
<option value="c">selectedPortraits</option>
</select>
</div>
<button class="getValue">Get Value</button>
<button class="setValue"> Set value </button>
<div class="divright">
<select id="drp_Books_Ill_Illustrations2" class="leaderMultiSelctdropdown Books_Illustrations" name="drp_Books_Ill_Illustrations" multiple="">
<option value=" ">No illustrations</option>
<option value="a" selected>Illustrations</option>
<option value="b">Maps</option>
<option value="c" selected>selectedPortraits</option>
</select>
</div>
<div class="divright">
<select id="drp_Books_Ill_Illustrations3" class=" Books_Illustrations" name="drp_Books_Ill_Illustrations" multiple="">
<option value=" ">No illustrations</option>
<option value="a">Illustrations</option>
<option value="b">Maps</option>
<option value="c">selectedPortraits</option>
</select>
</div>
<button class="getValue1">Get Value</button>
<button class="setValue1"> Set value </button>
The script:
var selectedValues = new Array();
selectedValues[0] = "a";
selectedValues[1] = "c";
$(".getValue").click(function() {
alert($(".leaderMultiSelctdropdown").val());
});
$(".setValue").click(function() {
$(".Books_Illustrations").val(selectedValues);
});
$('#drp_Books_Ill_Illustrations2, #drp_Books_Ill_Illustrations3').select2();
$(".getValue1").click(function() {
alert($(".leaderMultiSelctdropdown").val());
});
$(".setValue1").click(function() {
//You need a id for set values
$.each($(".Books_Illustrations"), function(){
$(this).select2('val', selectedValues);
});
});
If you are concatenating the enum with a string you can override toString method to return the int:
public String toString() {
return value + "";
}
Then you could simply use:
String something = "foo" + DownloadType.AUDIO;
and the toString() method will be invoked.
Note that using toString() programmatically is generally considered poor practice - it is intended for human eyes only, however this is the only way to achieve what you're asking.
@NgModule
constructs:import { x } from 'y';
: This is standard typescript syntax (ES2015/ES6
module syntax) for importing code from other files. This is not Angular specific. Also this is technically not part of the module, it is just necessary to get the needed code within scope of this file.imports: [FormsModule]
: You import other modules in here. For example we import FormsModule
in the example below. Now we can use the functionality which the FormsModule has to offer throughout this module.declarations: [OnlineHeaderComponent, ReCaptcha2Directive]
: You put your components, directives, and pipes here. Once declared here you now can use them throughout the whole module. For example we can now use the OnlineHeaderComponent
in the AppComponent
view (html file). Angular knows where to find this OnlineHeaderComponent
because it is declared in the @NgModule
.providers: [RegisterService]
: Here our services of this specific module are defined. You can use the services in your components by injecting with dependency injection.// Angular
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
// Components
import { AppComponent } from './app.component';
import { OfflineHeaderComponent } from './offline/offline-header/offline-header.component';
import { OnlineHeaderComponent } from './online/online-header/online-header.component';
// Services
import { RegisterService } from './services/register.service';
// Directives
import { ReCaptcha2Directive } from './directives/re-captcha2.directive';
@NgModule({
declarations: [
OfflineHeaderComponent,,
OnlineHeaderComponent,
ReCaptcha2Directive,
AppComponent
],
imports: [
BrowserModule,
FormsModule,
],
providers: [
RegisterService,
],
entryComponents: [
ChangePasswordComponent,
TestamentComponent,
FriendsListComponent,
TravelConfirmComponent
],
bootstrap: [AppComponent]
})
export class AppModule { }
it looks like you need a rule very similar to your checked rule
#ck-button input:hover + span {
background-color:#191;
color:#fff;
}
and for hover and clicked state:
#ck-button input:checked:hover + span {
background-color:#c11;
color:#fff;
}
the order is important though.
Suppose you are running a test python file named request.py
In request.py, you write
import request
so this also most likely a circular import.
Solution:
Just change your test file to another name such as aaa.py
, other than request.py
.
Do not use names that are already used by other libs.
Since tuples are immutable, this will result in a new tuple. Just place it back where you got the old one.
sometuple + (someitem,)
I'd like to offer this suggestion as a side note.
If you're looking to fix all the 'trailing whitespaces' warnings your linter
throws at you.
You can have VSCode automatically trim whitespaces from an entire file using
the keyboard chord.
CTRL+K / X (by default)
I was looking into showing whitespaces because my linter kept bugging me with whitespace warnings. So that's why I'm here.
You should use the Chartjs API function toBase64Image()
instead and call it after the animation is complete. Therefore:
var pieChart, URI;
var options = {
animation : {
onComplete : function(){
URI = pieChart.toBase64Image();
}
}
};
var content = {
type: 'pie', //whatever, not relevant for this example
data: {
datasets: dataset //whatever, not relevant for this example
},
options: options
};
pieChart = new Chart(pieChart, content);
You can check this example and run it
var chart = new Chart(ctx, {_x000D_
type: 'bar',_x000D_
data: {_x000D_
labels: ['Standing costs', 'Running costs'], // responsible for how many bars are gonna show on the chart_x000D_
// create 12 datasets, since we have 12 items_x000D_
// data[0] = labels[0] (data for first bar - 'Standing costs') | data[1] = labels[1] (data for second bar - 'Running costs')_x000D_
// put 0, if there is no data for the particular bar_x000D_
datasets: [{_x000D_
label: 'Washing and cleaning',_x000D_
data: [0, 8],_x000D_
backgroundColor: '#22aa99'_x000D_
}, {_x000D_
label: 'Traffic tickets',_x000D_
data: [0, 2],_x000D_
backgroundColor: '#994499'_x000D_
}, {_x000D_
label: 'Tolls',_x000D_
data: [0, 1],_x000D_
backgroundColor: '#316395'_x000D_
}, {_x000D_
label: 'Parking',_x000D_
data: [5, 2],_x000D_
backgroundColor: '#b82e2e'_x000D_
}, {_x000D_
label: 'Car tax',_x000D_
data: [0, 1],_x000D_
backgroundColor: '#66aa00'_x000D_
}, {_x000D_
label: 'Repairs and improvements',_x000D_
data: [0, 2],_x000D_
backgroundColor: '#dd4477'_x000D_
}, {_x000D_
label: 'Maintenance',_x000D_
data: [6, 1],_x000D_
backgroundColor: '#0099c6'_x000D_
}, {_x000D_
label: 'Inspection',_x000D_
data: [0, 2],_x000D_
backgroundColor: '#990099'_x000D_
}, {_x000D_
label: 'Loan interest',_x000D_
data: [0, 3],_x000D_
backgroundColor: '#109618'_x000D_
}, {_x000D_
label: 'Depreciation of the vehicle',_x000D_
data: [0, 2],_x000D_
backgroundColor: '#109618'_x000D_
}, {_x000D_
label: 'Fuel',_x000D_
data: [0, 1],_x000D_
backgroundColor: '#dc3912'_x000D_
}, {_x000D_
label: 'Insurance and Breakdown cover',_x000D_
data: [4, 0],_x000D_
backgroundColor: '#3366cc'_x000D_
}]_x000D_
},_x000D_
options: {_x000D_
responsive: false,_x000D_
legend: {_x000D_
position: 'right' // place legend on the right side of chart_x000D_
},_x000D_
scales: {_x000D_
xAxes: [{_x000D_
stacked: true // this should be set to make the bars stacked_x000D_
}],_x000D_
yAxes: [{_x000D_
stacked: true // this also.._x000D_
}]_x000D_
},_x000D_
animation : {_x000D_
onComplete : done_x000D_
} _x000D_
}_x000D_
});_x000D_
_x000D_
function done(){_x000D_
alert(chart.toBase64Image());_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>_x000D_
<canvas id="ctx" width="700"></canvas>
_x000D_
curl
doesn't have an option to that (without also specifying the filename), but wget
does. The directory can be relative or absolute. Also, the directory will automatically be created if it doesn't exist.
wget -P relative/dir "$url"
wget -P /absolute/dir "$url"
The simplest way to accomplish this is to use two commands.
First, get the local directory into the state that you want. Then,
$ git push origin +HEAD^:someBranch
removes the last commit from someBranch
in the remote only, not local. You can do this a few times in a row, or change +HEAD^
to reflect the number of commits that you want to batch remove from remote. Now you're back on your feet, and use
$ git push origin someBranch
as normal to update the remote.
Try this:
body
{
font-family:your font;
font-size:your value;
font-weight:your value;
}
Checkboxes (radio buttons and <select>
) are OS-level components, not browser-level. You cannot reliably style them in a manner that will be consistent across browsers and operating systems.
Your best bet it to put an overlay on top and style that instead.
Assuming you're currently on the branch you want to rename:
git branch -m newname
This is documented in the manual for git-branch
, which you can view using
man git-branch
or
git help branch
Specifically, the command is
git branch (-m | -M) [<oldbranch>] <newbranch>
where the parameters are:
<oldbranch>
The name of an existing branch to rename.
<newbranch>
The new name for an existing branch. The same restrictions as for <branchname> apply.
<oldbranch>
is optional, if you want to rename the current branch.
I guess you probably are running the preview of VS2013 Ultimate, because it is not present in my professional preview. But looking online I found that the feature is called Code Information Indicators
or CodeLens
, and can be located under
Tools ? Options ? Text Editor ? All Languages ? CodeLens
(for RC/final version)
or
Tools ? Options ? Text Editor ? All Languages ? Code Information Indicators
(for preview version)
That was according to this link. It seems to be pretty well hidden.
In Visual Studio 2013 RTM, you can also get to the CodeLens options by right clicking the indicators themselves in the editor:
documented in the Q&A section of the msdn CodeLens documentation
You are printing the enum object. Use the .value
attribute if you wanted just to print that:
print(D.x.value)
See the Programmatic access to enumeration members and their attributes section:
If you have an enum member and need its name or value:
>>> >>> member = Color.red >>> member.name 'red' >>> member.value 1
You could add a __str__
method to your enum, if all you wanted was to provide a custom string representation:
class D(Enum):
def __str__(self):
return str(self.value)
x = 1
y = 2
Demo:
>>> from enum import Enum
>>> class D(Enum):
... def __str__(self):
... return str(self.value)
... x = 1
... y = 2
...
>>> D.x
<D.x: 1>
>>> print(D.x)
1
You can view the java doc examples or the example of usage of Predicate here
Basically it is used to filter rows in the resultset based on any specific criteria that you may have and return true for those rows that are meeting your criteria:
// the age column to be between 7 and 10
AgeFilter filter = new AgeFilter(7, 10, 3);
// set the filter.
resultset.beforeFirst();
resultset.setFilter(filter);
Deleting the .git
folder may cause problems in your git repository. If you want to delete all your commit history but keep the code in its current state, it is very safe to do it as in the following:
Checkout
git checkout --orphan latest_branch
Add all the files
git add -A
Commit the changes
git commit -am "commit message"
Delete the branch
git branch -D main
Rename the current branch to main
git branch -m main
Finally, force update your repository
git push -f origin main
PS: this will not keep your old commit history around
$("#myselect option:contains('YourTextHere')").val();
will return the value of the first option containing your text description. Tested this and works.
Just call setTitle(null);
in onCreate()
Add:
for i, v in enumerate(y):
ax.text(v + 3, i + .25, str(v), color='blue', fontweight='bold')
result:
The y-values v
are both the x-location and the string values for ax.text
, and conveniently the barplot has a metric of 1 for each bar, so the enumeration i
is the y-location.
Run:
go mod init yellow
Then create a file yellow.go
:
package yellow
func Mix(s string) string {
return s + "Yellow"
}
Then create a file orange/orange.go
:
package main
import "yellow"
func main() {
s := yellow.Mix("Red")
println(s)
}
Then build:
go build
The csv.writer
writerow
method takes an iterable as an argument. Your result set has to be a list (rows) of lists (columns).
csvwriter.writerow(row)
Write the row parameter to the writer’s file object, formatted according to the current dialect.
Do either:
import csv
RESULTS = [
['apple','cherry','orange','pineapple','strawberry']
]
with open('output.csv','wb') as result_file:
wr = csv.writer(result_file, dialect='excel')
wr.writerows(RESULTS)
or:
import csv
RESULT = ['apple','cherry','orange','pineapple','strawberry']
with open('output.csv','wb') as result_file:
wr = csv.writer(result_file, dialect='excel')
wr.writerow(RESULT)
I have faced the same issue. The following steps in VS 2013 solved the problem for me:
I recommend you to use an unordered list for your image gallery.
You should use my code unless you want the image to gain instantly 50% opacity after you hover out. You will have a smoother transition.
#photos li {
opacity: .5;
transition: opacity .5s ease-out;
-moz-transition: opacity .5s ease-out;
-webkit-transition: opacity .5s ease-out;
-o-transition: opacity .5s ease-out;
}
#photos li:hover {
opacity: 1;
}
You need to use a group by clause.
SELECT site_id, MAX(ts) as TIME, count(*) group by site_id
In case you don't want/need to post:
@Html.ActionLink("link caption", "actionName", new { Model.Page }) // view's controller
@Html.ActionLink("link caption", "actionName", "controllerName", new { reportID = 1 }, null);
[HttpGet]
public ActionResult actionName(int reportID)
{
Note that the reportID in the new {} part matches reportID in the action parameters, you can add any number of parameters this way, but any more than 2 or 3 (some will argue always) you should be passing a model via a POST (as per other answer)
Edit: Added null for correct overload as pointed out in comments. There's a number of overloads and if you specify both action+controller, then you need both routeValues and htmlAttributes. Without the controller (just caption+action), only routeValues are needed but may be best practice to always specify both.
One thing that could have happened:
Hence, at compile time for the version X, the JVM will generate a first Serial ID (for version X) and it will do the same with the other version Y (another Serial ID).
When your program tries to de-serialize the data, it can't because the two classes do not have the same Serial ID and your program have no guarantee that the two Serialized objects correspond to the same class format.
Assuming you changed your constructor in the mean time and this should make sense to you.
I've tried the following:
codeEditText.setInputType(InputType.TYPE_NULL);
this.codeEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
pickCode();
}
}
});
this.codeEditText.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
pickCode();
}
});
but the problem was that if the edit text is the first in the form then it gets the focus and the pickCode() code which launches a new activity is called straight away. So I modified the code as follows and it seems to work quite well (except I cannot set the focus on the text edit but I don't need to):
itemCodeEditText.setFocusable(false);
this.itemCodeEditText.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
pickItem();
}
});
Best Regards,
Comments welcome,
John Goche
install the dependencies:
npm install jquery --save
npm install tether --save
npm install bootstrap@version --save;
next, add scripts in your angular-cli.json
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/tether/dist/js/tether.js",
"../node_modules/bootstrap/dist/js/bootstrap.min.js",
"script.js"
]
then, create a script.js
$("[data-toggle=tooltip]").tooltip();
now restart your server.
Posting your HTML might help a bit. Instead, you can get the element first and then check if it is null or not and then ask for its value rather than just asking for the value directly without knowing if the element is visible on the HTML or not.
element1 = document.getElementById(id);
if(element1 != null)
{
//code to set the value variable.
}
In your build.gradle
repositories {
jcenter()
}
implementation 'com.quickbirdstudios:opencv:4.1.0'
You could use id in span directly in your html.
<span id="span_id">Client</span>
Then your jQuery code would be
$("#span_id").text();
Some one helped me to check errors and found that he used val() instead of text(), it is not possible to use val() function in span. So
$("#span_id").val();
will return null.
I stole the logging code from virtualenv for a project of mine. Look in main()
of virtualenv.py
to see how it's initialized. The code is sprinkled with logger.notify()
, logger.info()
, logger.warn()
, and the like. Which methods actually emit output is determined by whether virtualenv was invoked with -v
, -vv
, -vvv
, or -q
.
Simply compare using .toDateString like below:
new Date().toDateString();
This will return you date part only and not time or timezone, like this:
"Fri Feb 03 2017"
Hence both date can be compared in this format likewise without time part of it.
The method len() returns the number of elements in the list.
Syntax:
len(myArray)
Eg:
myArray = [1, 2, 3]
len(myArray)
Output:
3
Go to the tsconfig.json file. write this code under angularCompilerOption:
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"strictInjectionParameters": true,
**"enableIvy": false**
}
You can use a single config file, and include the UglifyJS plugin conditionally using an environment variable:
const webpack = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');
const PROD = JSON.parse(process.env.PROD_ENV || '0');
module.exports = {
entry: './entry.js',
devtool: 'source-map',
output: {
path: './dist',
filename: PROD ? 'bundle.min.js' : 'bundle.js'
},
optimization: {
minimize: PROD,
minimizer: [
new TerserPlugin({ parallel: true })
]
};
and then just set this variable when you want to minify it:
$ PROD_ENV=1 webpack
Edit:
As mentioned in the comments, NODE_ENV
is generally used (by convention) to state whether a particular environment is a production or a development environment. To check it, you can also set const PROD = (process.env.NODE_ENV === 'production')
, and continue normally.
This is a select statement, so each branch of the case must return something. If you want to perform actions, just use an if.
This is in the feature backlog for Compose but it doesn't look like work has been started yet. Github issue.
Well, your syntax isn't really Python to begin with.
Iterations in Python are over he contents of containers (well, technically it's over iterators), with a syntax for item in container
. In this case, the container is the cars
list, but you want to skip the first and last elements, so that means cars[1:-1]
(python lists are zero-based, negative numbers count from the end, and :
is slicing syntax.
So you want
for c in cars[1:-1]:
do something with c
Robomongo's shell functionality will solve the problem. In my case I needed couple of columns as CSV format.
var cursor = db.getCollection('Member_details').find({Category: 'CUST'},{CustomerId :1,Name :1,_id:0})
while (cursor.hasNext()) {
var record = cursor.next();
print(record.CustomerID + "," + record.Name)
}
Output : -------
334, Harison
433, Rechard
453, Michel
533, Pal
A decimal will always have some default value. If you need to have a nullable type decimal, you can use decimal?
. Then you can do myDecimal.HasValue
No expensive forks, no pipes, no bashisms:
$ set -- $STRING
$ eval echo \${$N}
three
But beware of globbing.
To store the third line into a variable, use below syntax:
variable=`echo "$1" | sed '3q;d' urfile`
To store the changed line into a variable, use below syntax:
variable=echo 'overflow' | sed -e "s/over/"OVER"/g"
output:OVERflow
Well, you can use a regular expression to find the cases where "Milan" isn't followed by "Vasic":
Milan(?! Vasic)
and replace that by the full name:
String.replaceAll("Milan(?! Vasic)", "Milan Vasic")
The (?!...)
part is a negative lookahead which ensures that whatever matches isn't followed by the part in parentheses. It doesn't consume any characters in the match itself.
Alternatively, you can simply insert (well, technically replacing a zero-width match) the last name after the first name, unless it's followed by the last name already. This looks similar, but uses a positive lookbehind as well:
(?<=Milan)(?! Vasic)
You can replace this by just " Vasic"
(note the space at the start of the string):
String.replaceAll("(?<=Milan)(?! Vasic)", " Vasic")
You can try those things out here for example.
You can use the LocalCommand
command-line option if the PermitLocalCommand
option is enabled:
ssh username@hostname -o LocalCommand="tmux list-sessions"
For more details about the available options, see the ssh_config
man page.
As of this writing, in OS X, it will usually look like this
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --allow-file-access-from-files
If you are a freak like me, and put your apps in ~/Applications
, then it will be
"/Users/yougohere/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --allow-file-access-from-files
If neither of those are working, then type chrome://version
in your Chrome address bar, and it will tell you what "command line" invocation you should be using. Just add --allow-file-access-from-files
to that.
this issue can be resolved using 2 ways:
netstat -ao | find "8080" Taskkill /PID 1342 /F
server.port=8081
You need to use get_serving_url
from the Images API. As that page explains, you need to call create_gs_key()
first to get the key to pass to the Images API.
You might also want to check out the PyPy project - they have a Python to (anything) compiler, including Python to Javascript, C, and llvm. This allows you to write your code in Python and then compile it into Javascript as you desire.
Also, check out the informative blog:
Unfortunately though, you can't convert Javascript to Python this way. It seems to work really well overall, they used to have a Javascript (made from compiled Python) version of the Bub'n'Bros game online (though the server has been down for a while).
i got same error but actually due to this link(WSDL URL) not accessible from Machine. so please check first on browser(client) response after hitting URL ie if giving response as wsdl file or not then check it SOAP UI.
For eg: url?wsdl
Here's a cursor based solution. Kinda lengthy but works as a single SQL batch:
DROP PROCEDURE IF EXISTS `drop_all_tables`;
DELIMITER $$
CREATE PROCEDURE `drop_all_tables`()
BEGIN
DECLARE _done INT DEFAULT FALSE;
DECLARE _tableName VARCHAR(255);
DECLARE _cursor CURSOR FOR
SELECT table_name
FROM information_schema.TABLES
WHERE table_schema = SCHEMA();
DECLARE CONTINUE HANDLER FOR NOT FOUND SET _done = TRUE;
OPEN _cursor;
REPEAT FETCH _cursor INTO _tableName;
IF NOT _done THEN
SET @stmt_sql = CONCAT('DROP TABLE ', _tableName);
PREPARE stmt1 FROM @stmt_sql;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
END IF;
UNTIL _done END REPEAT;
CLOSE _cursor;
END$$
DELIMITER ;
call drop_all_tables();
DROP PROCEDURE IF EXISTS `drop_all_tables`;
SELECT *
INTO target
FROM source
WHERE 1 = 2
i have same problem and i think just set width and height programmatically :
set width of button's with metrics.widthPixels / 2 metrics is object of DisplayMetrics.
GridLayout gridLayout=findViewById(R.id.grid);
for (int i = 0; i <gridLayout.getChildCount() ; i++) {
View view= gridLayout.getChildAt(i);
if(view instanceof Button){
Button btn = (Button) view;
btn.setWidth(200);//metrics.widthPixels / 2
btn.setHeight(200);//metrics.heightPixels / 7
}
}
var jsonData = [{"person":"me","age":"30"},{"person":"you","age":"25"}];
for(var i in jsonData){
var key = i;
var val = jsonData[i];
for(var j in val){
var sub_key = j;
var sub_val = val[j];
console.log(sub_key);
}
}
EDIT
var jsonObj = {"person":"me","age":"30"};
Object.keys(jsonObj); // returns ["person", "age"]
Object
has a property
keys
, returns an Array
of keys from that Object
Chrome, FF & Safari supports Object.keys
Here's a really simple way in python 3+:
f = open('filename.txt', 'w')
print('something', file = f)
^ found that from this answer: https://stackoverflow.com/a/4110906/6794367
Use some javascript!
xmlhttp=new XMLHttpRequest(); xmlhttp.open('PUT',http://www.mydomain.org/documents/standards/browsers/supportlist) xmlhttp.send("page content goes here");
This happened to me yesterday and in my case was because I was following a PDF manual to develop some module to communicate with an API and while copying the link directly from the manual, for some odd reason, the hyphen
from the copied link was in a different encoding and hence the curl_exec()
was always returning false
because it was unable to communicate with the server.
It took me a couple hours to finally understand the diference in the characters bellow:
https://www.e-example.com/api
https://www.e-example.com/api
Every time I tried to access the link directly from a browser it converted to something likehttps://www.xn--eexample-0m3d.com/api
.
It may seem to you that they are equal but if you check the encoding of the hyphens
here you'll see that the first hyphen
is a unicode characters U+2010 and the other is a U+002D.
Hope this helps someone.
you can simply send the data using window.location.href
first store the value to send from testing.html
in the script tag, variable say
<script>
var data = value_to_send
window.loaction.href="next.htm?data="+data
</script>
this is sending through a get request
if you want to run spring boot without a servlet container, but with one on the classpath (e.g. for tests), use the following, as described in the spring boot documentation:
@Configuration
@EnableAutoConfiguration
public class MyClass{
public static void main(String[] args) throws JAXBException {
SpringApplication app = new SpringApplication(MyClass.class);
app.setWebEnvironment(false); //<<<<<<<<<
ConfigurableApplicationContext ctx = app.run(args);
}
}
also, I just stumbled across this property:
spring.main.web-environment=false
One way would be to convert both strings to upper or lower:
test $(echo "string" | /bin/tr '[:upper:]' '[:lower:]') = $(echo "String" | /bin/tr '[:upper:]' '[:lower:]') && echo same || echo different
Another way would be to use grep:
echo "string" | grep -qi '^String$' && echo same || echo different
Java programming language enums
are far more powerful than their counterparts in other languages, which are little more than glorified integers. The new enum declaration defines a full-fledged class (dubbed an enum type). In addition to solving all the problems(Not typesafe, No namespace, Brittleness and Printed values are uninformative
) that exists with following int Enum pattern which was used prior to java 5.0 :
public static final int SEASON_WINTER = 0;
it also allows you to add arbitrary methods and fields to an enum type, to implement arbitrary interfaces, and more. Enum types provide high-quality implementations of all the Object methods. They are Comparable
and Serializable
, and the serial form is designed to withstand arbitrary changes in the enum type. You can also use Enum in switch
case.
Read the full article on Java Enums http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html for more details.
%PROGRAMFILES%\Git\etc
profile
HOME="c:\location_were_you_want_gitconfig"
Note: The file permissions are usually restricted, so change them accordingly or you won't be able to save your changes.
The EOF flag is only set after a read operation attempts to read past the end of the file. get()
is returning the symbolic constant traits::eof()
(which just happens to equal -1) because it reached the end of the file and could not read any more data, and only at that point will eof()
be true. If you want to check for this condition, you can do something like the following:
int ch;
while ((ch = inf.get()) != EOF) {
std::cout << static_cast<char>(ch) << "\n";
}
In order to resolve this issue make all your data flow tasks in one sequence. It means it should not execute parallel. One data flow task sequence should contain only one data flow task and for this another data flow task as sequence.
Ex:-
You might be interested in this query. It tells you how much space is allocated for each table taking into account the indexes and any LOBs on the table. Often you are interested to know "How much spaces the the Purchase Order table take, including any indexes" rather than just the table itself. You can always delve into the details. Note that this requires access to the DBA_* views.
COLUMN TABLE_NAME FORMAT A32
COLUMN OBJECT_NAME FORMAT A32
COLUMN OWNER FORMAT A10
SELECT
owner,
table_name,
TRUNC(sum(bytes)/1024/1024) Meg,
ROUND( ratio_to_report( sum(bytes) ) over () * 100) Percent
FROM
(SELECT segment_name table_name, owner, bytes
FROM dba_segments
WHERE segment_type IN ('TABLE', 'TABLE PARTITION', 'TABLE SUBPARTITION')
UNION ALL
SELECT i.table_name, i.owner, s.bytes
FROM dba_indexes i, dba_segments s
WHERE s.segment_name = i.index_name
AND s.owner = i.owner
AND s.segment_type IN ('INDEX', 'INDEX PARTITION', 'INDEX SUBPARTITION')
UNION ALL
SELECT l.table_name, l.owner, s.bytes
FROM dba_lobs l, dba_segments s
WHERE s.segment_name = l.segment_name
AND s.owner = l.owner
AND s.segment_type IN ('LOBSEGMENT', 'LOB PARTITION')
UNION ALL
SELECT l.table_name, l.owner, s.bytes
FROM dba_lobs l, dba_segments s
WHERE s.segment_name = l.index_name
AND s.owner = l.owner
AND s.segment_type = 'LOBINDEX')
WHERE owner in UPPER('&owner')
GROUP BY table_name, owner
HAVING SUM(bytes)/1024/1024 > 10 /* Ignore really small tables */
ORDER BY SUM(bytes) desc
;
I fixed the error with virtualenv by doing this:
Copied pkg_resources.py from
/Library/Python/2.7/site-packages/setuptools
to
/Library/Python/2.7/site-packages/
This may be a cheap workaround, but it worked for me.
.
If setup tools doesn't exist, you can try installing system-site-packages by typing virtualenv --system-site-packages /DESTINATION DIRECTORY
, changing the last part to be the directory you want to install to. pkg_rousources.py
will be under that directory in lib/python2.7/site-packages
You need to do two things:
The code:
dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))
library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha = 0.35, linetype=0)+
geom_line(aes(linetype=model), size = 1) +
geom_point(aes(shape=model), size=4) +
theme(legend.position=c(.6,0.8)) +
theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
scale_linetype_discrete("Model 1") +
scale_shape_discrete("Model 1") +
scale_colour_discrete("Model 1")
However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha=0.2, colour=NA)+
geom_line() +
geom_point() +
facet_wrap(~model)
A related question you should be considering is how cohesive the routine is. A large number of parameters may be a smell that's telling you that the routine itself is trying to do too much and hence it's cohesion is suspect. I agree that a hard and fast number of parameters is probably impossible but I would guess that a high cohesion routine would imply a low number of parameters.
Give the command SHOW CREATE TABLE whatever
Then look at the table definition.
It probably has a line like this
logtime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
in it. DEFAULT CURRENT_TIMESTAMP
means that any INSERT
without an explicit time stamp setting uses the current time. Likewise, ON UPDATE CURRENT_TIMESTAMP
means that any update without an explicit timestamp results in an update to the current timestamp value.
You can control this default behavior when creating your table.
Or, if the timestamp column wasn't created correctly in the first place, you can change it.
ALTER TABLE whatevertable
CHANGE whatevercolumn
whatevercolumn TIMESTAMP NOT NULL
DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP;
This will cause both INSERT and UPDATE operations on the table automatically to update your timestamp column. If you want to update whatevertable
without changing the timestamp, that is,
To prevent the column from updating when other columns change
then you need to issue this kind of update.
UPDATE whatevertable
SET something = 'newvalue',
whatevercolumn = whatevercolumn
WHERE someindex = 'indexvalue'
This works with TIMESTAMP
and DATETIME
columns. (Prior to MySQL version 5.6.5 it only worked with TIMESTAMP
s) When you use TIMESTAMP
s, time zones are accounted for: on a correctly configured server machine, those values are always stored in UTC and translated to local time upon retrieval.
The simplest is to do a PivotChart. Select your array of dates (with a header) and create a new Pivot Chart (Insert / PivotChart / Ok) Then on the field list window, drag and drop the date column in the Axis list first and then in the value list first.
Step 1:
Step 2:
Your question title mentions Blocking Queues. However, ConcurrentLinkedQueue
is not a blocking queue.
The BlockingQueue
s are ArrayBlockingQueue
, DelayQueue
, LinkedBlockingDeque
, LinkedBlockingQueue
, PriorityBlockingQueue
, and SynchronousQueue
.
Some of these are clearly not fit for your purpose (DelayQueue
, PriorityBlockingQueue
, and SynchronousQueue
). LinkedBlockingQueue
and LinkedBlockingDeque
are identical, except that the latter is a double-ended Queue (it implements the Deque interface).
Since ArrayBlockingQueue
is only useful if you want to limit the number of elements, I'd stick to LinkedBlockingQueue
.
A different approach.
On the figure()
call specify properties or modify the figure handle properties after h = figure()
.
This creates a full screen figure based on normalized units.
figure('units','normalized','outerposition',[0 0 1 1])
The units
property can be adjusted to inches, centimeters, pixels, etc.
See figure
documentation.
Most preferably you might want to use AVFoundation. It provides all the essentials for working with audiovisual media.
Update: Compatible with Swift 2, Swift 3 and Swift 4 as suggested by some of you in the comments.
import AVFoundation
var player: AVAudioPlayer?
func playSound() {
let url = NSBundle.mainBundle().URLForResource("soundName", withExtension: "mp3")!
do {
player = try AVAudioPlayer(contentsOfURL: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error as NSError {
print(error.description)
}
}
import AVFoundation
var player: AVAudioPlayer?
func playSound() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
let player = try AVAudioPlayer(contentsOf: url)
player.play()
} catch let error {
print(error.localizedDescription)
}
}
import AVFoundation
var player: AVAudioPlayer?
func playSound() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
/* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
Make sure to change the name of your tune as well as the extension. The file needs to be properly imported (
Project Build Phases
>Copy Bundle Resources
). You might want to place it inassets.xcassets
for greater convenience.
For short sound files you might want to go for non-compressed audio formats such as .wav
since they have the best quality and a low cpu impact. The higher disk-space consumption should not be a big deal for short sound files. The longer the files are, you might want to go for a compressed format such as .mp3
etc. pp. Check the compatible audio formats of CoreAudio
.
Fun-fact: There are neat little libraries which make playing sounds even easier. :)
For example: SwiftySound
If order does matter, how about:
>>> foo = 'mppmt'
>>> ''.join(sorted(set(foo), key=foo.index))
'mpt'
You can change it in new Android studio version(0.8.X)
FIle-> Other Settings -> Default Settings -> Compiler (Expand it by clicking left arrow) -> Java Compiler -> You can change the Project bytecode version here
Ok I found out the answer myself. Much like npm cache clean
, Yarn also has its own
yarn cache clean
I think most people want their placeholder text to be in grey and appear only once, so this is what I did:
Set your color in viewDidLoad()
(not in IB)
commentsTextView.textColor = UIColor.darkGray
Implement UITextViewDelegate
to your controller
add function to your controller
func textViewDidBeginEditing(_ textView: UITextView) {
if (commentsTextView.textColor == UIColor.darkGray) {
commentsTextView.text = ""
commentsTextView.textColor = UIColor.black
}
}
This solution is simple.
As long as your vector remains in global scope you can return:
&(*iterator)
I'll caution you that this is pretty dangerous in general. If your vector is ever moved out of global scope and is destructed, any pointers to myObject become invalid. If you're writing these functions as part of a larger project, returning a non-const pointer could lead someone to delete the return value. This will have undefined, and catastrophic, effects on the application.
I'd rewrite this as:
myObject myFunction(const vector<myObject>& objects)
{
// find the object in question and return a copy
return *iterator;
}
If you need to modify the returned myObject, store your values as pointers and allocate them on the heap:
myObject* myFunction(const vector<myObject*>& objects)
{
return *iterator;
}
That way you have control over when they're destructed.
Something like this will break your app:
g_vector<tmpClass> myVector;
tmpClass t;
t.i = 30;
myVector.push_back(t);
// my function returns a pointer to a value in myVector
std::auto_ptr<tmpClass> t2(myFunction());
If you use EclipseLink instead of Hibernate you can optimize your queries by "query hints". See this article from the Eclipse Wiki: EclipseLink/Examples/JPA/QueryOptimization.
There is a chapter about "Joined Reading".
An alternative on Linux to using either /proc/self/exe
or argv[0]
is using the information passed by the ELF interpreter, made available by glibc as such:
#include <stdio.h>
#include <sys/auxv.h>
int main(int argc, char **argv)
{
printf("%s\n", (char *)getauxval(AT_EXECFN));
return(0);
}
Note that getauxval
is a glibc extension, and to be robust you should check so that it doesn't return NULL
(indicating that the ELF interpreter hasn't provided the AT_EXECFN
parameter), but I don't think this is ever actually a problem on Linux.
clear site data in your browser. and it will be fixed. sometimes when you run proxies, vpns or some other programs this error happens.
You don't need any calls to pthread_exit(3)
in your particular code.
In general, the main
thread should not call pthread_exit
, but should often call pthread_join(3)
to wait for some other thread to finish.
In your PrintHello
function, you don't need to call pthread_exit
because it is implicit after returning from it.
So your code should rather be:
void *PrintHello(void *threadid) {
long tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
return threadid;
}
int main (int argc, char *argv[]) {
pthread_t threads[NUM_THREADS];
int rc;
intptr_t t;
// create all the threads
for(t=0; t<NUM_THREADS; t++){
printf("In main: creating thread %ld\n", (long) t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc) { fprintf(stderr, "failed to create thread #%ld - %s\n",
(long)t, strerror(rc));
exit(EXIT_FAILURE);
};
}
pthread_yield(); // useful to give other threads more chance to run
// join all the threads
for(t=0; t<NUM_THREADS; t++){
printf("In main: joining thread #%ld\n", (long) t);
rc = pthread_join(&threads[t], NULL);
if (rc) { fprintf(stderr, "failed to join thread #%ld - %s\n",
(long)t, strerror(rc));
exit(EXIT_FAILURE);
}
}
}
If you want to remove all instances of 4 without needing to know the index:
LINQ: (.NET Framework 3.5)
int[] numbers = { 1, 3, 4, 9, 2 };
int numToRemove = 4;
numbers = numbers.Where(val => val != numToRemove).ToArray();
Non-LINQ: (.NET Framework 2.0)
static bool isNotFour(int n)
{
return n != 4;
}
int[] numbers = { 1, 3, 4, 9, 2 };
numbers = Array.FindAll(numbers, isNotFour).ToArray();
If you want to remove just the first instance:
LINQ: (.NET Framework 3.5)
int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int numIndex = Array.IndexOf(numbers, numToRemove);
numbers = numbers.Where((val, idx) => idx != numIndex).ToArray();
Non-LINQ: (.NET Framework 2.0)
int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int numIdx = Array.IndexOf(numbers, numToRemove);
List<int> tmp = new List<int>(numbers);
tmp.RemoveAt(numIdx);
numbers = tmp.ToArray();
Edit: Just in case you hadn't already figured it out, as Malfist pointed out, you need to be targetting the .NET Framework 3.5 in order for the LINQ code examples to work. If you're targetting 2.0 you need to reference the Non-LINQ examples.
OpenJDK is a reference model and open source, while Oracle JDK is an implementation of the OpenJDK and is not open source. Oracle JDK is more stable than OpenJDK.
OpenJDK is released under GPL v2 license whereas Oracle JDK is licensed under Oracle Binary Code License Agreement.
OpenJDK and Oracle JDK have almost the same code, but Oracle JDK has more classes and some bugs fixed.
So if you want to develop enterprise/commercial software I would suggest to go for Oracle JDK, as it is thoroughly tested and stable.
I have faced lot of problems with application crashes using OpenJDK, which are fixed just by switching to Oracle JDK
There are two ways to look at it:
Inline functions are defined in the header because, in order to inline a function call, the compiler must be able to see the function body. For a naive compiler to do that, the function body must be in the same translation unit as the call. (A modern compiler can optimize across translation units, and so a function call may be inlined even though the function definition is in a separate translation unit, but these optimizations are expensive, aren't always enabled, and weren't always supported by the compiler)
functions defined in the header must be marked inline
because otherwise, every translation unit which includes the header will contain a definition of the function, and the linker will complain about multiple definitions (a violation of the One Definition Rule). The inline
keyword suppresses this, allowing multiple translation units to contain (identical) definitions.
The two explanations really boil down to the fact that the inline
keyword doesn't exactly do what you'd expect.
A C++ compiler is free to apply the inlining optimization (replace a function call with the body of the called function, saving the call overhead) any time it likes, as long as it doesn't alter the observable behavior of the program.
The inline
keyword makes it easier for the compiler to apply this optimization, by allowing the function definition to be visible in multiple translation units, but using the keyword doesn't mean the compiler has to inline the function, and not using the keyword doesn't forbid the compiler from inlining the function.
request.data
This is great to use but remember that it comes in as a string and will need iterated through.
Yes, each package must be defined in its own directory.
The source structure is defined in How to Write Go Code.
A package is a component that you can use in more than one program, that you can publish, import, get from an URL, etc. So it makes sense for it to have its own directory as much as a program can have a directory.
If you want to have a dynamic function like the __call
function in PHP, you could use Proxies.
const target = {};
const handler = {
get: function (target, name) {
return (myArg) => {
return new Promise(resolve => setTimeout(() => resolve('some' + myArg), 600))
}
}
};
const proxy = new Proxy(target, handler);
(async function() {
const result = await proxy.foo('string')
console.log('result', result) // 'result somestring' after 600 ms
})()
Yet, it is possible to fake it using a dedicated table, named for your fake-sp, with an AFTER INSERT trigger. The dedicated table rows contain the parameters for your fake sp, and if it needs to return results you can have a second (poss. temp) table (with name related to the fake-sp) to contain those results. It would require two queries: first to INSERT data into the fake-sp-trigger-table, and the second to SELECT from the fake-sp-results-table, which could be empty, or have a message-field if something went wrong.
this is a example for Horizontal and Vertical alignment simultaneously
<View style={{width: 200, flexDirection: 'row',alignItems: 'center'}}>
<Text style={{width: '100%',textAlign: 'center'}} />
</View>
You must take the whole directory where java is installed, in my case:
export JAVA_HOME=/usr/java/jdk1.8.0_31
Edit 2: See @flodel's answer. Much better.
Try:
# assuming SFI is your data.frame
as.matrix(sapply(SFI, as.numeric))
Edit: or as @ CarlWitthoft suggested in the comments:
matrix(as.numeric(unlist(SFI)),nrow=nrow(SFI))
Make sure there is no exception raised in the onCreateView method of the fragment. If any exception is raised in this method, logcat won't show exact details of the exception, instead it always shows the message:
Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.fragment"
on path: DexPathList[[zip file "/data/app/com.package/base.apk"],
nativeLibraryDirectories=[/data/app/com.package/lib/arm64, /vendor/lib64, /system/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
The best approach I've come up with is to use Sass imports on a selected basis to pull in your bootstrap (or any other) styles into emails as might be needed.
First, create a new scss parent file something like email.scss
for your email style. This could look like this:
// Core variables and mixins
@import "css/main/ezdia-variables";
@import "css/bootstrap/mixins";
@import "css/main/ezdia-mixins";
// Import base classes
@import "css/bootstrap/scaffolding";
@import "css/bootstrap/type";
@import "css/bootstrap/buttons";
@import "css/bootstrap/alerts";
// nest conflicting bootstrap styles
.bootstrap-style {
//use single quotes for nested imports
@import 'css/bootstrap/normalize';
@import 'css/bootstrap/tables';
}
@import "css/main/main";
// Main email classes
@import "css/email/zurb";
@import "css/email/main";
Then in your email templates, only reference your compiled email.css file, which only contains the selected bootstrap styles referenced and nested properly in your email.scss.
For example, certain bootstrap styles will conflict with Zurb's responsive table style. To fix that, you can nest bootstrap's styles within a parent class or other selector in order to call bootstrap's table styles only when needed.
This way, you have the flexibility to pull in classes only when needed. You'll see that I use http://zurb.com/
which is a great responsive email library to use. See also http://zurb.com/ink/
Lastly, use a premailer like https://github.com/fphilipe/premailer-rails3
mentioned above to process the style into inline css, compiling inline styles to only what is used in that particular email template. For instance, for premailer, your ruby file could look something like this to compile an email into inline style.
require 'rubygems' # optional for Ruby 1.9 or above.
require 'premailer'
premailer = Premailer.new('http://www.yourdomain.com/TestSnap/view/emailTemplates/DeliveryReport.jsp', :warn_level => Premailer::Warnings::SAFE)
# Write the HTML output
File.open("delivery_report.html", "w") do |fout|
fout.puts premailer.to_inline_css
end
# Write the plain-text output
File.open("output.txt", "w") do |fout|
fout.puts premailer.to_plain_text
end
# Output any CSS warnings
premailer.warnings.each do |w|
puts "#{w[:message]} (#{w[:level]}) may not render properly in #{w[:clients]}"
end
Hope this helps! Been struggling to find a flexible email templating framework across Pardot, Salesforce, and our product's built-in auto-response and daily emails.
<p class="pull-left">Text left</p>
<p class="text-right">Text right in same line</p>
This work for me.
edit: An example with your snippet:
@import url('https://unpkg.com/[email protected]/dist/css/bootstrap.css');_x000D_
.container {_x000D_
margin-top: 10px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="row-fluid">_x000D_
<div class="span6 pull-left">_x000D_
<p>Text left</p>_x000D_
</div>_x000D_
<div class="span6 text-right">_x000D_
<p>text right</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
There is collection of Func<...>
classes - Func that is probably what you are looking for:
void MyMethod(Func<int> param1 = null)
This defines method that have parameter param1
with default value null
(similar to AS), and a function that returns int
. Unlike AS in C# you need to specify type of the function's arguments.
So if you AS usage was
MyMethod(function(intArg, stringArg) { return true; })
Than in C# it would require param1
to be of type Func<int, siring, bool>
and usage like
MyMethod( (intArg, stringArg) => { return true;} );
You can use <LinearLayout>
to group elements horizontaly. Also you should use style to set margins, background and other properties. This will allow you not to repeat code for every label you use.
Here is an example:
<LinearLayout
style="@style/FormItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
style="@style/FormLabel"
android:layout_width="wrap_content"
android:layout_height="@dimen/default_element_height"
android:text="@string/name_label"
/>
<EditText
style="@style/FormText.Editable"
android:id="@+id/cardholderName"
android:layout_width="wrap_content"
android:layout_height="@dimen/default_element_height"
android:layout_weight="1"
android:gravity="right|center_vertical"
android:hint="@string/card_name_hint"
android:imeOptions="actionNext"
android:singleLine="true"
/>
</LinearLayout>
Also you can create a custom view base on the layout above. Have you looked at Creating custom view ?
Internet Explorer doesn't fully support Flexbox due to:
Partial support is due to large amount of bugs present (see known issues).
Screenshot and infos taken from caniuse.com
Internet Explorer before 10 doesn't support Flexbox, while IE 11 only supports the 2012 syntax.
display: flex
and flex-direction: column
will not properly calculate their flexed childrens' sizes if the container has min-height
but no explicit height
property. See bug.flex
is 0 0 auto
rather than 0 1 auto
as defined in the latest spec.min-height
is used. See bug.Flexbugs is a community-curated list of Flexbox issues and cross-browser workarounds for them. Here's a list of all the bugs with a workaround available and the browsers that affect.
align-items: center
overflow their containermin-height
on a flex container won't apply to its flex itemsflex
shorthand declarations with unitless flex-basis
values are ignoredflex
items don't always preserve intrinsic aspect ratiosflex-basis
doesn't account for box-sizing: border-box
flex-basis
doesn't support calc()
align-items: baseline
doesn't work with nested flex containersflex-flow: column wrap
do not contain their itemsmargin: auto
on the cross axisflex-basis
cannot be animatedmax-width
is usedA visual for those that benefit from it.
After right-clicking the project name ("test" in this example), select "Add framework support" and check the "Maven" option.
This batch script will do exactly what the O.P. wants (tested on Windows XP SP3).
I also used that clever registry trick described by "jph" previously which IMHO is the simplest way of getting 100% consistent formatting of the date to "yyyy_MM_dd"
on any Windows system new or old. The change to one Registry value for doing this is instantaneous temporary and trivial; it only lasts a few milliseconds before it is immediately reverted back.
Double-click this batch file for an instant demo, Command Prompt window will pop up and display your timestamp . . . . .
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: generates a custom formatted timestamp string using date and time.
:: run this batch file for an instant demo.
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
@ECHO OFF
SETLOCAL & MODE CON:COLS=80 LINES=15 & COLOR 0A
:: --- CHANGE THE COMPUTER DATE FORMAT TEMPORARILY TO MY PREFERENCE "yyyy_MM_dd",
REG COPY "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f 2>nul >nul
REG ADD "HKCU\Control Panel\International" /v sShortDate /d "yyyy_MM_dd" /f 2>nul >nul
SET MYDATE=%date%
:: --- REVERT COMPUTER DATE BACK TO SYSTEM PREFERENCE
REG COPY "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f 2>nul >nul
REG DELETE "HKCU\Control Panel\International-Temp" /f 2>nul >nul
:: --- SPLIT THE TIME [HH:MM:SS.SS] TO THREE SEPARATE VARIABLES [HH] [MM] [SS.SS]
FOR /F "tokens=1-3 delims=:" %%A IN ('echo %time%') DO (
SET HOUR=%%A
SET MINUTES=%%B
SET SECONDS=%%C
)
:: --- CHOOSE ONE OF THESE TWO OPTIONS :
:: --- FOR 4 DIGIT SECONDS //REMOVES THE DOT FROM THE SECONDS VARIABLE [SS.SS]
:: SET SECONDS=%SECONDS:.=%
:: --- FOR 2 DIGIT SECONDS //GETS THE FIRST TWO DIGITS FROM THE SECONDS VARIABLE [SS.SS]
SET SECONDS=%SECONDS:~0,2%
:: --- FROM 12 AM TO 9 AM, THE HOUR VARIABLE WE EXTRACTED FROM %TIME% RETURNS A SINGLE DIGIT,
:: --- WE PREFIX A ZERO CHARACTER TO THOSE CASES, SO THAT OUR WANTED TIMESTAMP
:: --- ALWAYS GENERATES DOUBLE-DIGIT HOURS (24-HOUR CLOCK TIME SYSTEM).
IF %HOUR%==0 (SET HOUR=00)
IF %HOUR%==1 (SET HOUR=01)
IF %HOUR%==2 (SET HOUR=02)
IF %HOUR%==3 (SET HOUR=03)
IF %HOUR%==4 (SET HOUR=04)
IF %HOUR%==5 (SET HOUR=05)
IF %HOUR%==6 (SET HOUR=06)
IF %HOUR%==7 (SET HOUR=07)
IF %HOUR%==8 (SET HOUR=08)
IF %HOUR%==9 (SET HOUR=09)
:: --- GENERATE OUR WANTED TIMESTAMP
SET TIMESTAMP=%MYDATE%__%HOUR%_%MINUTES%_%SECONDS%
:: --- VIEW THE RESULT IN THE CONSOLE SCREEN
ECHO.
ECHO Generate a custom formatted timestamp string using date and time.
ECHO.
ECHO Your timestamp is: %TIMESTAMP%
ECHO.
ECHO.
ECHO Job is done. Press any key to exit . . .
PAUSE > NUL
EXIT
I noticed this issue recently and it is frustrating that excel changes a blank string into a 0. I do not think that a formula should solve this issue because adding more logic to a complex formula may be cumbersome and might even end up breaking the original formula. I have two non formula options below.
If you want to keep the formulas in the cells and have them return 0 instead of "" use the following Click Path:
Scroll to "Display options for this worksheet:"
I also want to give a simple manual solution if you want to change a value (as opposed to a formula) from 0 to a blank string. This solution is better than Find and Replace because it will not replace a number like 101 with 11.
The other data will remain if you used the filter properly and the back button is always there if something goes wrong. I understand option 2 is very manual and "unelegant" but it does successfully convert a 0 into a blank string and it may relieve a frustrated individual who does not want to use an if statement.
I personally learned something exploring this (very dry) excel issue today and I am personally using these methods moving forward. A quick macro of option 2 could be a good option if this is a frequent task for an intermediate excel user.
I second Nic Gibson's method, this was always my favorite:
<xsl:variable name='nl'><xsl:text>
</xsl:text></xsl:variable>
However I have been using the Ant task <echoxml> to create stylesheets and run them against files. The task will do attribute value templates, e.g. ${DSTAMP} , but is also will reformat your xml, so in some cases, the entity reference is preferable.
<xsl:variable name='nl'><xsl:text>
</xsl:text></xsl:variable>
SELECT *
FROM (
SELECT empno,
deptno, sal,
dense_rank( ) over ( order by sal desc) NRANK
FROM emp
)
WHERE NRANK = 4
\r used for carriage return. (ASCII value is 13) \n used for new line. (ASCII value is 10)
Just use MultipleActiveResultSets=True
in your connection string.
I always use pseudo elements :before
and :after
for changing the appearance of checkboxes and radio buttons. it's works like a charm.
Refer this link for more info
Steps
visibility:hidden
or opacity:0
or position:absolute;left:-9999px
etc.:before
element and pass either an empty or a non-breaking space '\00a0'
;:checked
state, pass the unicode content: "\2713"
, which is a checkmark;:focus
style to make the checkbox accessible.Here is how I did it.
.box {_x000D_
background: #666666;_x000D_
color: #ffffff;_x000D_
width: 250px;_x000D_
padding: 10px;_x000D_
margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
margin: 1.5em 0;_x000D_
padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
visibility: hidden;_x000D_
}_x000D_
label {_x000D_
cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
border: 1px solid #333;_x000D_
content: "\00a0";_x000D_
display: inline-block;_x000D_
font: 16px/1em sans-serif;_x000D_
height: 16px;_x000D_
margin: 0 .25em 0 0;_x000D_
padding: 0;_x000D_
vertical-align: top;_x000D_
width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
background: #fff;_x000D_
color: #333;_x000D_
content: "\2713";_x000D_
text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
<div class="box">_x000D_
<p>_x000D_
<input type="checkbox" id="c1" name="cb">_x000D_
<label for="c1">Option 01</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c2" name="cb">_x000D_
<label for="c2">Option 02</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c3" name="cb">_x000D_
<label for="c3">Option 03</label>_x000D_
</p>_x000D_
</div>_x000D_
</div>
_x000D_
Much more stylish using :before
and :after
body{_x000D_
font-family: sans-serif; _x000D_
}_x000D_
_x000D_
.container {_x000D_
margin-top: 50px;_x000D_
margin-left: 20px;_x000D_
margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
width: 100%;_x000D_
margin: 15px auto;_x000D_
position: relative;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
width: auto;_x000D_
opacity: 0.00000001;_x000D_
position: absolute;_x000D_
left: 0;_x000D_
margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
content: '';_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
margin: 4px;_x000D_
width: 22px;_x000D_
height: 22px;_x000D_
transition: transform 0.28s ease;_x000D_
border-radius: 3px;_x000D_
border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
content: '';_x000D_
display: block;_x000D_
width: 10px;_x000D_
height: 5px;_x000D_
border-bottom: 2px solid #7bbe72;_x000D_
border-left: 2px solid #7bbe72;_x000D_
-webkit-transform: rotate(-45deg) scale(0);_x000D_
transform: rotate(-45deg) scale(0);_x000D_
transition: transform ease 0.25s;_x000D_
will-change: transform;_x000D_
position: absolute;_x000D_
top: 12px;_x000D_
left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
-webkit-transform: rotate(-45deg) scale(1);_x000D_
transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
min-height: 34px;_x000D_
display: block;_x000D_
padding-left: 40px;_x000D_
margin-bottom: 0;_x000D_
font-weight: normal;_x000D_
cursor: pointer;_x000D_
vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
-webkit-transform: translateY(-50%);_x000D_
transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox" name="" value="">_x000D_
<label for="checkbox"><span>Checkbox</span></label>_x000D_
</div>_x000D_
_x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox2" name="" value="">_x000D_
<label for="checkbox2"><span>Checkbox</span></label>_x000D_
</div>_x000D_
</div>
_x000D_
As a similar alternative to s k's answer, I am able to pass a date formatted by Date.prototype.toISOString()
in the query string. This is the standard ISO 8601 format, and it is accepted by .Net Web API controllers without any additional configuration of the route or action.
e.g.
var dateString = dateObject.toISOString(); // "2019-07-01T04:00:00.000Z"
Just run php --ini
and look for Loaded Configuration File
in output for the location of php.ini
used by your CLI
As a checkbox click = a checkbox change the following will also work:
<CheckBox Click="CheckBox_Click" />
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
// ... do some stuff
}
It has the additional advantage of working when IsThreeState="True"
whereas just handling Checked and Unchecked does not.
If you're working under your feature and don't want to checkout back to master, you can run:
cd ./myrepo
git worktree add ../myrepo_master master
git worktree remove ../myrepo_master
It will create ../myrepo_master
directory with master
branch commits, where you can continue work
In case you want to use str()
and a custom str method. This also works for repr.
class TypeProxy:
def __init__(self, _type):
self._type = _type
def __call__(self, *args, **kwargs):
return self._type(*args, **kwargs)
def __str__(self):
return self._type.__name__
def __repr__(self):
return "TypeProxy(%s)" % (repr(self._type),)
>>> str(TypeProxy(str))
'str'
>>> str(TypeProxy(type("")))
'str'
How about using java.util.Arrays?
List<String> list = Arrays.asList((String[])jsonArray.toArray())
You can set this using the Sys.setenv()
function. My R session defaults to English, so I'll set it to French and then back again:
> Sys.setenv(LANG = "fr")
> 2 + x
Erreur : objet 'x' introuvable
> Sys.setenv(LANG = "en")
> 2 + x
Error: object 'x' not found
A list of the abbreviations can be found here.
Sys.getenv()
gives you a list of all the environment variables that are set.
Maybe cheating a little, but the MAC Address of a machines Ethernet adapter rarely changes without the motherboard changing these days.
You can transfer value from controller using ViewData[""]
.
ViewData["hdnFlag"] = userId;
return View();
Now, In you view.
@{
var localVar = ViewData["hdnFlag"]
}
<input type="hidden" asp-for="@localVar" />
Hope this will help...
You can also use the $inject service to get whatever service you like. I find that useful if I don't know the service name ahead of time but know the service interface. For example a directive that will plug a table into an ngResource end point or a generic delete-record button which interacts with any api end point. You don't want to re-implement the table directive for every controller or data-source.
template.html
<div my-directive api-service='ServiceName'></div>
my-directive.directive.coffee
angular.module 'my.module'
.factory 'myDirective', ($injector) ->
directive =
restrict: 'A'
link: (scope, element, attributes) ->
scope.apiService = $injector.get(attributes.apiService)
now your 'anonymous' service is fully available. If it is ngResource for example you can then use the standard ngResource interface to get your data
For example:
scope.apiService.query((response) ->
scope.data = response
, (errorResponse) ->
console.log "ERROR fetching data for service: #{attributes.apiService}"
console.log errorResponse.data
)
I have found this technique to be very useful when making elements that interact with API endpoints especially.
if you want to invoke ps1 scripts from cmd and pass arguments without invoking the script like
powershell.exe script.ps1 -c test
script -c test ( wont work )
you can do the following
setx PATHEXT "%PATHEXT%;.PS1;" /m
assoc .ps1=Microsoft.PowerShellScript.1
ftype Microsoft.PowerShellScript.1=powershell.exe "%1" %*
This is assuming powershell.exe is in your path
https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/ftype
For those still having this issue, my issue was resolved in the AndroidManifest.xml file. Where it says <activity android:name=".MainActivity" android:theme="@style/AppTheme.NoActionBar">
, you need to remove NoActionBar
, making it <activity android:name=".MainActivity" android:theme="@style/AppTheme">
, because with NoActionBar set the app doesnt know whether or not it wants an action bar when you call one up inside of MainActivity.java
Working example. Notes below.
class Animal {
constructor(public name) {
}
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
move() {
alert(this.name + " is Slithering...");
super.move(5);
}
}
class Horse extends Animal {
move() {
alert(this.name + " is Galloping...");
super.move(45);
}
}
var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
You don't need to manually assign the name to a public variable. Using public name
in the constructor definition does this for you.
You don't need to call super(name)
from the specialised classes.
Using this.name
works.
Notes on use of super
.
This is covered in more detail in section 4.9.2 of the language specification.
The behaviour of the classes inheriting from Animal
is not dissimilar to the behaviour in other languages. You need to specify the super
keyword in order to avoid confusion between a specialised function and the base class function. For example, if you called move()
or this.move()
you would be dealing with the specialised Snake
or Horse
function, so using super.move()
explicitly calls the base class function.
There is no confusion of properties, as they are the properties of the instance. There is no difference between super.name
and this.name
- there is simply this.name
. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.
I had to spend a few hours to figure out why a[3] is changing on each iteration. This is the explanation at which I arrived.
There are two types of variables in PHP: normal variables and reference variables. If we assign a reference of a variable to another variable, the variable becomes a reference variable.
for example in
$a = array('zero', 'one', 'two', 'three');
if we do
$v = &$a[0]
the 0th element ($a[0]
) becomes a reference variable. $v
points towards that variable; therefore, if we make any change to $v
, it will be reflected in $a[0]
and vice versa.
now if we do
$v = &$a[1]
$a[1]
will become a reference variable and $a[0]
will become a normal variable (Since no one else is pointing to $a[0]
it is converted to a normal variable. PHP is smart enough to make it a normal variable when no one else is pointing towards it)
This is what happens in the first loop
foreach ($a as &$v) {
}
After the last iteration $a[3]
is a reference variable.
Since $v
is pointing to $a[3]
any change to $v
results in a change to $a[3]
in the second loop,
foreach ($a as $v) {
echo $v.'-'.$a[3].PHP_EOL;
}
in each iteration as $v
changes, $a[3]
changes. (because $v
still points to $a[3]
). This is the reason why $a[3]
changes on each iteration.
In the iteration before the last iteration, $v
is assigned the value 'two'. Since $v
points to $a[3]
, $a[3]
now gets the value 'two'. Keep this in mind.
In the last iteration, $v
(which points to $a[3]
) now has the value of 'two', because $a[3]
was set to two in the previous iteration. two
is printed. This explains why 'two' is repeated when $v is printed in the last iteration.
Session ID resetting may have many causes. However any mentioned above doesn't relate to my problem. So I'll describe it for future reference.
In my case a new session created on each request resulted in infinite redirect loop. The redirect action takes place in OnActionExecuting event.
Also I've been clearing all http headers (also in OnActionExecuting event using Response.ClearHeaders method) in order to prevent caching sites on client side. But that method clears all headers including informations about user's session, and consequently all data in Temp storage (which I was using later in program). So even setting new session in Session_Start event didn't help.
To resolve my problem I ensured not to remove the headers when a redirection occurs.
Hope it helps someone.
I believe that Maven has a bad rep because most detractors have not observed the combination of Maven + Hudson + Sonar. If they had, they would be asking "how do I get started"?
This answer is for those seeking to just change the value of a data-attribute
The suggested will not change the value of your Jquery data-attr correctly as @adeneo has stated. For some reason though, I'm not seeing him (or any others) post the correct method for those seeking to update their data-attr. The answer that @Lucas Willems has posted may be the answer to problem Brian Tompsett - ??? is having, but it's not the answer to the inquiry that may be bringing other users here.
Quick answer in regards to original inquiry statement
-To update data-attr
$('#ElementId').attr('data-attributeTitle',newAttributeValue);
Easy mistakes* - there must be "data-" at the beginning of your attribute you're looking to change the value of.
This can be achieved in various methods in Swift 3.0 Worked on Latest version MAY- 2019
Directly assign the Height & Width values for a view:
userView.frame.size.height = 0
userView.frame.size.width = 10
Assign the CGRect for the Frame
userView.frame = CGRect(x:0, y: 0, width:0, height:0)
Method Details:
CGRect(x: point of X, y: point of Y, width: Width of View, height: Height of View)
Using an Extension method for CGRECT
Add following extension code in any swift file,
extension CGRect {
init(_ x:CGFloat, _ y:CGFloat, _ w:CGFloat, _ h:CGFloat) {
self.init(x:x, y:y, width:w, height:h)
}
}
Use the following code anywhere in your application for the view to set the size parameters
userView.frame = CGRect(1, 1, 20, 45)
Quickest way:
?omputational complexity is O(n).
function howMuchIsRepeated_es5(arr) {_x000D_
const count = {};_x000D_
for (let i = 0; i < arr.length; i++) {_x000D_
const val = arr[i];_x000D_
if (val in count) {_x000D_
count[val] = count[val] + 1;_x000D_
} else {_x000D_
count[val] = 1;_x000D_
}_x000D_
}_x000D_
_x000D_
for (let key in count) {_x000D_
console.log("Value " + key + " is repeated " + count[key] + " times");_x000D_
}_x000D_
}_x000D_
_x000D_
howMuchIsRepeated_es5(['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a']);
_x000D_
The shortest code:
Use ES6.
function howMuchIsRepeated_es6(arr) {_x000D_
// count is [ [valX, count], [valY, count], [valZ, count]... ];_x000D_
const count = [...new Set(arr)].map(val => [val, arr.join("").split(val).length - 1]);_x000D_
_x000D_
for (let i = 0; i < count.length; i++) {_x000D_
console.log(`Value ${count[i][0]} is repeated ${count[i][1]} times`);_x000D_
}_x000D_
}_x000D_
_x000D_
howMuchIsRepeated_es6(['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a']);
_x000D_
If you are getting a JS based date String
then first use the new Date(String)
constructor and then pass the Date
object to the moment
method. Like:
var dateString = 'Thu Jul 15 2016 19:31:44 GMT+0200 (CEST)';
var dateObj = new Date(dateString);
var momentObj = moment(dateObj);
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15
In case dateString
is 15-07-2016
, then you should use the moment(date:String, format:String)
method
var dateString = '07-15-2016';
var momentObj = moment(dateString, 'MM-DD-YYYY');
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15
For those who are still having trouble with this, try separating the two lines as below.
override func viewDidLoad() {
self.navigationController!.interactivePopGestureRecognizer!.delegate = self
...
override func viewWillAppear(_ animated: Bool) {
self.navigationController!.interactivePopGestureRecognizer!.isEnabled = true
...
Obviously, in my app,
interactivePopGestureRecognizer!.isEnabled
got reset to false
before the view was shown for some reason.
As your clock.js is in the root, put your code as this to call your javascript in the index.html found in the folders you mentioned.
<SCRIPT LANGUAGE="JavaScript" SRC="../clock.js"></SCRIPT>
This will call the clock.js which you put in the root of your web site.
Found this thread while I was looking for a solution to the exact problem described in the original post. None of the answers met my situation entirely, however. Brody's answer was pretty close. Here is my situation and solution I found to it.
I have two ILists of the same type returned by NHibernate and have emerged the two IList into one, hence the need for sorting.
Like Brody said I implemented an ICompare on the object (ReportFormat) which is the type of my IList:
public class FormatCcdeSorter:IComparer<ReportFormat>
{
public int Compare(ReportFormat x, ReportFormat y)
{
return x.FormatCode.CompareTo(y.FormatCode);
}
}
I then convert the merged IList to an array of the same type:
ReportFormat[] myReports = new ReportFormat[reports.Count]; //reports is the merged IList
Then sort the array:
Array.Sort(myReports, new FormatCodeSorter());//sorting using custom comparer
Since one-dimensional array implements the interface System.Collections.Generic.IList<T>
, the array can be used just like the original IList.
This should work:
background: -moz-linear-gradient(center top , #fad59f, #fa9907) repeat scroll 0 0 transparent;
/* For WebKit (Safari, Google Chrome etc) */
background: -webkit-gradient(linear, left top, left bottom, from(#fad59f), to(#fa9907));
/* For Mozilla/Gecko (Firefox etc) */
background: -moz-linear-gradient(top, #fad59f, #fa9907);
/* For Internet Explorer 5.5 - 7 */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907);
/* For Internet Explorer 8 */
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907)";
Otherwise generate using the following link and get the code.
The following examples show how to make an AND statement (used for setting variables or including parameters for a command).
To start Notepad and close the CMD window:
start notepad.exe & exit
To set variables x, y, and z to values if the variable 'a' equals blah.
IF "%a%"=="blah" (set x=1) & (set y=2) & (set z=3)
Hope that helps!
$insert = $this->db->insert('email_notification', $data);
$this->session->set_flashdata("msg", "<div class='alert alert-success'> Cafe has been added Successfully.</div>");
//require ("plugins/mailer/PHPMailerAutoload.php");
$mail = new PHPMailer;
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true,
),
);
$message="
Your Account Has beed created successfully by Admin:
Username: ".$this->input->post('username')." <br><br>
Email: ".$this->input->post('sender_email')." <br><br>
Regargs<br>
<div class='background-color:#666;color:#fff;padding:6px;
text-align:center;'>
Bookly Admin.
</div>
";
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true;
$subject = "Hello ".$this->input->post('username');
$mail->SMTDebug=2;
$email = $this->input->post('sender_email'); //this email is user email
$from_label = "Account Creation";
$mail->Username = 'your email'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;
$mail->setFrom($from_label);
$mail->addAddress($email, 'Bookly Admin');
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if($mail->send()){
}
Unbelievable, but on httpd 2.2 on centos 6.4 this works.
Export env vars in /etc/sysconfig/httpd
export mydocroot=/var/www/html
Then simply do this...
<VirtualHost *:80>
DocumentRoot ${mydocroot}
</VirtualHost>
Then finally....
service httpd restart;
localStorage
only supports strings. Use JSON.stringify()
and JSON.parse()
.
var names = [];
names[0] = prompt("New member name?");
localStorage.setItem("names", JSON.stringify(names));
//...
var storedNames = JSON.parse(localStorage.getItem("names"));
Suppose we have variable date , month and year then we can write it in the java like this.
int date=15,month=4,year=2016;
System.out.println(date+ "/"+month+"/"+year);
output of this will be like below:
15/4/2016
fsspec is a great option for this, it offers a filesystem like implementation of sftp.
from fsspec.implementations.sftp import SFTPFileSystem
fs = SFTPFileSystem(host=host, username=username, password=password)
# list a directory
fs.ls("/")
# open a file
with fs.open(file_name) as file:
content = file.read()
Also worth noting that fsspec uses paramiko in the implementation.
I've found you can use a very non verbose and straightforward approach to checking for the existence various SQL Server objects this way:
IF OBJECTPROPERTY (object_id('schemaname.scalarfuncname'), 'IsScalarFunction') = 1
IF OBJECTPROPERTY (object_id('schemaname.tablefuncname'), 'IsTableFunction') = 1
IF OBJECTPROPERTY (object_id('schemaname.procname'), 'IsProcedure') = 1
This is based on the OBJECTPROPERTY function which is available in SQL 2005+. The MSDN article can be found here.
The OBJECTPROPERTY function uses the following signature:
OBJECTPROPERTY ( id , property )
You pass a literal value into the property parameter, designating the type of object you are looking for. There's a massive list of values you can supply.
Declare @tablename varchar(50)
set @tablename = 'Your table Name'
EXEC('select * from ' + @tablename)
is it possible to extend query results with literals like this?
Yes.
Select Name
From Customers
UNION ALL
Select 'Jason'
UNION
to add Jason if it isn't already in the result set.UNION ALL
to add Jason whether or not he's already in the result set.If you're using ES6, here's some simple example code:
import React from 'wherever_react_is';
class TestApp extends React.Component {
getComponent(event) {
console.log('li item clicked!');
event.currentTarget.style.backgroundColor = '#ccc';
}
render() {
return(
<div>
<ul>
<li onClick={this.getComponent.bind(this)}>Component 1</li>
</ul>
</div>
);
}
}
export default TestApp;
In ES6 class bodies, functions no longer require the 'function' keyword and they don't need to be separated by commas. You can also use the => syntax as well if you wish.
Here's an example with dynamically created elements:
import React from 'wherever_react_is';
class TestApp extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{name: 'Name 1', id: 123},
{name: 'Name 2', id: 456}
]
}
}
getComponent(event) {
console.log('li item clicked!');
event.currentTarget.style.backgroundColor = '#ccc';
}
render() {
<div>
<ul>
{this.state.data.map(d => {
return(
<li key={d.id} onClick={this.getComponent.bind(this)}>{d.name}</li>
)}
)}
</ul>
</div>
);
}
}
export default TestApp;
Note that each dynamically created element should have a unique reference 'key'.
Furthermore, if you would like to pass the actual data object (rather than the event) into your onClick function, you will need to pass that into your bind. For example:
New onClick function:
getComponent(object) {
console.log(object.name);
}
Passing in the data object:
{this.state.data.map(d => {
return(
<li key={d.id} onClick={this.getComponent.bind(this, d)}>{d.name}</li>
)}
)}
#!/bin/bash
echo Please, enter your name
read NAME
echo "Hi $NAME!"
if [ "x$NAME" = "xyes" ] ; then
# do something
fi
I s a short script to read in bash and echo back results.
And to add to this answer, make sure the image itself has a transparent background.
find() and closest() seems slightly slower than:
$(this).parent().attr("id");
A cursor will only accept a select statement, so if the SQL really needs to be dynamic make the declare cursor part of the statement you are executing. For the below to work your server will have to be using global cursors.
Declare @UserID varchar(100)
declare @sqlstatement nvarchar(4000)
--move declare cursor into sql to be executed
set @sqlstatement = 'Declare users_cursor CURSOR FOR SELECT userId FROM users'
exec sp_executesql @sqlstatement
OPEN users_cursor
FETCH NEXT FROM users_cursor
INTO @UserId
WHILE @@FETCH_STATUS = 0
BEGIN
Print @UserID
EXEC asp_DoSomethingStoredProc @UserId
FETCH NEXT FROM users_cursor --have to fetch again within loop
INTO @UserId
END
CLOSE users_cursor
DEALLOCATE users_cursor
If you need to avoid using the global cursors, you could also insert the results of your dynamic SQL into a temporary table, and then use that table to populate your cursor.
Declare @UserID varchar(100)
create table #users (UserID varchar(100))
declare @sqlstatement nvarchar(4000)
set @sqlstatement = 'Insert into #users (userID) SELECT userId FROM users'
exec(@sqlstatement)
declare users_cursor cursor for Select UserId from #Users
OPEN users_cursor
FETCH NEXT FROM users_cursor
INTO @UserId
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC asp_DoSomethingStoredProc @UserId
FETCH NEXT FROM users_cursor
INTO @UserId
END
CLOSE users_cursor
DEALLOCATE users_cursor
drop table #users
I actually came to this question looking for an answer myself, and after reading the given answers I can only agree that the best way to compare DB queries performance is to get real-world numbers because there are just to many variables to be taken into account BUT, I also think that comparing the numbers between them leads to no good in almost all cases. What I mean is that the numbers should always be compared with an acceptable number and definitely not compared with each other.
I can understand if one way of querying takes say 0.02 seconds and the other one takes 20 seconds, that's an enormous difference. But what if one way of querying takes 0.0000000002 seconds, and the other one takes 0.0000002 seconds ? In both cases one way is a whopping 1000 times faster than the other one, but is it really still "whopping" in the second case ?
Bottom line as I personally see it: if it performs well, go for the easy solution.
Other than setting JAVA_HOME
environment variable, you got to make sure you are using the correct JDK in your Maven run configuration. Go to Run -> Run Configuration, select your Maven Build configuration, go to JRE tab and set the correct Runtime JRE.
here is a quick review and with a simple and quick understanding
from teacher Beau Carnes from freecodecamp
How about this:
$(document).ready(function() {
$('#subscribeForm').submit(function() {
var $fields = $(this).find('input[name="list"]:checked');
if (!$fields.length) {
alert('You must check at least one box!');
return false; // The form will *not* submit
}
});
});
Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS
request. So the error comes from the fact that the preflight request doesn't produce the necessary headers.
For RESTeasy, you should use CorsFilter
. You can see here for some example how to configure it. This filter will handle the preflight request. So you can remove all those headers you have in your resource methods.
See Also:
To obtain shared preferences, use the following method In your activity:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To read preferences:
String dateTimeKey = "com.example.app.datetime";
// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());
To edit and save preferences
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();
The android sdk's sample directory contains an example of retrieving and storing shared preferences. Its located in the:
<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory
Edit==>
I noticed, it is important to write difference between commit()
and apply()
here as well.
commit()
return true
if value saved successfully otherwise false
. It save values to SharedPreferences synchronously.
apply()
was added in 2.3 and doesn't return any value either on success or failure. It saves values to SharedPreferences immediately but starts an asynchronous commit.
More detail is here.
There are a couple ways you can do this. The simplest way to do so is to use the dockerfile ADD
command like so:
ADD . /path/inside/docker/container
However, any changes made to this directory on the host after building the dockerfile will not show up in the container. This is because when building a container, docker compresses the directory into a .tar
and uploads that context into the container permanently.
The second way to do this is the way you attempted, which is to mount a volume. Due to trying to be as portable as possible you cannot map a host directory to a docker container directory within a dockerfile, because the host directory can change depending on which machine you are running on. To map a host directory to a docker container directory you need to use the -v
flag when using docker run
, e.g.,:
# Run a container using the `alpine` image, mount the `/tmp`
# directory from your host into the `/container/directory`
# directory in your container, and run the `ls` command to
# show the contents of that directory.
docker run \
-v /tmp:/container/directory \
alpine \
ls /container/directory
The most "foolproof" way is to check for the availability of URL:
public boolean isURL(String url) {
try {
(new java.net.URL(url)).openStream().close();
return true;
} catch (Exception ex) { }
return false;
}
You can try settings of code::block
, there is a complier..., then you select in C mode.
I faced the problem with display:none
I have several horizontal bars with transition effects but I wanted to show only part of that container and fold the rest while maintaining the effects. I reproduced a small demo here
The obvious was to wrap those hidden animated bars in a div then toggle that element's height and opacity
.hide{
opacity: 0;
height: 0;
}
.bars-wrapper.expanded > .hide{
opacity: 1;
height: auto;
}
The animation works well but the issue was that these hidden bars were still consuming space on my page and overlapping other elements
so adding display:none
to the hidden wrapper .hide
solves the margin issue but not the transition, neither applying display:none
or height:0;opacity:0
works on the children elements.
So my final workaround was to give those hidden bars a negative and absolute position and it worked well with CSS transitions.
I don't have Python 2.7 installed, but in Python 3.3 calling Popen
with stdout
set to sys.stdout
worked just fine. Not before I had escaped the backslashes in the path, though.
>>> import subprocess
>>> import sys
>>> p = subprocess.Popen(['powershell.exe', 'C:\\Temp\\test.ps1'], stdout=sys.stdout)
>>> Hello World
_
For testing on both laptops on the same wireless and across the internet you could use a service like http://localhost.run/ or https://ngrok.com/
Here is my way:
function xml2array($xml_data)
{
$xml_to_array = [];
if(isset($xml_data))
{
if(is_iterable($xml_data))
{
foreach($xml_data as $key => $value)
{
if(is_object($value))
{
if(empty((array)$value))
{
$value = (string)$value;
}
else
{
$value = (array)$value;
}
$value = xml2array($value);
}
$xml_to_array[$key] = $value;
}
}
else
{
$xml_to_array = $xml_data;
}
}
return $xml_to_array;
}
I guess you've meant:
[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
This would be sorted like this:
sorted(l,cmp=lambda x,y: cmp(x['name'],y['name']))
As mentioned by Quynh Nguyen, you don't need the '.' in the className. However - document.getElementsByClassName('col1') will return an array of objects.
This will return an "undefined" value because an array doesn't have a class. You'll still need to loop through the array elements...
function changeBGColor() {
var cols = document.getElementsByClassName('col1');
for(i = 0; i < cols.length; i++) {
cols[i].style.backgroundColor = 'blue';
}
}
You can also do something much shorter:
SELECT FORMAT(2.3332232,'N2')
UICollectionView implementation is quite interesting. You can use the simple source code and watch a video tutorial using these links :
https://github.com/Ady901/Demo02CollectionView.git
https://www.youtube.com/watch?v=5SrgvZF67Yw
extension ViewController : UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return nameArr.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DummyCollectionCell", for: indexPath) as! DummyCollectionCell
cell.titleLabel.text = nameArr[indexPath.row]
cell.userImageView.backgroundColor = .blue
return cell
}
}
extension ViewController : UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let alert = UIAlertController(title: "Hi", message: "\(nameArr[indexPath.row])", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}
Here's my own:
class Program
{
static void Main(string[] args)
{
var tree = new Tree<string>()
.Begin("Fastfood")
.Begin("Pizza")
.Add("Margherita")
.Add("Marinara")
.End()
.Begin("Burger")
.Add("Cheese burger")
.Add("Chili burger")
.Add("Rice burger")
.End()
.End();
tree.Nodes.ForEach(p => PrintNode(p, 0));
Console.ReadKey();
}
static void PrintNode<T>(TreeNode<T> node, int level)
{
Console.WriteLine("{0}{1}", new string(' ', level * 3), node.Value);
level++;
node.Children.ForEach(p => PrintNode(p, level));
}
}
public class Tree<T>
{
private Stack<TreeNode<T>> m_Stack = new Stack<TreeNode<T>>();
public List<TreeNode<T>> Nodes { get; } = new List<TreeNode<T>>();
public Tree<T> Begin(T val)
{
if (m_Stack.Count == 0)
{
var node = new TreeNode<T>(val, null);
Nodes.Add(node);
m_Stack.Push(node);
}
else
{
var node = m_Stack.Peek().Add(val);
m_Stack.Push(node);
}
return this;
}
public Tree<T> Add(T val)
{
m_Stack.Peek().Add(val);
return this;
}
public Tree<T> End()
{
m_Stack.Pop();
return this;
}
}
public class TreeNode<T>
{
public T Value { get; }
public TreeNode<T> Parent { get; }
public List<TreeNode<T>> Children { get; }
public TreeNode(T val, TreeNode<T> parent)
{
Value = val;
Parent = parent;
Children = new List<TreeNode<T>>();
}
public TreeNode<T> Add(T val)
{
var node = new TreeNode<T>(val, this);
Children.Add(node);
return node;
}
}
Output:
Fastfood
Pizza
Margherita
Marinara
Burger
Cheese burger
Chili burger
Rice burger
You can copy it as a new file and then delete the old one using the System.IO.File
class:
if (File.Exists(oldName))
{
File.Copy(oldName, newName, true);
File.Delete(oldName);
}