I do the following in my eBay listings:
<p style="border:solid thick darkblue; border-radius: 1em;
border-width:3px; padding-left:9px; padding-top:6px;
padding-bottom:6px; margin:2px; width:980px;">
This produces a box border with rounded corners.You can play with the variables.
Angular 7 Service:
this.http.post(environment.urlRest + '/my-operation',body, { headers: headers, observe: 'response'});Component:
this.myService.myfunction().subscribe( (res: HttpResponse) => { console.log(res.headers.get('x-token')); } , error =>{ })
<div class="row" id="divcashgap" style="display:none">_x000D_
<div class="col-md-12">_x000D_
<div class="table-responsive">_x000D_
<table class="table table-default" id="gvcashgapp">_x000D_
<thead>_x000D_
<tr>_x000D_
<th class="1">BranchCode</th>_x000D_
<th class="2"><a>TC</a></th>_x000D_
<th class="3">VourNo</th>_x000D_
<th class="4" style="min-width:120px;">VourDate</th>_x000D_
<th class="5" style="min-width:120px;">RCPT Date</th>_x000D_
<th class="6">RCPT No</th>_x000D_
<th class="7"><a>PIS No</a></th>_x000D_
<th class="8" style="min-width:160px;">RCPT Ammount</th>_x000D_
<th class="9">Agging</th>_x000D_
<th class="10" style="min-width:160px;">DesPosition Days</th>_x000D_
<th class="11" style="min-width:150px;">Bank Credit Date</th>_x000D_
<th class="12">Comments</th>_x000D_
<th class="13" style="min-width:150px;">BAC Comment</th>_x000D_
<th class="14">BAC Ramark</th>_x000D_
<th class="15" style="min-width:150px;">RAC Comment</th>_x000D_
<th class="16">RAC Ramark</th>_x000D_
<th class="17" style="min-width:120px;">Update Status</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody id="tbdCashGapp"></tbody>_x000D_
</table>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Here is how you set the date and time:
update user set expiry_date=TO_DATE('31/DEC/2017 12:59:59', 'dd/mm/yyyy hh24:mi:ss') where id=123;
You're seeing the space for descenders (the bits that hang off the bottom of 'y' and 'p') because img
is an inline element by default. This removes the gap:
.youtube-thumb img { display: block; }
$this->db1->where('tennant_id', $tennant_id);
$this->db1->order_by('id', 'DESC');
return $this->db1->get('courses')->result();
I had the following
document.getElementById("search-button") != null
which worked fine in all browsers except ie8. ( I didnt check ie6 or ie7)
I changed it to
document.getElementById("searchBtn") != null
and updated the id attribute on the field in my html and it now works in ie8
Also with python3 you might find convenient to use Extended Iterable Unpacking to handle optional positional arguments without additional dependencies:
try:
_, arg1, arg2, arg3, *_ = sys.argv + [None] * 2
except ValueError:
print("Not enough arguments", file=sys.stderr) # unhandled exception traceback is meaningful enough also
exit(-1)
The above argv
unpack makes arg2
and arg3
"optional" - if they are not specified in argv
, they will be None, while if the first is not specified, ValueError will be thouwn:
Traceback (most recent call last):
File "test.py", line 3, in <module>
_, arg1, arg2, arg3, *_ = sys.argv + [None] * 2
ValueError: not enough values to unpack (expected at least 4, got 3)
if using /bin/sh
you can use:
if [ <condition> ] && [ <condition> ]; then
...
fi
if using /bin/bash
you can use:
if [[ <condition> && <condition> ]]; then
...
fi
You can say getenv('USERNAME')
If you have lodash you can use its .get
method
_.get(a, 'b.c.d.e')
or give it a default value
_.get(a, 'b.c.d.e', default)
EDIT: From ECMAScript 2018 onwards, lookbehind assertions (even unbounded) are supported natively.
In previous versions, you can do this:
^(?:(?!filename\.js$).)*\.js$
This does explicitly what the lookbehind expression is doing implicitly: check each character of the string if the lookbehind expression plus the regex after it will not match, and only then allow that character to match.
^ # Start of string
(?: # Try to match the following:
(?! # First assert that we can't match the following:
filename\.js # filename.js
$ # and end-of-string
) # End of negative lookahead
. # Match any character
)* # Repeat as needed
\.js # Match .js
$ # End of string
Another edit:
It pains me to say (especially since this answer has been upvoted so much) that there is a far easier way to accomplish this goal. There is no need to check the lookahead at every character:
^(?!.*filename\.js$).*\.js$
works just as well:
^ # Start of string
(?! # Assert that we can't match the following:
.* # any string,
filename\.js # followed by filename.js
$ # and end-of-string
) # End of negative lookahead
.* # Match any string
\.js # Match .js
$ # End of string
I agree with Hugh W post "I conclude that the same error code is used to indicate multiple unrelated problems"
Other posts have not mentioned that this error occurs frequently if the worksheet is locked. While I haven't tested every scenario, it seems that anything that you can not do in excel when a worksheet is locked with throw this error if you attempt to do it via VSTO/Com while the sheet is locked. E.G. Changing any style artifact (font, font size, colour, underline), changing the Excel Validation, changing the column widths, row heights, formulas
Be sure to go to Sheharyar's great Answer. There are so many answers and comments that follow it that it would be easy to get confused and give up, but don't. That answer works.
In short, you do three things:
(1) Deselect Compact Empty Middle Packages
.
(2) Refactor
then Rename
each old directory node by choosing Change Package
(not Change Directory
) to match the new package name. (Be sure to do a preview of changes.)
(3) Edit the build.gradle
file and make APPLICATION_ID
match the new package name.
Keep in mind while using HTML5 pushstate if a user copies or bookmarks a deep link and visits it again, then that will be a direct server hit which will 404 so you need to be ready for it and even a pushstate js library won't help you. The easiest solution is to add a rewrite rule to your Nginx or Apache server like so:
Apache (in your vhost if you're using one):
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
Nginx
rewrite ^(.+)$ /index.html last;
I think the second is "proper," but to be honest I don't think it will matter. The compiler should be smart enough to compile any of those to the exact same bytecode. I use "" myself.
kubectl run
= kubectl create deployment
kubectl create -f your-object-config.yaml
kubectl delete -f your-object-config.yaml
kubectl replace -f your-object-config.yaml
kubectl diff -f configs/
kubectl apply -f configs/
From the documentation:
UPSERT is a special syntax addition to INSERT that causes the INSERT to behave as an UPDATE or a no-op if the INSERT would violate a uniqueness constraint. UPSERT is not standard SQL. UPSERT in SQLite follows the syntax established by PostgreSQL. UPSERT syntax was added to SQLite with version 3.24.0 (pending).
An UPSERT is an ordinary INSERT statement that is followed by the special ON CONFLICT clause
Image source: https://www.sqlite.org/images/syntax/upsert-clause.gif
You have it almost done. Just explicitly say where to create the file
@echo off
echo.>"d:\testing\dblank.txt"
This creates a file containing a blank line (CR + LF = 2 bytes).
If you want the file empty (0 bytes)
@echo off
break>"d:\testing\dblank.txt"
This is my "crutches" solution by using html and css. There used 2 tables and fixed width of tables and table cell`s
https://jsfiddle.net/babaikawow/s2xyct24/1/
HTML:
<div class="container">
<table class="table" border = 1; > <!-- fixed width header -->
<thead >
<tr>
<th class="tbDataId" >?</th>
<th class="tbDataName">?????????</th>
<th class="tbDataData">????</th>
<th class="tbDataData">?????? ??</th>
<th class="tbDataDiseases">????????1</th>
<th class="tbDataDiseases">????????2</th>
<th class="tbDataDiseases">????????3</th>
<th class="tbDataDiseases">????????4</th>
<th class="tbDataDiseases">????????5</th>
</tr>
</thead>
</table>
<div class="scrollTable"> <!-- scrolling block -->
<table class="table" border = 1;>
<tbody>
<tr>
<td class="tbDataId" >?</td>
<td class="tbDataName">?????????</td>
<td class="tbDataData">????</td>
<td class="tbDataData">?????? ??</td>
<td class="tbDataDiseases">????????1</td>
<td class="tbDataDiseases">????????2</td>
<td class="tbDataDiseases">????????3</td>
<td class="tbDataDiseases">????????4</td>
<td class="tbDataDiseases">????????5</td>
</tr>
<tr>
<td class="tbDataId" >?</td>
<td class="tbDataName">?????????</td>
<td class="tbDataData">????</td>
<td class="tbDataData">?????? ??</td>
<td class="tbDataDiseases">????????1</td>
<td class="tbDataDiseases">????????2</td>
<td class="tbDataDiseases">????????3</td>
<td class="tbDataDiseases">????????4</td>
<td class="tbDataDiseases">????????5</td>
</tr>
<tr>
<td class="tbDataId" >?</td>
<td class="tbDataName">?????????</td>
<td class="tbDataData">????</td>
<td class="tbDataData">?????? ??</td>
<td class="tbDataDiseases">????????1</td>
<td class="tbDataDiseases">????????2</td>
<td class="tbDataDiseases">????????3</td>
<td class="tbDataDiseases">????????4</td>
<td class="tbDataDiseases">????????5</td>
</tr>
<tr>
<td class="tbDataId" >?</td>
<td class="tbDataName">?????????</td>
<td class="tbDataData">????</td>
<td class="tbDataData">?????? ??</td>
<td class="tbDataDiseases">????????1</td>
<td class="tbDataDiseases">????????2</td>
<td class="tbDataDiseases">????????3</td>
<td class="tbDataDiseases">????????4</td>
<td class="tbDataDiseases">????????5</td>
</tr>
<tr>
<td class="tbDataId" >?</td>
<td class="tbDataName">?????????</td>
<td class="tbDataData">????</td>
<td class="tbDataData">?????? ??</td>
<td class="tbDataDiseases">????????1</td>
<td class="tbDataDiseases">????????2</td>
<td class="tbDataDiseases">????????3</td>
<td class="tbDataDiseases">????????4</td>
<td class="tbDataDiseases">????????5</td>
</tr>
</tbody>
</table>
</div>
</div>
CSS:
*{
box-sizing: border-box;
}
.container{
width:1000px;
}
.scrollTable{
overflow: scroll;
overflow-x: hidden;
height: 100px;
}
table{
margin: 0px!important;
width:983px!important;
border-collapse: collapse;
}
/* Styles of the th and td */
/* Id */
.tbDataId{
width:5%;
}
/* ????,
?????? ?? */
.tbDataData{
/*width:170px;*/
width: 15%;
}
/* ? ? ? */
.tbDataName{
width: 15%;
}
/*???????? */
.tbDataDiseases{
width:10%;
}
In Python 2:
mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))
In Python 3 (where print
is a builtin function and not a syntax feature anymore):
mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))
Both return:
[x, 3, b]
This is using the map()
function to call str for each element of mylist, creating a new list of strings that is then joined into one string with str.join()
. Then, the %
string formatting operator substitutes the string in instead of %s
in "[%s]"
.
For me it started working when i have set explicitly the headers that I was sending. I was adding the content-type header, and then it worked.
.net
.WithHeaders("Authorization","Content-Type")
javascript:
this.fetchoptions = {
method: 'GET',
cache: 'no-cache',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
redirect: 'follow',
};
git remote show origin -n | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
It was tested with three different URL styles:
echo "Fetch URL: http://user@pass:gitservice.org:20080/owner/repo.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
echo "Fetch URL: Fetch URL: [email protected]:home1-oss/oss-build.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
echo "Fetch URL: https://github.com/owner/repo.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
'Caret' package provides methods for preprocessing data (e.g. centering and scaling). You could also use the following code:
library(caret)
# Assuming goal class is column 10
preObj <- preProcess(data[, -10], method=c("center", "scale"))
newData <- predict(preObj, data[, -10])
More details: http://www.inside-r.org/node/86978
This solution preserves the index of the df2
DataFrame, unlike any solution that uses tolist()
:
df3 = df2.teams.apply(pd.Series)
df3.columns = ['team1', 'team2']
Here's the result:
team1 team2
0 SF NYG
1 SF NYG
2 SF NYG
3 SF NYG
4 SF NYG
5 SF NYG
6 SF NYG
I also had the issue of parsing and using JSON objects in C#. I checked the dynamic type with some libraries, but the issue was always checking if a property exists.
In the end, I stumbled upon this web page, which saved me a lot of time. It automatically creates a strongly typed class based on your JSON data, that you will use with the Newtonsoft library, and it works perfectly. It also works with languages other than C#.
In MySQL, you can do this as well:
SELECT count(*) AS total
, sum(myCol) AS countTrue --yes, you can add TRUEs as TRUE=1 and FALSE=0 !!
FROM yourTable
;
I think that in Postgres, this works:
SELECT count(*) AS total
, sum(myCol::int) AS countTrue --convert Boolean to Integer
FROM yourTable
;
or better (to avoid :: and use standard SQL syntax):
SELECT count(*) AS total
, sum(CAST(myCol AS int)) AS countTrue --convert Boolean to Integer
FROM yourTable
;
Add yourself to the vboxsf
group within the guest VM.
Solution 1
Run sudo adduser $USER vboxsf
from terminal.
(On Suse it's sudo usermod --append --groups vboxsf $USER
)
To take effect you should log out and then log in, or you may need to reboot.
Solution 2
Edit the file /etc/group
(you will need root privileges). Look for the line vboxsf:x:999
and add at the end :yourusername
-- use this solution if you don't have sudo.
To take effect you should log out and then log in, or you may need to reboot.
if using JQuery, you can do this :
<script type="text/javascript">
$('#buttonid').click(function () {
document.location = '@Url.Action("ActionName","ControllerName")';
});
</script>
Unlike other answers this will ..
START THE SERVICE AUTOMATICALLY ON SYSTEM REBOOT / RESTART
(1) Install MongoDB
(2) Add bin to path
(3) Create c:\data\db
(4) Create c:\data\log
(5) Create c:\data\mongod.cfg with contents ..
systemLog:
destination: file
path: c:\data\log\mongod.log
storage:
dbPath: c:\data\db
(6) To create service that will auto start on reboot .. RUN AS ADMIN ..
sc.exe create MongoDB binPath= "\"C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe\" --service --config=\"C:\data\mongod.cfg\"" DisplayName= "MongoDB" start= "auto"
(7) Start the service .. RUN AS ADMIN ..
net start MongoDB
IMPORTANT: Even if this says 'The MongoDB service was started successfully' it can fail
To double check open Control Panel > Services, ensure the status of the MongoDB service is 'Running'
If not, check your log file at C:\data\log\mongod.log for the reason for failure and fix it
(Do not start MongoDB via Control Panel > Services, use .. net start MongoDB)
(8) Finally, restart your machine with MongoDB running and it will still be running on restart
If you ever want to kill it ..
net stop MongoDB
sc.exe delete MongoDB
I would assume your variable mean_temp already has the values loaded in to it and is nX1 dimension (i.e only one row). Now to achieve what you want, you can :
Change the datatype of your variable:
def coldest_location(data):
mean_temp = numpy.mat(mean_temp) #data is now matrix type
min_index = numpy.nonzero(mean_temp == mean_temp.min()) # this returns list of indexes
print mean_temp[min_index[0],min_index[1]] # printing minimum value, i.e -24.6 in you data i believe
Thread.sleep can throw an InterruptedException which is a checked exception. All checked exceptions must either be caught and handled or else you must declare that your method can throw it. You need to do this whether or not the exception actually will be thrown. Not declaring a checked exception that your method can throw is a compile error.
You either need to catch it:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
// handle the exception...
// For example consider calling Thread.currentThread().interrupt(); here.
}
Or declare that your method can throw an InterruptedException
:
public static void main(String[]args) throws InterruptedException
Related
You may like the way that we do it. I wanted a reversible unique code that looked "random" -a fairly common problem.
We now have a number that varies wildly between calls and is guaranteed to be less than 10,000,000,000. Not a bad start.
The reason for choosing base 34 is so that we don't worry about 0/O and 1/l collisions. Now you have a short random-looking key that you can use to look up a LONG database identifier.
First, add the dependency of FFmpeg library
implementation 'com.writingminds:FFmpegAndroid:0.3.2'
Then load in activity
FFmpeg ffmpeg;
private void trimVideo(ProgressDialog progressDialog) {
outputAudioMux = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath()
+ "/VidEffectsFilter" + "/" + new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date())
+ "filter_apply.mp4";
if (startTrim.equals("")) {
startTrim = "00:00:00";
}
if (endTrim.equals("")) {
endTrim = timeTrim(player.getDuration());
}
String[] cmd = new String[]{"-ss", startTrim + ".00", "-t", endTrim + ".00", "-noaccurate_seek", "-i", videoPath, "-codec", "copy", "-avoid_negative_ts", "1", outputAudioMux};
execFFmpegBinary1(cmd, progressDialog);
}
private void execFFmpegBinary1(final String[] command, ProgressDialog prpg) {
ProgressDialog progressDialog = prpg;
try {
ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
@Override
public void onFailure(String s) {
progressDialog.dismiss();
Toast.makeText(PlayerTestActivity.this, "Fail to generate video", Toast.LENGTH_SHORT).show();
Log.d(TAG, "FAILED with output : " + s);
}
@Override
public void onSuccess(String s) {
Log.d(TAG, "SUCCESS wgith output : " + s);
// pathVideo = outputAudioMux;
String finalPath = outputAudioMux;
videoPath = outputAudioMux;
Toast.makeText(PlayerTestActivity.this, "Storage Path =" + finalPath, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(PlayerTestActivity.this, ShareVideoActivity.class);
intent.putExtra("pathGPU", finalPath);
startActivity(intent);
finish();
MediaScannerConnection.scanFile(PlayerTestActivity.this, new String[]{finalPath}, new String[]{"mp4"}, null);
}
@Override
public void onProgress(String s) {
Log.d(TAG, "Started gcommand : ffmpeg " + command);
progressDialog.setMessage("Please Wait video triming...");
}
@Override
public void onStart() {
Log.d(TAG, "Startedf command : ffmpeg " + command);
}
@Override
public void onFinish() {
Log.d(TAG, "Finished f command : ffmpeg " + command);
progressDialog.dismiss();
}
});
} catch (FFmpegCommandAlreadyRunningException e) {
// do nothing for now
}
}
private void loadFFMpegBinary() {
try {
if (ffmpeg == null) {
ffmpeg = FFmpeg.getInstance(this);
}
ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
@Override
public void onFailure() {
showUnsupportedExceptionDialog();
}
@Override
public void onSuccess() {
Log.d("dd", "ffmpeg : correct Loaded");
}
});
} catch (FFmpegNotSupportedException e) {
showUnsupportedExceptionDialog();
} catch (Exception e) {
Log.d("dd", "EXception no controlada : " + e);
}
}
private void showUnsupportedExceptionDialog() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Not Supported")
.setMessage("Device Not Supported")
.setCancelable(false)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create()
.show();
}
public String timeTrim(long milliseconds) {
String finalTimerString = "";
String minutString = "";
String secondsString = "";
// Convert total duration into time
int hours = (int) (milliseconds / (1000 * 60 * 60));
int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60);
int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
// Add hours if there
if (hours < 10) {
finalTimerString = "0" + hours + ":";
} else {
finalTimerString = hours + ":";
}
if (minutes < 10) {
minutString = "0" + minutes;
} else {
minutString = "" + minutes;
}
// Prepending 0 to seconds if it is one digit
if (seconds < 10) {
secondsString = "0" + seconds;
} else {
secondsString = "" + seconds;
}
finalTimerString = finalTimerString + minutString + ":" + secondsString;
// return timer string
return finalTimerString;
}
Also use another feature by FFmpeg
===> merge audio to video
String[] cmd = new String[]{"-i", yourRealPath, "-i", arrayList.get(posmusic).getPath(), "-map", "1:a", "-map", "0:v", "-codec", "copy", "-shortest", outputcrop};
===> Flip vertical :
String[] cm = new String[]{"-i", yourRealPath, "-vf", "vflip", "-codec:v", "libx264", "-preset", "ultrafast", "-codec:a", "copy", outputcrop1};
===> Flip horizontally :
String[] cm = new String[]{"-i", yourRealPath, "-vf", "hflip", "-codec:v", "libx264", "-preset", "ultrafast", "-codec:a", "copy", outputcrop1};
===> Rotate 90 degrees clockwise:
String[] cm=new String[]{"-i", yourRealPath, "-c", "copy", "-metadata:s:v:0", "rotate=90", outputcrop1};
===> Compress Video
String[] complexCommand = {"-y", "-i", yourRealPath, "-strict", "experimental", "-vcodec", "libx264", "-preset", "ultrafast", "-crf", "24", "-acodec", "aac", "-ar", "22050", "-ac", "2", "-b", "360k", "-s", "1280x720", outputcrop1};
===> Speed up down video
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=2.0*PTS[v];[0:a]atempo=0.5[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=1.0*PTS[v];[0:a]atempo=1.0[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=0.75*PTS[v];[0:a]atempo=1.5[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=0.5*PTS[v];[0:a]atempo=2.0[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
===> Add two mp3 files
StringBuilder sb = new StringBuilder();
sb.append("-i ");
sb.append(textSngname);
sb.append(" -i ");
sb.append(mAudioFilename);
sb.append(" -filter_complex [0:0][1:0]concat=n=2:v=0:a=1[out] -map [out] ");
sb.append(finalfile);
---> ffmpeg.execute(sb.toString().split(" "), new ExecuteBinaryResponseHandler()
===> Add three mp3 files
StringBuilder sb = new StringBuilder();
sb.append("-i ");
sb.append(firstSngname);
sb.append(" -i ");
sb.append(textSngname);
sb.append(" -i ");
sb.append(mAudioFilename);
sb.append(" -filter_complex [0:0][1:0][2:0]concat=n=3:v=0:a=1[out] -map [out] ");
sb.append(finalfile);
---> ffmpeg.execute(sb.toString().split(" "), new ExecuteBinaryResponseHandler()
One way that I see more powerful and avoid having a isDefault
in all the models is by using the ng-attributes ng-model
, ng-value
and ng-checked
.
ng-model: binds the value to your model.
ng-value: the value to pass to the ng-model
binding.
ng-checked: value or expression that is evaluated. Useful for radio-button and check-boxes.
Example of use: In the following example, I have my model and a list of languages that my site supports. To display the different languages supported and updating the model with the selecting language we can do it in this way.
<!-- Radio -->
<div ng-repeat="language in languages">
<div>
<label>
<input ng-model="site.lang"
ng-value="language"
ng-checked="(site.lang == language)"
name="localizationOptions"
type="radio">
<span> {{language}} </span>
</label>
</div>
</div>
<!-- end of Radio -->
Our model site.lang
will get a language
value whenever the expression under evaluation (site.lang == language)
is true. This will allow you to sync it with server easily since your model already has the change.
Or maybe even easier
grep -R put **/*bills*
The **
glob syntax means "any depth of directories". It will work in Zsh, and I think recent versions of Bash too.
Swift:
func updateCell(path:Int){
let indexPath = NSIndexPath(forRow: path, inSection: 1)
tableView.beginUpdates()
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) //try other animations
tableView.endUpdates()
}
How to throttle requestAnimationFrame to a specific frame rate
Demo throttling at 5 FPS: http://jsfiddle.net/m1erickson/CtsY3/
This method works by testing the elapsed time since executing the last frame loop.
Your drawing code executes only when your specified FPS interval has elapsed.
The first part of the code sets some variables used to calculate elapsed time.
var stop = false;
var frameCount = 0;
var $results = $("#results");
var fps, fpsInterval, startTime, now, then, elapsed;
// initialize the timer variables and start the animation
function startAnimating(fps) {
fpsInterval = 1000 / fps;
then = Date.now();
startTime = then;
animate();
}
And this code is the actual requestAnimationFrame loop which draws at your specified FPS.
// the animation loop calculates time elapsed since the last loop
// and only draws if your specified fps interval is achieved
function animate() {
// request another frame
requestAnimationFrame(animate);
// calc elapsed time since last loop
now = Date.now();
elapsed = now - then;
// if enough time has elapsed, draw the next frame
if (elapsed > fpsInterval) {
// Get ready for next frame by setting then=now, but also adjust for your
// specified fpsInterval not being a multiple of RAF's interval (16.7ms)
then = now - (elapsed % fpsInterval);
// Put your drawing code here
}
}
You can use CFArray instead of NSArray. Here is an article explaining how.
CFMutableArrayRef ar = CFArrayCreateMutable(NULL, 0, NULL);
for (NSUInteger i = 0; i < 1000; i++)
{
CFArrayAppendValue(ar, (void*)i);
}
CFRelease(ar); /* Releasing the array */
The same applies for the CoreFoundation version of the other containers too.
If you have a symbolic link in the /usr/local/etc/openssl pointing to cert.pem try to do this:
ruby -ropenssl -e "p OpenSSL::X509::DEFAULT_CERT_FILE" (should be /usr/local/etc/openssl)
cd /usr/local/etc/openssl
wget http://curl.haxx.se/ca/cacert.pem
ln -s cacert.pem 77ee3751.0 (77ee3751.0 is my symbolic link, should depend on the openssl version)
Not fitting 100% to this particular question but if you want to split from the back you can do it like this:
theStringInQuestion[::-1].split('/', 1)[1][::-1]
This code splits once at symbol '/' from behind.
Update: Simply using a hash function is not strong enough for storing passwords. You should read the answer from Gilles on this thread for a more detailed explanation.
For passwords, use a key-strengthening hash algorithm like Bcrypt or Argon2i. For example, in PHP, use the password_hash() function, which uses Bcrypt by default.
$hash = password_hash("rasmuslerdorf", PASSWORD_DEFAULT);
The result is a 60-character string similar to the following (but the digits will vary, because it generates a unique salt).
$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a
Use the SQL data type CHAR(60)
to store this encoding of a Bcrypt hash. Note this function doesn't encode as a string of hexadecimal digits, so we can't as easily unhex it to store in binary.
Other hash functions still have uses, but not for storing passwords, so I'll keep the original answer below, written in 2008.
It depends on the hashing algorithm you use. Hashing always produces a result of the same length, regardless of the input. It is typical to represent the binary hash result in text, as a series of hexadecimal digits. Or you can use the UNHEX()
function to reduce a string of hex digits by half.
As of 2015, NIST recommends using SHA-256 or higher for any applications of hash functions requiring interoperability. But NIST does not recommend using these simple hash functions for storing passwords securely.
Lesser hashing algorithms have their uses (like internal to an application, not for interchange), but they are known to be crackable.
From the oracle documentation, the below query explains it better
INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;
You can read this link
Your query would be as follows
//just the concept
INSERT INTO quotedb
(COLUMN_NAMES) //seperated by comma
SELECT COLUMN_NAMES FROM tickerdb,quotedb WHERE quotedb.ticker = tickerdb.ticker
Note: Make sure the columns in insert and select are in right position as per your requirement
Hope this helps!
I had a similar problem and was able to solve it by following the below approach (similar to other answers but needed credentials too),
1- add Microsoft.SharePointOnline.CSOM by tools->NuGet Package Manager->Manage NuGet Packages for solution->Browse-> select and install
2- Add "using Microsoft.SharePoint.Client; "
then the below code
string siteUrl = "https://yourcompany.sharepoint.com/sites/Yoursite";
SecureString passWord = new SecureString();
var password = "Your password here";
var securePassword = new SecureString();
foreach (char c in password)
{
securePassword.AppendChar(c);
}
ClientContext clientContext = new ClientContext(siteUrl);
clientContext.Credentials = new SharePointOnlineCredentials("[email protected]", securePassword);/*passWord*/
List oList = clientContext.Web.Lists.GetByTitle("The name of your list here");
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem oListItem = oList.AddItem(itemCreateInfo);
oListItem["PK"] = "1";
oListItem["Precinct"] = "Mangere";
oListItem["Title"] = "Innovation";
oListItem["Project_x005F_x0020_Name"] = "test from C#";
oListItem["Project_x005F_x0020_ID"] = "ID_123_from C#";
oListItem["Project_x005F_x0020_start_x005F_x0020_date"] = "2020-05-01 01:01:01";
oListItem.Update();
clientContext.ExecuteQuery();
Remember that your fields may be different with what you see, for example in my list I see "Project Name", while the actual value is "Project_x005F_x0020_ID". How to get these values (i.e. internal filed values)?
A few approaches:
1- Use MS flow and see them
2- https://mstechtalk.com/check-column-internal-name-sharepoint-list/ or https://sharepoint.stackexchange.com/questions/787/finding-the-internal-name-and-display-name-for-a-list-column
3- Use a C# reader and read your sharepoint list
The rest of operations (update/delete): https://docs.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ee539976(v%3Doffice.14)
u should add a theme
to ur all activities (u should add theme
for all application in ur <application>
in ur manifest)
but if u have set different theme to ur activity u can use :
android:theme="@style/Theme.AppCompat"
or each kind of AppCompat
theme!
Another possible reason is indirect reference. If a code references to a struct that not included in current c file, the compiler will complain.
a->b->c //error if b not included in current c file
Free to try with a nagging banner... DevExpress XtraReports and XRCharts. Very nice dev tool, great support, speaking from experience.
Yes it is, there have to be boolean expresion after IF. Here you have a direct link. I hope it helps. GL!
It may be in options. Here is the identical Java code.
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setHeadless(true);
WebDriver driver = new ChromeDriver(chromeOptions);
You can do it with the pause
command, example:
dir
pause
echo Now about to end...
pause
You may also use math.log1p
.
According to the official documentation :
math.log1p(x)
Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.
You may convert back to the original value using math.expm1
which returns e
raised to the power x, minus 1.
How about:
ACell.ListObject.DataBodyRange.Rows.Delete
That will keep your table structure and headings, but clear all the data and rows.
EDIT: I'm going to just modify a section of my answer from your previous post, as it does mostly what you want. This leaves just one row:
With loSource
.Range.AutoFilter
.DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
.DataBodyRange.Rows(1).Specialcells(xlCellTypeConstants).ClearContents
End With
If you want to leave all the rows intact with their formulas and whatnot, just do:
With loSource
.Range.AutoFilter
.DataBodyRange.Specialcells(xlCellTypeConstants).ClearContents
End With
Which is close to what @Readify suggested, except it won't clear formulas.
I would propose changing the function declaration as follows so you can do what you want:
function foo($blah, $x = null, $y = null) {
if (null === $x) {
$x = "some value";
}
if (null === $y) {
$y = "some other value";
}
code here!
}
This way, you can make a call like foo('blah', null, 'non-default y value');
and have it work as you want, where the second parameter $x
still gets its default value.
With this method, passing a null value means you want the default value for one parameter when you want to override the default value for a parameter that comes after it.
As stated in other answers,
default parameters only work as the last arguments to the function. If you want to declare the default values in the function definition, there is no way to omit one parameter and override one following it.
If I have a method that can accept varying numbers of parameters, and parameters of varying types, I often declare the function similar to the answer shown by Ryan P.
Here is another example (this doesn't answer your question, but is hopefully informative:
public function __construct($params = null)
{
if ($params instanceof SOMETHING) {
// single parameter, of object type SOMETHING
} elseif (is_string($params)) {
// single argument given as string
} elseif (is_array($params)) {
// params could be an array of properties like array('x' => 'x1', 'y' => 'y1')
} elseif (func_num_args() == 3) {
$args = func_get_args();
// 3 parameters passed
} elseif (func_num_args() == 5) {
$args = func_get_args();
// 5 parameters passed
} else {
throw new \InvalidArgumentException("Could not figure out parameters!");
}
}
First is you have to understand the difference between MyISAM
and InnoDB
Engines. And this is clearly stated on this link. You can use this sql statement if you want to convert InnoDB to MyISAM:
ALTER TABLE t1 ENGINE=MyISAM;
i think this solution is shorter and simpler than older answers. This is Js Code:
const navbar = document.querySelector('.nav-fixed');
window.onscroll = () => {
if (window.scrollY > 300) {
navbar.classList.add('nav-active');
} else {
navbar.classList.remove('nav-active');
}
};
And my css:
header.nav-fixed {
width: 100%;
position: fixed;
transition: 0.3s ease-in-out;
}
.nav-active {
background-color:#fff;
box-shadow: 5px -1px 12px -5px grey;
}
For those using TortoiseSVN, you can accomplish this by using the Repository Browser (it's labeled "Repo-browser" in the context menu.)
Find the branch folder you want to delete, right-click it, and select "Delete."
Enter your commit message, and you're done.
In my case conda Path was properly set (in .bashrc) by the conda installation bash. But to make it works I had to give executable file permissions to files in bin sub folder with chmod +x *
.
My system info:
conda 4.2.9
Operating System: Debian GNU/Linux 8 (jessie)
Kernel: Linux 3.16.0-4-amd64
Architecture: x86-64
git push
or
git push server_name master
should do the trick, after you have made a commit to your local repository.
You can try the following VBA code to export Macro contents directly without converting them to VBA first. Unlike Tables, Forms, Reports, and Modules, the Macros are in a container called Scripts. But they are there and can be exported and imported using SaveAsText and LoadFromText
Option Compare Database
Option Explicit
Public Sub ExportDatabaseObjects()
On Error GoTo Err_ExportDatabaseObjects
Dim db As Database
Dim d As Document
Dim c As Container
Dim sExportLocation As String
Set db = CurrentDb()
sExportLocation = "C:\SomeFolder\"
Set c = db.Containers("Scripts")
For Each d In c.Documents
Application.SaveAsText acMacro, d.Name, sExportLocation & "Macro_" & d.Name & ".txt"
Next d
An alternative object to use is as follows:
For Each obj In Access.Application.CurrentProject.AllMacros
Access.Application.SaveAsText acMacro, obj.Name, strFilePath & "\Macro_" & obj.Name & ".txt"
Next
After you've run the Inspect by Name, select all the locations, and make use of the Apply quick fixes to all the problems drop-down, and use either (or both) of Delete unused parameter(s) and Safe Delete.
Don't forget to hit Do Refactor afterwards.
Then you'll need to run another analysis, as the refactored code will no doubt reveal more unused declarations.
This is tailored to finding formulas but you should be able to expand it to general content by altering how you test the starting cells. You'll have to handle single cell ranges outside of this.
public static Range GetUsedPartOfRange(this Range range)
{
Excel.Range beginCell = range.Cells[1, 1];
Excel.Range endCell = range.Cells[range.Rows.Count, range.Columns.Count];
if (!beginCell.HasFormula)
{
var beginCellRow = range.Find(
"*",
beginCell,
XlFindLookIn.xlFormulas,
XlLookAt.xlPart,
XlSearchOrder.xlByRows,
XlSearchDirection.xlNext,
false);
var beginCellCol = range.Find(
"*",
beginCell,
XlFindLookIn.xlFormulas,
XlLookAt.xlPart,
XlSearchOrder.xlByColumns,
XlSearchDirection.xlNext,
false);
if (null == beginCellRow || null == beginCellCol)
return null;
beginCell = range.Worksheet.Cells[beginCellRow.Row, beginCellCol.Column];
}
if (!endCell.HasFormula)
{
var endCellRow = range.Find(
"*",
endCell,
XlFindLookIn.xlFormulas,
XlLookAt.xlPart,
XlSearchOrder.xlByRows,
XlSearchDirection.xlPrevious,
false);
var endCellCol = range.Find(
"*",
endCell,
XlFindLookIn.xlFormulas,
XlLookAt.xlPart,
XlSearchOrder.xlByColumns,
XlSearchDirection.xlPrevious,
false);
if (null == endCellRow || null == endCellCol)
return null;
endCell = range.Worksheet.Cells[endCellRow.Row, endCellCol.Column];
}
if (null == endCell || null == beginCell)
return null;
Excel.Range finalRng = range.Worksheet.Range[beginCell, endCell];
return finalRng;
}
}
Here is an easy and short method
document.getElementById('elementID').selectedOptions[0].innerHTML
Cleaner way is to use joi-browser package. In the state you should have errors object that includes all the errors in the form. Initially it shoud be set to an empty object. Create schema;
import Joi from "joi-browser";
schema = {
username: Joi.string()
.required()
.label("Username")
.email(),
password: Joi.string()
.required()
.label("Password")
.min(8)
.regex(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,1024}$/) //special/number/capital
};
Then validate the form with the schema:
validate = () => {
const options = { abortEarly: false };
const result = Joi.validate(this.state.data, this.schema, options);
console.log(data) // always analyze your data
if (!result.error) return null;
const errors = {};
for (let item of result.error.details) errors[item.path[0]] = item.message; //in details array, there are 2 properties,path and message.path is the name of the input, message is the error message for that input.
return errors;
};
Before submitting the form, check the form:
handleSubmit = e => {
e.preventDefault();
const errors = this.validate(); //will return an object
console.log(errors);
this.setState({ errors: errors || {} }); //in line 9 if we return {}, we dont need {} here
if (errors) return;
//so we dont need to call the server
alert("success");
//if there is no error call the server
this.dosubmit();
};
I got this issue when I used an ajax call to retrieve data from the database. When the controller returned the array it converted it to a boolean. The problem was that I had "invalid characters" like Ăş (u with accent).
If you're sharing code between C and C++, remember to add the following to the shared.h
file:
#ifdef __cplusplus
extern "C" {
#endif
extern int my_global;
/* other extern declarations ... */
#ifdef __cplusplus
}
#endif
I ran into this a couple times a quarter. This time I had a minimal change summary in my git diff and tracked the problem to a reset classpath (missing my WEB-INF/lib dependency) in eclipse. This seems to occur any time I pull in or pull out parent/sibling maven projects.
There are mentions of adding your spring jars to the tomcat web container lib - this is ok and is the way most EE servers run. However be aware that by placing spring higher in the classloader tree on tomcat you will be running higher than the classloader level of your war context. I recommend you leave the libs in a per/war lower level classloader.
We see the following after a truncated .classpath after a structural project change in eclipse.
Dec 18, 2016 11:13:39 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class org.springframework.web.context.request.RequestContextListener
java.lang.ClassNotFoundException: org.springframework.web.context.request.RequestContextListener
My classpath was reset and the WEB-INF/lib dependency was removed.
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
</attributes>
</classpathentry>
put back
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
and you will be OK.
thank you /michael
keydown
with event.key === "Backspace" or "Delete"
More recent and much cleaner: use event.key
. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
Modern style:
input.addEventListener('keydown', ({key}) => {
if (["Backspace", "Delete"].includes(key)) {
return false
}
})
For those who are looking for a date-only solution, it is:
import datetime
datetime.date.today().isoformat()
In Swift 3.01 using WKWebView:
let localURL = URL.init(fileURLWithPath: Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "CWP")!)
myWebView.load(NSURLRequest.init(url: localURL) as URLRequest)
This adjusts for some of the finer syntax changes in 3.01 and keeps the directory structure in place so you can embed related HTML files.
You're effectively scanning the list once to find the min value, then scanning it again to find the index, you can do both in one go:
from operator import itemgetter
min(enumerate(a), key=itemgetter(1))[0]
I never liked the way of asserting exceptions with Junit. If I use the "expected" in the annotation, seems from my point of view we're violating the "given, when, then" pattern because the "then" is placed at the top of the test definition.
Also, if we use "@Rule", we have to deal with so much boilerplate code. So, if you can install new libraries for your tests, I'd suggest to have a look to the AssertJ (that library now comes with SpringBoot)
Then a test which is not violating the "given/when/then" principles, and it is done using AssertJ to verify:
1 - The exception is what we're expecting. 2 - It has also an expected message
Will look like this:
@Test
void should_throwIllegalUse_when_idNotGiven() {
//when
final Throwable raisedException = catchThrowable(() -> getUserDAO.byId(null));
//then
assertThat(raisedException).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Id to fetch is mandatory");
}
char ch = 't';
char chArray[2];
sprintf(chArray, "%c", ch);
char chOutput[10]="tes";
strcat(chOutput, chArray);
cout<<chOutput;
OUTPUT:
test
I would suggest using absolute positioning within the element.
I've created this to help you visualize it a bit.
#parent {_x000D_
width:400px;_x000D_
height:400px;_x000D_
background-color:white;_x000D_
border:2px solid blue;_x000D_
position:relative;_x000D_
}_x000D_
#div1 {position:absolute;bottom:0;right:0;background:green;width:100px;height:100px;}_x000D_
#div2 {width:100px;height:100px;position:absolute;bottom:0;left:0;background:red;}_x000D_
#div3 {width:100px;height:100px;position:absolute;top:0;right:0;background:yellow;}_x000D_
#div4 {width:100px;height:100px;position:absolute;top:0;left:0;background:gray;}
_x000D_
<div id="parent">_x000D_
<div id="div1"></div>_x000D_
<div id="div2"></div>_x000D_
<div id="div3"></div>_x000D_
<div id="div4"></div>_x000D_
_x000D_
</div>
_x000D_
If the program you're using to execute your script needs parameters, you can put them at the end of the #! line:
#!/usr/bin/R --random --switches --f
Not knowing R, I can't test properly, but this seems to work:
axa@artemis:~$ cat r.test
#!/usr/bin/R -q -f
error
axa@artemis:~$ ./r.test
> #!/usr/bin/R -q -f
> error
Error: object "error" not found
Execution halted
axa@artemis:~$
They're commonly used as a verbose form of callback.
I suppose you could say they're an advantage compared to not having them, and having to create a named class every time, but similar concepts are implemented much better in other languages (as closures or blocks)
Here's a swing example
myButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// do stuff here...
}
});
Although it's still messily verbose, it's a lot better than forcing you to define a named class for every throw away listener like this (although depending on the situation and reuse, that may still be the better approach)
Probably AES. Blowfish was the direct predecessor to Twofish. Twofish was Bruce Schneier's entry into the competition that produced AES. It was judged as inferior to an entry named Rijndael, which was what became AES.
Interesting aside: at one point in the competition, all the entrants were asked to give their opinion of how the ciphers ranked. It's probably no surprise that each team picked its own entry as the best -- but every other team picked Rijndael as the second best.
That said, there are some basic differences in the basic goals of Blowfish vs. AES that can (arguably) favor Blowfish in terms of absolute security. In particular, Blowfish attempts to make a brute-force (key-exhaustion) attack difficult by making the initial key setup a fairly slow operation. For a normal user, this is of little consequence (it's still less than a millisecond) but if you're trying out millions of keys per second to break it, the difference is quite substantial.
In the end, I don't see that as a major advantage, however. I'd generally recommend AES. My next choices would probably be Serpent, MARS and Twofish in that order. Blowfish would come somewhere after those (though there are a couple of others that I'd probably recommend ahead of Blowfish).
In my case, i was not able to see logs because there is some text in Filter field, which caused results of console.log to disappear. Once we clear text in Filter field, it should show.
Animuson gives a decent way to do it, but no help on understanding it. I kept looking and came across a forum thread with this commands:
Echo Off
IF Not EXIST n:\dbfs\doekasp.txt GOTO DoNothing
copy n:\dbfs\doekasp.txt n:\history\doekasp.txt
Rem rename command is done twice (2) to allow for 1 or 2 digit hour,
Rem If before 10am (1digit) hour Rename starting at location (0) for (2) chars,
Rem will error out, as location (0) will have a space
Rem and space is invalid character for file name,
Rem so second remame will be used.
Rem
Rem if equal 10am or later (2 digit hour) then first remame will work and second will not
Rem as doekasp.txt will not be found (remamed)
ren n:\history\doekasp.txt doekasp-%date:~4,2%-%date:~7,2%-%date:~10,4%_@_%time:~0,2%h%time:~3,2%m%time:~6,2%s%.txt
ren n:\history\doekasp.txt doekasp-%date:~4,2%-%date:~7,2%-%date:~10,4%_@_%time:~1,1%h%time:~3,2%m%time:~6,2%s%.txt
I always name year first YYYYMMDD, but wanted to add time. Here you will see that he has given a reason why 0,2 will not work and 1,1 will, because (space) is an invalid character. This opened my eyes to the issue. Also, by default you're in 24hr mode.
I ended up with:
ren Logs.txt Logs-%date:~10,4%%date:~7,2%%date:~4,2%_%time:~0,2%%time:~3,2%.txt
ren Logs.txt Logs-%date:~10,4%%date:~7,2%%date:~4,2%_%time:~1,1%%time:~3,2%.txt
Output:
Logs-20121707_1019
????: Quote:
Usually the progress bar is either themed or honors the user's color preferences. So for changing the color you either need to turn off visual styles and set ForeColor
or draw the control yourself.
As for the continuous style instead of blocks you can set the Style
property:
pBar.Style = ProgressBarStyle.Continuous;
ProgressBarStyle.Continuous versus Blocks is useless with VistualStyles enabled...
Block(s) will only work with visual styles disabled ... which renders all of this a moot point (with regards to custom progress color) With vistual styles disabled ... the progress bar should be colored based on the forecolor.
I used a combination of William Daniel's answer (with visual styles enabled, so the ForeColor will not just be flat with no style) and Barry's answer (to custom text on the progress bar) from: How do I put text on ProgressBar?
You could remove the folder and update the parent directory before committing:
rm -r some_dir
svn update some_dir_parent
You need to loop over loadDT.Columns
, like this:
foreach (DataColumn column in loadDT.Columns)
{
Console.Write("Item: ");
Console.Write(column.ColumnName);
Console.Write(" ");
Console.WriteLine(row[column]);
}
Assuming no SecurityManager
is preventing you from doing this, you can use setAccessible
to get around private
and resetting the modifier to get rid of final
, and actually modify a private static final
field.
Here's an example:
import java.lang.reflect.*;
public class EverythingIsTrue {
static void setFinalStatic(Field field, Object newValue) throws Exception {
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
public static void main(String args[]) throws Exception {
setFinalStatic(Boolean.class.getField("FALSE"), true);
System.out.format("Everything is %s", false); // "Everything is true"
}
}
Assuming no SecurityException
is thrown, the above code prints "Everything is true"
.
What's actually done here is as follows:
boolean
values true
and false
in main
are autoboxed to reference type Boolean
"constants" Boolean.TRUE
and Boolean.FALSE
public static final Boolean.FALSE
to refer to the Boolean
referred to by Boolean.TRUE
false
is autoboxed to Boolean.FALSE
, it refers to the same Boolean
as the one refered to by Boolean.TRUE
"false"
now is "true"
static final File.separatorChar
for unit testingInteger
's cache, mutating a String
, etcExtreme care should be taken whenever you do something like this. It may not work because a SecurityManager
may be present, but even if it doesn't, depending on usage pattern, it may or may not work.
JLS 17.5.3 Subsequent Modification of Final Fields
In some cases, such as deserialization, the system will need to change the
final
fields of an object after construction.final
fields can be changed via reflection and other implementation dependent means. The only pattern in which this has reasonable semantics is one in which an object is constructed and then thefinal
fields of the object are updated. The object should not be made visible to other threads, nor should thefinal
fields be read, until all updates to thefinal
fields of the object are complete. Freezes of afinal
field occur both at the end of the constructor in which thefinal
field is set, and immediately after each modification of afinal
field via reflection or other special mechanism.Even then, there are a number of complications. If a
final
field is initialized to a compile-time constant in the field declaration, changes to thefinal
field may not be observed, since uses of thatfinal
field are replaced at compile time with the compile-time constant.Another problem is that the specification allows aggressive optimization of
final
fields. Within a thread, it is permissible to reorder reads of afinal
field with those modifications of a final field that do not take place in the constructor.
private static final boolean
, because it's inlineable as a compile-time constant and thus the "new" value may not be observableEssentially,
field.getModifiers() & ~Modifier.FINAL
turns off the bit corresponding to Modifier.FINAL
from field.getModifiers()
. &
is the bitwise-and, and ~
is the bitwise-complement.
Still not being able to solve this?, have fallen onto depression like I did for it? Does your code looks like this?
public class A {
private final String myVar = "Some Value";
}
Reading the comments on this answer, specially the one by @Pshemo, it reminded me that Constant Expressions are handled different so it will be impossible to modify it. Hence you will need to change your code to look like this:
public class A {
private final String myVar;
private A() {
myVar = "Some Value";
}
}
if you are not the owner of the class... I feel you!
For more details about why this behavior read this?
As in the answer of Escobar Ceaser, I suggest to use quotes arround the whole path. It's the common way to wrap the whole path in "", not only separate directory names within the path.
I had a similar issue that it didn't work for me. But it was no option to use "" within the path for separate directory names because the path contained environment variables, which theirself cover more than one directory hierarchies. The conclusion was that I missed the space between the closing " and the (
The correct version, with the space before the bracket, would be
If NOT exist "C:\Documents and Settings\John\Start Menu\Programs\Software Folder" (
start "\\filer\repo\lab\software\myapp\setup.exe"
pause
)
The simple thing is to put the script below the document, just before your closing </body>
tag:
<body>
<div id="main">
<div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
</div>
<script src="app.js"></script>
</body>
app.js file:
var main = new Vue({
el: '#main',
data: {
currentActivity: 'home'
}
});
Slowest and doesn't work in Python3: concatenate the items
and call dict
on the resulting list:
$ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
'd4 = dict(d1.items() + d2.items() + d3.items())'
100000 loops, best of 3: 4.93 usec per loop
Fastest: exploit the dict
constructor to the hilt, then one update
:
$ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
'd4 = dict(d1, **d2); d4.update(d3)'
1000000 loops, best of 3: 1.88 usec per loop
Middling: a loop of update
calls on an initially-empty dict:
$ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
'd4 = {}' 'for d in (d1, d2, d3): d4.update(d)'
100000 loops, best of 3: 2.67 usec per loop
Or, equivalently, one copy-ctor and two updates:
$ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
'd4 = dict(d1)' 'for d in (d2, d3): d4.update(d)'
100000 loops, best of 3: 2.65 usec per loop
I recommend approach (2), and I particularly recommend avoiding (1) (which also takes up O(N) extra auxiliary memory for the concatenated list of items temporary data structure).
Practical example:
Imagine that you are modelling something like an I2C bus (signals called SCL
for clock and SDA
for data), where the bus is tri-state and both nets have a weak pull-up. Your testbench should model the pull-up resistor on the PCB with a value of 'H'.
scl <= 'H'; -- Testbench resistor pullup
Your I2C master or slave devices can drive the bus to '1' or '0' or leave it alone by assigning a 'Z'
Assigning a '1' to the SCL net will cause an event to happen, because the value of SCL changed.
If you have a line of code that relies on (scl'event and scl =
'1')
, then you'll get a false trigger.
If you have a line of code that relies on rising_edge(scl)
, then
you won't get a false trigger.
Continuing the example: you assign a '0' to SCL, then assign a 'Z'. The SCL net goes to '0', then back to 'H'.
Here, going from '1' to '0' isn't triggering either case, but going from '0' to 'H' will trigger a rising_edge(scl)
condition (correct), but the (scl'event and scl = '1')
case will miss it (incorrect).
General Recommenation:
Use rising_edge(clk)
and falling_edge(clk)
instead of clk'event
for all code.
Adding a new answer to this as the question of printing PDF's in .net has been around for a long time and most of the answers pre-date the Google Pdfium library, which now has a .net wrapper. For me I was researching this problem myself and kept coming up blank, trying to do hacky solutions like spawning Acrobat or other PDF readers, or running into commercial libraries that are expensive and have not very compatible licensing terms. But the Google Pdfium library and the PdfiumViewer .net wrapper are Open Source so are a great solution for a lot of developers, myself included. PdfiumViewer is licensed under the Apache 2.0 license.
You can get the NuGet package here:
https://www.nuget.org/packages/PdfiumViewer/
and you can find the source code here:
https://github.com/pvginkel/PdfiumViewer
Here is some simple code that will silently print any number of copies of a PDF file from it's filename. You can load PDF's from a stream also (which is how we normally do it), and you can easily figure that out looking at the code or examples. There is also a WinForm PDF file view so you can also render the PDF files into a view or do print preview on them. For us I simply needed a way to silently print the PDF file to a specific printer on demand.
public bool PrintPDF(
string printer,
string paperName,
string filename,
int copies)
{
try {
// Create the printer settings for our printer
var printerSettings = new PrinterSettings {
PrinterName = printer,
Copies = (short)copies,
};
// Create our page settings for the paper size selected
var pageSettings = new PageSettings(printerSettings) {
Margins = new Margins(0, 0, 0, 0),
};
foreach (PaperSize paperSize in printerSettings.PaperSizes) {
if (paperSize.PaperName == paperName) {
pageSettings.PaperSize = paperSize;
break;
}
}
// Now print the PDF document
using (var document = PdfDocument.Load(filename)) {
using (var printDocument = document.CreatePrintDocument()) {
printDocument.PrinterSettings = printerSettings;
printDocument.DefaultPageSettings = pageSettings;
printDocument.PrintController = new StandardPrintController();
printDocument.Print();
}
}
return true;
} catch {
return false;
}
}
You can use the following queries to Backup and Restore, you must change the path for your backup
Database name=[data]
Backup:
BACKUP DATABASE [data] TO DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\data.bak' WITH NOFORMAT, NOINIT, NAME = N'data-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10
GO
Restore:
RESTORE DATABASE [data] FROM DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\data.bak' WITH FILE = 1, NOUNLOAD, REPLACE, STATS = 10
GO
For me following code work
$(function () {
debugger;
document.getElementById("FormId").addEventListener("submit", function (e) {
debugger;
if (ValidDateFrom()) { // Check Validation
var form = e.target;
if (form.getAttribute("enctype") === "multipart/form-data") {
debugger;
if (form.dataset.ajax) {
e.preventDefault();
e.stopImmediatePropagation();
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.onreadystatechange = function (result) {
debugger;
if (xhr.readyState == 4 && xhr.status == 200) {
debugger;
var responseData = JSON.parse(xhr.responseText);
SuccessMethod(responseData); // Redirect to your Success method
}
};
xhr.send(new FormData(form));
}
}
}
}, true);
});
In your Action Post Method, pass parameter as HttpPostedFileBase UploadFile and make sure your file input has same as mentioned in your parameter of the Action Method. It should work with AJAX Begin form as well.
Remember over here that your AJAX BEGIN Form will not work over here since you make your post call defined in the code mentioned above and you can reference your method in the code as per the Requirement
I know I am answering late but this is what worked for me
I encountered this problem too, reconnecting the WiFi can solve this.
For us ,we can check if the phone can resolve the host to IP when we start application. If it cannot resolve, tell the user to check the WiFi and then exit.
I hope it helps.
This is a highly inefficient way of doing it. You can use the merge
statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.
MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
UPDATE SET l.studName = s.studName
WHERE l.studName != s.studName
WHEN NOT MATCHED THEN
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)
Make sure you commit
, once completed, in order to be able to see this in the database.
To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.
It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.
However, as I say this will not be as efficient as merge
.
declare
cursor c_data is
select b.rowid as rid, a.studId, a.studName
from student a
left outer join studLoad b
on a.studId = b.studId
and a.studName <> b.studName
;
type t__data is table of c_data%rowtype index by binary_integer;
t_data t__data;
begin
open c_data;
loop
fetch c_data bulk collect into t_data limit 10000;
exit when t_data.count = 0;
for idx in t_data.first .. t_data.last loop
if t_data(idx).rid is null then
insert into studLoad (studId, studName)
values (t_data(idx).studId, t_data(idx).studName);
else
update studLoad
set studName = t_data(idx).studName
where rowid = t_data(idx).rid
;
end if;
end loop;
end loop;
close c_data;
end;
/
Resources in Scala work exactly as they do in Java.
It is best to follow the Java best practices and put all resources in src/main/resources
and src/test/resources
.
Example folder structure:
testing_styles/
+-- build.sbt
+-- src
¦  +-- main
¦  +-- resources
¦  ¦  +-- readme.txt
To read resources the object Source provides the method fromResource.
import scala.io.Source
val readmeText : Iterator[String] = Source.fromResource("readme.txt").getLines
To read resources you can use getClass.getResource and getClass.getResourceAsStream .
val stream: InputStream = getClass.getResourceAsStream("/readme.txt")
val lines: Iterator[String] = scala.io.Source.fromInputStream( stream ).getLines
To avoid undebuggable Java NPEs, consider:
import scala.util.Try
import scala.io.Source
import java.io.FileNotFoundException
object Example {
def readResourceWithNiceError(resourcePath: String): Try[Iterator[String]] =
Try(Source.fromResource(resourcePath).getLines)
.recover(throw new FileNotFoundException(resourcePath))
}
Keep in mind that getResourceAsStream also works fine when the resources are part of a jar, getResource, which returns a URL which is often used to create a file can lead to problems there.
In production code I suggest to make sure that the source is closed again.
Version 0.7.7 of Socket.IO now claims to return the client's IP address. I've had success with:
var socket = io.listen(server);
socket.on('connection', function (client) {
var ip_address = client.connection.remoteAddress;
}
I already had this same issue and I've got the solution writing a container (.divtagABS-container, in your case) absolutely positioned and then relatively positioning the content inside it (.divtagABS, in your case).
Done! The margin-left and margin-right AUTO for your .divtagABS will now work.
If we have a code:
<div id="myDiv" class="myClass myClass2"></div>
to take class name by using jQuery we could define and use a simple plugin method:
$.fn.class = function(){
return Array.prototype.slice.call( $(this)[0].classList );
}
or
$.fn.class = function(){
return $(this).prop('class');
}
The use of the method will be:
$('#myDiv').class();
We have to notice that it will return a list of classes unlike of native method element.className which returns only first class of the attached classes. Because often the element has more than one class attached to it, I recommend you not to use this native method but element.classlist or the method described above.
The first variant of it will return a list of classes as an array, the second as a string - class names separated by spaces:
// [myClass, myClass2]
// "myClass myClass2"
Another important notice is that both methods as well as jQuery method
$('div').prop('class');
return only class list of the first element caught by the jQuery object if we use a more common selector which points many other elements. In such a case we have to mark the element, we want to get his classes, by using some index, e.g.
$('div:eq(2)').prop('class');
It depends also what you need to do with these classes. If you want just to check for a class into the class list of the element with this id you should just use method "hasClass":
if($('#myDiv').hasClass('myClass')){
// do something
}
as mentioned in the comments above. But if you could need to take all classes as a selector, then use this code:
$.fn.classes = function(){
var o = $(this);
return o.prop('class')? [''].concat( o.prop('class').split(' ') ).join('.') : '';
}
var mySelector = $('#myDiv').classes();
The result will be:
// .myClass.myClass2
and you could get it to create dynamically a specific rewriting css rule for example.
Regards
Go here and download and unzip to an easy location:
http://developer.android.com/sdk/win-usb.html#top Download and install
As an addition to e.g. @Intrepidd s answer, in certain situations you want to use fetch
instead of []
. For fetch
not to throw an exception when the key is not found, pass it a default value.
puts "ok" if hash.fetch('key', nil) == 'X'
Reference: https://docs.ruby-lang.org/en/2.3.0/Hash.html .
It sounds like you want to convert the rownames to a proper column of the data.frame. eg:
# add the rownames as a proper column
myDF <- cbind(Row.Names = rownames(myDF), myDF)
myDF
# Row.Names id val vr2
# row_one row_one A 1 23
# row_two row_two A 2 24
# row_three row_three B 3 25
# row_four row_four C 4 26
If you want to then remove the original rownames:
rownames(myDF) <- NULL
myDF
# Row.Names id val vr2
# 1 row_one A 1 23
# 2 row_two A 2 24
# 3 row_three B 3 25
# 4 row_four C 4 26
Alternatively, if all of your data is of the same class (ie, all numeric, or all string), you can convert to Matrix and name the dimnames
myMat <- as.matrix(myDF)
names(dimnames(myMat)) <- c("Names.of.Rows", "")
myMat
# Names.of.Rows id val vr2
# row_one "A" "1" "23"
# row_two "A" "2" "24"
# row_three "B" "3" "25"
# row_four "C" "4" "26"
First of all, link_to is a html tag helper, its second argument is the url, followed by html_options. What you would like is to pass account_id as a url parameter to the path. If you have set up named routes correctly in routes.rb, you can use path helpers.
link_to "+ Service", new_my_service_path(:account_id => acct.id)
I think the best practice is to pass model values as a param nested within :
link_to "+ Service", new_my_service_path(:my_service => { :account_id => acct.id })
# my_services_controller.rb
def new
@my_service = MyService.new(params[:my_service])
end
And you need to control that account_id is allowed for 'mass assignment'. In rails 3 you can use powerful controls to filter valid params within the controller where it belongs. I highly recommend.
http://apidock.com/rails/ActiveModel/MassAssignmentSecurity/ClassMethods
Also note that if account_id is not freely set by the user (e.g., a user can only submit a service for the own single account_id, then it is better practice not to send it via the request, but set it within the controller by adding something like:
@my_service.account_id = current_user.account_id
You can surely combine the two if you only allow users to create service on their own account, but allow admin to create anyone's by using roles in attr_accessible.
hope this helps
I think you have putted e.preventDefault(); before ajax call that's why its prevent calling of that function and your Ajax call will not call.
So try to remove that e.prevent Default() before Ajax call and add it to the after Ajax call.
Tab Control gives nice control in a similar manner to that described in your question.
Also nice, for JavaScript developers, is ESLint Tab Length for using ESLint config.
Or if you're using an .editorconfig
for defining project-specific indentation rules, there is EditorConfig
There is a change in syntax from Python 2 to Python 3. In Python 2,
print "Hello, World!"
will work but in Python 3, use parentheses as
print("Hello, World!")
This is equivalent syntax to Scala and near to Java.
Using nltk.
from nltk.tokenize import sent_tokenize, word_tokenize
sentences = sent_tokenize("This is a string.")
words_in_each_sentence = word_tokenize(sentences)
You may use TweetTokenizer for parsing casual text with emoticons and such.
The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.
According to this Google blogpost:
It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.
When referencing the mipmap- folders ensure you are using the following reference:
android:icon="@mipmap/ic_launcher"
The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.
I think a simpler and faster approach is iterate by each character of the alphabet:
DECLARE @i int
SET @i = 0
WHILE(@i < 256)
BEGIN
IF char(@i) NOT IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.')
UPDATE Table SET Column = replace(Column, char(@i), '')
SET @i = @i + 1
END
I would point a beginner to the Wiki article on the Main function, then supplement it with this.
Java only starts running a program with the specific public static void main(String[] args)
signature, and one can think of a signature like their own name - it's how Java can tell the difference between someone else's main()
and the one true main()
.
String[] args
is a collection of String
s, separated by a space, which can be typed into the program on the terminal. More times than not, the beginner isn't going to use this variable, but it's always there just in case.
more generally, for standard errors on any other parameter, you can use the boot package for bootstrap simulations (or write them on your own)
Pluto's idea in a nicer way:
CustomWebViewPage.cs:
public abstract class CustomWebViewPage<TModel> : WebViewPage<TModel> {
public IHtmlString PartialWithScripts(string partialViewName, object model) {
return Html.Partial(partialViewName: partialViewName, model: model, viewData: new ViewDataDictionary { ["view"] = this, ["html"] = Html });
}
public void RenderScriptsInBasePage(HelperResult scripts) {
var parentView = ViewBag.view as WebPageBase;
var parentHtml = ViewBag.html as HtmlHelper;
parentView.DefineSection("scripts", () => {
parentHtml.ViewContext.Writer.Write(scripts.ToHtmlString());
});
}
}
Views\web.config:
<pages pageBaseType="Web.Helpers.CustomWebViewPage">
View:
@PartialWithScripts("_BackendSearchForm")
Partial (_BackendSearchForm.cshtml):
@{ RenderScriptsInBasePage(scripts()); }
@helper scripts() {
<script>
//code will be rendered in a "scripts" section of the Layout page
</script>
}
Layout page:
@RenderSection("scripts", required: false)
<select id="select">_x000D_
<optgroup label="select one option">_x000D_
<option>one</option> _x000D_
<option>two</option> _x000D_
<option>three</option> _x000D_
<option>four</option> _x000D_
<option>five</option>_x000D_
</optgroup>_x000D_
</select>
_x000D_
It all sounded like a lot of hard work to me, when optgroup gives you what you need - at least I think it does.
Here is a minimal example using moviepy. For me this was the easiest solution.
import os
import moviepy.video.io.ImageSequenceClip
image_folder='folder_with_images'
fps=1
image_files = [image_folder+'/'+img for img in os.listdir(image_folder) if img.endswith(".png")]
clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(image_files, fps=fps)
clip.write_videofile('my_video.mp4')
Martijn's method as a prototype function:
String.prototype.escape = function() {
var tagsToReplace = {
'&': '&',
'<': '<',
'>': '>'
};
return this.replace(/[&<>]/g, function(tag) {
return tagsToReplace[tag] || tag;
});
};
var a = "<abc>";
var b = a.escape(); // "<abc>"
In python the with
keyword is used when working with unmanaged resources (like file streams). It is similar to the using
statement in VB.NET and C#. It allows you to ensure that a resource is "cleaned up" when the code that uses it finishes running, even if exceptions are thrown. It provides 'syntactic sugar' for try/finally
blocks.
From Python Docs:
The
with
statement clarifies code that previously would usetry...finally
blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.The
with
statement is a control-flow structure whose basic structure is:with expression [as variable]: with-block
The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has
__enter__()
and__exit__()
methods).
Update fixed VB callout per Scott Wisniewski's comment. I was indeed confusing with
with using
.
If you create your database in direct admin or cpanel, you must edit your sql with notepad or notepad++ and change CREATE DATABASE
command to CREATE DATABASE IF NOT EXISTS
in line22
This can be easily achieved via flex container.
.container{
width: 100%;
display: flex;
height: 100vh;
justify-content: center;
}
.item{
align-self: center;
}
server.session.timeout
in the application.properties
file is now deprecated. The correct setting is:
server.servlet.session.timeout=60s
Also note that Tomcat will not allow you to set the timeout any less than 60 seconds. For details about that minimum setting see https://github.com/spring-projects/spring-boot/issues/7383.
You can issue the INFO command, which returns information and statistics about the server. See here for an example output.
As mentioned in the comments by mVChr, you can use info keyspace
directly on the redis-cli.
redis> INFO
# Server
redis_version:6.0.6
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:b63575307aaffe0a
redis_mode:standalone
os:Linux 5.4.0-1017-aws x86_64
arch_bits:64
multiplexing_api:epoll
atomicvar_api:atomic-builtin
gcc_version:9.3.0
process_id:2854672
run_id:90a5246f10e0aeb6b02cc2765b485d841ffc924e
tcp_port:6379
uptime_in_seconds:2593097
uptime_in_days:30
hz:10
configured_hz:10
lru_clock:4030200
executable:/usr/local/bin/redis-server
Try this : (http://jsfiddle.net/TpqVx/)
.left-div {
float: left;
width: 100px;
/*height: 20px;*/
margin-right: 8px;
background-color: linen;
}
.right-div {
margin-left: 108px;
background-color: lime;
}??
<div class="left-div">
</div>
<div class="right-div">
My requirements are <b>[A]</b> Content in the two divs should line up at the top, <b>[B]</b> Long text in right-div should not wrap underneath left-div, and <b>[C]</b> I do not want to specify a width of right-div. I don't want to set the width of right-div because this markup needs to work within different widths.
</div>
<div style='clear:both;'> </div>
Hints :
float:left
in your left-most div only.height
, but anyway...<div 'clear:both'> </div>
after your last div.I advise you to use the shadowColor and shadowOffset properties of UILabel:
UILabel* label = [[UILabel alloc] init];
label.shadowColor = [UIColor whiteColor];
label.shadowOffset = CGSizeMake(0,1);
You can use:
f.Controls[name];
Where f
is your form variable. That gives you the control with name name
.
There's no goto
instruction in the Python programming language. You'll have to write your code in a structured way... But really, why do you want to use a goto
? that's been considered harmful for decades, and any program you can think of can be written without using goto
.
Of course, there are some cases where an unconditional jump might be useful, but it's never mandatory, there will always exist a semantically equivalent, structured solution that doesn't need goto
.
If you use Windows PowerShell, you could type "git" and the press F8. Continue to press F8 to cycle through all your git commands.
Or, if you use cygwin, you could do the same thing with ^R.
I recommend trying Kestrel, it's fast and simple as Beanstalk but supports fanout queues. Speaks memcached. It's built using Scala and used at Twitter.
Just an update for Mysqli users :
$base= mysqli_connect($dbhost, $dbuser, $dbpass, $dbbase);
if (mysqli_connect_errno())
die('Could not connect: ' . mysql_error());
$return_arr = array();
if ($result = mysqli_query( $base, $sql )){
while ($row = mysqli_fetch_assoc($result)) {
$row_array['id'] = $row['id'];
$row_array['col1'] = $row['col1'];
$row_array['col2'] = $row['col2'];
array_push($return_arr,$row_array);
}
}
mysqli_close($base);
echo json_encode($return_arr);
Just came across the same problem on a freshly installed CentOS 6.4 64-bit machine. A single yum command will fix this plus 99% of similar problems:
yum groupinstall "Compatibility libraries"
Either prefix this with 'sudo' or run as root, whichever works best for you.
Try this simple function to add an dictionary item if it does not exist or update when it exists:
public void AddOrUpdateDictionaryEntry(string key, int value)
{
if (dict.ContainsKey(key))
{
dict[key] = value;
}
else
{
dict.Add(key, value);
}
}
This is the same as dict[key] = value.
The code below is the combination of Chintan Panchal's answer along with Antoine Leclair's comment (placing the code in the windows resize event). (I didn't need the debounce mentioned by Antoine Leclair, however that could be a best practice.)
$(window).resize( function() {
$("#example").DataTable().columns.adjust().draw();
});
This was the approach that worked in my case.
The Y in atan2 is, by default, the first parameter. Here is the documentation. You will need to switch your inputs to get the correct bearing angle.
bearing = atan2(sin(lon2-lon1)*cos(lat2), cos(lat1)*sin(lat2)in(lat1)*cos(lat2)*cos(lon2-lon1))
bearing = degrees(bearing)
bearing = (bearing + 360) % 360
Apache has 2 types of MPM (Multi-Processing Modules) defined:
1:Prefork 2: Worker
By default, Apacke is configured in preforked mode i.e. non-threaded pre-forking web server. That means that each Apache child process contains a single thread and handles one request at a time. Because of that, it consumes more resources.
Apache also has the worker MPM that turns Apache into a multi-process, multi-threaded web server. Worker MPM uses multiple child processes with many threads each.
A portable approach that works equally well on Linux or Windows (where there is no /dev/null):
echo | gcc -dM -E -
For c++ you may use (replace c++11
with whatever version you use):
echo | gcc -x c++ -std=c++11 -dM -E -
It works by telling gcc to preprocess stdin (which is produced by echo) and print all preprocessor defines (search for -dletters
). If you want to know what defines are added when you include a header file you can use -dD
option which is similar to -dM but does not include predefined macros:
echo "#include <stdlib.h>" | gcc -x c++ -std=c++11 -dD -E -
Note, however, that empty input still produces lots of defines with -dD
option.
Simply it's work fine, in HTML:
<button type="button" id="btn_CommitAll"class="btn_CommitAll">save</button>
In JQuery side put this function for disable button:
function disableButton() {
$('.btn_CommitAll').prop("disabled", true);
}
For enable button:
function enableButton() {
$('.btn_CommitAll').prop("disabled", false);
}
That's all.
use this to clear the previous keyboard buffer before scanning the string it will solve your problem scanner.nextLine();//this is to clear the keyboard buffer
If you are using SQL Server 2016 or newer, you can also select it as JSON result and display it in JSON Visualizer, it's much easier to read it than in XML and allows you to filter results.
DECLARE @v nvarchar(max) = (SELECT * FROM Suppliers FOR JSON AUTO)
There are two ways to go about this. You can either use the IDE to generate a WSDL, or you can do it via the command line.
1. To create it via the IDE:
In the solution explorer pane, right click on the project that you would like to add the Service to:
Then, you can enter the path to your service WSDL and hit go:
2. To create it via the command line:
Open a VS 2010 Command Prompt (Programs -> Visual Studio 2010 -> Visual Studio Tools)
Then execute:
WSDL /verbose C:\path\to\wsdl
WSDL.exe will then output a .cs file for your consumption.
If you have other dependencies that you received with the file, such as xsd's, add those to the argument list:
WSDL /verbose C:\path\to\wsdl C:\path\to\some\xsd C:\path\to\some\xsd
If you need VB output, use /language:VB
in addition to the /verbose
.
void main ()
{
int temp,integer,count=0,i,cnd=0;
char ascii[10]={0};
printf("enter a number");
scanf("%d",&integer);
if(integer>>31)
{
/*CONVERTING 2's complement value to normal value*/
integer=~integer+1;
for(temp=integer;temp!=0;temp/=10,count++);
ascii[0]=0x2D;
count++;
cnd=1;
}
else
for(temp=integer;temp!=0;temp/=10,count++);
for(i=count-1,temp=integer;i>=cnd;i--)
{
ascii[i]=(temp%10)+0x30;
temp/=10;
}
printf("\n count =%d ascii=%s ",count,ascii);
}
-- If you are using a variable for the database name.
-- Try something like this.
DECLARE @DBName varchar(50)
Set @DBName = 'Database1'; /* could be passed in by a parameter. */
IF( @DBName = 'Database1')
Begin
USE [Database1];
SELECT FROM Table1;
End
IF( @DBName = 'Database2')
Begin
USE [Database2];
SELECT FROM Table2;
End
IF( @DBName is null)
Begin
USE [Database1];
End
a = '1000' # also tested for 'abc100', 'a100bc', '100abc'
isinstance(a, str) or isinstance(a, unicode)
returns True
type(a) in [str, unicode]
returns True
Please Download from this
https://www.enterprisedb.com/downloads/postgres-postgresql-downloads
install above downloaded file
then
The solution was simply to delete %appdata%\pgAdmin (win key + r then type %appdata% got folder pgAdmin) which was created by an earlier version. On systems other than Windows, there probably is a pgAdmin directory in your user directory. Of course, all session settings etc. are gone after deleting this.
I think the best example would be using services. Let's say that I want to grab data from my server when my component gets 'Activated'. Let's say that I also want to do some additional things to the data after I get it from the server, maybe I get an error and want to log it differently.
It is really easy with ngOnInit over a constructor, it also limits how many callback layers I need to add to my application.
For Example:
export class Users implements OnInit{
user_list: Array<any>;
constructor(private _userService: UserService){
};
ngOnInit(){
this.getUsers();
};
getUsers(){
this._userService.getUsersFromService().subscribe(users => this.user_list = users);
};
}
with my constructor I could just call my _userService and populate my user_list, but maybe I want to do some extra things with it. Like make sure everything is upper_case, I am not entirely sure how my data is coming through.
So it makes it much easier to use ngOnInit.
export class Users implements OnInit{
user_list: Array<any>;
constructor(private _userService: UserService){
};
ngOnInit(){
this.getUsers();
};
getUsers(){
this._userService.getUsersFromService().subscribe(users => this.user_list = users);
this.user_list.toUpperCase();
};
}
It makes it much easier to see, and so I just call my function within my component when I initialize instead of having to dig for it somewhere else. Really it's just another tool you can use to make it easier to read and use in the future. Also I find it really bad practice to put function calls within a constructor!
str[a:b]
tl;dr: use a colon :
instead of a comma in between the two indices a
and b
in str[a:b]
When working with strings and slice notation (a common sequence operation), it can happen that a TypeError
is raised, pointing out that the indices must be integers, even if they obviously are.
>>> my_string = "hello world"
>>> my_string[0,5]
TypeError: string indices must be integers
We obviously passed two integers for the indices to the slice notation, right? So what is the problem here?
This error can be very frustrating - especially at the beginning of learning Python - because the error message is a little bit misleading.
We implicitly passed a tuple of two integers (0 and 5) to the slice notation when we called my_string[0,5]
because 0,5
(even without the parentheses) evaluates to the same tuple as (0,5)
would do.
A comma ,
is actually enough for Python to evaluate something as a tuple:
>>> my_variable = 0,
>>> type(my_variable)
<class 'tuple'>
So what we did there, this time explicitly:
>>> my_string = "hello world"
>>> my_tuple = 0, 5
>>> my_string[my_tuple]
TypeError: string indices must be integers
Now, at least, the error message makes sense.
We need to replace the comma ,
with a colon :
to separate the two integers correctly:
>>> my_string = "hello world"
>>> my_string[0:5]
'hello'
A clearer and more helpful error message could have been something like:
TypeError: string indices must be integers (not tuple)
A good error message shows the user directly what they did wrong and it would have been more obvious how to solve the problem.
[So the next time when you find yourself responsible for writing an error description message, think of this example and add the reason or other useful information to error message to let you and maybe other people understand what went wrong.]
:
to separate its indices (and step range, e.g. str[from:to:step]
),
(e.g. t = 1,
)Cheers and happy programming
winklerrr
[I know this question was already answered and this wasn't exactly the question the thread starter asked, but I came here because of the above problem which leads to the same error message. At least it took me quite some time to find that little typo.
So I hope that this will help someone else who stumbled upon the same error and saves them some time finding that tiny mistake.]
From http://en.wikipedia.org/wiki/Printf_format_string
use 0 instead of spaces to pad a field when the width option is specified. For example, printf("%2d", 3)
results in " 3", while printf("%02d", 3)
results in "03".
If you're using Ubuntu, run sudo apt install libssl-dev
.
To check column exists
select column_name as found
from user_tab_cols
where table_name = '__TABLE_NAME__'
and column_name = '__COLUMN_NAME__'
What I believe you're looking for is a way to work with arrays as object values:
var o = {} // empty Object
var key = 'Orientation Sensor';
o[key] = []; // empty Array, which you can push() values into
var data = {
sampleTime: '1450632410296',
data: '76.36731:3.4651554:0.5665419'
};
var data2 = {
sampleTime: '1450632410296',
data: '78.15431:0.5247617:-0.20050584'
};
o[key].push(data);
o[key].push(data2);
This is standard JavaScript and not something NodeJS specific. In order to serialize it to a JSON string you can use the native JSON.stringify
:
JSON.stringify(o);
//> '{"Orientation Sensor":[{"sampleTime":"1450632410296","data":"76.36731:3.4651554:0.5665419"},{"sampleTime":"1450632410296","data":"78.15431:0.5247617:-0.20050584"}]}'
DELIMITER $$
DROP TRIGGER IF EXISTS `setEditStatus`$$
CREATE TRIGGER `setEditStatus` **BEFORE** INSERT on ACCOUNTS
FOR EACH ROW BEGIN
SET NEW.STATUS = 'E';
END$$
DELIMITER ;
It's hard for us to bind a specific USB device to a docker container which is also specific. As you can see, the recommended way to achieve is:
docker run -t -i --privileged -v /dev/bus/usb:/dev/bus/usb ubuntu bash
It will bind all the devices to this container. It's unsafe. Every containers were granted to operate all of them.
Another way is binding devices by devpath. It may looks like:
docker run -t -i --privileged -v /dev/bus/usb/001/002:/dev/bus/usb/001/002 ubuntu bash
or --device
(better, no privileged
):
docker run -t -i --device /dev/bus/usb/001/002 ubuntu bash
Much safer. But actually it is hard to know what the devpath of a specific device is.
I have wrote this repo to solve this problem.
https://github.com/williamfzc/usb2container
After deploying this server, you can easily get all the connected devices' information via HTTP request:
curl 127.0.0.1:9410/api/device
and get:
{
"/devices/pci0000:00/0000:00:14.0/usb1/1-13": {
"ACTION": "add",
"DEVPATH": "/devices/pci0000:00/0000:00:14.0/usb1/1-13",
"DEVTYPE": "usb_device",
"DRIVER": "usb",
"ID_BUS": "usb",
"ID_FOR_SEAT": "xxxxx",
"ID_MODEL": "xxxxx",
"ID_MODEL_ID": "xxxxx",
"ID_PATH": "xxxxx",
"ID_PATH_TAG": "xxxxx",
"ID_REVISION": "xxxxx",
"ID_SERIAL": "xxxxx",
"ID_SERIAL_SHORT": "xxxxx",
"ID_USB_INTERFACES": "xxxxx",
"ID_VENDOR": "xxxxx",
"ID_VENDOR_ENC": "xxxxx",
"ID_VENDOR_FROM_DATABASE": "",
"ID_VENDOR_ID": "xxxxx",
"INTERFACE": "",
"MAJOR": "189",
"MINOR": "119",
"MODALIAS": "",
"PRODUCT": "xxxxx",
"SEQNUM": "xxxxx",
"SUBSYSTEM": "usb",
"TAGS": "",
"TYPE": "0/0/0",
"USEC_INITIALIZED": "xxxxx",
"adb_user": "",
"_empty": false,
"DEVNAME": "/dev/bus/usb/001/120",
"BUSNUM": "001",
"DEVNUM": "120",
"ID_MODEL_ENC": "xxxxx"
},
...
}
and bind them to your containers. For example, you can see the DEVNAME of this device is /dev/bus/usb/001/120
:
docker run -t -i --device /dev/bus/usb/001/120 ubuntu bash
Maybe it will help.
It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.
Edit: This is what the forums say:
By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.
To disable:
/system/bin/bugmailer.sh must be deleted/renamed.
There should be a folder on your SD card called "bug reports".
Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948
And this one: http://forum.xda-developers.com/showthread.php?t=1405639
Unless there is some other requirement not specified, I would simply convert your color image to grayscale and work with that only (no need to work on the 3 channels, the contrast present is too high already). Also, unless there is some specific problem regarding resizing, I would work with a downscaled version of your images, since they are relatively large and the size adds nothing to the problem being solved. Then, finally, your problem is solved with a median filter, some basic morphological tools, and statistics (mostly for the Otsu thresholding, which is already done for you).
Here is what I obtain with your sample image and some other image with a sheet of paper I found around:
The median filter is used to remove minor details from the, now grayscale, image. It will possibly remove thin lines inside the whitish paper, which is good because then you will end with tiny connected components which are easy to discard. After the median, apply a morphological gradient (simply dilation
- erosion
) and binarize the result by Otsu. The morphological gradient is a good method to keep strong edges, it should be used more. Then, since this gradient will increase the contour width, apply a morphological thinning. Now you can discard small components.
At this point, here is what we have with the right image above (before drawing the blue polygon), the left one is not shown because the only remaining component is the one describing the paper:
Given the examples, now the only issue left is distinguishing between components that look like rectangles and others that do not. This is a matter of determining a ratio between the area of the convex hull containing the shape and the area of its bounding box; the ratio 0.7 works fine for these examples. It might be the case that you also need to discard components that are inside the paper, but not in these examples by using this method (nevertheless, doing this step should be very easy especially because it can be done through OpenCV directly).
For reference, here is a sample code in Mathematica:
f = Import["http://thwartedglamour.files.wordpress.com/2010/06/my-coffee-table-1-sa.jpg"]
f = ImageResize[f, ImageDimensions[f][[1]]/4]
g = MedianFilter[ColorConvert[f, "Grayscale"], 2]
h = DeleteSmallComponents[Thinning[
Binarize[ImageSubtract[Dilation[g, 1], Erosion[g, 1]]]]]
convexvert = ComponentMeasurements[SelectComponents[
h, {"ConvexArea", "BoundingBoxArea"}, #1 / #2 > 0.7 &],
"ConvexVertices"][[All, 2]]
(* To visualize the blue polygons above: *)
Show[f, Graphics[{EdgeForm[{Blue, Thick}], RGBColor[0, 0, 1, 0.5],
Polygon @@ convexvert}]]
If there are more varied situations where the paper's rectangle is not so well defined, or the approach confuses it with other shapes -- these situations could happen due to various reasons, but a common cause is bad image acquisition -- then try combining the pre-processing steps with the work described in the paper "Rectangle Detection based on a Windowed Hough Transform".
You could use position:fixed;
to bottom
.
eg:
#footer{
position:fixed;
bottom:0;
left:0;
}
As the documentation says, this method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)". This means that you will get numbers from 0 to 9 in your case. So you've done everything correctly by adding one to that number.
Generally speaking, if you need to generate numbers from min
to max
(including both), you write
random.nextInt(max - min + 1) + min
This script will read lines from large file and write to new small files. Will duplicate the header of the first line (Header) to all child files
Dim strLine
lCounter = 1
fCounter = 1
cPosition = 1
MaxLine = 1000
splitAt = MaxLine
Dim fHeader
sFile = "inputFile.txt"
dFile = LEFT(sFile, (LEN(sFile)-4))& "_0" & fCounter & ".txt"
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile(sFile,1)
Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
do while not objFileToRead.AtEndOfStream
strLine = objFileToRead.ReadLine()
objFileToWrite.WriteLine(strLine)
If cPosition = 1 Then
fHeader = strLine
End If
If cPosition = splitAt Then
fCounter = fCounter + 1
splitAt = splitAt + MaxLine
objFileToWrite.Close
Set objFileToWrite = Nothing
If fCounter < 10 Then
dFile=LEFT(dFile, (LEN(dFile)-5))& fCounter & ".txt"
Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
objFileToWrite.WriteLine(fHeader)
ElseIf fCounter <100 Or fCounter = 100 Then
dFile=LEFT(dFile, (LEN(dFile)-6))& fCounter & ".txt"
Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
objFileToWrite.WriteLine(fHeader)
Else
dFile=LEFT(dFile, (LEN(dFile)-7)) & fCounter & ".txt"
Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
objFileToWrite.WriteLine(fHeader)
End If
End If
lCounter=lCounter + 1
cPosition=cPosition + 1
Loop
objFileToWrite.Close
Set objFileToWrite = Nothing
objFileToRead.Close
Set objFileToRead = Nothing
NULL-safe condition would looks like:
select * from table
where NOT (tester <=> 'username')
Anything that is not stored on an EBS volume that is mounted to the instance will be lost.
For example, if you mount your EBS volume at /mystuff
, then anything not in /mystuff
will be lost. If you don't mount an ebs volume and save stuff on it, then I believe everything will be lost.
You can create an AMI from your current machine state, which will contain everything in your ephemeral storage. Then, when you launch a new instance based on that AMI it will contain everything as it is now.
Update: to clarify based on comments by mattgmg1990 and glenn bech:
Note that there is a difference between "stop" and "terminate". If you "stop" an instance that is backed by EBS then the information on the root volume will still be in the same state when you "start" the machine again. According to the documentation, "By default, the root device volume and the other Amazon EBS volumes attached when you launch an Amazon EBS-backed instance are automatically deleted when the instance terminates" but you can modify that via configuration.
You should be pointing it towards the Developer
directory, not the Xcode application bundle. Run this:
sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.
Why not just use:
$("#foo span")
or
$("#foo > span")
$('span', $('#foo'));
works fine on my machine ;)
I ran into this issue. I had three folders in the same directory so I had to specify which folder. Ex: from Folder import script
I would say parsing it is the only way you can really entirely tell. Exception will be raised by python's json.loads()
function (almost certainly) if not the correct format. However, the the purposes of your example you can probably just check the first couple of non-whitespace characters...
I'm not familiar with the JSON that facebook sends back, but most JSON strings from web apps will start with a open square [
or curly {
bracket. No images formats I know of start with those characters.
Conversely if you know what image formats might show up, you can check the start of the string for their signatures to identify images, and assume you have JSON if it's not an image.
Another simple hack to identify a graphic, rather than a text string, in the case you're looking for a graphic, is just to test for non-ASCII characters in the first couple of dozen characters of the string (assuming the JSON is ASCII).
I Hope that this helps you out... Because I tried all the answers but nothing worked perfectly. So, I had to come up with a solution on my own.
#horizontal-style {
padding-inline-start: 0 !important; // Just in case if you find that there is an extra padding at the start of the line
justify-content: space-around;
display: flex;
}
#horizontal-style a {
text-align: center;
color: white;
text-decoration: none;
}
window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1));
Use the native pathname
property because it's simplest and has already been parsed and resolved by the browser. $(this).attr("href")
can return values like ../..
which would not give you the correct result.
If you need to keep the search
and hash
(e.g. foo?bar#baz
from http://quux.com/path/to/foo?bar#baz
) use this:
window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1) + this.search + this.hash);
If you put your JavaScript code in the PHP file, you can, but not otherwise. For example:
page.php (this will work)
function jst()
{
var i = 0;
i = <?php echo 35; ?>;
alert(i);
}
page.js (this won't work)
function jst()
{
var i = 0;
i = <?php echo 35; ?>
alert(i);
}
Using CSS you cannot, CSS will only change the appearance of the span. However you can do it without changing the structure of the div by adding an onclick handler to the span:
<html>
<head>
</head>
<body>
<div>
<a href="http://www.google.com">
<span>title<br></span>
<span onclick='return false;'>description<br></span>
<span>some url</span>
</a>
</div>
</body>
</html>
You can then style it so that it looks un-clickable too:
<html>
<head>
<style type='text/css'>
a span.unclickable { text-decoration: none; }
a span.unclickable:hover { cursor: default; }
</style>
</head>
<body>
<div>
<a href="http://www.google.com">
<span>title<br></span>
<span class='unclickable' onclick='return false;'>description<br></span>
<span>some url</span>
</a>
</div>
</body>
</html>
You could wrapping the transaction over try..catch or even reverse them,
here my example code I used to in laravel 5,, if you look deep inside DB:transaction()
in Illuminate\Database\Connection
that the same like you write manual transaction.
Laravel Transaction
public function transaction(Closure $callback)
{
$this->beginTransaction();
try {
$result = $callback($this);
$this->commit();
}
catch (Exception $e) {
$this->rollBack();
throw $e;
} catch (Throwable $e) {
$this->rollBack();
throw $e;
}
return $result;
}
so you could write your code like this, and handle your exception like throw message back into your form via flash or redirect to another page. REMEMBER return inside closure is returned in transaction() so if you return redirect()->back()
it won't redirect immediately, because the it returned at variable which handle the transaction.
Wrap Transaction
$result = DB::transaction(function () use ($request, $message) {
try{
// execute query 1
// execute query 2
// ..
return redirect(route('account.article'));
} catch (\Exception $e) {
return redirect()->back()->withErrors(['error' => $e->getMessage()]);
}
});
// redirect the page
return $result;
then the alternative is throw boolean variable and handle redirect outside transaction function or if your need to retrieve why transaction failed you can get it from $e->getMessage()
inside catch(Exception $e){...}
Basically, pip comes with python itself.Therefore it carries no meaning for using pip itself to install or upgrade python. Thus,try to install python through installer itself,visit the site "https://www.python.org/downloads/" for more help. Thank you.
Yet another (dynamic) way:
$("form").validate().settings.ignore = "*";
And to re-enable it, we just set back the default value:
$("form").validate().settings.ignore = ":hidden";
Source: https://github.com/jzaefferer/jquery-validation/issues/725#issuecomment-17601443
For me echo XYZ_20200824.zip | grep -Eo '[[:digit:]]{4}[[:digit:]]{2}[[:digit:]]{2}'
was working fine but unable to store output of command into variable.
I had same issue I tried eval
but didn't got output.
Here is answer for my problem:
cmd=$(echo XYZ_20200824.zip | grep -Eo '[[:digit:]]{4}[[:digit:]]{2}[[:digit:]]{2}')
echo $cmd
My output is now 20200824
Have you tried the __name__
attribute of the class? ie type(x).__name__
will give you the name of the class, which I think is what you want.
>>> import itertools
>>> x = itertools.count(0)
>>> type(x).__name__
'count'
If you're still using Python 2, note that the above method works with new-style classes only (in Python 3+ all classes are "new-style" classes). Your code might use some old-style classes. The following works for both:
x.__class__.__name__
Actually, with strings, you can do something like this:
oldStr = 'Hello World!'
newStr = ''
for i in oldStr:
if 'a' < i < 'z':
newStr += chr(ord(i)-32)
else:
newStr += i
print(newStr)
'HELLO WORLD!'
Basically, I'm "adding"+"strings" together into a new string :).
In my Angular Bootstrap dropdowns I initialize the JSON Array (vm.zoneDropdown) with ng-init (you can also have ng-init inside the directive template) and I pass the Array in a custom src attribute
<custom-dropdown control-id="zone" label="Zona" model="vm.form.zone" src="vm.zoneDropdown"
ng-init="vm.getZoneDropdownSrc()" is-required="true" form="farmaciaForm" css-class="custom-dropdown col-md-3"></custom-dropdown>
Inside the controller:
vm.zoneDropdown = [];
vm.getZoneDropdownSrc = function () {
vm.zoneDropdown = $customService.getZone();
}
And inside the customDropdown directive template(note that this is only one part of the bootstrap dropdown):
<ul class="uib-dropdown-menu" role="menu" aria-labelledby="btn-append-to-body">
<li role="menuitem" ng-repeat="dropdownItem in vm.src" ng-click="vm.setValue(dropdownItem)">
<a ng-click="vm.preventDefault($event)" href="##">{{dropdownItem.text}}</a>
</li>
</ul>
An Event declaration adds a layer of abstraction and protection on the delegate instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list.
This answer will help in case, If you are working with Data Bases then mostly take the help of try-catch block statement, which will help and guide you with your code. Here i am showing you that how to insert some values in Data Base with a Button Click Event.
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
@"Data source= C:\Users\pir fahim shah\Documents\TravelAgency.accdb";
try
{
conn.Open();
String ticketno=textBox1.Text.ToString();
String Purchaseprice=textBox2.Text.ToString();
String sellprice=textBox3.Text.ToString();
String my_querry = "INSERT INTO Table1(TicketNo,Sellprice,Purchaseprice)VALUES('"+ticketno+"','"+sellprice+"','"+Purchaseprice+"')";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfuly...!");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to"+ex.Message);
}
finally
{
conn.Close();
}
you could submit all parameters with such naming:
params[0][topdiameter]
params[0][bottomdiameter]
params[1][topdiameter]
params[1][bottomdiameter]
then later you do something like this:
foreach ($_REQUEST['params'] as $item) {
echo $item['topdiameter'];
echo $item['bottomdiameter'];
}
This happens because of your application does not allow to append iframe from origin other than your application domain.
If your application have web.config then add the following tag in web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="X-Frame-Options" value="ALLOW" />
</customHeaders>
</httpProtocol>
</system.webServer>
This will allow application to append iframe from other origin also. You can also use the following value for X-Frame-Option
X-FRAME-OPTIONS: ALLOW-FROM https://example.com/
The following solution work for me
@RequestMapping(value="/download")
public void getLogFile(HttpSession session,HttpServletResponse response) throws Exception {
try {
String fileName="archivo demo.pdf";
String filePathToBeServed = "C:\\software\\Tomcat 7.0\\tmpFiles\\";
File fileToDownload = new File(filePathToBeServed+fileName);
InputStream inputStream = new FileInputStream(fileToDownload);
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment; filename="+fileName);
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
inputStream.close();
} catch (Exception exception){
System.out.println(exception.getMessage());
}
}
This standard provides a common basis for Unix-like operating systems. It specifies how the shell should work, what to expect from commands like ls and grep, and a number of C libraries that C authors can expect to have available.
For example, the pipes that command-line users use to string together commands are specified in detail here, which means C’s popen (pipe open) function is POSIX-standard, not ISO C-standard.
It is not required for me to use the PDFBox library, so a solution that uses another library is fine
Camelot and Excalibur
You may want to try Python library Camelot, an open source library for Python. If you are not inclined to write code, you may use the web interface Excalibur created around Camelot. You "upload" the document to a localhost web server, and "download" the result from this localhost server.
Here is an example from using this python code:
import camelot
tables = camelot.read_pdf('foo.pdf', flavor="stream")
tables[0].to_csv('foo.csv')
The input is a pdf containing this table:
Sample table from the PDF-TREX set
No help is provided to camelot, it is working on its own by looking at pieces of text relative alignment. The result is returned in a csv file:
PDF table extracted from sample by camelot
"Rules" can de added to help camelot identify where are fillets in sophisticated tables:
Rule added in Excalibur. Source
GitHub:
The two projects are active.
Here is a comparison with other software (with test based on actual documents), Tabula, pdfplumber, pdftables, pdf-table-extract.
I want is to be able to parse the file and know what each parsed number means
You cannot do that automatically, as pdf is not semantically structured.
Book versus document
Pdf "documents" are unstructured from a semantic standpoint (it's like a notepad file), the pdf document gives instructions on where to print a text fragment, unrelated to other fragments of the same section, there is no separation between content (what to print, and whether this is a fragment of a title, a table or a footnote) and the visual representation (font, location, etc). Pdf is an extension of PostScript, which describes a Hello world! page this way:
!PS
/Courier % font
20 selectfont % size
72 500 moveto % current location to print at
(Hello world!) show % add text fragment
showpage % print all on the page
(Wikipedia).
One can imagine what a table looks like with the same instructions.
We could say html is not clearer, however there is a big difference: Html describes the content semantically (title, paragraph, list, table header, table cell, ...) and associates the css to produce a visual form, hence content is fully accessible. In this sense, html is a simplified descendant of sgml which puts constraints to allow data processing:
Markup should describe a document's structure and other attributes rather than specify the processing that needs to be performed, because it is less likely to conflict with future developments.
exactly the opposite of PostScript/Pdf. SGML is used in publishing. Pdf doesn't embed this semantical structure, it carries only the css-equivalent associated to plain character strings which may not be complete words or sentences. Pdf is used for closed documents and now for the so-called workflow management.
After having experimented the uncertainty and difficulty in trying to extract data from pdf, it's clear pdf is not at all a solution to preserve a document content for the future (in spite Adobe has obtained from their pairs a pdf standard).
What is actually preserved well is the printed representation, as the pdf was fully dedicated to this aspect when created. Pdf are nearly as dead as printed books.
When reusing the content matters, one must rely again on manual re-entering of data, like from a printed book (possibly trying to do some OCR on it). This is more and more true, as many pdf even prevent the use of copy-paste, introducing multiple spaces between words or produce an unordered characters gibberish when some "optimization" is done for web use.
When the content of the document, not its printed representation, is valuable, then pdf is not the correct format. Even Adobe is unable to recreate perfectly the source of a document from its pdf rendering.
So open data should never be released in pdf format, this limits their use to reading and printing (when allowed), and makes reuse harder or impossible.
Here a reagent solution for a input component that has a :focus property.
The field will be focused as long as this prop is set to true and will not have focus as long as this is false.
Unfortunately this component needs to have a :ref defined, I could not find an other way to call .focus() on it. I am happy about suggestions.
(defn focusable-input [init-attrs]
(r/create-class
{:display-name "focusable-input"
:component-will-receive-props
(fn [this new-argv]
(let [ref-c (aget this "refs" (:ref init-attrs))
focus (:focus (ru/extract-props new-argv))
is-focused (.isFocused ref-c)]
(if focus
(when-not is-focused (.focus ref-c))
(when is-focused (.blur ref-c)))))
:reagent-render
(fn [attrs]
(let [init-focus (:focus init-attrs)
auto-focus (or (:auto-focus attrs) init-focus)
attrs (assoc attrs :auto-focus auto-focus)]
[input attrs]))}))
https://gist.github.com/Knotschi/6f97efe89681ac149113ddec4c396cc5
The idea of retrying the query in case of Deadlock exception is good, but it can be terribly slow, since mysql query will keep waiting for locks to be released. And incase of deadlock mysql is trying to find if there is any deadlock, and even after finding out that there is a deadlock, it waits a while before kicking out a thread in order to get out from deadlock situation.
What I did when I faced this situation is to implement locking in your own code, since it is the locking mechanism of mysql is failing due to a bug. So I implemented my own row level locking in my java code:
private HashMap<String, Object> rowIdToRowLockMap = new HashMap<String, Object>();
private final Object hashmapLock = new Object();
public void handleShortCode(Integer rowId)
{
Object lock = null;
synchronized(hashmapLock)
{
lock = rowIdToRowLockMap.get(rowId);
if (lock == null)
{
rowIdToRowLockMap.put(rowId, lock = new Object());
}
}
synchronized (lock)
{
// Execute your queries on row by row id
}
}
mysql -u <user> -p -e "select * from schema.table"
Here's one way to solve it. Remove non-numeric characters then cast it as a number.
cast(regexp_replace('0419 853 694', '[^0-9]+', '') as number)
You can set the background color of an object using CSS.
You can also use JavaScript to attach click handlers to objects and they can change the style of an object using element.style.property = 'value';
. In the example below I've attached it in the HTML to a button but the handler could equally have been added to the body element or defined entirely in JavaScript.
body {_x000D_
background-color: blue;_x000D_
}
_x000D_
<button onclick="document.body.style.backgroundColor = 'green';">Green</button>
_x000D_
To fully answer this question in 2020, let me quote several statements from official Python docs:
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.
Changed in version 3.7: Dictionary order is guaranteed to be insertion order.
Changed in version 3.8: Dictionaries are now reversible.
Dictionaries and dictionary views are reversible.
A statement regarding OrderedDict vs Dict:
Ordered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations. They have become less important now that the built-in dict class gained the ability to remember insertion order (this new behavior became guaranteed in Python 3.7).
Another thing to consider is that, since there is no multiple inheritance, if you want a class to be able to implement/inherit from your interface/abstract class, but inherit from another base class, use an interface.
In Centos 7 default filesystem is xfs.
xfs file system support only extend not reduce. So if you want to resize the filesystem use xfs_growfs rather than resize2fs.
xfs_growfs /dev/root_vg/root
Note: For ext4 filesystem use
resize2fs /dev/root_vg/root
Push a new page onto the stack, then remove the current page. This results in a switch.
item.Tapped += async (sender, e) => {
await Navigation.PushAsync (new SecondPage ());
Navigation.RemovePage(this);
};
You need to be in a Navigation Page first:
MainPage = NavigationPage(new FirstPage());
Switching content isn't ideal as you have just one big page and one set of page events like OnAppearing ect.
The following example for complex numbers should be self explanatory including the error message at the end
>>> x=complex(1,2)
>>> print x
(1+2j)
>>> y=complex(3,4)
>>> print y
(3+4j)
>>> z=x+y
>>> print x
(1+2j)
>>> print z
(4+6j)
>>> z=x*y
>>> print z
(-5+10j)
>>> z=x/y
>>> print z
(0.44+0.08j)
>>> print x.conjugate()
(1-2j)
>>> print x.imag
2.0
>>> print x.real
1.0
>>> print x>y
Traceback (most recent call last):
File "<pyshell#149>", line 1, in <module>
print x>y
TypeError: no ordering relation is defined for complex numbers
>>> print x==y
False
>>>
Or, if you want a more general approach - i.e. for nesting up to "levelN":
void Main()
{
XElement rootElement = XElement.Load(@"c:\events\test.xml");
Console.WriteLine(GetOutline(0, rootElement));
}
private string GetOutline(int indentLevel, XElement element)
{
StringBuilder result = new StringBuilder();
if (element.Attribute("name") != null)
{
result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
}
foreach (XElement childElement in element.Elements())
{
result.Append(GetOutline(indentLevel + 1, childElement));
}
return result.ToString();
}
You can use this function:
UIImageWriteToSavedPhotosAlbum(UIImage *image,
id completionTarget,
SEL completionSelector,
void *contextInfo);
You only need completionTarget, completionSelector and contextInfo if you want to be notified when the UIImage
is done saving, otherwise you can pass in nil
.
See the official documentation for UIImageWriteToSavedPhotosAlbum()
.
javamonkey79 is right. But don't forget what you might want to do (e.g. try something else or notify someone) if object is not an instance of String.
String myString;
if (object instanceof String) {
myString = (String) object;
} else {
// do something else
}
BTW: If you use ClassCastException instead of Exception in your code above, you can be sure that you will catch the exception caused by casting object to String. And not any other exceptions caused by other code (e.g. NullPointerExceptions).
You could add justify-content: space-between
to the parent element. In doing so, the children flexbox items will be aligned to opposite sides with space between them.
#container {
width: 500px;
border: solid 1px #000;
display: flex;
justify-content: space-between;
}
#container {_x000D_
width: 500px;_x000D_
border: solid 1px #000;_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}_x000D_
_x000D_
#a {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
}_x000D_
_x000D_
#b {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
height: 200px;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="a">_x000D_
a_x000D_
</div>_x000D_
<div id="b">_x000D_
b_x000D_
</div>_x000D_
</div>
_x000D_
You could also add margin-left: auto
to the second element in order to align it to the right.
#b {
width: 20%;
border: solid 1px #000;
height: 200px;
margin-left: auto;
}
#container {_x000D_
width: 500px;_x000D_
border: solid 1px #000;_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
#a {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
margin-right: auto;_x000D_
}_x000D_
_x000D_
#b {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
height: 200px;_x000D_
margin-left: auto;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="a">_x000D_
a_x000D_
</div>_x000D_
<div id="b">_x000D_
b_x000D_
</div>_x000D_
</div>
_x000D_
There are multiple options available for generating HTML reports for Selenium WebDriver scripts.
1. Use the JUNIT TestWatcher class for creating your own Selenium HTML reports
The TestWatcher JUNIT class allows overriding the failed() and succeeded() JUNIT methods that are called automatically when JUNIT tests fail or pass.
The TestWatcher JUNIT class allows overriding the following methods:
failed() method is invoked when a test fails
finished() method is invoked when a test method finishes (whether passing or failing)
skipped() method is invoked when a test is skipped due to a failed assumption.
starting() method is invoked when a test is about to start
succeeded() method is invoked when a test succeeds
See below sample code for this case:
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class TestClass2 extends WatchManClassConsole {
@Test public void testScript1() {
assertTrue(1 < 2); >
}
@Test public void testScript2() {
assertTrue(1 > 2);
}
@Test public void testScript3() {
assertTrue(1 < 2);
}
@Test public void testScript4() {
assertTrue(1 > 2);
}
}
import org.junit.Rule;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
public class WatchManClassConsole {
@Rule public TestRule watchman = new TestWatcher() {
@Override public Statement apply(Statement base, Description description) {
return super.apply(base, description);
}
@Override protected void succeeded(Description description) {
System.out.println(description.getDisplayName() + " " + "success!");
}
@Override protected void failed(Throwable e, Description description) {
System.out.println(description.getDisplayName() + " " + e.getClass().getSimpleName());
}
};
}
2. Use the Allure Reporting framework
Allure framework can help with generating HTML reports for your Selenium WebDriver projects.
The reporting framework is very flexible and it works with many programming languages and unit testing frameworks.
You can read everything about it at http://allure.qatools.ru/.
You will need the following dependencies and plugins to be added to your pom.xml file
See more details including code samples on this article: http://test-able.blogspot.com/2015/10/create-selenium-html-reports-with-allure-framework.html
I use __dict__
Example:
class MyObj(object):
def __init__(self):
self.name = 'Chuck Norris'
self.phone = '+6661'
obj = MyObj()
print(obj.__dict__)
# Output:
# {'phone': '+6661', 'name': 'Chuck Norris'}
See http://api.jquery.com/jQuery.ajax/, there's mention of datatype and contentType there.
They are both used in the request to the server so the server knows what kind of data to receive/send.
I've gotten that error twice:
1) When I wrote:
var app = module('flapperNews', []);
instead of:
var app = angular.module('flapperNews', []);
2) When I copy and pasted some html, and the controller name in the html did not exactly match the controller name in my app.js file, for instance:
index.html:
<script src="app.js"></script>
...
...
<body ng-app="flapperNews" ng-controller="MainCtrl">
app.js:
var app = angular.module('flapperNews', []);
app.controller('MyCtrl', ....
In the html, the controller name is "MainCtrl", and in the js I used the name "MyCtrl".
There is actually an error message embedded in the error url:
Error: [ng:areq] http://errors.angularjs.org/1.3.2/ng/areq?p0=MainCtrl&p1=not%20a%20function%2C%20got%20undefined
Here it is without the hieroglyphics:
MainCtrl not a function got undefined
In other words, "There is no function named MainCtrl. Check your spelling."
Already very good solution came. I'm just puting the total code so that a newbie get total help
<?php
extract($_GET); //you can send some parameter by query variable. I have sent table name in *table* variable
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$table.csv");
header("Pragma: no-cache");
header("Expires: 0");
require_once("includes/functions.php"); //necessary mysql connection functions here
//first of all I'll get the column name to put title of csv file.
$query = "SHOW columns FROM $table";
$headers = mysql_query($query) or die(mysql_error());
$csv_head = array();
while ($row = mysql_fetch_array($headers, MYSQL_ASSOC))
{
$csv_head[] = $row['Field'];
}
echo implode(",", $csv_head)."\n";
//now I'll bring the data.
$query = "SELECT * FROM $table";
$select_c = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
foreach ($row as $key => $value) {
//there may be separator (here I have used comma) inside data. So need to put double quote around such data.
if(strpos($value, ',') !== false || strpos($value, '"') !== false || strpos($value, "\n") !== false) {
$row[$key] = '"' . str_replace('"', '""', $value) . '"';
}
}
echo implode(",", $row)."\n";
}
?>
I have saved this code in csv-download.php
Now see how I have used this data to download csv file
<a href="csv-download.php?table=tbl_vfm"><img title="Download as Excel" src="images/Excel-logo.gif" alt="Download as Excel" /><a/>
So when I have clicked the link it download the file without taking me to csv-download.php page on browser.
InstanceID.getInstance(getApplicationContext()).getToken(authorizedEntity,scope)
authorizedEntity is the project number of the server
func fucntion()
{
var parameters = [String:String]()
let apiToken = "Bearer \(ApiUtillity.sharedInstance.getUserData(key: "vAuthToken"))"
let headers = ["Vauthtoken":apiToken]
parameters = ["firstname":name,"lastname":last_name,"mobile":mobile_number,"email":emails_Address]
Alamofire.request(ApiUtillity.sharedInstance.API(Join: "user/edit_profile"), method: .post, parameters: parameters, encoding: URLEncoding.default,headers:headers).responseJSON { response in
debugPrint(response)
if let json = response.result.value {
let dict:NSDictionary = (json as? NSDictionary)!
print(dict)
// print(response)
let StatusCode = dict.value(forKey: "status") as! Int
if StatusCode==200
{
ApiUtillity.sharedInstance.dismissSVProgressHUDWithSuccess(success: "Success")
let UserData = dict.value(forKey: "data") as! NSDictionary
print(UserData)
}
else if StatusCode==401
{
let ErrorDic:NSDictionary = dict.value(forKey: "message") as! NSDictionary
let ErrorMessage = ErrorDic.value(forKey: "error") as! String
}
else
{
let ErrorDic:NSDictionary = dict.value(forKey: "message") as! NSDictionary
let ErrorMessage = ErrorDic.value(forKey: "error") as! String
}
}
else
{
ApiUtillity.sharedInstance.dismissSVProgressHUDWithError(error: "Something went wrong")
}
}
Why not using grid?
.container {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
grid-column-gap: 20px
}
Edited to reflect update to question
$(document).ready(function() {
$(".res a").click(function() {
alert($(this).attr("href"));
});
});