Map
s.No, its not possible with objects.
You should either iterate with for..in
, or Object.keys
, like this
for (var key in dictionary) {
// check if the property/key is defined in the object itself, not in parent
if (dictionary.hasOwnProperty(key)) {
console.log(key, dictionary[key]);
}
}
Note: The if
condition above is necessary, only if you want to iterate the properties which are dictionary
object's very own. Because for..in
will iterate through all the inherited enumerable properties.
Or
Object.keys(dictionary).forEach(function(key) {
console.log(key, dictionary[key]);
});
In ECMAScript 2015, you can use Map
objects and iterate them with Map.prototype.entries
. Quoting example from that page,
var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
var mapIter = myMap.entries();
console.log(mapIter.next().value); // ["0", "foo"]
console.log(mapIter.next().value); // [1, "bar"]
console.log(mapIter.next().value); // [Object, "baz"]
Or iterate with for..of
, like this
'use strict';
var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
for (const entry of myMap.entries()) {
console.log(entry);
}
[ '0', 'foo' ]
[ 1, 'bar' ]
[ {}, 'baz' ]
Or
for (const [key, value] of myMap.entries()) {
console.log(key, value);
}
0 foo
1 bar
{} baz
ECMAScript 2017 would introduce a new function Object.entries
. You can use this to iterate the object as you wanted.
'use strict';
const object = {'a': 1, 'b': 2, 'c' : 3};
for (const [key, value] of Object.entries(object)) {
console.log(key, value);
}
a 1
b 2
c 3
fscanf
- "On success, the function returns the number of items successfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure.
In the case of an input failure before any data could be successfully read, EOF is returned."
So, instead of doing nothing with the return value like you are right now, you can check to see if it is == EOF
.
You should check for EOF when you call fscanf
, not check the array slot for EOF.
Only "keyboard focusable" elements can be focused with .focus()
. div
aren't meant to be natively focusable. You have to add tabindex="0"
attributes to it to achieve that. input
, button
, a
etc... are natively focusable.
package com.ezeon.util.gen;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.*;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
/*** Encryption and Decryption of String data; PBE(Password Based Encryption and Decryption)
* @author Vikram
*/
public class CryptoUtil
{
Cipher ecipher;
Cipher dcipher;
// 8-byte Salt
byte[] salt = {
(byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32,
(byte) 0x56, (byte) 0x35, (byte) 0xE3, (byte) 0x03
};
// Iteration count
int iterationCount = 19;
public CryptoUtil() {
}
/**
*
* @param secretKey Key used to encrypt data
* @param plainText Text input to be encrypted
* @return Returns encrypted text
* @throws java.security.NoSuchAlgorithmException
* @throws java.security.spec.InvalidKeySpecException
* @throws javax.crypto.NoSuchPaddingException
* @throws java.security.InvalidKeyException
* @throws java.security.InvalidAlgorithmParameterException
* @throws java.io.UnsupportedEncodingException
* @throws javax.crypto.IllegalBlockSizeException
* @throws javax.crypto.BadPaddingException
*
*/
public String encrypt(String secretKey, String plainText)
throws NoSuchAlgorithmException,
InvalidKeySpecException,
NoSuchPaddingException,
InvalidKeyException,
InvalidAlgorithmParameterException,
UnsupportedEncodingException,
IllegalBlockSizeException,
BadPaddingException {
//Key generation for enc and desc
KeySpec keySpec = new PBEKeySpec(secretKey.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
//Enc process
ecipher = Cipher.getInstance(key.getAlgorithm());
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
String charSet = "UTF-8";
byte[] in = plainText.getBytes(charSet);
byte[] out = ecipher.doFinal(in);
String encStr = new String(Base64.getEncoder().encode(out));
return encStr;
}
/**
* @param secretKey Key used to decrypt data
* @param encryptedText encrypted text input to decrypt
* @return Returns plain text after decryption
* @throws java.security.NoSuchAlgorithmException
* @throws java.security.spec.InvalidKeySpecException
* @throws javax.crypto.NoSuchPaddingException
* @throws java.security.InvalidKeyException
* @throws java.security.InvalidAlgorithmParameterException
* @throws java.io.UnsupportedEncodingException
* @throws javax.crypto.IllegalBlockSizeException
* @throws javax.crypto.BadPaddingException
*/
public String decrypt(String secretKey, String encryptedText)
throws NoSuchAlgorithmException,
InvalidKeySpecException,
NoSuchPaddingException,
InvalidKeyException,
InvalidAlgorithmParameterException,
UnsupportedEncodingException,
IllegalBlockSizeException,
BadPaddingException,
IOException {
//Key generation for enc and desc
KeySpec keySpec = new PBEKeySpec(secretKey.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
//Decryption process; same key will be used for decr
dcipher = Cipher.getInstance(key.getAlgorithm());
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
byte[] enc = Base64.getDecoder().decode(encryptedText);
byte[] utf8 = dcipher.doFinal(enc);
String charSet = "UTF-8";
String plainStr = new String(utf8, charSet);
return plainStr;
}
public static void main(String[] args) throws Exception {
CryptoUtil cryptoUtil=new CryptoUtil();
String key="ezeon8547";
String plain="This is an important message";
String enc=cryptoUtil.encrypt(key, plain);
System.out.println("Original text: "+plain);
System.out.println("Encrypted text: "+enc);
String plainAfter=cryptoUtil.decrypt(key, enc);
System.out.println("Original text after decryption: "+plainAfter);
}
}
Apart from steps mentioned in posted answers by @daniele3004 above, I had to open SSMS as Administrator otherwise it was showing Primary file is read only error.
Go to Start Menu , navigate to SSMS link , right click on the SSMS link , select Run As Administrator. Then perform the above steps.
IF CHARINDEX('TextToSearch',@TextWhereISearch, 0) > 0 => TEXT EXISTS
IF PATINDEX('TextToSearch', @TextWhereISearch) > 0 => TEXT EXISTS
Additionally we can also use LIKE but I usually don't use LIKE.
This should do what you want:
sed 's/two.*/BLAH/'
$ echo " one two three five
> four two five five six
> six one two seven four" | sed 's/two.*/BLAH/'
one BLAH
four BLAH
six one BLAH
The $
is unnecessary because the .*
will finish at the end of the line anyways, and the g
at the end is unnecessary because your first match will be the first two
to the end of the line.
For readers with an angular.json
(not angular-cli.json
) the key correct key is outputPath. I guess the angular configuration changed to angular.json
in Angular 6, so if you are using version 6 or above you most likely have a angular.json
file.
To change the output path you have to change outputPath und the build options.
example angular.json
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"projects": {
"angular-app": {
"projectType": "application",
[...]
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/angular-app",
"index": "src/index.html",
"main": "src/main.ts",
[...]
I could not find any official docs on this (not included in https://angular.io/guide/workspace-config as I would have expected), maybe someone can link an official resource on this.
You could use a VB Script I wrote exactly for this purpose: https://github.com/ezrarieben/mssql-backup-vbs/
Schedule a task in the "Task Scheduler" to execute the script as you like and it'll backup the entire DB to a BAK file and save it wherever you specify.
This is a maven specific problem I think. Maven does not copy the files form /src/main/resources
to the target-test folder. You will have to do this yourself by configuring the resources plugin, if you absolutely want to go this way.
An easier way is to instead put a test specific context definition in the /src/test/resources
directory and load via:
@ContextConfiguration(locations = { "classpath:mycontext.xml" })
As Sotirios Delimanolis already pointed out in the comments, there are two options:
ResponseEntity
with error messageChange your method like this:
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity getUser(@RequestHeader(value="Access-key") String accessKey,
@RequestHeader(value="Secret-key") String secretKey) {
try {
// see note 1
return ResponseEntity
.status(HttpStatus.CREATED)
.body(this.userService.chkCredentials(accessKey, secretKey, timestamp));
}
catch(ChekingCredentialsFailedException e) {
e.printStackTrace(); // see note 2
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body("Error Message");
}
}
Note 1: You don't have to use the ResponseEntity
builder but I find it helps with keeping the code readable. It also helps remembering, which data a response for a specific HTTP status code should include. For example, a response with the status code 201 should contain a link to the newly created resource in the Location
header (see Status Code Definitions). This is why Spring offers the convenient build method ResponseEntity.created(URI)
.
Note 2: Don't use printStackTrace()
, use a logger instead.
@ExceptionHandler
Remove the try-catch block from your method and let it throw the exception. Then create another method in a class annotated with @ControllerAdvice
like this:
@ControllerAdvice
public class ExceptionHandlerAdvice {
@ExceptionHandler(ChekingCredentialsFailedException.class)
public ResponseEntity handleException(ChekingCredentialsFailedException e) {
// log exception
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body("Error Message");
}
}
Note that methods which are annotated with @ExceptionHandler
are allowed to have very flexible signatures. See the Javadoc for details.
OneToOneField: if second table is related with
table2_col1 = models.OneToOneField(table1,on_delete=models.CASCADE, related_name='table1_id')
table2 will contains only one record corresponding to table1's pk value, i.e table2_col1 will have unique value equal to pk of table
table2_col1 == models.ForeignKey(table1, on_delete=models.CASCADE, related_name='table1_id')
table2 may contains more than one record corresponding to table1's pk value.
Follow the below steps it will helps you.
step 1: Go to to your site root folder and you can find the .htaccess
file there. Open it with a text editor and find the line #RewriteBase /magento/
. Just replace it with #RewriteBase /
take out just the 'magento/'
step 2: Then go to your admin panel and enable the Rewrites(set yes for Use Web Server Rewrites). You can find it at System->Configuration->Web->Search Engine Optimization.
step 3: Then go to Cache management page (system cache management ) and refresh your cache and refresh to check the site.
This will check for empty textarea as well as will not allow only Spaces in textarea coz that looks empty too.
var txt_msg = $("textarea").val();
if (txt_msg.replace(/^\s+|\s+$/g, "").length == 0 || txt_msg=="") {
return false;
}
If you run the following command :
ALTER TABLE users ADD id int NOT NULL AUTO_INCREMENT PRIMARY KEY;
This will show you the error :
ERROR 1060 (42S21): Duplicate column name 'id'
This is because this command will try to add the new column named id
to the existing table.
To modify the existing column you have to use the following command :
ALTER TABLE users MODIFY id int NOT NULL AUTO_INCREMENT PRIMARY KEY;
This should work for changing the existing column constraint....!
in typeScript
of angular 6
, this code is working for me.
var formData = new FormData();
formData.append('name', 'value1');
formData.append('name', 'value2');
console.log(formData.get('name')); // this is return first element value.
or for all values:
console.log(formData.getAll('name')); // return all values
Cookies and local storage serve different purposes. Cookies are primarily for reading server-side, local storage can only be read by the client-side. So the question is, in your app, who needs this data — the client or the server?
If it's your client (your JavaScript), then by all means switch. You're wasting bandwidth by sending all the data in each HTTP header.
If it's your server, local storage isn't so useful because you'd have to forward the data along somehow (with Ajax or hidden form fields or something). This might be okay if the server only needs a small subset of the total data for each request.
You'll want to leave your session cookie as a cookie either way though.
As per the technical difference, and also my understanding:
Apart from being an old way of saving data, Cookies give you a limit of 4096 bytes (4095, actually) — it's per cookie. Local Storage is as big as 5MB per domain — SO Question also mentions it.
localStorage
is an implementation of the Storage
Interface. It stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser Cache / Locally Stored Data — unlike cookie expiry.
Consider two class-typed variables:
class Boo { ... };
Boo b0; // mutable object
const Boo b1; // non-mutable object
Now you are able to call any member function of Boo
on b0
, but only const
-qualified member functions on b1
.
Stuzor and hexcodes solution worked for me as well. However, if you do want the latest connector you have to download another product. From the oracle website:
Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html).
func showAlertAction(title: String, message: String){
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: {(action:UIAlertAction!) in
print("Action")
}))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
I think best approach is xian's answer.
but...
This approach is dirty, but can solve at all version.
so, I often use it in macro functions.
for(int _int=0, /* make local variable */ \
loopOnce=true; loopOnce==true; loopOnce=false)
for(char _char=0; _char<3; _char++)
{
// do anything with
// _int, _char
}
It can also be used to declare local variables
and initialize global variables
.
float globalFloat;
for(int localInt=0, /* decalre local variable */ \
_=1;_;_=0)
for(globalFloat=2.f; localInt<3; localInt++) /* initialize global variable */
{
// do.
}
Good example : with macro function.
(If best approach can't be used because it is a for-loop-macro)
#define for_two_decl(_decl_1, _decl_2, cond, incr) \
for(_decl_1, _=1;_;_=0)\
for(_decl_2; (cond); (incr))
for_two_decl(int i=0, char c=0, i<3, i++)
{
// your body with
// i, c
}
if (A* a=nullptr);
else
for(...) // a is visible
If you want initialize to 0
or nullptr
, you can use this trick.
but I don't recommend this because of hard reading.
and it seems like bug.
To add to Blender's answer, you can disable SSL certificate validation for all requests using Session.verify = False
import requests
session = requests.Session()
session.verify = False
session.post(url='https://example.com', data={'bar':'baz'})
Note that urllib3
, (which Requests uses), strongly discourages making unverified HTTPS requests and will raise an InsecureRequestWarning
.
After searching a bit about the method to open the existing sheet in xlxs, i discovered
existingWorksheet = wb.get_worksheet_by_name('Your Worksheet name goes here...')
existingWorksheet.write_row(0,0,'xyz')
You can now append/write any data to the open worksheet. I hope it helps. Thanks
select to_timestamp(cast(epoch_ms/1000 as bigint))::date
worked for me
Similar to accepted answer but allows use of ColumnNames and binds to RowDataBound().
Dictionary<string, int> _headerIndiciesForAbcGridView = null;
protected void abcGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (_headerIndiciesForAbcGridView == null) // builds once per http request
{
int index = 0;
_headerIndiciesForAbcGridView = ((Table)((GridView)sender).Controls[0]).Rows[0].Cells
.Cast<TableCell>()
.ToDictionary(c => c.Text, c => index++);
}
e.Row.Cells[_headerIndiciesForAbcGridView["theColumnName"]].Visible = false;
}
Not sure if it works with RowCreated().
go to Services, find SQL Server Browser, right click --> Properties --> General tab --> Startup Type --> select automatic . Then go back to configuration management, start it.
This query i have generated for inserting the Excel file data into database In this id and price are numeric values and date field as well. This query summarized all the type which I require It may useful to you as well
="insert into product (product_id,name,date,price) values("&A1&",'" &B1& "','" &C1& "'," &D1& ");"
Id Name Date price
7 Product 7 2017-01-05 15:28:37 200
8 Product 8 2017-01-05 15:28:37 40
9 Product 9 2017-01-05 15:32:31 500
10 Product 10 2017-01-05 15:32:31 30
11 Product 11 2017-01-05 15:32:31 99
12 Product 12 2017-01-05 15:32:31 25
if you want to get the index values, you can simply do:
dataframe.index
this will output a pandas.core.index
Here is my solution for this :
mkdir temp
mkdir results
cp /usr/share/dict/american-english ~/temp/american-english-dictionary
cp /usr/share/dict/british-english ~/temp/british-english-dictionary
cat ~/temp/american-english-dictionary | wc -l > ~/results/count-american-english-dictionary
cat ~/temp/british-english-dictionary | wc -l > ~/results/count-british-english-dictionary
grep -Fxf ~/temp/american-english-dictionary ~/temp/british-english-dictionary > ~/results/common-english
grep -Fxvf ~/results/common-english ~/temp/american-english-dictionary > ~/results/unique-american-english
grep -Fxvf ~/results/common-english ~/temp/british-english-dictionary > ~/results/unique-british-english
The term cohesion is indeed a little counter intuitive for what it means in software design.
Cohesion common meaning is that something that sticks together well, is united, which are characterized by strong bond like molecular attraction. However in software design, it means striving for a class that ideally does only one thing, so multiple sub-modules are not even involved.
Perhaps we can think of it this way. A part has the most cohesion when it is the only part (does only one thing and can't be broken down further). This is what is desired in software design. Cohesion simply is another name for "single responsibility" or "separation of concerns".
The term coupling on the hand is quite intuitive which means when a module doesn't depend on too many other modules and those that it connects with can be easily replaced for example obeying liskov substitution principle .
I have constructed this JavaScript script to parse a CSV in string to array object. I find it better to break down the whole CSV into lines, fields and process them accordingly. I think that it will make it easy for you to change the code to suit your need.
//
//
// CSV to object
//
//
const new_line_char = '\n';
const field_separator_char = ',';
function parse_csv(csv_str) {
var result = [];
let line_end_index_moved = false;
let line_start_index = 0;
let line_end_index = 0;
let csr_index = 0;
let cursor_val = csv_str[csr_index];
let found_new_line_char = get_new_line_char(csv_str);
let in_quote = false;
// Handle \r\n
if (found_new_line_char == '\r\n') {
csv_str = csv_str.split(found_new_line_char).join(new_line_char);
}
// Handle the last character is not \n
if (csv_str[csv_str.length - 1] !== new_line_char) {
csv_str += new_line_char;
}
while (csr_index < csv_str.length) {
if (cursor_val === '"') {
in_quote = !in_quote;
} else if (cursor_val === new_line_char) {
if (in_quote === false) {
if (line_end_index_moved && (line_start_index <= line_end_index)) {
result.push(parse_csv_line(csv_str.substring(line_start_index, line_end_index)));
line_start_index = csr_index + 1;
} // Else: just ignore line_end_index has not moved or line has not been sliced for parsing the line
} // Else: just ignore because we are in a quote
}
csr_index++;
cursor_val = csv_str[csr_index];
line_end_index = csr_index;
line_end_index_moved = true;
}
// Handle \r\n
if (found_new_line_char == '\r\n') {
let new_result = [];
let curr_row;
for (var i = 0; i < result.length; i++) {
curr_row = [];
for (var j = 0; j < result[i].length; j++) {
curr_row.push(result[i][j].split(new_line_char).join('\r\n'));
}
new_result.push(curr_row);
}
result = new_result;
}
return result;
}
function parse_csv_line(csv_line_str) {
var result = [];
//let field_end_index_moved = false;
let field_start_index = 0;
let field_end_index = 0;
let csr_index = 0;
let cursor_val = csv_line_str[csr_index];
let in_quote = false;
// Pretend that the last char is the separator_char to complete the loop
csv_line_str += field_separator_char;
while (csr_index < csv_line_str.length) {
if (cursor_val === '"') {
in_quote = !in_quote;
} else if (cursor_val === field_separator_char) {
if (in_quote === false) {
if (field_start_index <= field_end_index) {
result.push(parse_csv_field(csv_line_str.substring(field_start_index, field_end_index)));
field_start_index = csr_index + 1;
} // Else: just ignore field_end_index has not moved or field has not been sliced for parsing the field
} // Else: just ignore because we are in quote
}
csr_index++;
cursor_val = csv_line_str[csr_index];
field_end_index = csr_index;
field_end_index_moved = true;
}
return result;
}
function parse_csv_field(csv_field_str) {
with_quote = (csv_field_str[0] === '"');
if (with_quote) {
csv_field_str = csv_field_str.substring(1, csv_field_str.length - 1); // remove the start and end quotes
csv_field_str = csv_field_str.split('""').join('"'); // handle double quotes
}
return csv_field_str;
}
// Initial method: check the first newline character only
function get_new_line_char(csv_str) {
if (csv_str.indexOf('\r\n') > -1) {
return '\r\n';
} else {
return '\n'
}
}
If you have a lot of variables in your Rdata
file and don't want them to clutter your global environment, create a new environment and load all of the data to this new environment.
load(file.path("C:/Users/isfar.RData"), isfar_env <- new.env() )
# Access individual variables in the RData file using '$' operator
isfar_env$var_name
# List all of the variable names in RData:
ls(isfar_env)
The "image" people generally show during an ajax call is an animated gif. Since there is no way to determine the percent complete of the ajax request, the animated gifs used are indeterminate spinners. This is just an image repeating over and over like a ball of circles of varying sizes. A good site to create your own custom indeterminate spinner is http://ajaxload.info/
These guys gave you the reason why is failing but not how to solve it. This problem may appear even if you have a jdk which matches JVM which you are trying it into.
Project -> Properties -> Java Compiler
Enable project specific settings.
Then select Compiler Compliance Level to 1.6 or 1.5, build and test your app.
Now, it should be fine.
You can use Java 7's Key and Certificate Management Tool keytool
to check the signature of a keystore or an APK without extracting any files.
# APK file
keytool -printcert -jarfile app.apk
# AAB file
keytool -printcert -jarfile app.aab
The output will reveal the signature owner/issuer and MD5, SHA1 and SHA256 fingerprints of the APK file app.apk
or AAB file app.aab
.
(Note that the -jarfile
argument was introduced in Java 7; see the documentation for more details.)
keytool -list -v -keystore release.jks
The output will reveal the aliases (entries) in the keystore file release.jks
, with the certificate fingerprints (MD5, SHA1 and SHA256).
If the SHA1 fingerprints between the APK and the keystore match, then you can rest assured that that app is signed with the key.
Instead of adding any tag which is never a good solution. You can always use margin
property with the required element.
You can add the margin on row class itself. So it will affect globally.
.row{
margin-top: 30px;
margin-bottom: 30px
}
Update: Better solution in all cases would be to introduce a new class and then use it along with .row
class.
.row-m-t{
margin-top : 20px
}
Then use it wherever you want
<div class="row row-m-t"></div>
For me, the only thing which worked is
git diff HEAD
including the staged files, git diff --cached
only shows staged files.
Byte[] -> String: use system.convert.tobase64string
Convert.ToBase64String(byte[] data)
String -> Byte[]: use system.convert.frombase64string
Convert.FromBase64String(string data)
Just for the sake of completeness, here is a solution with lambda and method reference:
Description: The following method
String
with the pattern yyyy-MM-dd
into a Timestamp
, if a valid input is given,null
, if a null
value is given,DateTimeParseException
, if an invalid input is givenCode:
static Timestamp convertStringToTimestamp(String strDate) {
return Optional.ofNullable(strDate) // wrap the String into an Optional
.map(str -> LocalDate.parse(str).atStartOfDay()) // convert into a LocalDate and fix the hour:minute:sec to 00:00:00
.map(Timestamp::valueOf) // convert to Timestamp
.orElse(null); // if no value is present, return null
}
Validation:
This method can be tested with those unit tests:
(with Junit5 and Hamcrest)
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenValidInput() {
// given
String strDate = "2020-01-30";
// when
final Timestamp result = convertStringToTimestamp(strDate);
// then
final LocalDateTime dateTime = LocalDateTime.ofInstant(result.toInstant(), ZoneId.systemDefault());
assertThat(dateTime.getYear(), is(2020));
assertThat(dateTime.getMonthValue(), is(1));
assertThat(dateTime.getDayOfMonth(), is(30));
}
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenInvalidInput() {
// given
String strDate = "7770-91-30";
// when, then
assertThrows(DateTimeParseException.class, () -> convertStringToTimestamp(strDate));
}
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenNullInput() {
// when
final Timestamp result = convertStringToTimestamp(null);
// then
assertThat(result, is(nullValue()));
}
Usually, the string to parse comes with another format. A way to deal with it is to use a formatter to convert it to another format. Here is an example:
Input: 20200130 11:30
Pattern: yyyyMMdd HH:mm
Output: Timestamp of this input
Code:
static Timestamp convertStringToTimestamp(String strDate) {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm");
return Optional.ofNullable(strDate) //
.map(str -> LocalDateTime.parse(str, formatter))
.map(Timestamp::valueOf) //
.orElse(null);
}
Test:
@Test
void convertStringToTimestamp_shouldReturnTimestamp_whenValidInput() {
// given
String strDate = "20200130 11:30";
// when
final Timestamp result = convertStringToTimestamp(strDate);
// then
final LocalDateTime dateTime = LocalDateTime.ofInstant(result.toInstant(), ZoneId.systemDefault());
assertThat(dateTime.getYear(), is(2020));
assertThat(dateTime.getMonthValue(), is(1));
assertThat(dateTime.getDayOfMonth(), is(30));
assertThat(dateTime.getHour(), is(11));
assertThat(dateTime.getMinute(), is(30));
}
I think we could write in the following way to retrieve(below code is just an example, please modify as needed):
Create FUNCTION dbo.ufnGetEmployeeMultiple(@DepartmentID int)
RETURNS VARCHAR(1000) AS
BEGIN
DECLARE @Employeelist varchar(1000)
SELECT @Employeelist = COALESCE(@Employeelist + ', ', '') + E.LoginID
FROM humanresources.Employee E
Left JOIN humanresources.EmployeeDepartmentHistory H ON
E.BusinessEntityID = H.BusinessEntityID
INNER JOIN HumanResources.Department D ON
H.DepartmentID = D.DepartmentID
Where H.DepartmentID = @DepartmentID
Return @Employeelist
END
SELECT D.name as Department, dbo.ufnGetEmployeeMultiple (D.DepartmentID)as Employees
FROM HumanResources.Department D
SELECT Distinct (D.name) as Department, dbo.ufnGetEmployeeMultiple (D.DepartmentID) as
Employees
FROM HumanResources.Department D
no need for the padding or the corners.
here's a sample:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
<gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
android:angle="270"/>
</shape>
based on :
dumpbin
from the Visual Studio command prompt:
dumpbin /exports csp.dll
Example of output:
Microsoft (R) COFF/PE Dumper Version 10.00.30319.01
Copyright (C) Microsoft Corporation. All rights reserved.
Dump of file csp.dll
File Type: DLL
Section contains the following exports for CSP.dll
00000000 characteristics
3B1D0B77 time date stamp Tue Jun 05 12:40:23 2001
0.00 version
1 ordinal base
25 number of functions
25 number of names
ordinal hint RVA name
1 0 00001470 CPAcquireContext
2 1 000014B0 CPCreateHash
3 2 00001520 CPDecrypt
4 3 000014B0 CPDeriveKey
5 4 00001590 CPDestroyHash
6 5 00001590 CPDestroyKey
7 6 00001560 CPEncrypt
8 7 00001520 CPExportKey
9 8 00001490 CPGenKey
10 9 000015B0 CPGenRandom
11 A 000014D0 CPGetHashParam
12 B 000014D0 CPGetKeyParam
13 C 00001500 CPGetProvParam
14 D 000015C0 CPGetUserKey
15 E 00001580 CPHashData
16 F 000014F0 CPHashSessionKey
17 10 00001540 CPImportKey
18 11 00001590 CPReleaseContext
19 12 00001580 CPSetHashParam
20 13 00001580 CPSetKeyParam
21 14 000014F0 CPSetProvParam
22 15 00001520 CPSignHash
23 16 000015A0 CPVerifySignature
24 17 00001060 DllRegisterServer
25 18 00001000 DllUnregisterServer
Summary
1000 .data
1000 .rdata
1000 .reloc
1000 .rsrc
1000 .text
There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is InternalsVisibleTo. I've only ever used this attribute for testing - where it's very handy!
Example: To be placed in AssemblyInfo.cs
[assembly: InternalsVisibleTo("OtherAssembly")]
With VSCode you can find the merge conflicts easily with the following UI.
(if you do not have the topbar, set "editor.codeLens": true
in User Preferences)
It indicates the current change that you have and incoming change from the server. This makes it easy to resolve the conflicts - just press the buttons above <<<< HEAD
.
If you have multiple changes and want to apply all of them at once - open command palette (View -> Command Palette) and start typing merge - multiple options will appear including Merge Conflict: Accept Incoming
, etc.
I found the WINDOWS-1252
encoding to be the least frustrating when dealing with Excel. Since its basically Microsofts own proprietary character set, one can assume it will work on both the Mac and the Windows version of MS-Excel. Both versions at least include a corresponding "File origin" or "File encoding" selector which correctly reads the data.
Depending on your system and the tools you use, this encoding could also be named CP1252
, ANSI
, Windows (ANSI)
, MS-ANSI
or just Windows
, among other variations.
This encoding is a superset of ISO-8859-1
(aka LATIN1
and others), so you can fallback to ISO-8859-1
if you cannot use WINDOWS-1252
for some reason. Be advised that ISO-8859-1
is missing some characters from WINDOWS-1252
as shown here:
| Char | ANSI | Unicode | ANSI Hex | Unicode Hex | HTML entity | Unicode Name | Unicode Range |
| € | 128 | 8364 | 0x80 | U+20AC | € | euro sign | Currency Symbols |
| ‚ | 130 | 8218 | 0x82 | U+201A | ‚ | single low-9 quotation mark | General Punctuation |
| ƒ | 131 | 402 | 0x83 | U+0192 | ƒ | Latin small letter f with hook | Latin Extended-B |
| „ | 132 | 8222 | 0x84 | U+201E | „ | double low-9 quotation mark | General Punctuation |
| … | 133 | 8230 | 0x85 | U+2026 | … | horizontal ellipsis | General Punctuation |
| † | 134 | 8224 | 0x86 | U+2020 | † | dagger | General Punctuation |
| ‡ | 135 | 8225 | 0x87 | U+2021 | ‡ | double dagger | General Punctuation |
| ˆ | 136 | 710 | 0x88 | U+02C6 | ˆ | modifier letter circumflex accent | Spacing Modifier Letters |
| ‰ | 137 | 8240 | 0x89 | U+2030 | ‰ | per mille sign | General Punctuation |
| Š | 138 | 352 | 0x8A | U+0160 | Š | Latin capital letter S with caron | Latin Extended-A |
| ‹ | 139 | 8249 | 0x8B | U+2039 | ‹ | single left-pointing angle quotation mark | General Punctuation |
| Œ | 140 | 338 | 0x8C | U+0152 | Œ | Latin capital ligature OE | Latin Extended-A |
| Ž | 142 | 381 | 0x8E | U+017D | | Latin capital letter Z with caron | Latin Extended-A |
| ‘ | 145 | 8216 | 0x91 | U+2018 | ‘ | left single quotation mark | General Punctuation |
| ’ | 146 | 8217 | 0x92 | U+2019 | ’ | right single quotation mark | General Punctuation |
| “ | 147 | 8220 | 0x93 | U+201C | “ | left double quotation mark | General Punctuation |
| ” | 148 | 8221 | 0x94 | U+201D | ” | right double quotation mark | General Punctuation |
| • | 149 | 8226 | 0x95 | U+2022 | • | bullet | General Punctuation |
| – | 150 | 8211 | 0x96 | U+2013 | – | en dash | General Punctuation |
| — | 151 | 8212 | 0x97 | U+2014 | — | em dash | General Punctuation |
| ˜ | 152 | 732 | 0x98 | U+02DC | ˜ | small tilde | Spacing Modifier Letters |
| ™ | 153 | 8482 | 0x99 | U+2122 | ™ | trade mark sign | Letterlike Symbols |
| š | 154 | 353 | 0x9A | U+0161 | š | Latin small letter s with caron | Latin Extended-A |
| › | 155 | 8250 | 0x9B | U+203A | › | single right-pointing angle quotation mark | General Punctuation |
| œ | 156 | 339 | 0x9C | U+0153 | œ | Latin small ligature oe | Latin Extended-A |
| ž | 158 | 382 | 0x9E | U+017E | | Latin small letter z with caron | Latin Extended-A |
| Ÿ | 159 | 376 | 0x9F | U+0178 | Ÿ | Latin capital letter Y with diaeresis | Latin Extended-A |
Note that the euro sign is missing. This table can be found at Alan Wood.
Conversion is done differently in every tool and language. However, suppose you have a file query_result.csv
which you know is UTF-8
encoded. Convert it to WINDOWS-1252
using iconv
:
iconv -f UTF-8 -t WINDOWS-1252 query_result.csv > query_result-win.csv
Let's take a simple example. Let's say two tables named test
and customer
are there described as:
create table test(
test_id int(11) not null auto_increment,
primary key(test_id));
create table customer(
customer_id int(11) not null auto_increment,
name varchar(50) not null,
primary key(customer_id));
One more table is there which keeps the track of test
s and customer
:
create table tests_purchased(
customer_id int(11) not null,
test_id int(11) not null,
created_date datetime not null,
primary key(customer_id, test_id));
We can see that in the table tests_purchased
the primary key is a composite key, so we will use the <composite-id ...>...</composite-id>
tag in the hbm.xml
mapping file. So the PurchasedTest.hbm.xml
will look like:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="entities.PurchasedTest" table="tests_purchased">
<composite-id name="purchasedTestId">
<key-property name="testId" column="TEST_ID" />
<key-property name="customerId" column="CUSTOMER_ID" />
</composite-id>
<property name="purchaseDate" type="timestamp">
<column name="created_date" />
</property>
</class>
</hibernate-mapping>
But it doesn't end here. In Hibernate we use session.load (entityClass
, id_type_object
) to find and load the entity using primary key. In case of composite keys, the ID object should be a separate ID class (in above case a PurchasedTestId
class) which just declares the primary key attributes like below:
import java.io.Serializable;
public class PurchasedTestId implements Serializable {
private Long testId;
private Long customerId;
// an easy initializing constructor
public PurchasedTestId(Long testId, Long customerId) {
this.testId = testId;
this.customerId = customerId;
}
public Long getTestId() {
return testId;
}
public void setTestId(Long testId) {
this.testId = testId;
}
public Long getCustomerId() {
return customerId;
}
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
@Override
public boolean equals(Object arg0) {
if(arg0 == null) return false;
if(!(arg0 instanceof PurchasedTestId)) return false;
PurchasedTestId arg1 = (PurchasedTestId) arg0;
return (this.testId.longValue() == arg1.getTestId().longValue()) &&
(this.customerId.longValue() == arg1.getCustomerId().longValue());
}
@Override
public int hashCode() {
int hsCode;
hsCode = testId.hashCode();
hsCode = 19 * hsCode+ customerId.hashCode();
return hsCode;
}
}
Important point is that we also implement the two functions hashCode()
and equals()
as Hibernate relies on them.
An elegant way is to use .env
file to locally override production settings.
No need for command line switches. No need for all those commas and brackets in a config.json
file. See my answer here
Example: on my machine the .env
file is this:
NODE_ENV=dev
TWITTER_AUTH_TOKEN=something-needed-for-api-calls
My local .env
overrides any environment variables. But on the staging or production servers (maybe they're on heroku.com) the environment variables are pre-set to stage NODE_ENV=stage
or production NODE_ENV=prod
.
when using the categorical_crossentropy
loss, your targets should be in categorical format (e.g. if you have 10 classes, the target for each sample should be a 10-dimensional vector that is all-zeros except for a 1 at the index corresponding to the class of the sample).
Take a look at "Literal String Interpolation" https://www.python.org/dev/peps/pep-0498/
I found it through the http://www.malemburg.com/
I think one possible solution to this is to use display: table
:
.header {
display: table;
width: 100%;
box-sizing: border-box;
}
.header > * {
display: table-cell;
}
.header > *:last-child {
text-align: right;
}
h1 {
font-size: 32px;
}
nav {
vertical-align: baseline;
}
JSFiddle: http://jsfiddle.net/yxxrnn7j/1/
I know that in SQL 2012 (may work in other versions) you can do the following:
That will give you a list of the top 1000 tables and then you can order it by data size etc.
(Alt + Shift + X) , then M
to Run Maven Build. You will need to specify the Maven goals you want on Run -> Run Configurations
validate last name is blank
SELECT
person.fullName,
(CASE WHEN 0 = CHARINDEX(' ', person.fullName)
then person.fullName
ELSE SUBSTRING(person.fullName, 1, CHARINDEX(' ', person.fullName)) end) as first_name,
(CASE WHEN 0 = CHARINDEX(' ', person.fullName)
THEN ''
ELSE SUBSTRING(person.fullName,CHARINDEX(' ', person.fullName), LEN(person.fullName) )end) last_name
FROM person
CSV export is simple, easy to implement, and fast. There is one potential issue worth noting, though. Excel (up to 2007) does not preserve leading zeros in CSV files. This will garble ZIP codes, product ids, and other textual data containing numeric values. There is one trick that will make Excel import the values correctly (using delimiters and prefix values with the = sign, if I remember correctly, e.g. ..,="02052",...). If you have users who will do post-processing tasks with the CSV, they need to be aware that they need to change the format to XLS and not save the file back to CSV. If they do, leading zeros will be lost for good.
Vanilla JS:
var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable
function activitiesReset() {
var checkboxesChecked = function () { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false.
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead.
if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked
error[2].style.display = 'block'; // red error label is now visible.
}
}
for (var i=0; i<checkboxes.length; i++) { // whenever a checkbox is checked or unchecked, activitiesReset runs.
checkboxes[i].addEventListener('change', activitiesReset);
}
Explanation:
Once a form submit has been attempted, this will update your checkbox section's label to notify the user to check a checkbox if he/she hasn't yet. If no checkboxes are checked, a hidden 'error' label is revealed prompting the user to 'Please check a checkbox!'. If the user checks at least one checkbox, the red label is instantaneously hidden again, revealing the original label. If the user again un-checks all checkboxes, the red label returns in real-time. This is made possible by JavaScript's onchange
event (written as .addEventListener('change', function(){});
In my case for a API in .NET-Core, the api is set to work with XML (by default is set to response with JSON), so I add this annotation in my Controller :
[Produces("application/xml")]
public class MyController : ControllerBase {...}
Thank you for putting me on the path !
Another way to deal with this kind of problem is to use Exception().
for ii in range(200):
try:
for jj in range(200, 400):
...block0...
if something:
raise Exception()
except Exception:
continue
...block1...
For example:
for n in range(1,4):
for m in range(1,4):
print n,'-',m
result:
1-1
1-2
1-3
2-1
2-2
2-3
3-1
3-2
3-3
Assuming we want to jump to the outer n loop from m loop if m =3:
for n in range(1,4):
try:
for m in range(1,4):
if m == 3:
raise Exception()
print n,'-',m
except Exception:
continue
result:
1-1
1-2
2-1
2-2
3-1
3-2
Reference link:http://www.programming-idioms.org/idiom/42/continue-outer-loop/1264/python
An SMS Push is a message to tell the terminal to initiate the session. This happens because you can't initiate an IP session simply because you don't know the IP Adress of the mobile terminal. Mostly used to send a few lines of data to end recipient, to the effect of sending information, or reminding of events.
WAP Push is an SMS within the header of which is included a link to a WAP address. On receiving a WAP Push, the compatible mobile handset automatically gives the user the option to access the WAP content on his handset. The WAP Push directs the end-user to a WAP address where content is stored ready for viewing or downloading onto the handset. This wap address may be a page or a WAP site.
The user may “take action” by using a developer-defined soft-key to immediately activate an application to accomplish a specific task, such as downloading a picture, making a purchase, or responding to a marketing offer.
if key in array:
# do something
Associative arrays are called dictionaries in Python and you can learn more about them in the stdtypes documentation.
A call to your parent class's empty constructor super()
is done automatically when you don't do it yourself. That's the reason you've never had to do it in your code. It was done for you.
When your superclass doesn't have a no-arg constructor, the compiler will require you to call super
with the appropriate arguments. The compiler will make sure that you instantiate the class correctly. So this is not something you have to worry about too much.
Whether you call super()
in your constructor or not, it doesn't affect your ability to call the methods of your parent class.
As a side note, some say that it's generally best to make that call manually for reasons of clarity.
CSS 3
divContainer input[type="text"] {
width:150px;
}
CSS2 add a class "text" to the text inputs then in your css
.divContainer.text{
width:150px;
}
If you are totally new like me, you must install the minimum SDK at first. Check the link.
This worked out perfectly for me:
Same problem other post with a good solution
Regards,
Khaled.
The current directory is a system-level feature; it returns the directory that the server was launched from. It has nothing to do with the website.
You want HttpRuntime.AppDomainAppPath
.
If you're in an HTTP request, you can also call Server.MapPath("~/Whatever")
.
A PendingIntent
is a token that you give to a foreign application (e.g. NotificationManager
, AlarmManager
, Home Screen AppWidgetManager
, or other 3rd party applications), which allows the foreign application to use your application's permissions to execute a predefined piece of code.
If you give the foreign application an Intent, it will execute your Intent
with its own permissions. But if you give the foreign application a PendingIntent
, that application will execute your Intent
using your application's permission.
Although VS Code is a great editor for TypeScript projects, it needs a kick every now and again. Often, without warning, certain files cause it to freak out and complain. Mostly the fix seems to be to save and close all open files, then open tsconfig.json
. After that you should be able to re-open the offending file without error. If it doesn't work, lather, rinse, and repeat.
If your tsconfig.json
specifies its source files using the files
array, IntelliSense will only function correctly if the file in question is referenced such that VS Code can find it by traversing the input file tree.
Edit: The 'reload window' command (added ages ago now) should solve this problem once and for all.
Found one solution for WIFI (works for Android 4.3, 4.4):
use an infinity loop like what you have originally done. Its cleanest and you can incorporate many conditions as you wish
while 1:
if condition1 and condition2:
break
...
...
if condition3: break
...
...
Think I found the correct way to do it using ngx-bootstrap. First import following classes:
import { ViewChild } from '@angular/core';
import { BsModalService, ModalDirective } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';
Inside the class implementation of your component add a @ViewCild property, a function to open the modal and do not forget to setup modalService as a private property inside the components class constructor:
@ViewChild('editSomething') editSomethingModal : TemplateRef<any>;
...
modalRef: BsModalRef;
openModal(template: TemplateRef<any>) {
this.modalRef = this.modalService.show(template);
}
...
constructor(
private modalService: BsModalService) { }
The 'editSomething' part of the @ViewChild declaration refers to the component template file and its modal template implementation (#editSomething):
...
<ng-template #editSomething>
<div class="modal-header">
<h4 class="modal-title pull-left">Edit ...</h4>
<button type="button" class="close pull-right" aria-label="Close"
(click)="modalRef.hide()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
(click)="modalRef.hide()"
>Close</button>
</div>
</ng-template>
And finaly call the method to open the modal wherever you want like so:
console.log(this.editSomethingModal);
this.openModal( this.editSomethingModal );
this.editSomethingModal is a TemplateRef that could be shown by the ModalService.
Et voila! The modal defined in your component template file is shown by a call from inside your component class implementation. In my case I used this to show a modal from inside an event handler.
func setTitleColor(_ color: UIColor?, for state: UIControl.State)
Parameters:
color:
The color of the title to use for the specified state.state:
The state that uses the specified color. The possible values are described in UIControl.State.
Sample:
let MyButton = UIButton()
MyButton.setTitle("Click Me..!", for: .normal)
MyButton.setTitleColor(.green, for: .normal)
I have added in Application Class
@Bean
@ConfigurationProperties("app.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
application.properties I have added
app.datasource.url=jdbc:mysql://localhost/test
app.datasource.username=dbuser
app.datasource.password=dbpass
app.datasource.pool-size=30
More details Configure a Custom DataSource
numpy.random.randint
accepts a third argument (size
) , in which you can specify the size of the output array. You can use this to create your DataFrame
-
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
Here - np.random.randint(0,100,size=(100, 4))
- creates an output array of size (100,4)
with random integer elements between [0,100)
.
Demo -
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
which produces:
A B C D
0 45 88 44 92
1 62 34 2 86
2 85 65 11 31
3 74 43 42 56
4 90 38 34 93
5 0 94 45 10
6 58 23 23 60
.. .. .. .. ..
We released a package, roperators, to help with this kind of thing. You can read more about it here: https://happylittlescripts.blogspot.com/2018/09/make-your-r-code-nicer-with-roperators.html
install.packages('roperators')
require(roperators)
x <- 1:3
x %+=% 1; x
x %-=% 3; x
y <- c('a', 'b', 'c')
y %+=% 'text'; y
y %-=% 'text'; y
# etc
This one works best for me. Use:
os.path.abspath('')
On mac it should print something like:
'/Users/<your username>/<path_to_where_you_at>'
To get the abs path to the current wd, this one is better because now you can go up if you want, like this:
os.path.abspath('../')
And now:
'/Users/<your username>/'
So if you wanna import utils
from here '/Users/<your username>/'
All you've got left to do is:
import sys
sys.path.append(os.path.abspath('../'))
There are a number of variables that the system (Python interpreter) provides for source files (modules). You can get their values anytime you want, so, let us focus on the __name__ variable/attribute:
When Python loads a source code file, it executes all of the code found in it. (Note that it doesn't call all of the methods and functions defined in the file, but it does define them.)
Before the interpreter executes the source code file though, it defines a few special variables for that file; __name__ is one of those special variables that Python automatically defines for each source code file.
If Python is loading this source code file as the main program (i.e. the file you run), then it sets the special __name__ variable for this file to have a value "__main__".
If this is being imported from another module, __name__ will be set to that module's name.
So, in your example in part:
if __name__ == "__main__":
lock = thread.allocate_lock()
thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))
means that the code block:
lock = thread.allocate_lock()
thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))
will be executed only when you run the module directly; the code block will not execute if another module is calling/importing it because the value of __name__ will not equal to "main" in that particular instance.
Hope this helps out.
You can directly import github projects into Android Studio. File -> New -> Project from Version Control -> GitHub. Then enter your github username and password.Select the repository and hit clone.
The github repo will be created as a new project in android studio.
You can use site https://regex101.com/ for building your own specific pattern for some country:
For example, Poland:
-pattern = xxxxxxxxx OR xxx-xxx-xxx OR xxx xxx xxx
-regexp ="^\d{9}|^\d{3}-\d{3}-\d{3}|^\d{3}\s\d{3}\s\d{3}"
I usually create a global function called is_empty() just to get around this issue
function is_empty($var)
{
return empty($var);
}
Then anywhere I would normally have used empty() I just use is_empty()
Yet another parse_requirements
hack that also parses environment markers into extras_require
:
from collections import defaultdict
from pip.req import parse_requirements
requirements = []
extras = defaultdict(list)
for r in parse_requirements('requirements.txt', session='hack'):
if r.markers:
extras[':' + str(r.markers)].append(str(r.req))
else:
requirements.append(str(r.req))
setup(
...,
install_requires=requirements,
extras_require=extras
)
It should support both sdist and binary dists.
As stated by others, parse_requirements
has several shortcomings, so this is not what you should do on public projects, but it may suffice for internal/personal projects.
There is no way you can delete a pull request yourself -- you and the repo owner (and all users with push access to it) can close it, but it will remain in the log. This is part of the philosophy of not denying/hiding what happened during development.
However, if there are critical reasons for deleting it (this is mainly violation of Github Terms of Service), Github support staff will delete it for you.
Whether or not they are willing to delete your PR for you is something you can easily ask them, just drop them an email at [email protected]
UPDATE: Currently Github requires support requests to be created here: https://support.github.com/contact
You need to use Arrow function ()=>
ES6 feature to preserve this
context within setTimeout
.
// var that = this; // no need of this line
this.messageSuccess = true;
setTimeout(()=>{ //<<<---using ()=> syntax
this.messageSuccess = false;
}, 3000);
From the documentation (assuming that you use SQL-Server):
USE AdventureWorks;
GO
DECLARE @returnstatus nvarchar(15);
SET @returnstatus = NULL;
EXEC @returnstatus = dbo.ufnGetSalesOrderStatusText @Status = 2;
PRINT @returnstatus;
GO
So yes, it should work that way.
Check if window.history.length
is equal to 0.
Tested and working!
with https, user & password
<?php
//Data, connection, auth
$dataFromTheForm = $_POST['fieldName']; // request data from the form
$soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
$soapUser = "username"; // username
$soapPassword = "password"; // password
// xml post structure
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
<PRICE>'.$dataFromTheForm.'</PRICE>
</GetItemPrice >
</soap:Body>
</soap:Envelope>'; // data from the form, e.g. some ID number
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
// converting
$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);
// convertingc to XML
$parser = simplexml_load_string($response2);
// user $parser to get your data out of XML response and to display it.
?>
Using Abizern code for swift 2.2
let objectData = responseString!.dataUsingEncoding(NSUTF8StringEncoding)
let json = try NSJSONSerialization.JSONObjectWithData(objectData!, options: NSJSONReadingOptions.MutableContainers)
Why not try find /usr/include/X11 -name Xlib.h
If there is a hit, you have Xlib.h
If not install it using sudo apt-get install libx11-dev
and you are good to go :)
In WebStart and the new 6u10 PlugIn you can use the FileOpenService, even without security permissions. For obvious reasons, you only get the file contents, not the file path.
You also need to add /usr/include/libxml2
to your include path.
If you are using maven try to maven update all projects and force for snapshots. It will clean as well and rebuilt all classpath.. It solved my problem..
This is a example for get the url image, escape the p tag from some item.
Try this:
$('#img').attr('src').split('<p>')[1].split('</p>')[0]
You can use the Feed Dialog via URL to emulate the behavior of Sharer.php, but it's a little more complicated. You need a Facebook App setup with the Base URL of the URL you plan to share configured. Then you can do the following:
1) Create a link like:
http://www.facebook.com/dialog/feed?app_id=[FACEBOOK_APP_ID]' +
'&link=[FULLY_QUALIFIED_LINK_TO_SHARE_CONTENT]' +
'&picture=[LINK_TO_IMAGE]' +
'&name=' + encodeURIComponent('[CONTENT_TITLE]') +
'&caption=' + encodeURIComponent('[CONTENT_CAPTION]) +
'&description=' + encodeURIComponent('[CONTENT_DESCRIPTION]') +
'&redirect_uri=' + FBVars.baseURL + '[URL_TO_REDIRECT_TO_AFTER_SHARE]' +
'&display=popup';
(obviously replace the [CONTENT] with the appropriate content. Documentation here: https://developers.facebook.com/docs/reference/dialogs/feed)
2) Open that link in a popup window with JavaScript on click of the share link
3) I like to create file (i.e. popupclose.html) to redirect users back to when they finish sharing, this file will contain <script>window.close();</script>
to close the popup window
The only downside of using the Feed Dialog (besides setup) is that, if you manage Pages as well, you don't have the ability to choose to share via a Page, only a regular user account can share. And it can give you some really cryptic error messages, most of them are related to the setup of your Facebook app or problems with either the content or URL you are sharing.
As it allows to install more than one version of java, I had install many 3 versions unknowingly but it was point to latest version "11.0.2"
I could able to solve this issue with below steps to move to "1.8"
$java -version
openjdk version "11.0.2" 2019-01-15 OpenJDK Runtime Environment 18.9 (build 11.0.2+9) OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)
cd /Library/Java/JavaVirtualMachines
ls
jdk1.8.0_201.jdk jdk1.8.0_202.jdk openjdk-11.0.2.jdk
sudo rm -rf openjdk-11.0.2.jdk
sudo rm -rf jdk1.8.0_201.jdk
ls
jdk1.8.0_202.jdk
java -version
java version "1.8.0_202-ea" Java(TM) SE Runtime Environment (build 1.8.0_202-ea-b03) Java HotSpot(TM) 64-Bit Server VM (build 25.202-b03, mixed mode)
Please refer to this updated answer: https://stackoverflow.com/a/46830425/4031815
I'm not aware of any current technique to avoid the flicker as the font loads, however you can minimize it by sending proper cache headers for your font and making sure that that request goes through as quickly as possible.
readings = (infile.readline())
print readings
while readings != 0:
global count
readings = int(readings)
There's a problem with that code. readings
is a new line read from the file - it's a string. Therefore you should not compare it to 0. Further, you can't just convert it to an integer unless you're sure it's indeed one. For example, empty lines will produce errors here (as you've surely found out).
And why do you need the global count? That's most certainly bad design in Python.
this may be a simpler approach:
(DesiredFigure).get_figure().savefig('figure_name.png')
i.e.
dfcorr.hist(bins=50).get_figure().savefig('correlation_histogram.png')
For my case, I was trying to execute procedure code in MySQL, and due to some issue with server in which Server can't figure out where to end the statement I was getting Error Code 1064. So I wrapped the procedure with custom DELIMITER and it worked fine.
For example, Before it was:
DROP PROCEDURE IF EXISTS getStats;
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
/*Procedure Code Here*/
END;
After putting DELIMITER it was like this:
DROP PROCEDURE IF EXISTS getStats;
DELIMITER $$
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
/*Procedure Code Here*/
END;
$$
DELIMITER ;
The default JSP file encoding is specified by JSR315 as ISO-8859-1. This is the encoding that the JSP engine uses to read the JSP file and it is unrelated to the servlet request or response encoding.
If you have non-latin characters in your JSP files, save the JSP file as UTF-8 with BOM or set pageEncoding
in the beginning of the JSP page:
<%@page pageEncoding="UTF-8" %>
However, you might want to change the default to UTF-8 globally for all JSP pages. That can be done via web.xml
:
<jsp-config>
<jsp-property-group>
<url-pattern>/*</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>
Or, when using Spring Boot with an (embedded) Tomcat, via a TomcatContextCustomizer
:
@Component
public class JspConfig implements TomcatContextCustomizer {
@Override
public void customize(Context context) {
JspPropertyGroup pg = new JspPropertyGroup();
pg.addUrlPattern("/*");
pg.setPageEncoding("UTF-8");
pg.setTrimWhitespace("true"); // optional, but nice to have
ArrayList<JspPropertyGroupDescriptor> pgs = new ArrayList<>();
pgs.add(new JspPropertyGroupDescriptorImpl(pg));
context.setJspConfigDescriptor(new JspConfigDescriptorImpl(pgs, new ArrayList<TaglibDescriptor>()));
}
}
For JSP to work with Spring Boot, don't forget to include these dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
And to make a "runnable" .war file, repackage it:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
. . .
The comma got eaten by the quotes!
This part:
("username," visitorName);
Should be this:
("username", visitorName);
Aside: For pasting code into the console, you can paste them in one line at a time to help you pinpoint where things went wrong ;-)
You have two options here, you can make it open in a new window/tab with JS:
<td onClick={()=> window.open("someLink", "_blank")}>text</td>
But a better option is to use a regular link but style it as a table cell:
<a style={{display: "table-cell"}} href="someLink" target="_blank">text</a>
This should do it:
declare
v_count integer;
begin
for r in (select table_name, owner from all_tables
where owner = 'SCHEMA_NAME')
loop
execute immediate 'select count(*) from ' || r.table_name
into v_count;
INSERT INTO STATS_TABLE(TABLE_NAME,SCHEMA_NAME,RECORD_COUNT,CREATED)
VALUES (r.table_name,r.owner,v_count,SYSDATE);
end loop;
end;
I removed various bugs from your code.
Note: For the benefit of other readers, Oracle does not provide a table called STATS_TABLE
, you would need to create it.
It's used to make std::string
interoperable with C code that requires a null terminated char*
.
When all else fails, try quitting your IDE. I had many cases in which PyCharm was causing this. As soon as I quit PyCharm, I was able to finally install my packages from the command line. Alternatively, you can also install through PyCharm itself in Settings -> Project: xxx -> Project Interpreter -> +.
Probably not the most performance friendly way, but you could create a scalar function that pulls from the information schema with the table and column name, and then call that using the isnull logic you tried earlier:
CREATE FUNCTION GetDefaultValue
(
@TableName VARCHAR(200),
@ColumnName VARCHAR(200)
)
RETURNS VARCHAR(200)
AS
BEGIN
-- you'd probably want to have different functions for different data types if
-- you go this route
RETURN (SELECT TOP 1 REPLACE(REPLACE(REPLACE(COLUMN_DEFAULT, '(', ''), ')', ''), '''', '')
FROM information_schema.columns
WHERE table_name = @TableName AND column_name = @ColumnName)
END
GO
And then call it like this:
INSERT INTO t (value) VALUES ( ISNULL(@value, SELECT dbo.GetDefaultValue('t', 'value') )
if you are on Mac as myself, try in terminal: xcode-select --install
Then accept the installation request, then it works afterward https://github.com/python-pillow/Pillow/issues/3438
use parse_url
and then output the result in a loop:
$urlinfo = parse_url($the_url);
echo makelink($urlinfo['hostname']);
foreach($breadcrumb in $urlinfo['path']) {
echo makelink($breadcrumb);
}
function makelink($str) {
return '<a href="'.urlencode($str).'" title="'.htmlspecialchars($str).'">'.htmlspecialchars($str).'</a>';
}
(pseudocode)
It's indeed almost a duplicate. I guess the regex you're looking for is
(?!foo).*
int main()
{
char string[200];
int g,a,i,G[20],A[20],met;
gets(string);
g=convert_input(G,string);
for(i=0;i<=g;i++)
printf("\n%d>>%d",i,G[i]);
return 0;
}
int convert_input(int K[],char string[200])
{
int j=0,i=0,temp=0;
while(string[i]!='\0')
{
temp=0;
while(string[i]!=' ' && string[i]!='\0')
temp=temp*10 + (string[i++]-'0') ;
if(string[i]==' ')
i++;
K[j++]=temp;
}
return j-1;
}
It is as simple as this query shown below.
UPDATE
Table1 T1 join Table2 T2 on T1.id = T2.id
SET
T1.LastName='DR. XXXXXX',
T2.WAprrs='start,stop'
WHERE
T1.id = '010008'
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.InputStream.Length);
line 2 should be replaced with
byte[] binData = b.ReadBytes(file.ContentLength);
if you want progress download try this:
var fs = require('fs');
var request = require('request');
var progress = require('request-progress');
module.exports = function (uri, path, onProgress, onResponse, onError, onEnd) {
progress(request(uri))
.on('progress', onProgress)
.on('response', onResponse)
.on('error', onError)
.on('end', onEnd)
.pipe(fs.createWriteStream(path))
};
how to use:
var download = require('../lib/download');
download("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png", "~/download/logo.png", function (state) {
console.log("progress", state);
}, function (response) {
console.log("status code", response.statusCode);
}, function (error) {
console.log("error", error);
}, function () {
console.log("done");
});
note: you should install both request & request-progress modules using:
npm install request request-progress --save
You can use git reset
. This will 'unstage' all the files you've added after your last commit.
If you want to unstage only some files, use git reset -- <file 1> <file 2> <file n>
.
Also it's possible to unstage some of the changes in files by using git reset -p
.
Take a look at this:
http://developer.android.com/reference/android/util/DisplayMetrics.html
You can get the heigth of the screen and it's simple math to calculate 68 percent of the screen.
i think it should be
select convert(varchar(10),StandardCost) +'S' from DimProduct where ProductKey = 212
or
select cast(StandardCost as varchar(10)) + 'S' from DimProduct where ProductKey = 212
First create the menu layouts in the your Activity layout xml file. For e.g. a linear layout with horizontal orientation and include a TextView for label then a Floating Action Button beside the TextView.
Create the menu layouts as per your need and number.
Create a Base Floating Action Button and on its click of that change the visibility of the Menu Layouts.
Please check the below code for the reference and for more info checkout my project from github
<android.support.constraint.ConstraintLayout
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.app.fabmenu.MainActivity">
<android.support.design.widget.FloatingActionButton
android:id="@+id/baseFloatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:clickable="true"
android:onClick="@{FabHandler::onBaseFabClick}"
android:tint="@android:color/white"
app:fabSize="normal"
app:layout_constraintBottom_toBottomOf="@+id/activity_main"
app:layout_constraintRight_toRightOf="@+id/activity_main"
app:srcCompat="@drawable/ic_add_black_24dp" />
<LinearLayout
android:id="@+id/shareLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:layout_marginEnd="24dp"
android:layout_marginRight="24dp"
android:gravity="center_vertical"
android:orientation="horizontal"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="@+id/createLayout"
app:layout_constraintLeft_toLeftOf="@+id/createLayout"
app:layout_constraintRight_toRightOf="@+id/activity_main">
<TextView
android:id="@+id/shareLabelTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:background="@drawable/shape_fab_label"
android:elevation="2dp"
android:fontFamily="sans-serif"
android:padding="5dip"
android:text="Share"
android:textColor="@android:color/white"
android:typeface="normal" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/shareFab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:onClick="@{FabHandler::onShareFabClick}"
android:tint="@android:color/white"
app:fabSize="mini"
app:srcCompat="@drawable/ic_share_black_24dp" />
</LinearLayout>
<LinearLayout
android:id="@+id/createLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:layout_marginEnd="24dp"
android:layout_marginRight="24dp"
android:gravity="center_vertical"
android:orientation="horizontal"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="@+id/baseFloatingActionButton"
app:layout_constraintRight_toRightOf="@+id/activity_main">
<TextView
android:id="@+id/createLabelTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:background="@drawable/shape_fab_label"
android:elevation="2dp"
android:fontFamily="sans-serif"
android:padding="5dip"
android:text="Create"
android:textColor="@android:color/white"
android:typeface="normal" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/createFab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:onClick="@{FabHandler::onCreateFabClick}"
android:tint="@android:color/white"
app:fabSize="mini"
app:srcCompat="@drawable/ic_create_black_24dp" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
These are the animations-
Opening animation of FAB Menu:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<scale
android:duration="300"
android:fromXScale="0"
android:fromYScale="0"
android:interpolator="@android:anim/linear_interpolator"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="1"
android:toYScale="1" />
<alpha
android:duration="300"
android:fromAlpha="0.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="1.0" />
</set>
Closing animation of FAB Menu:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<scale
android:duration="300"
android:fromXScale="1"
android:fromYScale="1"
android:interpolator="@android:anim/linear_interpolator"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="0.0"
android:toYScale="0.0" />
<alpha
android:duration="300"
android:fromAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="0.0" />
</set>
Then in my Activity I've simply used the animations above to show and hide the FAB menu :
Show Fab Menu:
private void expandFabMenu() {
ViewCompat.animate(binding.baseFloatingActionButton).rotation(45.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
binding.createLayout.startAnimation(fabOpenAnimation);
binding.shareLayout.startAnimation(fabOpenAnimation);
binding.createFab.setClickable(true);
binding.shareFab.setClickable(true);
isFabMenuOpen = true;
}
Close Fab Menu:
private void collapseFabMenu() {
ViewCompat.animate(binding.baseFloatingActionButton).rotation(0.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
binding.createLayout.startAnimation(fabCloseAnimation);
binding.shareLayout.startAnimation(fabCloseAnimation);
binding.createFab.setClickable(false);
binding.shareFab.setClickable(false);
isFabMenuOpen = false;
}
Here is the the Activity class -
package com.app.fabmenu;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.OvershootInterpolator;
import com.app.fabmenu.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
private Animation fabOpenAnimation;
private Animation fabCloseAnimation;
private boolean isFabMenuOpen = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setFabHandler(new FabHandler());
getAnimations();
}
private void getAnimations() {
fabOpenAnimation = AnimationUtils.loadAnimation(this, R.anim.fab_open);
fabCloseAnimation = AnimationUtils.loadAnimation(this, R.anim.fab_close);
}
private void expandFabMenu() {
ViewCompat.animate(binding.baseFloatingActionButton).rotation(45.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
binding.createLayout.startAnimation(fabOpenAnimation);
binding.shareLayout.startAnimation(fabOpenAnimation);
binding.createFab.setClickable(true);
binding.shareFab.setClickable(true);
isFabMenuOpen = true;
}
private void collapseFabMenu() {
ViewCompat.animate(binding.baseFloatingActionButton).rotation(0.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
binding.createLayout.startAnimation(fabCloseAnimation);
binding.shareLayout.startAnimation(fabCloseAnimation);
binding.createFab.setClickable(false);
binding.shareFab.setClickable(false);
isFabMenuOpen = false;
}
public class FabHandler {
public void onBaseFabClick(View view) {
if (isFabMenuOpen)
collapseFabMenu();
else
expandFabMenu();
}
public void onCreateFabClick(View view) {
Snackbar.make(binding.coordinatorLayout, "Create FAB tapped", Snackbar.LENGTH_SHORT).show();
}
public void onShareFabClick(View view) {
Snackbar.make(binding.coordinatorLayout, "Share FAB tapped", Snackbar.LENGTH_SHORT).show();
}
}
@Override
public void onBackPressed() {
if (isFabMenuOpen)
collapseFabMenu();
else
super.onBackPressed();
}
}
Here are the screenshots
In TorpedoQuery it look like this
Entity from = from(Entity.class);
where(from.getCode()).in("Joe", "Bob");
Query<Entity> select = select(from);
Maybe you should try LocallyDB it's easy-to-use and lightweight in addition to the with advanced selecting system similar to javascript conditional expression...
There are several tools for converting Matlab to Python code.
The only one that's seen recent activity (last commit from June 2018) is Small Matlab to Python compiler (also developed here: SMOP@chiselapp).
Other options include:
Also, for those interested in an interface between the two languages and not conversion:
pymatlab
: communicate from Python by sending data to the MATLAB workspace, operating on them with scripts and pulling back the resulting data.pymat2
: continuation of the seemingly abandoned PyMat.mlabwrap
, mlabwrap-purepy: make Matlab look like Python library (based on PyMat).oct2py
: run GNU Octave commands from within Python.pymex
: Embeds the Python Interpreter in Matlab, also on File Exchange.matpy
: Access MATLAB in various ways: create variables, access .mat files, direct interface to MATLAB engine (requires MATLAB be installed).Btw might be helpful to look here for other migration tips:
On a different note, though I'm not a fortran
fan at all, for people who might find it useful there is:
Check tis article on Partial Key Verification which covers the following requirements:
License keys must be easy enough to type in.
We must be able to blacklist (revoke) a license key in the case of chargebacks or purchases with stolen credit cards.
No “phoning home” to test keys. Although this practice is becoming more and more prevalent, I still do not appreciate it as a user, so will not ask my users to put up with it.
It should not be possible for a cracker to disassemble our released application and produce a working “keygen” from it. This means that our application will not fully test a key for verification. Only some of the key is to be tested. Further, each release of the application should test a different portion of the key, so that a phony key based on an earlier release will not work on a later release of our software.
Important: it should not be possible for a legitimate user to accidentally type in an invalid key that will appear to work but fail on a future version due to a typographical error.
if you are adding multiple items to the list use this:
mAdapter.notifyItemRangeInserted(startPosition, itemcount);
This notify any registered observers that the currently reflected itemCount items starting at positionStart have been newly inserted. The item previously located at positionStart and beyond can now be found starting at position positinStart+itemCount
existing item in the dataset still considered up to date.
Off the top of my head and not guaranteed to be correct: I believe the second will be faster in this case.
IN
will short-circuit as soon as it finds a match.For Windows:
Save the following as MSFT.vbs:
set SOAPClient = createobject("MSSOAP.SOAPClient")
SOAPClient.mssoapinit "https://sandbox.mediamind.com/Eyeblaster.MediaMind.API/V2/AuthenticationService.svc?wsdl"
WScript.Echo "MSFT = " & SOAPClient.GetQuote("MSFT")
Then from a command prompt, run:
C:\>MSFT.vbs
Reference: http://blogs.msdn.com/b/bgroth/archive/2004/10/21/246155.aspx
You can write your own equals function:
a == b
Because you're dealing with json, you'll have standard python types: dict
, list
, etc., so you can do hard type checking if type(obj) == 'dict':
, etc.
Rough example (not tested):
def json_equals(jsonA, jsonB):
if type(jsonA) != type(jsonB):
# not equal
return False
if type(jsonA) == dict:
if len(jsonA) != len(jsonB):
return False
for keyA in jsonA:
if keyA not in jsonB or not json_equal(jsonA[keyA], jsonB[keyA]):
return False
elif type(jsonA) == list:
if len(jsonA) != len(jsonB):
return False
for itemA, itemB in zip(jsonA, jsonB):
if not json_equal(itemA, itemB):
return False
else:
return jsonA == jsonB
If you use df.replace([None], np.nan, inplace=True), this changed all datetime objects with missing data to object dtypes. So now you may have broken queries unless you change them back to datetime which can be taxing depending on the size of your data.
If you want to use this method, you can first identify the object dtype fields in your df and then replace the None:
obj_columns = list(df.select_dtypes(include=['object']).columns.values)
df[obj_columns] = df[obj_columns].replace([None], np.nan)
In Intellij, I simple changed the name of the docker files to *.Dockerfile, and associated the file type *.Dockerfile to docker syntax.
Late edit: there is an official plugin for Chart.js 2.7.0+
to do this: https://github.com/chartjs/chartjs-plugin-datalabels
Original answer:
You can loop through the points / bars onAnimationComplete and display the values
Preview
HTML
<canvas id="myChart1" height="300" width="500"></canvas>
<canvas id="myChart2" height="300" width="500"></canvas>
Script
var chartData = {
labels: ["January", "February", "March", "April", "May", "June"],
datasets: [
{
fillColor: "#79D1CF",
strokeColor: "#79D1CF",
data: [60, 80, 81, 56, 55, 40]
}
]
};
var ctx = document.getElementById("myChart1").getContext("2d");
var myLine = new Chart(ctx).Line(chartData, {
showTooltips: false,
onAnimationComplete: function () {
var ctx = this.chart.ctx;
ctx.font = this.scale.font;
ctx.fillStyle = this.scale.textColor
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
this.datasets.forEach(function (dataset) {
dataset.points.forEach(function (points) {
ctx.fillText(points.value, points.x, points.y - 10);
});
})
}
});
var ctx = document.getElementById("myChart2").getContext("2d");
var myBar = new Chart(ctx).Bar(chartData, {
showTooltips: false,
onAnimationComplete: function () {
var ctx = this.chart.ctx;
ctx.font = this.scale.font;
ctx.fillStyle = this.scale.textColor
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
this.datasets.forEach(function (dataset) {
dataset.bars.forEach(function (bar) {
ctx.fillText(bar.value, bar.x, bar.y - 5);
});
})
}
});
Fiddle - http://jsfiddle.net/uh9vw0ao/
Java does not support multiple inheritance because of two reasons:
Object
class. When it inherits from more than one super class, sub class gets the ambiguity to
acquire the property of Object class..super()
to invoke the
supper class constructor. If the class has more than one super class, it
gets confused.So when one class extends from more than one super class, we get compile time error.
Here's a nice hack for windows
process.on('exit', async () => {
require('fs').writeFileSync('./tmp.js', 'crash', 'utf-8')
});
#include <fstream>
#include <iostream>
FILE * pFileTXT;
int counter
int main()
{
pFileTXT = fopen ("aTextFile.txt","a");// use "a" for append, "w" to overwrite, previous content will be deleted
for(counter=0;counter<9;counter++)
fprintf (pFileTXT, "%c", characterarray[counter] );// character array to file
fprintf(pFileTXT,"\n");// newline
for(counter=0;counter<9;counter++)
fprintf (pFileTXT, "%d", digitarray[counter] ); // numerical to file
fprintf(pFileTXT,"A Sentence"); // String to file
fprintf (pFileXML,"%.2x",character); // Printing hex value, 0x31 if character= 1
fclose (pFileTXT); // must close after opening
return 0;
}
"hello _there_".replace(/_(.*?)_/, function(a, b){
return '<div>' + b + '</div>';
})
Oh, or you could also:
"hello _there_".replace(/_(.*?)_/, "<div>$1</div>")
EDIT by Liran H:
For six other people including myself, $1
did not work, whereas \1
did.
Why don't you consider www.cameraftp.com? it supports image upload and online viewer
You are getting confused with transclude: true
, which would append the inner content.
replace: true
means that the content of the directive template will replace the element that the directive is declared on, in this case the <div myd1>
tag.
http://plnkr.co/edit/k9qSx15fhSZRMwgAIMP4?p=preview
For example without replace:true
<div myd1><span class="replaced" myd1="">directive template1</span></div>
and with replace:true
<span class="replaced" myd1="">directive template1</span>
As you can see in the latter example, the div tag is indeed replaced.
Overload less than operator, then sort. This is an example I found off the web...
class MyData
{
public:
int m_iData;
string m_strSomeOtherData;
bool operator<(const MyData &rhs) const { return m_iData < rhs.m_iData; }
};
std::sort(myvector.begin(), myvector.end());
Source: here
Not an exact answer because you're using xml data and there is currently no pd.read_xml()
function (as of v0.23.4), but pandas (starting with v0.21.0) can uncompress the file for you! Thanks Wes!
import pandas as pd
import os
fn = '../data/file_to_load.json.gz'
print(os.path.isfile(fn))
df = pd.read_json(fn, lines=True, compression='gzip')
df.tail()
If you use FireBug, on the Network tab's drop down menu there is an option do disable the browser's cache.
Find String regex = "^\\+(?:[0-9] ?){6,14}[0-9]$";
helpful for international numbers.
I would try the itemStateChanged()
method of the ItemListener
interface if jodonnell's solution fails.
You didn't specified what JAXB-IMPL version are you using, but once I had the same problem (with jaxb-impl 2.0.5) and solved it using the annotation at the getter level instead of using it at the member level.
Based on this HTML5 Doctor diagram, I'm thinking this may be the best markup:
<aside class="sidebar">
<article id="widget_1" class="widget">...</article>
<article id="widget_2" class="widget">...</article>
<article id="widget_3" class="widget">...</article>
</aside> <!-- end .sidebar -->
I think it's clear that <aside>
is the appropriate element as long as it's outside the main <article>
element.
Now, I'm thinking that <article>
is also appropriate for each widget in the aside. In the words of the W3C:
The article element represents a self-contained composition in a document, page, application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.
If you have Git bash installed, you can do something like this:
/c/Program\ Files\ \(x86\)/PostgreSQL/9.3/bin/psql -U <pg_role_name> -d <pg_database_name> < <path_to_your>.sql
You can change the default location of .m2 directory in m2.conf file. It resides in your maven installation directory.
add modify this line in
m2.conf
set maven.home C:\Users\me\.m2
You need something like this:
foreach(DataColumn c in dr.Table.Columns)
{
MessageBox.Show(c.ColumnName);
}
For ListBox / DropDown in MVC5 - i've found this to work for me sofar:
in Model:
[Required(ErrorMessage = "- Select item -")]
public List<string> SelectedItem { get; set; }
public List<SelectListItem> AvailableItemsList { get; set; }
in View:
@Html.ListBoxFor(model => model.SelectedItem, Model.AvailableItemsList)
@Html.ValidationMessageFor(model => model.SelectedItem, "", new { @class = "text-danger" })
MongoDB needs data directory to store data.
Default path is /data/db
When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx
permission to user.
If you want to change the path of your data directory then you should specify it while starting mongod server like,
mongod --dbpath /data/<path> --port <port no>
This should help you start your mongod server with custom path and port.
This would be easier to do with flexbox. Using flexbox will let you not to specify the height of your content and can adjust automatically on the height it contains.
here's the gist of the demo
.container{
display: flex;
height: 100%;
justify-content: center;
align-items: center;
}
html
<div class="container">
<div class='content'> //you can size this anyway you want
put anything you want here,
</div>
</div>
I haven't used Angular, but reading the link above, it seems that you're trying to code for something that you don't need to handle. You make changes to state in your React component hierarchy (via this.setState()) and React will cause your component to be re-rendered (effectively 'listening' for changes). If you want to 'listen' from another component in your hierarchy then you have two options:
I'm not sure whether it is a new feature in later versions of matplotlib, but at least for 1.3.1, this is simply:
plt.title(figure_title, y=1.08)
This also works for plt.suptitle()
, but not (yet) for plt.xlabel()
, etc.
Place the body of your loop after the while
and before the test. The actual body of the while
loop should be a no-op.
while
check_if_file_present
#do other stuff
(( current_time <= cutoff ))
do
:
done
Instead of the colon, you can use continue
if you find that more readable. You can also insert a command that will only run between iterations (not before first or after last), such as echo "Retrying in five seconds"; sleep 5
. Or print delimiters between values:
i=1; while printf '%d' "$((i++))"; (( i <= 4)); do printf ','; done; printf '\n'
I changed the test to use double parentheses since you appear to be comparing integers. Inside double square brackets, comparison operators such as <=
are lexical and will give the wrong result when comparing 2 and 10, for example. Those operators don't work inside single square brackets.
ConcurrentLinkedQueue is lock-free, LinkedBlockingQueue is not. Every time you invoke LinkedBlockingQueue.put() or LinkedBlockingQueue.take(), you need acquire the lock first. In other word, LinkedBlockingQueue has poor concurrency. If you care performance, try ConcurrentLinkedQueue + LockSupport.
I wanted to add my solution since the accepted one didn't quite work for me.
I needed to add a directive but also keep mine on the element.
In this example I am adding a simple ng-style directive to the element. To prevent infinite compile loops and allowing me to keep my directive I added a check to see if what I added was present before recompiling the element.
angular.module('some.directive', [])
.directive('someDirective', ['$compile',function($compile){
return {
priority: 1001,
controller: ['$scope', '$element', '$attrs', '$transclude' ,function($scope, $element, $attrs, $transclude) {
// controller code here
}],
compile: function(element, attributes){
var compile = false;
//check to see if the target directive was already added
if(!element.attr('ng-style')){
//add the target directive
element.attr('ng-style', "{'width':'200px'}");
compile = true;
}
return {
pre: function preLink(scope, iElement, iAttrs, controller) { },
post: function postLink(scope, iElement, iAttrs, controller) {
if(compile){
$compile(iElement)(scope);
}
}
};
}
};
}]);
Daniel's script appears to be a good all encompassing solution, but even he admitted that his laptop ran out of memory. Here is an option I came up with. I based my procedure off of Mohammad Nizamuddin's post on TechNet. I added an initial cursor loop that pulls all the database names into a temporary table and then uses that to pull all the base table names from each of those databases.
You can optionally pass the fill factor you would prefer and specify a target database if you do not want to re-index all databases.
--===============================================================
-- Name: sp_RebuildAllIndexes
-- Arguements: [Fill Factor], [Target Database name]
-- Purpose: Loop through all the databases on a server and
-- compile a list of all the table within them.
-- This list is then used to rebuild indexes for
-- all the tables in all the database. Optionally,
-- you may pass a specific database name if you only
-- want to reindex that target database.
--================================================================
CREATE PROCEDURE sp_RebuildAllIndexes(
@FillFactor INT = 90,
@TargetDatabase NVARCHAR(100) = NULL)
AS
BEGIN
DECLARE @TablesToReIndex TABLE (
TableName VARCHAR(200)
);
DECLARE @DbName VARCHAR(50);
DECLARE @TableSelect VARCHAR(MAX);
DECLARE @DatabasesToIndex CURSOR;
IF ISNULL( @TargetDatabase, '' ) = ''
SET @DatabasesToIndex = CURSOR
FOR SELECT NAME
FROM master..sysdatabases
ELSE
SET @DatabasesToIndex = CURSOR
FOR SELECT NAME
FROM master..sysdatabases
WHERE NAME = @TargetDatabase
OPEN DatabasesToIndex
FETCH NEXT FROM DatabasesToIndex INTO @DbName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @TableSelect = 'INSERT INTO @TablesToReIndex SELECT CONCAT(TABLE_CATALOG, ''.'', TABLE_SCHEMA, ''.'', TABLE_NAME) AS TableName FROM '
+ @DbName
+ '.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ''base table''';
EXEC sp_executesql
@TableSelect;
FETCH NEXT FROM DatabasesToIndex INTO @DbName
END
CLOSE DatabasesToIndex
DEALLOCATE DatabasesToIndex
DECLARE @TableName VARCHAR(255)
DECLARE TableCursor CURSOR FOR
SELECT TableName
FROM @TablesToReIndex
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
DBCC DBREINDEX(@TableName, ' ', @FillFactor)
FETCH NEXT FROM TableCursor INTO @TableName
END
CLOSE TableCursor
DEALLOCATE TableCursor
END
You could use LINQBridge (MIT Licensed) to add support for lambda expressions to C# 2.0:
With Studio's multi-targeting and LINQBridge, you'll be able to write local (LINQ to Objects) queries using the full power of the C# 3.0 compiler—and yet your programs will require only Framework 2.0.
I had this problem on my ubuntu.
I just ran adb from sdk/platform-tools
instead of pre-installed version on my system and it worked fine.
Rotate by 90 degress around 0,0:
x' = -y
y' = x
Rotate by 90 degress around px,py:
x' = -(y - py) + px
y' = (x - px) + py
Using array formula.
=SUM(COUNT(IF(D1:D5="Yes",COUNT(D1:D5),"")),COUNT(IF(D1:D5="No",COUNT(D1:D5),"")),COUNT(IF(D1:D5="Agree",COUNT(D1:D5),"")))
PRESS = CTRL + SHIFT + ENTER.
In my case this worked perfectly:
jQuery(document).on('mouseup keydown touchend', function (event) {
var eventType = event.type;
if (eventType == 'touchend') {
jQuery(this).off('mouseup');
}
});
The main problem was when instead mouseup I tried with click, on touch devices triggered click and touchend at the same time, if i use the click off, some functionality didn't worked at all on mobile devices. The problem with click is that is a global event that fire the rest of the event including touchend.
If you have queries that will be frequently using a relatively static set of columns, creating a single covering index that includes them all will improve performance dramatically.
By putting multiple columns in your index, the optimizer will only have to access the table directly if a column is not in the index. I use these a lot in data warehousing. The downside is that doing this can cost a lot of overhead, especially if the data is very volatile.
Creating indexes on single columns is useful for lookup operations frequently found in OLTP systems.
You should ask yourself why you're indexing the columns and how they'll be used. Run some query plans and see when they are being accessed. Index tuning is as much instinct as science.
If you have trouble understanding, this code can help you
private void MyTabLayout(){
TabLayout.Tab myTab = myTabLayout.newTab(); // create a new tab
myTabLayout.addTab(myTab); // add my new tab to myTabLayout
myTab.setText("new tab");
myTab.select(); // select the new tab
}
You can also add this to your code:
myTabLayout.setTabTextColors(getColor(R.color.colorNormalTab),getColor(R.color.colorSelectedTab));
Another variant to POST this content type and which does not use a dictionary would be:
StringContent postData = new StringContent(JSON_CONTENT, Encoding.UTF8, "application/x-www-form-urlencoded");
using (HttpResponseMessage result = httpClient.PostAsync(url, postData).Result)
{
string resultJson = result.Content.ReadAsStringAsync().Result;
}
You don't need to run Xcode 10.2 for iOS 12.2 support. You just need access to the appropriate folder in DeviceSupport.
A possible solution is
/Applications
. It's possible to have multiple Xcode versions in the same directory.Create a symbolic link in Terminal.app to have access to the 12.2 device support folder in Xcode 10.2
ln -s /Applications/Xcode102.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/12.2\ \(16E226\) /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport
You can move Xcode 10.2 to somewhere else but then you have to adjust the path.
Now Xcode 10.1 supports devices running iOS 12.2
I would say it has capabilities to seem OO. Especially if you take advantage of it's ability to create methods on an existing object (anonymous methods in some languages). Client script libraries like jquery (jquery.com) or prototype (prototypejs.org) are good examples of libraries taking advantage of this, making javascript behave pretty OO-like.
Do I need to make another view which holds these 2 views?
Isn't there another way such as (without the BigViewModel):
Yes, you can use Tuple (brings magic in view having multiple model).
Code:
@model Tuple<LoginViewModel, RegisterViewModel>
@using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
@Html.TextBoxFor(tuple=> tuple.Item.Name)
@Html.TextBoxFor(tuple=> tuple.Item.Email)
@Html.PasswordFor(tuple=> tuple.Item.Password)
}
@using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
@Html.TextBoxFor(tuple=> tuple.Item1.Email)
@Html.PasswordFor(tuple=> tuple.Item1.Password)
}
For those who (unlike OP) are using the express lib:
http.get('*',function(req,res){
res.redirect('http://exmple.com'+req.url)
})
Your log indicates ClientAbortException, which occurs when your HTTP client drops the connection with the server and this happened before server could close the server socket Connection.
For exceptional cases, I will recommend you to adopt RFC-7807 Problem Details for HTTP APIs standard in your application.
Zalando's Problems for Spring provides a good integration with Spring Boot, you can integrate it easily with your existing Spring Boot based application. Just like what JHipster did.
After adopting RFC-7087 in your application, just throw Exception in your controller method, and you will get a detailed and standard error response like:
{
"type": "https://example.com/probs/validation-error",
"title": "Request parameter is malformed.",
"status": 400
"detail": "Validation error, value of xxx should be a positive number.",
"instance": "/account/12345/msgs/abc",
}
This helped me with the exact same problem.
Solution:
Forward declare the friend
function before the definition of the class
itself. For example:
template<typename T> class MyClass; // pre-declare the template class itself
template<typename T> std::ostream& operator<< (std::ostream& o, const MyClass <T>& x);
Declare your friend function in your class with "<>" appended to the function name.
friend std::ostream& operator<< <> (std::ostream& o, const Foo<T>& x);
You can use like this:
@Transactional(propagation = Propagation.REQUIRES_NEW)
public EventMessage<ModificaOperativitaRapporto> activate(EventMessage<ModificaOperativitaRapporto> eventMessage) {
//here some transaction related code
}
You can use this thing also:
public interface TransactionStatus extends SavepointManager {
boolean isNewTransaction();
boolean hasSavepoint();
void setRollbackOnly();
boolean isRollbackOnly();
void flush();
boolean isCompleted();
}
Javascript has a toUpperCase()
method. http://www.w3schools.com/jsref/jsref_toUpperCase.asp
So wherever you think best to put it in your code, you would have to do something like
$(".keywords").val().toUpperCase()
It works fine for my v. 5.4.5 of Notepad++. I just select multiple lines and press TAB.
If you want TAB to be replaced by SPACE than you need to go Settings > Preferences and select Edit Components tab. Next check Replace by spaces check box in Tab Setting section.
Update: In a newer version of Notepad++ this option is in Settings > Preferences > Languaage section.
I couldn't find a good solution on the web for this problem and solved it myself. There are lot of people suffering from this problem. Thus i want to share my solution here.
While scrolling, rows are recycled. Thus, checked checkboxes and highlighted rows do not work properly. I solved this problem by writing the below adapter class.
I also implement a full project. In this project, you can select multiple checkboxes. Rows including selected checkboxes are highlighted. And more importantly, these are not lost while scrolling. You can download it from the link :
https://www.dropbox.com/s/ssm58w62gw32i29/recyclerView_checkbox_highlight.zip?dl=0
public class RV_Adapter extends RecyclerView.Adapter<RV_Adapter.ViewHolder> {
public ArrayList<String> list;
boolean[] checkBoxState;
MainActivity mainActivity;
MyFragment myFragment;
View firstview;
private Context context;
FrameLayout framelayout;
public RV_Adapter() {
}
public RV_Adapter(Context context, MyFragment m, ArrayList<String> list ) {
this.list = list;
myFragment = m;
this.context = context;
mainActivity = (MainActivity) context;
checkBoxState = new boolean[list.size()];
// relativeLayoutState = new boolean[list.size()];
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textView;
public CheckBox checkBox;
RelativeLayout relativeLayout;
MainActivity mainActivity;
MyFragment myFragment;
public ViewHolder(View v,MainActivity mainActivity,MyFragment m) {
super(v);
textView = (TextView) v.findViewById(R.id.tv_foodname);
/**/
checkBox= (CheckBox) v.findViewById(R.id.checkBox);
relativeLayout = (RelativeLayout)v.findViewById(R.id.relativelayout);
this.mainActivity = mainActivity;
this.myFragment = m;
framelayout = (FrameLayout) v.findViewById(R.id.framelayout);
framelayout.setOnLongClickListener(m);
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
firstview = inflater.inflate(R.layout.row, parent, false);
return new ViewHolder(firstview,mainActivity, myFragment);
}
@Override
public void onBindViewHolder( final ViewHolder holder, final int position) {
holder.textView.setText(list.get(position));
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
// When action mode is active, checkboxes are displayed on each row, handle views(move icons) on each row are disappered.
if(!myFragment.is_in_action_mode)
{
holder.checkBox.setVisibility(View.GONE);
}
else
{
holder.checkBox.setVisibility(View.VISIBLE);
holder.checkBox.setChecked(false);
}
holder.checkBox.setTag(position);
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(compoundButton.isPressed()) // ekrandan kaybolan checkbox'lar otomatik olarak state degistiriyordu ve bu listener method cagiriliyordu, bunu onlemek icin isPressed() method'u ile kullanici mi basmis diye kontrol ediyorum.
{
int getPosition = (Integer) compoundButton.getTag(); // Here we get the position that we have set for the checkbox using setTag.
checkBoxState[getPosition] = compoundButton.isChecked(); // Set the value of checkbox to maintain its state.
//relativeLayoutState[getPosition] = compoundButton.isChecked();
if(checkBoxState[getPosition] && getPosition == position )
holder.relativeLayout.setBackgroundResource(R.color.food_selected); /** Change background color of the selected items in list view **/
else
holder.relativeLayout.setBackgroundResource(R.color.food_unselected); /** Change background color of the selected items in list view **/
myFragment.prepareselection(compoundButton, getPosition, holder.relativeLayout);
}
}
});
holder.checkBox.setChecked(checkBoxState[position]);
if(checkBoxState[position] )
holder.relativeLayout.setBackgroundResource(R.color.food_selected); /** Change background color of the selected items in list view **/
else
holder.relativeLayout.setBackgroundResource(R.color.food_unselected);
}
@Override
public int getItemCount() {
return list.size();
}
public void updateList(ArrayList<String> newList){
this.list = newList;
checkBoxState = new boolean[list.size()+1];
}
public void resetCheckBoxState(){
checkBoxState = null;
checkBoxState = new boolean[list.size()];
}
}
Screenshots of the app :
No, there is no nonsense like that. Something we have not missed in Python for 20 years.
As mentioned, but with a code sample:
foreach(var item in collection.ToArray())
collection.Add(new Item...);
You may also be interested in modifying it using jQuery: http://api.jquery.com/category/css/
The simplest way of doing this which I find useful is the below.
This might not be the official way but it works well.
Suppose you have a project named "XYZ
" on your PC.
Now you want to make a git repo of this project on github and use its functionalities.
Step 1: go to "www.github.com
"
Step 2: create a repository with a "README.md
" file (name it as you like it)
Step 3: clone the repository to your PC.
Step 4: In the cloned folder you will get two things : ".git
" folder and a "README.md
" file. Copy these two in your project folder "XYZ
".
Step 5: Delete the cloned repo.
Step 6: add, commit and push all the files and folders of your project.
Now, you can just use your project "XYZ
" as a git repository.
Wrong method was used for errors, here is the working code:
BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
Try browse the WCF in IIS see if it's alive and works normally,
In my case it's because the physical path of the WCF is misdirected.
How to disable clicking another div click until first one popup div close
<p class="btn1">One</p>
<div id="box1" class="popup">
Test Popup Box One
<span class="close">X</span>
</div>
<!-- Two -->
<p class="btn2">Two</p>
<div id="box2" class="popup">
Test Popup Box Two
<span class="close">X</span>
</div>
<style>
.disabledbutton {
pointer-events: none;
}
.close {
cursor: pointer;
}
</style>
<script>
$(document).ready(function(){
//One
$(".btn1").click(function(){
$("#box1").css('display','block');
$(".btn2,.btn3").addClass("disabledbutton");
});
$(".close").click(function(){
$("#box1").css('display','none');
$(".btn2,.btn3").removeClass("disabledbutton");
});
</script>
How about a single standalone function named as debug from https://github.com/hazardland/debug.php.
Typical debug() html output looks like this:
But you can output data as a plain text with same function also (with 4 space indented tabs) like this (and even log it in file if needed):
string : "Test string"
boolean : true
integer : 17
float : 9.99
array (array)
bob : "alice"
1 : 5
2 : 1.4
object (test2)
another (test3)
string1 : "3d level"
string2 : "123"
complicated (test4)
enough : "Level 4"
I tried all mentioned solutions but none of them worked. Using Internet Explorer 11 (11.0.9600.17914), there was no way of accepting invalid certificates as the error looked exactly as an 404.
What helped was the following: - add host to trusted sites (as mentioned a couple of times here) - disable TLS 1.2 and enable SSL 1.0 & SSL 2.0
The last step is something you should ONLY DO if you know what you're doing. We need to use a pretty strange setup here at work, thus we couldn't find another way of getting access to the system. Usually, downgrading security like that should not be done.
Another solution (from a script, for example):
sed -i'' -e "s/password=.*\$/password=$pass/g" ~/.my.cnf
mysql -h $host -u $user $db_name -e "$sql_cmd"
The -i''
option is here for compatibility with Mac OS X. Standard UNIX OSes can use straight -i
Deserialize your jsonstring to some class
List<User> UserList = JsonConvert.DeserializeObject<List<User>>(jsonString);
Write following extension method to your project
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection props =
TpeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for(int i = 0 ; i < props.Count ; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
Call extension method like
UserList.ToDataTable<User>();
Necromancing.
It looks you have just as good a schema to work with as me...
Here is how to do it correctly:
In this example, the table name is dbo.T_SYS_Language_Forms, and the column name is LANG_UID
-- First, chech if the table exists...
IF 0 < (
SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'T_SYS_Language_Forms'
)
BEGIN
-- Check for NULL values in the primary-key column
IF 0 = (SELECT COUNT(*) FROM T_SYS_Language_Forms WHERE LANG_UID IS NULL)
BEGIN
ALTER TABLE T_SYS_Language_Forms ALTER COLUMN LANG_UID uniqueidentifier NOT NULL
-- No, don't drop, FK references might already exist...
-- Drop PK if exists
-- ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT pk_constraint_name
--DECLARE @pkDropCommand nvarchar(1000)
--SET @pkDropCommand = N'ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT ' + QUOTENAME((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
--WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
--AND TABLE_SCHEMA = 'dbo'
--AND TABLE_NAME = 'T_SYS_Language_Forms'
----AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms'
--))
---- PRINT @pkDropCommand
--EXECUTE(@pkDropCommand)
-- Instead do
-- EXEC sp_rename 'dbo.T_SYS_Language_Forms.PK_T_SYS_Language_Forms1234565', 'PK_T_SYS_Language_Forms';
-- Check if they keys are unique (it is very possible they might not be)
IF 1 >= (SELECT TOP 1 COUNT(*) AS cnt FROM T_SYS_Language_Forms GROUP BY LANG_UID ORDER BY cnt DESC)
BEGIN
-- If no Primary key for this table
IF 0 =
(
SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'T_SYS_Language_Forms'
-- AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms'
)
ALTER TABLE T_SYS_Language_Forms ADD CONSTRAINT PK_T_SYS_Language_Forms PRIMARY KEY CLUSTERED (LANG_UID ASC)
;
-- Adding foreign key
IF 0 = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = 'FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms')
ALTER TABLE T_ZO_SYS_Language_Forms WITH NOCHECK ADD CONSTRAINT FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms FOREIGN KEY(ZOLANG_LANG_UID) REFERENCES T_SYS_Language_Forms(LANG_UID);
END -- End uniqueness check
ELSE
PRINT 'FSCK, this column has duplicate keys, and can thus not be changed to primary key...'
END -- End NULL check
ELSE
PRINT 'FSCK, need to figure out how to update NULL value(s)...'
END
Try This one:: Libav in Linux
Installation: run command
sudo apt-get install libav-tools
Video conversion command::Go to folder contains the video and run in terminal
avconv -i oldvideo.flv -ar 22050 convertedvideo.mp4
You could store intermediate values in a cell or column (which you could hide if you choose)
C1: = VLOOKUP(A1, B:B, 1, 0)
D1: = IF(C1 > 10, C1 - 10, C1)
My case: Seeing the same INFO message.
Centos 6.2 x86_64 Tomcat 6.0.24
This fixed the problem for me:
yum install tomcat-native
boom!
Could you add z-index style to the two sections so that the one you want appears on top?
Only Objective-C is allowed by now... but since a few months ago you are allowed to write scripts that will be interpreted in your application.
So you may be able to write a LUA interpreter or a Python interpreter, then write some part of your application in this scripting language. If you want your application accepted on the App Store, these scripts have to be bundled with the application (your application cannot download it from the Internet for example)
Your main problem is thinking that the variable you declared outside of the template is the same variable being "set" inside the choose statement. This is not how XSLT works, the variable cannot be reassigned. This is something more like what you want:
<xsl:template match="class">
<xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
<xsl:variable name="subexists">
<xsl:choose>
<xsl:when test="joined-subclass">true</xsl:when>
<xsl:otherwise>false</xsl:otherwise>
</xsl:choose>
</xsl:variable>
subexists: <xsl:value-of select="$subexists" />
</xsl:template>
And if you need the variable to have "global" scope then declare it outside of the template:
<xsl:variable name="subexists">
<xsl:choose>
<xsl:when test="/path/to/node/joined-subclass">true</xsl:when>
<xsl:otherwise>false</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:template match="class">
subexists: <xsl:value-of select="$subexists" />
</xsl:template>
;
to separate command \\
on any backslashes \
. "'
for passing safe address to switch command like "'PATH'".This ps1 command install locale pfx certificate.
powershell -Command "$pfxPassword = ConvertTo-SecureString -String "12345678" -Force -AsPlainText ; Import-PfxCertificate -FilePath "'C:\\Program Files\\VpnManagement\\resources\\assets\\cert\\localhost.pfx'" Cert:\\LocalMachine\\My -Password $pfxPassword ; Import-PfxCertificate -FilePath "'C:\\Program Files\\VpnManagement\\resources\\assets\\cert\\localhost.pfx'" Cert:\\LocalMachine\\Root -Password $pfxPassword"
just add below two annotations to your POJO.
@ComponentScan
@Configuration
public class YourClass {
//TODO
}
Maybe you are out of inodes. Try df -i
2591792 136322 2455470 6% /home
/dev/sdb1 1887488 1887488 0 100% /data
Disk used 6% but inode table full.
Another way is to use a DataView
// Create a DataTable
DataTable table = new DataTable()
...
// Filter and Sort expressions
string expression = "[Birth Year] >= 1983";
string sortOrder = "[Birth Year] ASC";
// Create a DataView using the table as its source and the filter and sort expressions
DataView dv = new DataView(table, expression, sortOrder, DataViewRowState.CurrentRows);
// Convert the DataView to a DataTable
DataTable new_table = dv.ToTable("NewTableName");
No. You can't. But it is very possible in Scala:
class Foo {val bar = "a"}
class Bar {val foo = "b"}
Either one should work OK. In fact, System.Threading.Timer uses System.Timers.Timer internally.
Having said that, it's easy to misuse System.Timers.Timer. If you don't store the Timer object in a variable somewhere, then it is liable to be garbage collected. If that happens, your timer will no longer fire. Call the Dispose method to stop the timer, or use the System.Threading.Timer class, which is a slightly nicer wrapper.
What problems have you seen so far?
For Select2 4.X
var instance = $('#select2Container').data('select2');
var searchVal = instance.dropdown.$search.val();
instance.trigger('query', {term:searchVal});