$('#some_select_box option:selected').remove();
You have to replace YourID and value="3" for your current ones.
$(document).ready(function() {_x000D_
$('#YourID option[value="3"]').attr("selected", "selected");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
<select id="YourID">_x000D_
<option value="1">A</option>_x000D_
<option value="2">B</option>_x000D_
<option value="3">C</option>_x000D_
<option value="4">D</option>_x000D_
</select>
_x000D_
and value="3" for your current ones.
$('#YourID option[value="3"]').attr("selected", "selected");
<select id="YourID" >
<option value="1">A </option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
You use the available API of JTable
and do not try to mess with the colors.
Some selection methods are available directly on the JTable
(like the setRowSelectionInterval
). If you want to have access to all selection-related logic, the selection model is the place to start looking
For overall:
$("#checkAll").click(function(){
$(".somecheckBoxes").prop('checked',$(this).prop('checked')?true:false);
});
I drilled down the formation of the drop down list instead of using @Html.DropDownList()
. This is useful if you have to set the value of the dropdown list at runtime in razor instead of controller:
<select id="NewsCategoriesID" name="NewsCategoriesID">
@foreach (SelectListItem option in ViewBag.NewsCategoriesID)
{
<option value="@option.Value" @(option.Value == ViewBag.ValueToSet ? "selected='selected'" : "")>@option.Text</option>
}
</select>
This is the code what I used for the set selected value
countryList: any = [{ "value": "AF", "group": "A", "text": "Afghanistan"}, { "value": "AL", "group": "A", "text": "Albania"}, { "value": "DZ", "group": "A", "text": "Algeria"}, { "value": "AD", "group": "A", "text": "Andorra"}, { "value": "AO", "group": "A", "text": "Angola"}, { "value": "AR", "group": "A", "text": "Argentina"}, { "value": "AM", "group": "A", "text": "Armenia"}, { "value": "AW", "group": "A", "text": "Aruba"}, { "value": "AU", "group": "A", "text": "Australia"}, { "value": "AT", "group": "A", "text": "Austria"}, { "value": "AZ", "group": "A", "text": "Azerbaijan"}];_x000D_
_x000D_
_x000D_
for (var j = 0; j < countryList.length; j++) {_x000D_
//debugger_x000D_
if (countryList[j].text == "Australia") {_x000D_
console.log(countryList[j].text); _x000D_
countryList[j].isSelected = 'selected';_x000D_
}_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>_x000D_
<label>Country</label>_x000D_
<select class="custom-select col-12" id="Country" name="Country" >_x000D_
<option value="0" selected>Choose...</option>_x000D_
<option *ngFor="let country of countryList" value="{{country.text}}" selected="{{country.isSelected}}" > {{country.text}}</option>_x000D_
</select>
_x000D_
try this on an angular framework
For Swift 3,4 and 5 you can do this in two ways.
1) class: UITableViewCell
override func awakeFromNib() {
super.awakeFromNib()
//Costumize cell
selectionStyle = .none
}
or
2) tableView cellForRowAt
cell.selectionStyle = .none
If you want to set selection color for specific cell, check this answer: https://stackoverflow.com/a/56166325/7987502
For those using Select2 4.x, you can disable an individual option by doing:
$('select option:selected').prop('disabled', true);
For those using Select2 4.x, you can disable the entire dropdown with:
$('select').prop('disabled', true);
foreach($array as $value=>$name)
{
if($value == $_GET['sel'])
{
echo "<option selected='selected' value='".$value."'>".$name."</option>";
}
else
{
echo "<option value='".$value."'>".$name."</option>";
}
}
You can use switch like this:
XML Layout
<RadioGroup
android:id="@+id/RG"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/R1"
android:layout_width="wrap_contnet"
android:layout_height="wrap_content"
android:text="R1" />
<RadioButton
android:id="@+id/R2"
android:layout_width="wrap_contnet"
android:layout_height="wrap_content"
android:text="R2" />
</RadioGroup>
And JAVA Activity
switch (RG.getCheckedRadioButtonId()) {
case R.id.R1:
regAuxiliar = ultimoRegistro;
case R.id.R2:
regAuxiliar = objRegistro;
default:
regAuxiliar = null; // none selected
}
You will also need to implement an onClick function with button or setOnCheckedChangeListener function to get required functionality.
I found the solution: need to add addition line
[button setImage:[UIImage imageNamed:@"pressed.png"] forState:UIControlStateSelected | UIControlStateHighlighted];
Date's compareTo() you're using will work for ascending order.
To do descending, just reverse the value of compareTo() coming out. You can use a single Comparator class that takes in a flag/enum in the constructor that identifies the sort order
public int compare(MyObject lhs, MyObject rhs) {
if(SortDirection.Ascending == m_sortDirection) {
return lhs.MyDateTime.compareTo(rhs.MyDateTime);
}
return rhs.MyDateTime.compareTo(lhs.MyDateTime);
}
You need to call Collections.sort() to actually sort the list.
As a side note, I'm not sure why you're defining your map inside your for loop. I'm not exactly sure what your code is trying to do, but I assume you want to populate the indexed values from your for loop in to the map.
json = ( new Function("return " + jsonString) )();
I landed here with the same issue, then figured it out on my own. This weird character was appearing with my HTML.
The issue is most likely your code editor. I use Espresso and sometimes run into issues like this.
To fix it, simply highlight the affected code, then go to the menu and click "convert to numeric entities". You'll see the numeric value of this character appear; simply delete it and it's gone forever.
Use DecimalFormat.
DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits. It also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), scientific notation (1.23E4), percentages (12%), and currency amounts ($123). All of these can be localized.
Code snippet -
double i2=i/60000;
tv.setText(new DecimalFormat("##.##").format(i2));
Output -
5.81
Turns out that this works.
var firstName = "John";
var id = 12;
var sql = "Update [User] SET FirstName = {0} WHERE Id = {1}";
ctx.Database.ExecuteSqlCommand(sql, firstName, id);
First choose or create the key you want to use for pushing to Bitbucket. Let's say its public key is at ~/.ssh/bitbucket.pub
~/.ssh/config
: Host bitbucket.org
IdentityFile ~/.ssh/bitbucket
download
attributeJust to allow user to download the image or other file you may use the HTML5 download
attribute.
Static file download
<a href="/images/image-name.jpg" download>
<!-- OR -->
<a href="/images/image-name.jpg" download="new-image-name.jpg">
Dynamic file download
In cases requesting image dynamically it is possible to emulate such download.
If your image is already loaded and you have the base64
source then:
function saveBase64AsFile(base64, fileName) {
var link = document.createElement("a");
document.body.appendChild(link); // for Firefox
link.setAttribute("href", base64);
link.setAttribute("download", fileName);
link.click();
}
Otherwise if image file is downloaded as Blob
you can use FileReader
to convert it to Base64:
function saveBlobAsFile(blob, fileName) {
var reader = new FileReader();
reader.onloadend = function () {
var base64 = reader.result ;
var link = document.createElement("a");
document.body.appendChild(link); // for Firefox
link.setAttribute("href", base64);
link.setAttribute("download", fileName);
link.click();
};
reader.readAsDataURL(blob);
}
Firefox
The anchor tag you are creating also needs to be added to the DOM in Firefox, in order to be recognized for click events (Link).
IE is not supported: Caniuse link
As others have mentioned, you can do this via nbextensions. I wanted to give the brief explanation of what I did, which was quick and easy:
To enable collabsible headings: In your terminal, enable/install Jupyter Notebook Extensions by first entering:
pip install jupyter_contrib_nbextensions
Then, enter:
jupyter contrib nbextension install
Re-open Jupyter Notebook. Go to "Edit" tab, and select "nbextensions config". Un-check box directly under title "Configurable nbextensions", then select "collapsible headings".
The server should respond with the correct MIME Type for JSONP application/javascript
and your request should tell jQuery you are loading JSONP dataType: 'jsonp'
Please see this answer for further details !
You can also have a look a this one as it explains why loading .js
file with text/plain
won't work.
go to project properties and change the target from 7 to 8 also change the target in android manifest and also go to properties of project by right clicking on the project and choose the target
Maybe for UWP C#
public static async Task<IStorageItem> AsIStorageItemAsync(this string iStorageItemPath)
{
if (string.IsNullOrEmpty(iStorageItemPath)) return null;
IStorageItem storageItem = null;
try
{
storageItem = await StorageFolder.GetFolderFromPathAsync(iStorageItemPath);
if (storageItem != null) return storageItem;
} catch { }
try
{
storageItem = await StorageFile.GetFileFromPathAsync(iStorageItemPath);
if (storageItem != null) return storageItem;
} catch { }
return storageItem;
}
Sometimes errors can be very silly
Before checking all the solutions up here , make sure you have imported all the basic stuff
import Foundation
import UIKit
It is quite a possibility that when you import some files from outside to your project, which may miss this basic things as I experienced once .
Your example declares a TypeScript < 1.5 internal module, which is now called a namespace. The old module App {}
syntax is now equivalent to namespace App {}
. As a result, the following works:
// test.ts
export namespace App {
export class SomeClass {
getName(): string {
return 'name';
}
}
}
// main.ts
import { App } from './test';
var a = new App.SomeClass();
Try to avoid exporting namespaces and instead export modules (which were previously called external modules). If needs be you can use a namespace on import with the namespace import pattern like this:
// test.ts
export class SomeClass {
getName(): string {
return 'name';
}
}
// main.ts
import * as App from './test'; // namespace import pattern
var a = new App.SomeClass();
If node-soap
doesn't work for you, just use node
request
module and then convert the xml to json if needed.
My request wasn't working with node-soap
and there is no support for that module beyond the paid support, which was beyond my resources. So i did the following:
curl http://192.168.0.28:10005/MainService/WindowsService?wsdl > wsdl_file.xml
File > New Soap project
and uploaded my wsdl_file.xml
.Show Request Editor
.From there I could send a request and make sure it worked and I could also use the Raw
or HTML
data to help me build an external request.
Raw from SoapUI for my request
POST http://192.168.0.28:10005/MainService/WindowsService HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: text/xml;charset=UTF-8
SOAPAction: "http://Main.Service/AUserService/GetUsers"
Content-Length: 303
Host: 192.168.0.28:10005
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
XML from SoapUI
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:qtre="http://Main.Service">
<soapenv:Header/>
<soapenv:Body>
<qtre:GetUsers>
<qtre:sSearchText></qtre:sSearchText>
</qtre:GetUsers>
</soapenv:Body>
</soapenv:Envelope>
I used the above to build the following node
request
:
var request = require('request');
let xml =
`<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:qtre="http://Main.Service">
<soapenv:Header/>
<soapenv:Body>
<qtre:GetUsers>
<qtre:sSearchText></qtre:sSearchText>
</qtre:GetUsers>
</soapenv:Body>
</soapenv:Envelope>`
var options = {
url: 'http://192.168.0.28:10005/MainService/WindowsService?wsdl',
method: 'POST',
body: xml,
headers: {
'Content-Type':'text/xml;charset=utf-8',
'Accept-Encoding': 'gzip,deflate',
'Content-Length':xml.length,
'SOAPAction':"http://Main.Service/AUserService/GetUsers"
}
};
let callback = (error, response, body) => {
if (!error && response.statusCode == 200) {
console.log('Raw result', body);
var xml2js = require('xml2js');
var parser = new xml2js.Parser({explicitArray: false, trim: true});
parser.parseString(body, (err, result) => {
console.log('JSON result', result);
});
};
console.log('E', response.statusCode, response.statusMessage);
};
request(options, callback);
FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.
Some references:
Though you can use any other client that allows automation.
You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).
Combine WinSCP scripting capabilities with Windows Scheduler:
A typical WinSCP script for upload (with SFTP) looks like:
open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close
With FTP, just replace the sftp://
with the ftp://
and remove the -hostkey="..."
switch.
Similarly for download: How to schedule an automatic FTP download on Windows?
WinSCP can even generate a script from an imported FileZilla session.
For details, see the guide to FileZilla automation.
(I'm the author of WinSCP)
Another option, if you are using SFTP, is the psftp.exe
client from PuTTY suite.
public static String detectDateFormat(String inputDate, String requiredFormat) {
String tempDate = inputDate.replace("/", "").replace("-", "").replace(" ", "");
String dateFormat;
if (tempDate.matches("([0-12]{2})([0-31]{2})([0-9]{4})")) {
dateFormat = "MMddyyyy";
} else if (tempDate.matches("([0-31]{2})([0-12]{2})([0-9]{4})")) {
dateFormat = "ddMMyyyy";
} else if (tempDate.matches("([0-9]{4})([0-12]{2})([0-31]{2})")) {
dateFormat = "yyyyMMdd";
} else if (tempDate.matches("([0-9]{4})([0-31]{2})([0-12]{2})")) {
dateFormat = "yyyyddMM";
} else if (tempDate.matches("([0-31]{2})([a-z]{3})([0-9]{4})")) {
dateFormat = "ddMMMyyyy";
} else if (tempDate.matches("([a-z]{3})([0-31]{2})([0-9]{4})")) {
dateFormat = "MMMddyyyy";
} else if (tempDate.matches("([0-9]{4})([a-z]{3})([0-31]{2})")) {
dateFormat = "yyyyMMMdd";
} else if (tempDate.matches("([0-9]{4})([0-31]{2})([a-z]{3})")) {
dateFormat = "yyyyddMMM";
} else {
return "Pattern Not Added";
//add your required regex
}
try {
String formattedDate = new SimpleDateFormat(requiredFormat, Locale.ENGLISH).format(new SimpleDateFormat(dateFormat).parse(tempDate));
return formattedDate;
} catch (Exception e) {
//
return "";
}
}
Here is a way to check is virtualization is enabled or disabled by the firmware as suggested by this link in parallels.com.
How to check that Intel VT-x is supported in CPU:
Open Terminal application from Application/Utilities
Copy/paste command bellow
sysctl -a | grep machdep.cpu.features
Mac:~ user$ sysctl -a | grep machdep.cpu.features
kern.exec: unknown type returned
machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM SSE3 MON VMX EST TM2 TPR PDCM
If you see VMX entry then CPU supports Intel VT-x feature, but it still may be disabled.
Refer to this link on Apple.com to enable hardware support for virtualization:
I had a similar issue where I had another class something like this:
public class Something {
MyActivity myActivity;
public Something(MyActivity myActivity) {
this.myActivity=myActivity;
}
public void someMethod() {
.
.
AlertDialog.Builder builder = new AlertDialog.Builder(myActivity);
.
AlertDialog alert = builder.create();
alert.show();
}
}
Worked fine most of the time, but sometimes it crashed with the same error. Then I realise that in MyActivity
I had...
public class MyActivity extends Activity {
public static Something something;
public void someMethod() {
if (something==null) {
something=new Something(this);
}
}
}
Because I was holding the object as static
, a second run of the code was still holding the original version of the object, and thus was still referring to the original Activity
, which no long existed.
Silly stupid mistake, especially as I really didn't need to be holding the object as static
in the first place...
Just simply use this Style
of DataGridRow
:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
</Style>
</DataGrid.RowStyle>
Want to format it automatically when you save the file???
then Goto Window > Preferences > Java > Editor > Save Actions
and configure your save actions.
Along with saving, you can format, Organize imports,add modifier ‘final’ where possible etc
Working for me on IE:
<script type="text/javascript">
var WinNetwork = new ActiveXObject("WScript.Network");
document.write(WinNetwork.UserName);
</script>
...but ActiveX controls needs to be on in security settings.
This is my Df contain 4 is repeated twice so here will remove repeated values.
scala> df.show
+-----+
|value|
+-----+
| 1|
| 4|
| 3|
| 5|
| 4|
| 18|
+-----+
scala> val newdf=df.dropDuplicates
scala> newdf.show
+-----+
|value|
+-----+
| 1|
| 3|
| 5|
| 4|
| 18|
+-----+
Here is my preferred way to check for "if null or empty":
SELECT *
FROM UserProfile
WHERE PropertydefinitionID in (40, 53)
AND NULLIF(PropertyValue, '') is null
Since it modifies the search argument (SARG) it might have performance issues because it might not use an existing index on the PropertyValue column.
Drag and drop is best solution. I am just showing another way to import by clicking the HAR import icon:
Active mode: -server initiates the connection.
Passive mode: -client initiates the connection.
Using parse_requirements
is problematic because the pip API isn't publicly documented and supported. In pip 1.6, that function is actually moving, so existing uses of it are likely to break.
A more reliable way to eliminate duplication between setup.py
and requirements.txt
is to specific your dependencies in setup.py
and then put -e .
into your requirements.txt
file. Some information from one of the pip
developers about why that's a better way to go is available here: https://caremad.io/blog/setup-vs-requirement/
with this code, the id will not appear on the link
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
Well if you have N objects and you need to get the Title of all of them you have to use a loop. If you only need the title and you really want to improve this, maybe you can make a separated array containing only the title, this would improve the performance. You need to define the amount of memory available and the amount of objects that you can handle before saying this can damage the performance, and in any case the solution would be changing the design of the program not the algorithm.
You can use the following command: jar xf rt.jar
Where X
stands for extraction and the f
would be any options that indicate that the JAR file from which files are to be extracted is specified on the command line, rather than through stdin.
When we use the round() function, it will not give correct values.
you can check it using, round (2.735) and round(2.725)
please use
import math
num = input('Enter a number')
print(math.ceil(num*100)/100)
Note that the bb.array() doesn't honor the byte-buffers position, and might be even worse if the bytebuffer you are working on is a slice of some other buffer.
I.e.
byte[] test = "Hello World".getBytes("Latin1");
ByteBuffer b1 = ByteBuffer.wrap(test);
byte[] hello = new byte[6];
b1.get(hello); // "Hello "
ByteBuffer b2 = b1.slice(); // position = 0, string = "World"
byte[] tooLong = b2.array(); // Will NOT be "World", but will be "Hello World".
byte[] world = new byte[5];
b2.get(world); // world = "World"
Which might not be what you intend to do.
If you really do not want to copy the byte-array, a work-around could be to use the byte-buffer's arrayOffset() + remaining(), but this only works if the application supports index+length of the byte-buffers it needs.
Run your program with valgrind of linked to efence. That will tell you where the pointer is being dereferenced and most likely fix your problem if you fix all the errors they tell you about.
Reverse the string, replace the char, reverse the string.
Here is a post for reversing a string in javascript: How do you reverse a string in place in JavaScript?
Copied from http://technet.microsoft.com/en-us/library/cc750354.aspx
What's FAT?
FAT may sound like a strange name for a file system, but it's actually an acronym for File Allocation Table. Introduced in 1981, FAT is ancient in computer terms. Because of its age, most operating systems, including Microsoft Windows NT®, Windows 98, the Macintosh OS, and some versions of UNIX, offer support for FAT.
The FAT file system limits filenames to the 8.3 naming convention, meaning that a filename can have no more than eight characters before the period and no more than three after. Filenames in a FAT file system must also begin with a letter or number, and they can't contain spaces. Filenames aren't case sensitive.
What About VFAT?
Perhaps you've also heard of a file system called VFAT. VFAT is an extension of the FAT file system and was introduced with Windows 95. VFAT maintains backward compatibility with FAT but relaxes the rules. For example, VFAT filenames can contain up to 255 characters, spaces, and multiple periods. Although VFAT preserves the case of filenames, it's not considered case sensitive.
When you create a long filename (longer than 8.3) with VFAT, the file system actually creates two different filenames. One is the actual long filename. This name is visible to Windows 95, Windows 98, and Windows NT (4.0 and later). The second filename is called an MS-DOS® alias. An MS-DOS alias is an abbreviated form of the long filename. The file system creates the MS-DOS alias by taking the first six characters of the long filename (not counting spaces), followed by the tilde [~] and a numeric trailer. For example, the filename Brien's Document.txt would have an alias of BRIEN'~1.txt.
An interesting side effect results from the way VFAT stores its long filenames. When you create a long filename with VFAT, it uses one directory entry for the MS-DOS alias and another entry for every 13 characters of the long filename. In theory, a single long filename could occupy up to 21 directory entries. The root directory has a limit of 512 files, but if you were to use the maximum length long filenames in the root directory, you could cut this limit to a mere 24 files. Therefore, you should use long filenames very sparingly in the root directory. Other directories aren't affected by this limit.
You may be wondering why we're discussing VFAT. The reason is it's becoming more common than FAT, but aside from the differences I mentioned above, VFAT has the same limitations. When you tell Windows NT to format a partition as FAT, it actually formats the partition as VFAT. The only time you'll have a true FAT partition under Windows NT 4.0 is when you use another operating system, such as MS-DOS, to format the partition.
FAT32
FAT32 is actually an extension of FAT and VFAT, first introduced with Windows 95 OEM Service Release 2 (OSR2). FAT32 greatly enhances the VFAT file system but it does have its drawbacks.
The greatest advantage to FAT32 is that it dramatically increases the amount of free hard disk space. To illustrate this point, consider that a FAT partition (also known as a FAT16 partition) allows only a certain number of clusters per partition. Therefore, as your partition size increases, the cluster size must also increase. For example, a 512-MB FAT partition has a cluster size of 8K, while a 2-GB partition has a cluster size of 32K.
This may not sound like a big deal until you consider that the FAT file system only works in single cluster increments. For example, on a 2-GB partition, a 1-byte file will occupy the entire cluster, thereby consuming 32K, or roughly 32,000 times the amount of space that the file should consume. This rule applies to every file on your hard disk, so you can see how much space can be wasted.
Converting a partition to FAT32 reduces the cluster size (and overcomes the 2-GB partition size limit). For partitions 8 GB and smaller, the cluster size is reduced to a mere 4K. As you can imagine, it's not uncommon to gain back hundreds of megabytes by converting a partition to FAT32, especially if the partition contains a lot of small files.
Note: This section of the quote/ article (1999) is out of date. Updated info quote below.
As I mentioned, FAT32 does have limitations. Unfortunately, it isn't compatible with any operating system other than Windows 98 and the OSR2 version of Windows 95. However, Windows 2000 will be able to read FAT32 partitions.
The other disadvantage is that your disk utilities and antivirus software must be FAT32-aware. Otherwise, they could interpret the new file structure as an error and try to correct it, thus destroying data in the process.
Finally, I should mention that converting to FAT32 is a one-way process. Once you've converted to FAT32, you can't convert the partition back to FAT16. Therefore, before converting to FAT32, you need to consider whether the computer will ever be used in a dual-boot environment. I should also point out that although other operating systems such as Windows NT can't directly read a FAT32 partition, they can read it across the network. Therefore, it's no problem to share information stored on a FAT32 partition with other computers on a network that run older operating systems.
Updated mentioned in comment by Doktor-J (assimilated to update out of date answer in case comment is ever lost):
I'd just like to point out that most modern operating systems (WinXP/Vista/7/8, MacOS X, most if not all Linux variants) can read FAT32, contrary to what the second-to-last paragraph suggests.
The original article was written in 1999, and being posted on a Microsoft website, probably wasn't concerned with non-Microsoft operating systems anyways.
The operating systems "excluded" by that paragraph are probably the original Windows 95, Windows NT 4.0, Windows 3.1, DOS, etc.
This code can be used to export any file, including csv
// application/octet-stream tells the browser not to try to interpret the file
header('Content-type: application/octet-stream');
header('Content-Length: ' . filesize($data));
header('Content-Disposition: attachment; filename="export.csv"');
I know this is old, but I ran into the same issue. I'm on a Mac/Ubuntu and switch back and forth. What I have found is that just sending a simple interrupt signal to the main R process does exactly what you're looking for. I've ran scripts that went on for as long as 24 hours and the signal interrupt works very well. You should be able to run kill in terminal:
$ kill -2 pid
You can find the pid by running
$ps aux | grep exec/R
Not sure about Windows since I'm not ever on there, but I can't imagine there's not an option to do this as well in Command Prompt/Task Manager
Hope this helps!
adding to scotty's answer:
Option 1: Either include this in your JS file:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
Option 2: or just use the URL to download 'angular-route.min.js' to your local.
and then (whatever option you choose) add this 'ngRoute' as dependency.
explained:
var app = angular.module('myapp', ['ngRoute']);
Cheers!!!
I have problems with set password too. And find answer at official site
SET PASSWORD FOR 'root'@'localhost' = 'your_password';
If you haven't made any changes inside the conflicted directory, you can also rm -rf conflicts_in_here/
and then svn up
. This worked for me at least.
Array.filter is not implemented in many browsers,It is better to define this function if it does not exist.
The source code for Array.prototype is posted in MDN
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp */)
{
"use strict";
if (this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in t)
{
var val = t[i]; // in case fun mutates this
if (fun.call(thisp, val, i, t))
res.push(val);
}
}
return res;
};
}
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for more details
A shell convention is that a successful executable should exit with the value 0. Anything else can be interpreted as a failure of some sort, on part of bash or the executable you that just ran. See also $PIPESTATUS and the EXIT STATUS section of the bash man page:
For the shell’s purposes, a command which exits with a zero exit status has succeeded. An exit status of zero indicates success. A non-zero exit status indicates failure. When a command terminates on a fatal signal N, bash uses the value of 128+N as the exit status.
If a command is not found, the child process created to execute it returns a status of 127. If a com-
mand is found but is not executable, the return status is 126.
If a command fails because of an error during expansion or redirection, the exit status is greater than
zero.
Shell builtin commands return a status of 0 (true) if successful, and non-zero (false) if an error
occurs while they execute. All builtins return an exit status of 2 to indicate incorrect usage.
Bash itself returns the exit status of the last command executed, unless a syntax error occurs, in
which case it exits with a non-zero value. See also the exit builtin command below.
gzip > stdin.gz
perhaps? Otherwise, you need to flesh out your question.
We avoid providing direct access to database connections because they're resource intensive. So we use a static factory method getDbConnection
that creates a connection if we're below the limit. Otherwise, it tries to provide a "spare" connection, failing with an exception if there are none.
public class DbConnection{
private static final int MAX_CONNS = 100;
private static int totalConnections = 0;
private static Set<DbConnection> availableConnections = new HashSet<DbConnection>();
private DbConnection(){
// ...
totalConnections++;
}
public static DbConnection getDbConnection(){
if(totalConnections < MAX_CONNS){
return new DbConnection();
}else if(availableConnections.size() > 0){
DbConnection dbc = availableConnections.iterator().next();
availableConnections.remove(dbc);
return dbc;
}else {
throw new NoDbConnections();
}
}
public static void returnDbConnection(DbConnection dbc){
availableConnections.add(dbc);
//...
}
}
you can also use:
SELECT CASE
WHEN upper(t.name) like 'P%' THEN
'productive'
WHEN upper(t.name) like 'T%' THEN
'test'
WHEN upper(t.name) like 'D%' THEN
'development'
ELSE
'unknown'
END as type
FROM table t
Try using this:
If you specify
ON DUPLICATE KEY UPDATE
, and a row is inserted that would cause a duplicate value in aUNIQUE index or
PRIMARY KEY, MySQL performs an [
UPDATE`](http://dev.mysql.com/doc/refman/5.7/en/update.html) of the old row...The
ON DUPLICATE KEY UPDATE
clause can contain multiple column assignments, separated by commas.With
ON DUPLICATE KEY UPDATE
, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify theCLIENT_FOUND_ROWS
flag tomysql_real_connect()
when connecting to mysqld, the affected-rows value is 1 (not 0) if an existing row is set to its current values...
With so many places where TransactionTooLargeException can happen-- here's one more new to Android 8--a crash when someone merely starts to type into an EditText if the content is too big.
It's related to the AutoFillManager (new in API 26) and the following code in StartSessionLocked()
:
mSessionId = mService.startSession(mContext.getActivityToken(),
mServiceClient.asBinder(), id, bounds, value, mContext.getUserId(),
mCallback != null, flags, mContext.getOpPackageName());
If I understand correctly, this calls the autofill service-- passing the AutofillManagerClient within the binder. And when the EditText has a lot of content, it seems to cause the TTLE.
A few things may mitigate it (or did as I was testing anyway): Add android:importantForAutofill="noExcludeDescendants"
in the EditText's xml layout declaration. Or in code:
EditText et = myView.findViewById(R.id.scriptEditTextView);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
et.setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS);
}
A 2nd awful, terrible workaround might also be to override the performClick()
and onWindowFocusChanged()
methods to catch the error in a TextEdit subclass itself. But I don't think that's wise really...
You can use jQuery
to achieve this
Example:
$(function () {
$('.map').maphilight();
});
Go through this LINK to know more.
If the above one doesnt work then go through this link.
EDIT :
Give same class to each area
tag like class="mapping"
and try this below code
$('.mapping').mouseover(function() {
alert($(this).attr('id'));
}).mouseout(function(){
alert('Mouseout....');
});
Include sites-available/default
in sites-enabled/default
. It requires only one line.
In sites-enabled/default
(new config version?):
It seems that the include path is relative to the file that included it
include sites-available/default;
See the include
documentation.
I believe that certain versions of nginx allows including/linking to other files purely by having a single line with the relative path to the included file. (At least that's what it looked like in some "inherited" config files I've been using, until a new nginx version broke them.)
In sites-enabled/default
(old config version?):
It seems that the include path is relative to the current file
../sites-available/default
What you are looking for is a query with WITH
clause, if your dbms supports it. Then
WITH NewScores AS (
SELECT *
FROM Score
WHERE InsertedDate >= DATEADD(mm, -3, GETDATE())
)
SELECT
<and the rest of your query>
;
Note that there is no ;
in the first half. HTH.
if (strstr(request, "favicon") != NULL) {
// contains
}
There is a property of the built-in window.location
object that will provide that for the current window.
// If URL is http://www.somedomain.com/account/search?filter=a#top
window.location.pathname // /account/search
// For reference:
window.location.host // www.somedomain.com (includes port if there is one)
window.location.hostname // www.somedomain.com
window.location.hash // #top
window.location.href // http://www.somedomain.com/account/search?filter=a#top
window.location.port // (empty string)
window.location.protocol // http:
window.location.search // ?filter=a
It turns out that this schema is being standardized as an interface called URLUtils, and guess what? Both the existing window.location
object and anchor elements implement the interface.
So you can use the same properties above for any URL — just create an anchor with the URL and access the properties:
var el = document.createElement('a');
el.href = "http://www.somedomain.com/account/search?filter=a#top";
el.host // www.somedomain.com (includes port if there is one[1])
el.hostname // www.somedomain.com
el.hash // #top
el.href // http://www.somedomain.com/account/search?filter=a#top
el.pathname // /account/search
el.port // (port if there is one[1])
el.protocol // http:
el.search // ?filter=a
[1]: Browser support for the properties that include port is not consistent, See: http://jessepollak.me/chrome-was-wrong-ie-was-right
This works in the latest versions of Chrome and Firefox. I do not have versions of Internet Explorer to test, so please test yourself with the JSFiddle example.
There's also a coming URL
object that will offer this support for URLs themselves, without the anchor element. Looks like no stable browsers support it at this time, but it is said to be coming in Firefox 26. When you think you might have support for it, try it out here.
Okay... Finally I could install it! Why? or what I did? well I am not sure. first I downloaded and installed the package (I installed all the files(3) from the disk image) but I couldn't start it. (nor from the preferences panel, nor from the termial)
second I removed it and installed through mac ports.
again, the same thing. could not start it.
Now I deleted it again, installed from the package. (i am not sure if it was the exact same package but I think it is) Only this time I got the package from another site(its a mirror).
the site:
http://www.mmisoftware.co.uk/weblog/2009/08/29/mac-os-x-10-6-snow-leopard-and-mysql/
and the link:
http://mirror.services.wisc.edu/mysql/Downloads/MySQL-5.1/mysql-5.1.37-osx10.5-x86.dmg
1.- install mysql-5-1.37-osx10.5-x86.pkg
2.- install MySQLStartupItem.pkg
3.- install MySQL.prefpanel
And this time is working fine (even the preferences panel!)
Nothing special, I don't know what happened the first two times.
But thank you all. Regards.
Just a quick addition to @TimGilbert's old-school answer...you can make your abstract base class's init() method throw an exception and that would prevent it from being instantiated, no?
>>> class Abstract(object):
... def __init__(self):
... raise NotImplementedError("You can't instantiate this class!")
...
>>> a = Abstract()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __init__
NotImplementedError: You can't instantiate this class!
I believe this is much simpler;
dynamic obj = JObject.Parse(jsonString);
string results = obj.results;
foreach(string result in result.Split('))
{
//Todo
}
If you want Console.WriteLine("example text")
output to show up in the Debug Output window, temporarily change the Output type of your Application from Console Application to Windows Application.
From menus choose Project + Properties, and navigate to Output type: drop down, change to Windows Application then run your application
Of course you should change it back for building a console application intended to run outside of the IDE.
(tested with Visual Studio 2008 and 2010, expect it should work in latter versions too)
I found the answers above didn't give me the guidance I needed (I too expected to be in the code for the .java file, and right-click on the tab and see a Refactor option). Here's what I did:
In case you encounter an error like this
mysqldump: 1044 Access denied when using LOCK TABLES
A quick workaround is to pass the –-single-transaction
option to mysqldump
.
So your command will be like this.
mysqldump --single-transaction -u user -p DBNAME > backup.sql
Before JavaScript 1.5: ^[a-zA-Z_$][0-9a-zA-Z_$]*$
In English: It must start with a dollar sign, underscore or one of letters in the 26-character alphabet, upper or lower case. Subsequent characters (if any) can be one of any of those or a decimal digit.
JavaScript 1.5 and later * : ^[\p{L}\p{Nl}$_][\p{L}\p{Nl}$\p{Mn}\p{Mc}\p{Nd}\p{Pc}]*$
This is more difficult to express in English, but it is conceptually similar to the older syntax with the addition that the letters and digits can be from any language. After the first character, there are also allowed additional underscore-like characters (collectively called “connectors”) and additional character combining marks (“modifiers”). (Other currency symbols are not included in this extended set.)
JavaScript 1.5 and later also allows Unicode escape sequences, provided that the result is a character that would be allowed in the above regular expression.
Identifiers also must not be a current reserved word or one that is considered for future use.
There is no practical limit to the length of an identifier. (Browsers vary, but you’ll safely have 1000 characters and probably several more orders of magnitude than that.)
Links to the character categories:
*n.b. This Perl regex is intended to describe the syntax only — it won’t work in JavaScript, which doesn’t (yet) include support for Unicode Properties. (There are some third-party packages that claim to add such support.)
Two observations:
You should write
<input type="button" value="button text" />
instead of
<input type="button">button text</input>
You should rename your function. The function click()
is already defined on a button (it simulates a click), and gets a higher priority then your method.
Note that there are a couple of suggestions here that are plain wrong, and you shouldn't spend to much time on them:
onclick="javascript:myfunc()"
. Only use the javascript:
prefix inside the href
attribute of a hyperlink: <a href="javascript:myfunc()">
.onclick="foo()"
and onclick="foo();"
both work just fine.onclick
, onClick
and ONCLICK
all work. It is common practice to write attributes in lowercase: onclick
. note that javascript itself is case sensitive, so if you write document.getElementById("...").onclick = ...
, then it must be all lowercase.# Pygame Example
import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('IBM Emulator')
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
fontObj = pygame.font.Font('freesansbold.ttf', 32)
textSurfaceObj = fontObj.render('IBM PC Emulator', True, GREEN,BLACK)
textRectObj = textSurfaceObj.get_rect()
textRectObj = (10, 10)
try:
while True: # main loop
DISPLAYSURF.fill(BLACK)
DISPLAYSURF.blit(textSurfaceObj, textRectObj)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
except SystemExit:
pass
It sounds like this
in your code is not referring to your .btn
element. Try referencing it explicitly with a selector:
var votevalue = parseInt($(".btn").data('votevalue'), 10);
Also, don't forget the radix.
The proposed solutions are perfect to download the images and if it is enough for you to save all the files in the directory you are using. But if you want to save all the images in a specified directory without reproducing the entire hierarchical tree of the site, try to add "cut-dirs" to the line proposed by Jon.
wget -r -P /save/location -A jpeg,jpg,bmp,gif,png http://www.boia.de --cut-dirs=1 --cut-dirs=2 --cut-dirs=3
in this case cut-dirs will prevent wget from creating sub-directories until the 3th level of depth in the website hierarchical tree, saving all the files in the directory you specified.You can add more 'cut-dirs' with higher numbers if you are dealing with sites with a deep structure.
Subversion implicitly has the remote repository associated with it at all times. Git, on the other hand, allows many "remotes", each of which represents a single remote place you can push to or pull from.
You need to add a remote for the GitHub repository to your local repository, then use git push ${remote}
or git pull ${remote}
to push and pull respectively - or the GUI equivalents.
Pro Git discusses remotes here: http://git-scm.com/book/ch2-5.html
The GitHub help also discusses them in a more "task-focused" way here: http://help.github.com/remotes/
Once you have associated the two you will be able to push or pull branches.
Try to check the length of the selector, if it returns you something then the element must exists else not.
if( $('#selector').length ) // use this if you are using id to check
{
// it exists
}
if( $('.selector').length ) // use this if you are using class to check
{
// it exists
}
Use the first if condition for id and the 2nd one for class.
exec('wget http://<url to the php script>')
worked for me.
It enable me to integrate two php files that were designed as web pages and run them as code to do work without affecting the calling page
You can do this :
<table id="table_header">
<tr>
<td contenteditable="true">a</td>
<td contenteditable="true">b</td>
<td contenteditable="true">c</td>
</tr>
</table>
The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc
A set of simple examples:
Using Gson:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class Gson {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
com.google.gson.Gson gson = new com.google.gson.Gson();
Response respuesta = gson.fromJson(json, Response.class);
System.out.println(respuesta.getExample());
System.out.println(respuesta.getFr());
} catch (IOException ex) {
}
return null;
}
public class Response{
private String example;
private String fr;
public String getExample() {
return example;
}
public void setExample(String example) {
this.example = example;
}
public String getFr() {
return fr;
}
public void setFr(String fr) {
this.fr = fr;
}
}
}
Using json-simple:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonSimple {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
try {
JSONParser parser = new JSONParser();
Object resultObject = parser.parse(json);
if (resultObject instanceof JSONArray) {
JSONArray array=(JSONArray)resultObject;
for (Object object : array) {
JSONObject obj =(JSONObject)object;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
}else if (resultObject instanceof JSONObject) {
JSONObject obj =(JSONObject)resultObject;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
} catch (Exception e) {
// TODO: handle exception
}
} catch (IOException ex) {
}
return null;
}
}
etc...
I created this test case: http://jsfiddle.net/ccQnK/1/ , I used the Javascript replace function with regular expressions to get the results that you want.
$(document).ready(function() {
var myContent = '<div id="test">Hello <span>world!</span></div>';
alert(myContent.replace(/(<([^>]+)>)/ig,""));
});
Looks like you have a corrupt tree object. You will need to get that object from someone else. Hopefully they will have an uncorrupted version.
You could actually reconstruct it if you can't find a valid version from someone else by guessing at what files should be there. You may want to see if the dates & times of the objects match up to it. Those could be the related blobs. You could infer the structure of the tree object from those objects.
Take a look at Scott Chacon's Git Screencasts regarding git internals. This will show you how git works under the hood and how to go about doing this detective work if you are really stuck and can't get that object from someone else.
Methods like sleep()
and wait()
of class Thread
might throw an InterruptedException
. This will happen if some other thread
wanted to interrupt the thread
that is waiting or sleeping.
System.setProperty("javax.net.ssl.trustStore", path_to_your_jks_file);
The accepted answer works only if you want exactly 31 days later. That means if you are using the date "2013-05-31" that you expect to not be in June which is not what I wanted.
If you want to have the next month, I suggest you to use the current year and month but keep using the 1st.
$date = date("Y-m-01");
$newdate = strtotime ( '+1 month' , strtotime ( $date ) ) ;
This way, you will be able to get the month and year of the next month without having a month skipped.
No, you'll have to specify the authentication method to use (typically "Basic") and the authentication realm. See http://en.wikipedia.org/wiki/Basic_access_authentication for an example request and response.
You might also want to read RFC 2617 - HTTP Authentication: Basic and Digest Access Authentication.
This should work.
int i = 1;
foreach (ListViewItem lvi in listView.Items) {
...
if(++i == 50) break;
}
decimal d = 3.00 is still 3. I guess you want to show it some where on screen or print it on log file as 3.00. You can do following
string str = d.ToString("F2");
or if you are using database to store the decimal then you can set pricision value in database.
just indent your code correctly:
def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
return period
if period>12: #i wrote this line to stop it..but seems its doesnt work....help..
return 0
else:
return period
You need to understand that the break
statement in your example will exit the infinite loop you've created with while True
. So when the break condition is True, the program will quit the infinite loop and continue to the next indented block. Since there is no following block in your code, the function ends and don't return anything. So I've fixed your code by replacing the break
statement by a return
statement.
Following your idea to use an infinite loop, this is the best way to write it:
def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
break
if period>12: #i wrote this line to stop it..but seems its doesnt work....help..
period = 0
break
return period
Swift 5
let attrStri = NSMutableAttributedString.init(string:"This is red")
let nsRange = NSString(string: "This is red").range(of: "red", options: String.CompareOptions.caseInsensitive)
attrStri.addAttributes([NSAttributedString.Key.foregroundColor : UIColor.red, NSAttributedString.Key.font: UIFont.init(name: "PTSans-Regular", size: 15.0) as Any], range: nsRange)
self.label.attributedText = attrStri
sda = new SqlCeDataAdapter("SELECT COUNT(regNumber) AS i FROM tblAttendance",con);
sda.Fill(dt);
string i = dt.Rows[0]["i"].ToString();
int bar = Convert.ToInt32(i);
if (bar >= 1){
dt.Clear();
MetroFramework.MetroMessageBox.Show(this, "something");
}
else if(bar <= 0) {
dt.Clear();
MetroFramework.MetroMessageBox.Show(this, "empty");
}
Consider this code:
Products::whereIn('id', function($query){
$query->select('paper_type_id')
->from(with(new ProductCategory)->getTable())
->whereIn('category_id', ['223', '15'])
->where('active', 1);
})->get();
Just use resize: none
textarea {
resize: none;
}
You can also decide to resize your textareas only horizontal or vertical, this way:
textarea { resize: vertical; }
textarea { resize: horizontal; }
Finally,
resize: both
enables the resize grabber.
I was having the exact same problem as OP. I had a DataTable which would not readjust its width after a jQuery animation (toogle("fast")) resized its container.
After reading these answers, and lots of try and error this did the trick for me:
$("#animatedElement").toggle(100, function() {
$("#dataTableId").resize();
});
After many test, i realized that i need to wait for the animation to finish for dataTables to calculate the correct width.
// Another simple example
var a = 11;
a == 10 ? alert("true") : alert("false");
To set the disabled
to false using the name
property of the input:
document.myForm.myInputName.disabled = false;
The value 1382086394000 is probably a time value, which is the number of milliseconds since 1970-01-01T00:00:00Z. You can use it to create an ECMAScript Date object using the Date constructor:
var d = new Date(1382086394000);
How you convert that into something readable is up to you. Simply sending it to output should call the internal (and entirely implementation dependent) toString method* that usually prints the equivalent system time in a human readable form, e.g.
Fri Oct 18 2013 18:53:14 GMT+1000 (EST)
In ES5 there are some other built-in formatting options:
and so on. Note that most are implementation dependent and will be different in different browsers. If you want the same format across all browsers, you'll need to format the date yourself, e.g.:
alert(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear());
* The format of Date.prototype.toString has been standardised in ECMAScript 2018. It might be a while before it's ubiquitous across all implementations, but at least the more common browsers support it now.
Dont complicate it, Solution for this is simple.
l = [1,5,8]
l = tuple(l)
params = {'l': l}
cursor.execute('SELECT * FROM table where id in %(l)s',params)
I hope this helped !!!
You can break a long string constant into logical chunks and assign them into an array. Then do a join
with an empty string as a delimiter.
var stringArray = [
'1. This is first part....',
'2. This is second part.....',
'3. Finishing here.'
];
var bigLongString = stringArray.join('');
console.log(bigLongString);
Output will be:
- This is first part....2. This is second part.....3. Finishing here.
There's a slight performance hit this way but you gain in code readability and maintainability.
In addition to the other answers, a struct can (but usually doesn't) have virtual functions, in which case the size of the struct will also include the space for the vtbl.
SharedPreferences mPref;
SharedPreferences.Editor editor;
public SharedPrefrences(Context mContext) {
mPref = mContext.getSharedPreferences(Constant.SharedPreferences, Context.MODE_PRIVATE);
editor=mPref.edit();
}
public void setLocation(String latitude, String longitude) {
SharedPreferences.Editor editor = mPref.edit();
editor.putString("latitude", latitude);
editor.putString("longitude", longitude);
editor.apply();
}
public String getLatitude() {
return mPref.getString("latitude", "");
}
public String getLongitude() {
return mPref.getString("longitude", "");
}
public void setGCM(String gcm_id, String device_id) {
editor.putString("gcm_id", gcm_id);
editor.putString("device_id", device_id);
editor.apply();
}
public String getGCMId() {
return mPref.getString("gcm_id", "");
}
public String getDeviceId() {
return mPref.getString("device_id", "");
}
public void setUserData(User user){
Gson gson = new Gson();
String json = gson.toJson(user);
editor.putString("user", json);
editor.apply();
}
public User getUserData(){
Gson gson = new Gson();
String json = mPref.getString("user", "");
User user = gson.fromJson(json, User.class);
return user;
}
public void setSocialMediaStatus(SocialMedialStatus status){
Gson gson = new Gson();
String json = gson.toJson(status);
editor.putString("status", json);
editor.apply();
}
public SocialMedialStatus getSocialMediaStatus(){
Gson gson = new Gson();
String json = mPref.getString("status", "");
SocialMedialStatus status = gson.fromJson(json, SocialMedialStatus.class);
return status;
}
Your syntax is pretty screwy.
Change this:
input:not(disabled)not:[type="submit"]:focus{
to:
input:not(:disabled):not([type="submit"]):focus{
Seems that many people don't realize :enabled
and :disabled
are valid CSS selectors...
In project ':app' you can add the following to your app/build.gradle file :
android {
configurations.all {
resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
}
}
I got this error message with vs2015, ssdt 14.1.xxx, ssrs. For me I think it was something different than described above with a 2 column, same name problem. I added this report, then deleted the report, then when I tried to add the query back in the ssrs wizard I got this message, " An error occurred while the query design method was being saved :invalid object name: tablename" . where tablename was the table on the query the wizard was reading. I tried cleaning the project, I tried rebuilding the project. In my opinion Microsoft isn't completing cleaning out the report when you delete it and as long as you try to add the original query back it won't add. The way I was able to fix it was to create the ssrs report in a whole new project (obviously nothing wrong with the query) and save it off to the side. Then I reopened my original ssrs project, right clicked on Reports, then Add, then add Existing Item. The report added back in just fine with no name conflict.
In order to read a file chosen by the user, using a file open dialog, you can use the <input type="file">
tag. You can find information on it from MSDN. When the file is chosen you can use the FileReader API to read the contents.
function onFileLoad(elementId, event) {_x000D_
document.getElementById(elementId).innerText = event.target.result;_x000D_
}_x000D_
_x000D_
function onChooseFile(event, onLoadFileHandler) {_x000D_
if (typeof window.FileReader !== 'function')_x000D_
throw ("The file API isn't supported on this browser.");_x000D_
let input = event.target;_x000D_
if (!input)_x000D_
throw ("The browser does not properly implement the event object");_x000D_
if (!input.files)_x000D_
throw ("This browser does not support the `files` property of the file input.");_x000D_
if (!input.files[0])_x000D_
return undefined;_x000D_
let file = input.files[0];_x000D_
let fr = new FileReader();_x000D_
fr.onload = onLoadFileHandler;_x000D_
fr.readAsText(file);_x000D_
}
_x000D_
<input type='file' onchange='onChooseFile(event, onFileLoad.bind(this, "contents"))' />_x000D_
<p id="contents"></p>
_x000D_
If you want to change all columns names, try df.toDF(*cols)
Maybe this answer will help:
nginx error connect to php5-fpm.sock failed (13: Permission denied)
The solution was to replace www-data with nginx in /var/www/php/fpm/pool.d/www.conf
And respectively modify the socket credentials:
$ sudo chmod nginx:nginx /var/run/php/php7.2-fpm.sock
$('#demoTable td').contents().each(function() {
if (this.nodeType === 3) {
this.textContent
? this.textContent = 'The text has been '
: this.innerText = 'The text has been '
} else {
this.innerHTML = 'changed';
return false;
}
})
Just to extend the @Joseph's answer:
After applying these commands your global .gitconfig
file will have the following lines (to speed up the process you can just copy them in the file):
[merge]
tool = kdiff3
[mergetool "kdiff3"]
path = C:/Program Files/KDiff3/kdiff3.exe
trustExitCode = false
[diff]
guitool = kdiff3
[difftool "kdiff3"]
path = C:/Program Files/KDiff3/kdiff3.exe
trustExitCode = false
My implementation, very self explanatory
function replaceAll(string, token, newtoken) {
if(token!=newtoken)
while(string.indexOf(token) > -1) {
string = string.replace(token, newtoken);
}
return string;
}
Once I'd discovered all the information of how my client was handling the encryption/decryption at their end it was straight forward using the AesManaged example suggested by dtb.
The finally implemented code started like this:
try
{
// Create a new instance of the AesManaged class. This generates a new key and initialization vector (IV).
AesManaged myAes = new AesManaged();
// Override the cipher mode, key and IV
myAes.Mode = CipherMode.ECB;
myAes.IV = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // CRB mode uses an empty IV
myAes.Key = CipherKey; // Byte array representing the key
myAes.Padding = PaddingMode.None;
// Create a encryption object to perform the stream transform.
ICryptoTransform encryptor = myAes.CreateEncryptor();
// TODO: perform the encryption / decryption as required...
}
catch (Exception ex)
{
// TODO: Log the error
throw ex;
}
Launch Developer command line "As an Administrator". This account has full access to Security log
select fields FROM table
WHERE date_created LIKE concat(LEFT(DATE_SUB(NOW(), interval 1 month),7),'%');
this one will be able to take advantage of an index if your date_created is indexed, because it doesn't apply any transformation function to the field value.
It is sometimes useful to force the use of a tab, if the user likes that. As Prakash stated above, this is sometimes dictated by the use of a non-user-initiated event, but there are ways around that.
For example:
$("#theButton").button().click( function(event) {
$.post( url, data )
.always( function( response ) {
window.open( newurl + response, '_blank' );
} );
} );
will always open "newurl" in a new browser window since the "always" function is not considered user-initiated. However, if we do this:
$("#theButton").button().click( function(event) {
var newtab = window.open( '', '_blank' );
$.post( url, data )
.always( function( response ) {
newtab.location = newurl + response;
} );
} );
we open the new browser window or create the new tab, as determined by the user preference in the button click which IS user-initiated. Then we just set the location to the desired URL after returning from the AJAX post. Voila, we force the use of a tab if the user likes that.
import cv2 as cv
im_color = cv.imread("lena.png", cv.IMREAD_COLOR)
im_gray = cv.cvtColor(im_color, cv.COLOR_BGR2GRAY)
At this point you have a color and a gray image. We are dealing with 8-bit
, uint8
images here. That means the images can have pixel values in the range of [0, 255]
and the values have to be integers.
Let's do a binary thresholding operation. It creates a black and white masked image. The black regions have value 0
and the white regions 255
_, mask = cv.threshold(im_gray, thresh=180, maxval=255, type=cv.THRESH_BINARY)
im_thresh_gray = cv.bitwise_and(im_gray, mask)
The mask can be seen below on the left. The image on it's right is the result of applying bitwise_and
operation between the gray image and the mask. What happened is, the spatial locations where the mask had a pixel value zero (black), became pixel value zero in the result image. The locations where the mask had pixel value 255 (white), the resulting image retained it's original gray value.
To apply this mask to our original color image, we need to convert the mask into a 3 channel image as the original color image is a 3 channel image.
mask3 = cv.cvtColor(mask, cv.COLOR_GRAY2BGR) # 3 channel mask
Then, we can apply this 3 channel mask to our color image using the same bitwise_and
function.
im_thresh_color = cv.bitwise_and(im_color, mask3)
mask3
from the code is the image below on the left, and im_thresh_color
is on its right.
You can plot the results and see for yourself.
cv.imshow("original image", im_color)
cv.imshow("binary mask", mask)
cv.imshow("3 channel mask", mask3)
cv.imshow("im_thresh_gray", im_thresh_gray)
cv.imshow("im_thresh_color", im_thresh_color)
cv.waitKey(0)
The original image is lenacolor.png
that I found here.
MYSQL 8.0:
Search my.ini
in disk, we will find this folder:
C:\ProgramData\MySQL\MySQL Server 8.0
It'sProgramData
, notProgram file
Data is in sub-folder: \Data
.
Each database
owns a folder, each table
is file, each index
is 1+ files.
2 more helpful methods: System.Environment.GetEnvironmentVariable("ComputerName" )
System.Environment.GetEnvironmentVariable("ClientName" ) to get the name of the user's PC if they're connected via Citrix XenApp or Terminal Services (aka RDS, RDP, Remote Desktop)
long hours = TimeUnit.MILLISECONDS.toHours(timeInMilliseconds);
long minutes = TimeUnit.MILLISECONDS.toMinutes(timeInMilliseconds - TimeUnit.HOURS.toMillis(hours));
long seconds = TimeUnit.MILLISECONDS
.toSeconds(timeInMilliseconds - TimeUnit.HOURS.toMillis(hours) - TimeUnit.MINUTES.toMillis(minutes));
long milliseconds = timeInMilliseconds - TimeUnit.HOURS.toMillis(hours)
- TimeUnit.MINUTES.toMillis(minutes) - TimeUnit.SECONDS.toMillis(seconds);
return String.format("%02d:%02d:%02d:%d", hours, minutes, seconds, milliseconds);
I'm having a similar issue.
I found
conda install pyodbc
is wrong!
when I use
apt-get install python-pyodbc
I solved this problem?
If you're not using jQuery... you need to access one of the event's TouchList
s to get a Touch
object which has pageX/Y
clientX/Y
etc.
Here are links to the relevant docs:
I'm using e.targetTouches[0].pageX
in my case.
use DataTable object instead:
private void doMore(DataTable dt)
{
foreach(DataColumn dc in dt.Columns)
{
MessageBox.Show(dc.ColumnName);
}
}
Split on tab, but then remove all blank matches.
text = "hi\tthere\t\t\tmy main man"
print [splits for splits in text.split("\t") if splits is not ""]
Outputs:
['hi', 'there', 'my main man']
See RFC 2822, section 2.1.1 to start.
There are two limits that this standard places on the number of characters in a line. Each line of characters MUST be no more than 998 characters, and SHOULD be no more than 78 characters, excluding the CRLF.
As the RFC states later, you can work around this limit (not that you should) by folding the subject over multiple lines.
Each header field is logically a single line of characters comprising the field name, the colon, and the field body. For convenience however, and to deal with the 998/78 character limitations per line, the field body portion of a header field can be split into a multiple line representation; this is called "folding". The general rule is that wherever this standard allows for folding white space (not simply WSP characters), a CRLF may be inserted before any WSP. For example, the header field:
Subject: This is a test
can be represented as:
Subject: This is a test
The recommendation for no more than 78 characters in the subject header sounds reasonable. No one wants to scroll to see the entire subject line, and something important might get cut off on the right.
You can easily call a method from any Fragment inside your Activity by doing a cast like this:
Java
((MainActivity)getActivity()).startChronometer();
Kotlin
(activity as MainActivity).startChronometer()
Just remember to make sure this Fragment's activity is in fact MainActivity before you do it.
Hope this helps!
With the new version of HttpClient
and without the WebApi
package it would be:
var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
var result = client.PostAsync(url, content).Result;
Or if you want it async
:
var result = await client.PostAsync(url, content);
you can fix problem by:
var canvas = $('#canvas');
var b64Text = canvas.toDataURL();
b64Text = b64Text.replace('data:image/png;base64,','');
var base64Data = b64Text;
I hope this help you
Use:
.content {
background: url('http://www.gransebryan.com/wp-content/uploads/2016/03/bryan-ganzon-granse-who.png') center no-repeat;
}
.displaybg {
text-align: center;
color: #FFF;
}
As a continuation on Matas' answer on benchmarking.
TL/DR: Exists() and Any() are equally fast.
First off: Benchmarking using Stopwatch is not precise (see series0ne's answer on a different, but similiar, topic), but it is far more precise than DateTime.
The way to get really precise readings is by using Performance Profiling. But one way to get a sense of how the two methods' performance measure up to each other is by executing both methods loads of times and then comparing the fastest execution time of each. That way, it really doesn't matter that JITing and other noise gives us bad readings (and it does), because both executions are "equally misguiding" in a sense.
static void Main(string[] args)
{
Console.WriteLine("Generating list...");
List<string> list = GenerateTestList(1000000);
var s = string.Empty;
Stopwatch sw;
Stopwatch sw2;
List<long> existsTimes = new List<long>();
List<long> anyTimes = new List<long>();
Console.WriteLine("Executing...");
for (int j = 0; j < 1000; j++)
{
sw = Stopwatch.StartNew();
if (!list.Exists(o => o == "0123456789012"))
{
sw.Stop();
existsTimes.Add(sw.ElapsedTicks);
}
}
for (int j = 0; j < 1000; j++)
{
sw2 = Stopwatch.StartNew();
if (!list.Exists(o => o == "0123456789012"))
{
sw2.Stop();
anyTimes.Add(sw2.ElapsedTicks);
}
}
long existsFastest = existsTimes.Min();
long anyFastest = anyTimes.Min();
Console.WriteLine(string.Format("Fastest Exists() execution: {0} ticks\nFastest Any() execution: {1} ticks", existsFastest.ToString(), anyFastest.ToString()));
Console.WriteLine("Benchmark finished. Press any key.");
Console.ReadKey();
}
public static List<string> GenerateTestList(int count)
{
var list = new List<string>();
for (int i = 0; i < count; i++)
{
Random r = new Random();
int it = r.Next(0, 100);
list.Add(new string('s', it));
}
return list;
}
After executing the above code 4 times (which in turn do 1 000 Exists()
and Any()
on a list with 1 000 000 elements), it's not hard to see that the methods are pretty much equally fast.
Fastest Exists() execution: 57881 ticks
Fastest Any() execution: 58272 ticks
Fastest Exists() execution: 58133 ticks
Fastest Any() execution: 58063 ticks
Fastest Exists() execution: 58482 ticks
Fastest Any() execution: 58982 ticks
Fastest Exists() execution: 57121 ticks
Fastest Any() execution: 57317 ticks
There is a slight difference, but it's too small a difference to not be explained by background noise. My guess would be that if one would do 10 000 or 100 000 Exists()
and Any()
instead, that slight difference would disappear more or less.
We can add additional columns to DataFrame directly with below steps:
from pyspark.sql.functions import when
df = spark.createDataFrame([["amit", 30], ["rohit", 45], ["sameer", 50]], ["name", "age"])
df = df.withColumn("profile", when(df.age >= 40, "Senior").otherwise("Executive"))
df.show()
The above works,(having an original document with mixed pages of 11' and 16' wide). However auto rotate needs to be off otherwise landscape pages are saved with page white top and bottom, so dont work in full screen view.
Solution is to re open the new PDF in acrobat and crop the first image (carefully to avoid white border), then select page range i.e. all, this then applies to all pages. job done !
jar cvfe myjar.jar package.MainClass *.class
where MainClass
is the class with your main
method, and package
is MainClass
's package.
Note you have to compile your .java
files to .class
files before doing this.
c create new archive
v generate verbose output on standard output
f specify archive file name
e specify application entry point for stand-alone application bundled into an executable jar file
This answer inspired by Powerslave's comment on another answer.
One small point: these are not operators. Operators are used in expressions to create new values from existing values (1+2 becomes 3, for example. The * and ** here are part of the syntax of function declarations and calls.
pprint.pprint()
is a good tool for this job:
>>> import pprint
>>> cars = {'A':{'speed':70,
... 'color':2},
... 'B':{'speed':60,
... 'color':3}}
>>> pprint.pprint(cars, width=1)
{'A': {'color': 2,
'speed': 70},
'B': {'color': 3,
'speed': 60}}
Strings, by C
definition, are terminated by '\0'
. You have no "C strings"
in your program.
Your program reads characters (buffered till ENTER) from the standard input (the keyboard) and writes them back to the standard output (the screen). It does this no matter how many characters you type or for how long you do this.
To stop the program you have to indicate that the standard input has no more data (huh?? how can a keyboard have no more data?).
You simply press Ctrl+D (Unix) or Ctrl+Z (Windows) to pretend the file has reached its end.
Ctrl+D (or Ctrl+Z) are not really characters in the C
sense of the word.
If you run your program with input redirection, the EOF
is the actual end of file, not a make belief one
./a.out < source.c
string.Format("{0:000}", myString);
This question is well answered but I think I can find a niche to fill here regardless, if only to reduce the workload on somebody googling this like I did. The answer from vagoberto gave me what I needed to solve my version of this problem and so I'll share my solution here.
I developed a plot script in an up-to-date environment which allowed me to do:
#!/usr/bin/gnuplot -c
set terminal png truecolor transparent crop
set output ARG1
set size 1, 0.2
rrLower = ARG2
rrUpper = ARG3
rrSD = ARG4
resultx = ARG5+0 # Type coercion required for data series
resulty = 0.02 # fixed
# etc.
This executes perfectly well from command-line in an environment with a recent gnuplot (5.0.3 in my case).
$ ./plotStuff.gp 'output.png' 2.3 6.7 4.3 7
When uploaded to my server and executed, it failed because the server version was 4.6.4 (current on Ubuntu 14.04 LTS). The below shim solved this problem without requiring any change to the original script.
#!/bin/bash
# GPlot v<4.6.6 doesn't support direct command line arguments.
#This script backfills the functionality transparently.
SCRIPT="plotStuff.gp"
ARG1=$1
ARG2=$2
ARG3=$3
ARG4=$4
ARG5=$5
ARG6=$6
gnuplot -e "ARG1='${ARG1}'; ARG2='${ARG2}'; ARG3='${ARG3}'; ARG4='${ARG4}'; ARG5='${ARG5}'; ARG6='${ARG6}'" $SCRIPT
The combination of these two scripts allows parameters to be passed from bash to gnuplot scripts without regard to the gnuplot version and in basically any *nix.
Here's a set of properties i made that feel more intuitive to use than the built in stuff. The conditions are based off of the truth table supplied above by ahmd0.
<!-- truth table for installer varables (install vs uninstall vs repair vs upgrade) https://stackoverflow.com/a/17608049/1721136 -->
<SetProperty Id="_INSTALL" After="FindRelatedProducts" Value="1"><![CDATA[Installed="" AND PREVIOUSVERSIONSINSTALLED=""]]></SetProperty>
<SetProperty Id="_UNINSTALL" After="FindRelatedProducts" Value="1"><![CDATA[PREVIOUSVERSIONSINSTALLED="" AND REMOVE="ALL"]]></SetProperty>
<SetProperty Id="_CHANGE" After="FindRelatedProducts" Value="1"><![CDATA[Installed<>"" AND REINSTALL="" AND PREVIOUSVERSIONSINSTALLED<>"" AND REMOVE=""]]></SetProperty>
<SetProperty Id="_REPAIR" After="FindRelatedProducts" Value="1"><![CDATA[REINSTALL<>""]]></SetProperty>
<SetProperty Id="_UPGRADE" After="FindRelatedProducts" Value="1"><![CDATA[PREVIOUSVERSIONSINSTALLED<>"" ]]></SetProperty>
Here's some sample usage:
<Custom Action="CaptureExistingLocalSettingsValues" After="InstallInitialize">NOT _UNINSTALL</Custom>
<Custom Action="GetConfigXmlToPersistFromCmdLineArgs" After="InstallInitialize">_INSTALL OR _UPGRADE</Custom>
<Custom Action="ForgetProperties" Before="InstallFinalize">_UNINSTALL OR _UPGRADE</Custom>
<Custom Action="SetInstallCustomConfigSettingsArgs" Before="InstallCustomConfigSettings">NOT _UNINSTALL</Custom>
<Custom Action="InstallCustomConfigSettings" Before="InstallFinalize">NOT _UNINSTALL</Custom>
Issues:
You can put the control you want to center inside a Panel and set the left and right padding values to something larger than the default. As long as they are equal and your control is anchored to the sides of the Panel, then it will appear centered in that Panel. Then you can anchor the container Panel to its parent as needed.
The code was most likely compiled with a later JDK (without using cross-compilation options) and is being run on an earlier JRE. While upgrading the JRE is one solution, it would be better to use the cross-compilation options to ensure the code will run on whatever JRE is intended as the minimum version for the app.
I am adding an answer using raw CSS3 and SVG without requiring LESS or SASS.
Basically, if the question is to make a colour 10%,25%,50% ligher or darker for the sakes of a global hover effect you can create an SVG data call like this
:root{
--lighten-bg: url('data:image/svg+xml;utf8,<svg version="1.1" id="cssLighten" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="50px" height="50px" viewBox="0 0 50 50" enable-background="new 0 0 50 50" xml:space="preserve"><rect opacity="0.2" fill="white" width="50" height="50"/></svg>') !important;
--darken-bg: url('data:image/svg+xml;utf8,<svg version="1.1" id="cssDarken" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="50px" height="50px" viewBox="0 0 50 50" enable-background="new 0 0 50 50" xml:space="preserve"><rect opacity="0.2" fill="black" width="50" height="50"/></svg>') !important;
}
.myButton{
color: white;
background-color:blue;
}
.myButton:hover{
background-image: var(--lighten-bg);
}
For some reason, unknown to me, the SVG won't allow me to enter a hex value in the "fill" attribute but "white" and "black" satisfy my need.
Food for thought: If you didn't mind using images, just use a 50% transparent PNG as the background image. If you wanted to be fancy, call a PHP script as the background image and pass it the HEX and OPACITY values and let it spit out the SVG code above.
If you want to build DOM you can use jsdom.
There's also cheerio, it has the jQuery interface and it's a lot faster than older versions of jsdom, although these days they are similar in performance.
You might wanna have a look at htmlparser2, which is a streaming parser, and according to its benchmark, it seems to be faster than others, and no DOM by default. It can also produce a DOM, as it is also bundled with a handler that creates a DOM. This is the parser that is used by cheerio.
parse5 also looks like a good solution. It's fairly active (11 days since the last commit as of this update), WHATWG-compliant, and is used in jsdom, Angular, and Polymer.
And if you want to parse HTML for web scraping, you can use YQL1. There is a node module for it. YQL I think would be the best solution if your HTML is from a static website, since you are relying on a service, not your own code and processing power. Though note that it won't work if the page is disallowed by the robot.txt of the website, YQL won't work with it.
If the website you're trying to scrape is dynamic then you should be using a headless browser like phantomjs. Also have a look at casperjs, if you're considering phantomjs. And you can control casperjs from node with SpookyJS.
Beside phantomjs there's zombiejs. Unlike phantomjs that cannot be embedded in nodejs, zombiejs is just a node module.
There's a nettuts+ toturial for the latter solutions.
1 Since Aug. 2014, YUI library, which is a requirement for YQL, is no longer actively maintained, source
For port 80, the command would be : netstat -an | find "80" For port n, the command would be : netstat -an | find "n"
Here, netstat is the instruction to your machine
-a : Displays all connections and listening ports -n : Displays all address and instructions in numerical format (This is required because output from -a can contain machine names)
Then, a find command to "Pattern Match" the output of previous command.
Your query should have date as
select * from table between `lowerdate` and `upperdate`
try
SELECT * FROM `objects`
WHERE (date_field BETWEEN '2010-01-30 14:15:55' AND '2010-09-29 10:15:55')
open
also has an -a flag, that you can use to open up an app from within the Applications folder by it's name (or by bundle identifier with -b flag). You can combine this with the --args option to achieve the result you want:
open -a APP_NAME --args ARGS
To open up a video in VLC player that should scale with a factor 2x and loop you would for example exectute:
open -a VLC --args -L --fullscreen
Note that I could not get the output of the commands to the terminal. (although I didn't try anything to resolve that)
They are returning false because you are testing for object identity rather than value equality. This returns false because your arrays are actually different objects in memory.
If you want to test for value equality should use the handy comparison functions in java.util.Arrays
e.g.
import java.util.Arrays;
'''''
Arrays.equals(a,b);
Updated for pandas
0.20
given that ix
is deprecated. This demonstrates not only how to use loc
, iloc
, at
, iat
, set_value
, but how to accomplish, mixed positional/label based indexing.
loc
- label based
Allows you to pass 1-D arrays as indexers. Arrays can be either slices (subsets) of the index or column, or they can be boolean arrays which are equal in length to the index or columns.
Special Note: when a scalar indexer is passed, loc
can assign a new index or column value that didn't exist before.
# label based, but we can use position values
# to get the labels from the index object
df.loc[df.index[2], 'ColName'] = 3
df.loc[df.index[1:3], 'ColName'] = 3
iloc
- position based
Similar to loc
except with positions rather that index values. However, you cannot assign new columns or indices.
# position based, but we can get the position
# from the columns object via the `get_loc` method
df.iloc[2, df.columns.get_loc('ColName')] = 3
df.iloc[2, 4] = 3
df.iloc[:3, 2:4] = 3
at
- label based
Works very similar to loc
for scalar indexers. Cannot operate on array indexers. Can! assign new indices and columns.
Advantage over loc
is that this is faster.
Disadvantage is that you can't use arrays for indexers.
# label based, but we can use position values
# to get the labels from the index object
df.at[df.index[2], 'ColName'] = 3
df.at['C', 'ColName'] = 3
iat
- position based
Works similarly to iloc
. Cannot work in array indexers. Cannot! assign new indices and columns.
Advantage over iloc
is that this is faster.
Disadvantage is that you can't use arrays for indexers.
# position based, but we can get the position
# from the columns object via the `get_loc` method
IBM.iat[2, IBM.columns.get_loc('PNL')] = 3
set_value
- label based
Works very similar to loc
for scalar indexers. Cannot operate on array indexers. Can! assign new indices and columns
Advantage Super fast, because there is very little overhead!
Disadvantage There is very little overhead because pandas
is not doing a bunch of safety checks. Use at your own risk. Also, this is not intended for public use.
# label based, but we can use position values
# to get the labels from the index object
df.set_value(df.index[2], 'ColName', 3)
set_value
with takable=True
- position based
Works similarly to iloc
. Cannot work in array indexers. Cannot! assign new indices and columns.
Advantage Super fast, because there is very little overhead!
Disadvantage There is very little overhead because pandas
is not doing a bunch of safety checks. Use at your own risk. Also, this is not intended for public use.
# position based, but we can get the position
# from the columns object via the `get_loc` method
df.set_value(2, df.columns.get_loc('ColName'), 3, takable=True)
I sovled this errors by modifying the Database charset.Old Database charset is cp1252
and i conver to utf-8
It really depends on what type of game you're planning on building: many games could be done in a language like C#. That being said, the majority of game development is done in C++ just becasue the majority of game development needs to eke out every last bit of performance that the platform can provide and that means either C, C++ or (shudder) assembler.
If you're just quickly looking to keep a cmd instance open instead of exiting immediately, simply doing the following is enough
set /p asd="Hit enter to continue"
at the end of your script and it'll keep the window open.
Note that this'll set asd
as an environment variable, and can be replaced with anything else.
Check out the discussion at Android WebView onReceivedError(). It's quite long, but the consensus seems to be that a) you can't stop the "web page not available" page appearing, but b) you could always load an empty page after you get an onReceivedError
Here is another way to iterate over the properties:
Enumeration eProps = properties.propertyNames();
while (eProps.hasMoreElements()) {
String key = (String) eProps.nextElement();
String value = properties.getProperty(key);
System.out.println(key + " => " + value);
}
The accepted answer to how to replace multiple strings together in Oracle suggests using nested REPLACE
statements, and I don't think there is a better way.
If you are going to make heavy use of this, you could consider writing your own function:
CREATE TYPE t_text IS TABLE OF VARCHAR2(256);
CREATE FUNCTION multiple_replace(
in_text IN VARCHAR2, in_old IN t_text, in_new IN t_text
)
RETURN VARCHAR2
AS
v_result VARCHAR2(32767);
BEGIN
IF( in_old.COUNT <> in_new.COUNT ) THEN
RETURN in_text;
END IF;
v_result := in_text;
FOR i IN 1 .. in_old.COUNT LOOP
v_result := REPLACE( v_result, in_old(i), in_new(i) );
END LOOP;
RETURN v_result;
END;
and then use it like this:
SELECT multiple_replace( 'This is #VAL1# with some #VAL2# to #VAL3#',
NEW t_text( '#VAL1#', '#VAL2#', '#VAL3#' ),
NEW t_text( 'text', 'tokens', 'replace' )
)
FROM dual
This is text with some tokens to replace
If all of your tokens have the same format ('#VAL' || i || '#'
), you could omit parameter in_old
and use your loop-counter instead.
The accepted answer doesn't work for me, I did it as below.
$( function() {
$( "#datepicker" ).datepicker();
$('#getLastDateOfMon').on('click', function(){
var date = $('#datepicker').val();
// Format 'mm/dd/yy' eg: 12/31/2018
var parts = date.split("/");
var lastDateOfMonth = new Date();
lastDateOfMonth.setFullYear(parts[2]);
lastDateOfMonth.setMonth(parts[0]);
lastDateOfMonth.setDate(0);
alert(lastDateOfMonth.toLocaleDateString());
});
});
_x000D_
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<p>Date: <input type="text" id="datepicker"></p>
<button id="getLastDateOfMon">Get Last Date of Month </button>
</body>
</html>
_x000D_
This might not work in all situations, but here is what I did: I extended the FilterInputStream class and do the required processing of the bytes as the external lib reads the data.
public class StreamBytesWithExtraProcessingInputStream extends FilterInputStream {
protected StreamBytesWithExtraProcessingInputStream(InputStream in) {
super(in);
}
@Override
public int read() throws IOException {
int readByte = super.read();
processByte(readByte);
return readByte;
}
@Override
public int read(byte[] buffer, int offset, int count) throws IOException {
int readBytes = super.read(buffer, offset, count);
processBytes(buffer, offset, readBytes);
return readBytes;
}
private void processBytes(byte[] buffer, int offset, int readBytes) {
for (int i = 0; i < readBytes; i++) {
processByte(buffer[i + offset]);
}
}
private void processByte(int readByte) {
// TODO do processing here
}
}
Then you simply pass an instance of StreamBytesWithExtraProcessingInputStream
where you would have passed in the input stream. With the original input stream as constructor parameter.
It should be noted that this works byte for byte, so don't use this if high performance is a requirement.
For non-grouped elements, name and id should be same. In this case you gave name as 'sp' and id as 'sp_100'. Don't do that, do it like this:
HTML:
<input type="hidden" id="msg" name="msg" value="" style="display:none"/>
<input type="checkbox" name="sp" value="100" id="sp">
Javascript:
var Msg="abc";
document.getElementById('msg').value = Msg;
document.getElementById('sp').checked = true;
For more details
please visit : http://www.impressivewebs.com/avoiding-problems-with-javascript-getelementbyid-method-in-internet-explorer-7/
why dont you use export, then click 'Custom - display all possible options' radio button, then choose your database, then go to Output and choose 'View output as text' just scroll down and Go. Voila!
short answer you have to mix between them , use json for data that you are not going to make relations with them like contact data , address , products variabls
public static boolean isEmailValid(String email) {
boolean isValid = false;
String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}
Mongoose basically wraps mongodb's api to give you a pseudo relational db api so queries are not going to be exactly like mongodb queries. Mongoose findOne query returns a query object, not a document. You can either use a callback as the solution suggests or as of v4+ findOne returns a thenable so you can use .then or await/async to retrieve the document.
// thenables
Auth.findOne({nick: 'noname'}).then(err, result) {console.log(result)};
Auth.findOne({nick: 'noname'}).then(function (doc) {console.log(doc)});
// To use a full fledge promise you will need to use .exec()
var auth = Auth.findOne({nick: 'noname'}).exec();
auth.then(function (doc) {console.log(doc)});
// async/await
async function auth() {
const doc = await Auth.findOne({nick: 'noname'}).exec();
return doc;
}
auth();
See the docs if you would like to use a third party promise library.
this
is the element, $(this)
is the jQuery object constructed with that element
$(".class").each(function(){
//the iterations current html element
//the classic JavaScript API is exposed here (such as .innerHTML and .appendChild)
var HTMLElement = this;
//the current HTML element is passed to the jQuery constructor
//the jQuery API is exposed here (such as .html() and .append())
var jQueryObject = $(this);
});
A deeper look
this
MDN is contained in an execution context
The scope refers to the current Execution ContextECMA. In order to understand this
, it is important to understand the way execution contexts operate in JavaScript.
execution contexts bind this
When control enters an execution context (code is being executed in that scope) the environment for variables are setup (Lexical and Variable Environments - essentially this sets up an area for variables to enter which were already accessible, and an area for local variables to be stored), and the binding of this
occurs.
jQuery binds this
Execution contexts form a logical stack. The result is that contexts deeper in the stack have access to previous variables, but their bindings may have been altered. Every time jQuery calls a callback function, it alters the this binding by using apply
MDN.
callback.apply( obj[ i ] )//where obj[i] is the current element
The result of calling apply
is that inside of jQuery callback functions, this
refers to the current element being used by the callback function.
For example, in .each
, the callback function commonly used allows for .each(function(index,element){/*scope*/})
. In that scope, this == element
is true.
jQuery callbacks use the apply function to bind the function being called with the current element. This element comes from the jQuery object's element array. Each jQuery object constructed contains an array of elements which match the selectorjQuery API that was used to instantiate the jQuery object.
$(selector)
calls the jQuery function (remember that $
is a reference to jQuery
, code: window.jQuery = window.$ = jQuery;
). Internally, the jQuery function instantiates a function object. So while it may not be immediately obvious, using $()
internally uses new jQuery()
. Part of the construction of this jQuery object is to find all matches of the selector. The constructor will also accept html strings and elements. When you pass this
to the jQuery constructor, you are passing the current element for a jQuery object to be constructed with. The jQuery object then contains an array-like structure of the DOM elements matching the selector (or just the single element in the case of this
).
Once the jQuery object is constructed, the jQuery API is now exposed. When a jQuery api function is called, it will internally iterate over this array-like structure. For each item in the array, it calls the callback function for the api, binding the callback's this
to the current element. This call can be seen in the code snippet above where obj
is the array-like structure, and i
is the iterator used for the position in the array of the current element.
You can use the extension method AsEnumerable in Assembly System.Core and System.Linq namespace :
List<Book> list = new List<Book>();
return list.AsEnumerable();
This will, as said on this MSDN link change the type of the List in compile-time. This will give you the benefits also to only enumerate your collection we needed (see MSDN example for this).
Just follow the steps:
Short answer:
const base64Canvas = canvas.toDataURL("image/jpeg").split(';base64,')[1];
THIS WORK ALSO WITH Arraylist
// Create a couple ArrayList objects and populate them
// with some delicious fruits.
ArrayList<String> firstList = new ArrayList<String>() {/**
*
*/
private static final long serialVersionUID = 1L;
{
add("apple");
add("orange");
add("pea");
}};
ArrayList<String> secondList = new ArrayList<String>() {
/**
*
*/
private static final long serialVersionUID = 1L;
{
add("apple");
add("orange");
add("banana");
add("strawberry");
}};
// Show the "before" lists
System.out.println("First List: " + firstList);
System.out.println("Second List: " + secondList);
// Remove all elements in firstList from secondList
secondList.removeAll(firstList);
// Show the "after" list
System.out.println("Result: " + secondList);
to convert a TimestampTZ in oracle, you do
TO_TIMESTAMP_TZ('2012-10-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR')
at time zone 'region'
see here: http://docs.oracle.com/cd/E11882_01/server.112/e10729/ch4datetime.htm#NLSPG264
and here for regions: http://docs.oracle.com/cd/E11882_01/server.112/e10729/applocaledata.htm#NLSPG0141
eg:
SQL> select a, sys_extract_utc(a), a at time zone '-05:00' from (select TO_TIMESTAMP_TZ('2013-04-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);
A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'-05:00'
---------------------------------------------------------------------------
09-APR-13 01.10.21.000000000 CST
09-APR-13 06.10.21.000000000
09-APR-13 01.10.21.000000000 -05:00
SQL> select a, sys_extract_utc(a), a at time zone '-05:00' from (select TO_TIMESTAMP_TZ('2013-03-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);
A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'-05:00'
---------------------------------------------------------------------------
09-MAR-13 01.10.21.000000000 CST
09-MAR-13 07.10.21.000000000
09-MAR-13 02.10.21.000000000 -05:00
SQL> select a, sys_extract_utc(a), a at time zone 'America/Los_Angeles' from (select TO_TIMESTAMP_TZ('2013-04-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);
A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'AMERICA/LOS_ANGELES'
---------------------------------------------------------------------------
09-APR-13 01.10.21.000000000 CST
09-APR-13 06.10.21.000000000
08-APR-13 23.10.21.000000000 AMERICA/LOS_ANGELES
Execute
set -o allexport
Any variables you source from a file after this will be exported in your shell.
source conf-file
When you're done execute. This will disable allexport mode.
set +o allexport
In .NET Framework 4 there is enhancement System.Guid structure, These includes new TryParse and TryParseExact methods to Parse GUID. Here is example for this.
//Generate New GUID
Guid objGuid = Guid.NewGuid();
//Take invalid guid format
string strGUID = "aaa-a-a-a-a";
Guid newGuid;
if (Guid.TryParse(objGuid.ToString(), out newGuid) == true)
{
Response.Write(string.Format("<br/>{0} is Valid GUID.", objGuid.ToString()));
}
else
{
Response.Write(string.Format("<br/>{0} is InValid GUID.", objGuid.ToString()));
}
Guid newTmpGuid;
if (Guid.TryParse(strGUID, out newTmpGuid) == true)
{
Response.Write(string.Format("<br/>{0} is Valid GUID.", strGUID));
}
else
{
Response.Write(string.Format("<br/>{0} is InValid GUID.", strGUID));
}
In this example we create new guid object and also take one string variable which has invalid guid. After that we use TryParse method to validate that both variable has valid guid format or not. By running example you can see that string variable has not valid guid format and it gives message of "InValid guid". If string variable has valid guid than this will return true in TryParse method.
Omit
the property when extending the interface:
interface A {
a: number;
b: number;
}
interface B extends Omit<A, 'a'> {
a: boolean;
}
The right way to iterate on a list inside list is:
//iterate on the general list
for(int i = 0 ; i < collection.size() ; i++) {
ArrayList<String> currentList = collection.get(i);
//now iterate on the current list
for (int j = 0; j < currentList.size(); j++) {
String s = currentList.get(1);
}
}
Project build settings have a block 'Swift Compiler - Languages', which stores information about Swift Language Version in key-value format. It will show you all available (supported) Swift Language Version for your Xcode and active version also by a tick mark.
Project ? (Select Your Project Target) ? Build Settings ? (Type 'swift_version' in the Search bar) Swift Compiler Language ? Swift Language Version ? Click on Language list to open it (and there will be a tick mark on any one of list-item, that will be current swift version).
Look at this snapshot, for easy understanding:
With help of following code, programmatically you can find Swift version supported by your project.
#if swift(>=5.3)
print("Hello, Swift 5.3")
#elseif swift(>=5.2)
print("Hello, Swift 5.2")
#elseif swift(>=5.1)
print("Hello, Swift 5.1")
#elseif swift(>=5.0)
print("Hello, Swift 5.0")
#elseif swift(>=4.2)
print("Hello, Swift 4.2")
#elseif swift(>=4.1)
print("Hello, Swift 4.1")
#elseif swift(>=4.0)
print("Hello, Swift 4.0")
#elseif swift(>=3.2)
print("Hello, Swift 3.2")
#elseif swift(>=3.0)
print("Hello, Swift 3.0")
#elseif swift(>=2.2)
print("Hello, Swift 2.2")
#elseif swift(>=2.1)
print("Hello, Swift 2.1")
#elseif swift(>=2.0)
print("Hello, Swift 2.0")
#elseif swift(>=1.2)
print("Hello, Swift 1.2")
#elseif swift(>=1.1)
print("Hello, Swift 1.1")
#elseif swift(>=1.0)
print("Hello, Swift 1.0")
#endif
Here is result using Playground (with Xcode 11.x)
The answer shared by @mockinterface is correct. Although I would like to add my 2 cents to it.
If someone is using frameworks like scrapy
the you will have to use /html/body//a[contains(@href,'com')][2]/@href
along with get() like this:
response.xpath('//a[contains(@href,'com')][2]/@href').get()
Paste this into the console and run the commands:
## How to update R in RStudio using installr package (for Windows)
## paste this into the console and run the commands
## "The updateR() command performs the following: finding the latest R version, downloading it, running the installer, deleting the installation file, copy and updating old packages to the new R installation."
## more info here: https://cran.r-project.org/web/packages/installr/index.html
install.packages("installr")
library(installr)
updateR()
## Watch for small pop up windows. There will be many questions and they don't always pop to the front.
## Note: It warns that it might work better in Rgui but I did it in Rstudio and it worked just fine.
Definitely it is not the case but I found this mistake pretty common and unobvious. The target of a FOREIGN KEY
could be not PRIMARY KEY
. Te answer which become useful for me is:
A FOREIGN KEY always must be pointed to a PRIMARY KEY true field of other table.
CREATE TABLE users(
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(40));
CREATE TABLE userroles(
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
FOREIGN KEY(user_id) REFERENCES users(id));
In case you use Spring Test try org.springframework.test.util.ReflectionTestUtils
ReflectionTestUtils.setField(testObject, "person", mockedPerson);
substring(0,38)
means the String has to be 38 characters or longer. If not, the "String index is out of range".
If you are making repeated calls and are concerned with performance, This test reveals the BASH method is ~15x faster than forking to sed and likely any other external process.
hello=123456789X123456789X123456789X123456789X123456789X123456789X123456789X123456789X123456789X123456789X123456789X
P1=$(date +%s)
for i in {1..10000}
do
echo $hello | sed s/X//g > /dev/null
done
P2=$(date +%s)
echo $[$P2-$P1]
for i in {1..10000}
do
echo ${hello//X/} > /dev/null
done
P3=$(date +%s)
echo $[$P3-$P2]
I found myself having to read a string with NULL in it, so here is a solution that will read anything you throw at it. Although if you actually are dealing with NULL, you will need to deal with that at the hex level.
$ cat > read.dd.sh
read.dd() {
buf=
while read; do
buf+=$REPLY
done < <( dd bs=1 2>/dev/null | xxd -p )
printf -v REPLY '%b' $( sed 's/../ \\\x&/g' <<< $buf )
}
Proof:
$ . read.dd.sh
$ read.dd < read.dd.sh
$ echo -n "$REPLY" > read.dd.sh.copy
$ diff read.dd.sh read.dd.sh.copy || echo "File are different"
$
HEREDOC example (with ^J, ^M, ^I):
$ read.dd <<'HEREDOC'
> (TAB)
> (SPACES)
(^J)^M(^M)
> DONE
>
> HEREDOC
$ declare -p REPLY
declare -- REPLY=" (TAB)
(SPACES)
(^M)
DONE
"
$ declare -p REPLY | xxd
0000000: 6465 636c 6172 6520 2d2d 2052 4550 4c59 declare -- REPLY
0000010: 3d22 0928 5441 4229 0a20 2020 2020 2028 =".(TAB). (
0000020: 5350 4143 4553 290a 285e 4a29 0d28 5e4d SPACES).(^J).(^M
0000030: 290a 444f 4e45 0a0a 220a ).DONE
The request body is available as byte stream by HttpServletRequest#getInputStream()
:
InputStream body = request.getInputStream();
// ...
Or as character stream by HttpServletRequest#getReader()
:
Reader body = request.getReader();
// ...
Note that you can read it only once. The client ain't going to resend the same request multiple times. Calling getParameter()
and so on will implicitly also read it. If you need to break down parameters later on, you've got to store the body somewhere and process yourself.
Just wondering why you are using 2 directives?
It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.
Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).
It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.
Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.
// This works on Android Lollipop 5.0.2
public static boolean launchApp(Context context, String packageName) {
final PackageManager manager = context.getPackageManager();
final Intent appLauncherIntent = new Intent(Intent.ACTION_MAIN);
appLauncherIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> resolveInfos = manager.queryIntentActivities(appLauncherIntent, 0);
if ((null != resolveInfos) && (!resolveInfos.isEmpty())) {
for (ResolveInfo rInfo : resolveInfos) {
String className = rInfo.activityInfo.name.trim();
String targetPackageName = rInfo.activityInfo.packageName.trim();
Log.d("AppsLauncher", "Class Name = " + className + " Target Package Name = " + targetPackageName + " Package Name = " + packageName);
if (packageName.trim().equals(targetPackageName)) {
Intent intent = new Intent();
intent.setClassName(targetPackageName, className);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
Log.d("AppsLauncher", "Launching Package '" + packageName + "' with Activity '" + className + "'");
return true;
}
}
}
return false;
}
Normal ways would be Integer.toString(i)
or String.valueOf(i)
.
int i = 5;
String strI = String.valueOf(i);
Or
int aInt = 1;
String aString = Integer.toString(aInt);
You can try
$string = "this is the test for string." ;
$string = str_replace(' ', '_', $string);
$string = substr($string,0,10);
var_dump($string);
Output
this_is_th
Because strip()
only strips trailing and leading characters, based on what you provided. I suggest:
>>> import re
>>> name = "Barack (of Washington)"
>>> name = re.sub('[\(\)\{\}<>]', '', name)
>>> print(name)
Barack of Washington
Yes, that will work as you expect it to. Unfortunately, I seem to be having trouble to find an explicit statement of this in the MySQL manual.
Foreign keys mean the value must exist in the other table. NULL refers to the absence of value, so when you set a column to NULL, it wouldn't make sense to try to enforce constraints on that.
ogdate
is itself a string, why are you trying to access it's value
property that it doesn't have ?
console.log(og_date.split('-'));
For those who are getting the error as:
I/O error on POST request for "anothermachine:31112/url/path";: class path
resource [fileName.csv] cannot be resolved to URL because it does not exist.
It can be resolved by using the
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new FileSystemResource(file));
If the file is not present in the classpath, and an absolute path is required.
Python is upset because you are attempting to assign a value to something that can't be assigned a value.
((t[1])/length) * t[1] += string
When you use an assignment operator, you assign the value of what is on the right to the variable or element on the left. In your case, there is no variable or element on the left, but instead an interpreted value: you are trying to assign a value to something that isn't a "container".
Based on what you've written, you're just misunderstanding how this operator works. Just switch your operands, like so.
string += str(((t[1])/length) * t[1])
Note that I've wrapped the assigned value in str
in order to convert it into a str
so that it is compatible with the string
variable it is being assigned to. (Numbers and strings can't be added together.)
Language independent version.
@Echo Off
Set ServiceName=Jenkins
SC queryex "%ServiceName%"|Find "STATE"|Find /v "RUNNING">Nul&&(
echo %ServiceName% not running
echo Start %ServiceName%
Net start "%ServiceName%">nul||(
Echo "%ServiceName%" wont start
exit /b 1
)
echo "%ServiceName%" started
exit /b 0
)||(
echo "%ServiceName%" working
exit /b 0
)
After struggling with git authentication and azure devops server and trying other answers this tip here worked for me.
Using Visual Studio? Team Explorer handles authentication with Azure Repos for you.
Once I connected to the repo using Team Explorer I could use command line to execute git commands.
I have tried all of these options and none seem to work. Sometimes I actually got a message "GoogleUpdate is disabled" when I checked the "About" page, but somehow a week later it was still updated.
Now I just add GoogleUpdate to the firewall and block internet access. If I check the "About" page I get a message it is updating and after a few seconds that it can't update and I should check my firewall.
<head>
<script type="text/javascript">
function SetMaxLength () {
var input = document.getElementById("myInput");
input.maxLength = 10;
}
</script>
</head>
<body>
<input id="myInput" type="text" size="20" />
</body>
There has been an open feature request since at least 2009. The long and short of it is that it will part of the functionality of JDK 8's java.util.StringJoiner class. http://download.java.net/lambda/b81/docs/api/java/util/StringJoiner.html
Here is the Oracle issue if you are interested. http://bugs.sun.com/view_bug.do?bug_id=5015163
Here is an example of the new JDK 8 StringJoiner on an array of String
String[] a = new String[]{"first","second","third"};
StringJoiner sj = new StringJoiner(",");
for(String s:a) sj.add(s);
System.out.println(sj); //first,second,third
A utility method in String makes this even simpler:
String s = String.join(",", stringArray);
In my case composer was not installed in that directory. So I run
composer install
then error resolved.
or you can try
composer update --no-scripts
cd bootstrap/cache/->rm -rf *.php
composer dump-autoload
You can try a list comp
>>> exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]
>>> keyValList = ['type2','type3']
>>> expectedResult = [d for d in exampleSet if d['type'] in keyValList]
>>> expectedResult
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]
Another way is by using filter
>>> list(filter(lambda d: d['type'] in keyValList, exampleSet))
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]
if you want to upgrade only a single column of a table row then you can use as following:
$this->db->set('column_header', $value); //value that used to update column
$this->db->where('column_id', $column_id_value); //which row want to upgrade
$this->db->update('table_name'); //table name
I loved the FireFox Header Spy extension so much that i built a HTTP Spy extension for Chrome. I used to use the developer tools too for debugging headers, but now my life is so much better.
Here is a Chrome extension that allows you to view request-, response headers and cookies without any extra clicks right after the page is loaded.
It also handles redirects. It comes with an unobtrusive micro-mode that only shows a hand picked selection of response headers and a normal mode that shows all the information.
https://chrome.google.com/webstore/detail/http-spy/agnoocojkneiphkobpcfoaenhpjnmifb
Enjoy!
What's even cooler is the fact that you can use an inline Table-Valued Function to select which (and how many via TOP
) row(s) to update. That is:
UPDATE MyTable
SET Column1=@Value1
FROM tvfSelectLatestRowOfMyTableMatchingCriteria(@Param1,@Param2,@Param3)
For the table valued function you have something interesting to select the row to update like:
CREATE FUNCTION tvfSelectLatestRowOfMyTableMatchingCriteria
(
@Param1 INT,
@Param2 INT,
@Param3 INT
)
RETURNS TABLE AS RETURN
(
SELECT TOP(1) MyTable.*
FROM MyTable
JOIN MyOtherTable
ON ...
JOIN WhoKnowsWhatElse
ON ...
WHERE MyTable.SomeColumn=@Param1 AND ...
ORDER BY MyTable.SomeDate DESC
)
..., and there lies (in my humble opinion) the true power of updating only top selected rows deterministically while at the same time simplifying the syntax of the UPDATE
statement.
List files between 2 dates
find . -type f -newermt "2019-01-01" ! -newermt "2019-05-01"
or
find path -type f -newermt "2019-01-01" ! -newermt "2019-05-01"
I implemented it in the following way. I wanted a generic MakeRequest
method that could call my API and receive content for the body of the request - and also deserialise the response into the desired type. I create a Dictionary<string, string>
object to house the content to be submitted, and then set the HttpRequestMessage
Content
property with it:
Generic method to call the API:
private static T MakeRequest<T>(string httpMethod, string route, Dictionary<string, string> postParams = null)
{
using (var client = new HttpClient())
{
HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), $"{_apiBaseUri}/{route}");
if (postParams != null)
requestMessage.Content = new FormUrlEncodedContent(postParams); // This is where your content gets added to the request body
HttpResponseMessage response = client.SendAsync(requestMessage).Result;
string apiResponse = response.Content.ReadAsStringAsync().Result;
try
{
// Attempt to deserialise the reponse to the desired type, otherwise throw an expetion with the response from the api.
if (apiResponse != "")
return JsonConvert.DeserializeObject<T>(apiResponse);
else
throw new Exception();
}
catch (Exception ex)
{
throw new Exception($"An error ocurred while calling the API. It responded with the following message: {response.StatusCode} {response.ReasonPhrase}");
}
}
}
Call the method:
public static CardInformation ValidateCard(string cardNumber, string country = "CAN")
{
// Here you create your parameters to be added to the request content
var postParams = new Dictionary<string, string> { { "cardNumber", cardNumber }, { "country", country } };
// make a POST request to the "cards" endpoint and pass in the parameters
return MakeRequest<CardInformation>("POST", "cards", postParams);
}
Taking SQL Server cluster role offline-Online on node 1 worked for me.
There's more to this than meets the eye. Most other answers are correct BUT ALSO..
new Array(n)
n
elements[1, 2, 3] || []
delete
or [1,,3]
syntax)for ..
, forEach
, map
, etc)This probably isn't the case for older browser versions/browsers.
Just wanted to add a bit of info, since I haven't seen it posted yet.
You'll very often see code in C headers like so:
#ifdef __cplusplus
extern "C" {
#endif
// all of your legacy C code here
#ifdef __cplusplus
}
#endif
What this accomplishes is that it allows you to use that C header file with your C++ code, because the macro "__cplusplus" will be defined. But you can also still use it with your legacy C code, where the macro is NOT defined, so it won't see the uniquely C++ construct.
Although, I have also seen C++ code such as:
extern "C" {
#include "legacy_C_header.h"
}
which I imagine accomplishes much the same thing.
Not sure which way is better, but I have seen both.
For those of us who found this and are not using Azure SQL Database:
STRING_AGG()
in PostgreSQL, SQL Server 2017 and Azure SQL
https://www.postgresql.org/docs/current/static/functions-aggregate.html
https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql
GROUP_CONCAT()
in MySQL
http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat
(Thanks to @Brianjorden and @milanio for Azure update)
select Id
, STRING_AGG(Name, ', ') Names
from Demo
group by Id
SQL Fiddle: http://sqlfiddle.com/#!18/89251/1
So I install MinGW and tack that on the install line as the compiler of choice. But then I get the error "RuntimeError: chmod error".
This error "RuntimeError: chmod error"
occurs because the install script didn't find the chmod
command.
How in the world do I get around this?
You only need to add the MSYS binaries to the PATH and re-run the install script.
(N.B: Note that MinGW comes with MSYS so )
For example, if we are in folder C:\<..>\pycrypto-2.6.1\dist\pycrypto-2.6.1>
C:\.....>
set PATH=C:\MinGW\msys\1.0\bin;%PATH%
C:\.....>
python setup.py install
Optional: you might need to clean before you re-run the script:
`C:\<..>\pycrypto-2.6.1\dist\pycrypto-2.6.1> python setup.py clean`
I use a personnal blend of the phantomjs waitfor.js
example.
This is my main.js
file:
'use strict';
var wasSuccessful = phantom.injectJs('./lib/waitFor.js');
var page = require('webpage').create();
page.open('http://foo.com', function(status) {
if (status === 'success') {
page.includeJs('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js', function() {
waitFor(function() {
return page.evaluate(function() {
if ('complete' === document.readyState) {
return true;
}
return false;
});
}, function() {
var fooText = page.evaluate(function() {
return $('#foo').text();
});
phantom.exit();
});
});
} else {
console.log('error');
phantom.exit(1);
}
});
And the lib/waitFor.js
file (which is just a copy and paste of the waifFor()
function from the phantomjs waitfor.js
example):
function waitFor(testFx, onReady, timeOutMillis) {
var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s
start = new Date().getTime(),
condition = false,
interval = setInterval(function() {
if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
// If not time-out yet and condition not yet fulfilled
condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
} else {
if(!condition) {
// If condition still not fulfilled (timeout but condition is 'false')
console.log("'waitFor()' timeout");
phantom.exit(1);
} else {
// Condition fulfilled (timeout and/or condition is 'true')
// console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condi>
clearInterval(interval); //< Stop this interval
}
}
}, 250); //< repeat check every 250ms
}
This method is not asynchronous but at least am I assured that all the resources were loaded before I try using them.
I was finding somethig for make a filter passing an Object, then i can use it like multi-filter:
i did this Beauty Solution:
filter.pipe.ts
import { PipeTransform, Pipe } from '@angular/core';
@Pipe({
name: 'filterx',
pure: false
})
export class FilterPipe implements PipeTransform {
transform(items: any, filter: any, isAnd: boolean): any {
let filterx=JSON.parse(JSON.stringify(filter));
for (var prop in filterx) {
if (Object.prototype.hasOwnProperty.call(filterx, prop)) {
if(filterx[prop]=='')
{
delete filterx[prop];
}
}
}
if (!items || !filterx) {
return items;
}
return items.filter(function(obj) {
return Object.keys(filterx).every(function(c) {
return obj[c].toLowerCase().indexOf(filterx[c].toLowerCase()) !== -1
});
});
}
}
component.ts
slotFilter:any={start:'',practitionerCodeDisplay:'',practitionerName:''};
componet.html
<tr>
<th class="text-center"> <input type="text" [(ngModel)]="slotFilter.start"></th>
<th class="text-center"><input type="text" [(ngModel)]="slotFilter.practitionerCodeDisplay"></th>
<th class="text-left"><input type="text" [(ngModel)]="slotFilter.practitionerName"></th>
<th></th>
</tr>
<tbody *ngFor="let item of practionerRoleList | filterx: slotFilter">...
You may try
pip install [email protected]/my_name/my_repo.git
without ssh:...
. That works for me.
To get the value of a pointer, just de-reference the pointer.
int *ptr;
int value;
*ptr = 9;
value = *ptr;
value is now 9.
I suggest you read more about pointers, this is their base functionality.