In my case, where the timezones are not available on the server, this works great:
SELECT CONVERT_TZ(`date_field`,'+00:00',@@global.time_zone) FROM `table`
Note: global.time_zone uses the server timezone. You have to make sure, that it has the desired timezone!
If you just need the time without the date.
time_t rawtime;
struct tm * timeinfo;
time( &rawtime );
timeinfo = localtime( &rawtime );
printf("%02d:%02d:%02d", timeinfo->tm_hour, timeinfo->tm_min,
timeinfo->tm_sec);
I'll slightly expand @assylias answer to take time zone into account. There are at least two ways to get LocalDateTime for specific time zone.
You can use setDefault time zone for whole application. It should be called before any timestamp -> java.time conversion:
public static void main(String... args) {
TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
TimeZone.setDefault(utcTimeZone);
...
timestamp.toLocalDateTime().toLocalDate();
}
Or you can use toInstant.atZone chain:
timestamp.toInstant()
.atZone(ZoneId.of("UTC"))
.toLocalDate();
Here is a quick and dirty version that uses the local systems settings to work out the time difference. NOTE: This will not work if you need to convert to a timezone that your current system is not running in. I have tested this with UK settings under BST timezone
from datetime import datetime
def ConvertP4DateTimeToLocal(timestampValue):
assert isinstance(timestampValue, int)
# get the UTC time from the timestamp integer value.
d = datetime.utcfromtimestamp( timestampValue )
# calculate time difference from utcnow and the local system time reported by OS
offset = datetime.now() - datetime.utcnow()
# Add offset to UTC time and return it
return d + offset
Here's a summary of common Python time conversions.
Some methods drop fractions of seconds, and are marked with (s). An explicit formula such as ts = (d - epoch) / unit
can be used instead (thanks jfs).
calendar.timegm(struct_time)
calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple())
calendar.timegm(dt.utctimetuple())
calendar.timegm(dt.utctimetuple())
time.gmtime(t)
stz.localize(dt, is_dst=None).utctimetuple()
dt.utctimetuple()
dt.utctimetuple()
datetime.fromtimestamp(t, None)
datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
dt.astimezone(tz).replace(tzinfo=None)
datetime.utcfromtimestamp(t)
datetime.datetime(*struct_time[:6])
stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None)
dt.astimezone(UTC).replace(tzinfo=None)
datetime.fromtimestamp(t, tz)
datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz)
stz.localize(dt, is_dst=None)
dt.replace(tzinfo=UTC)
Source: taaviburns.ca
In my case, it was Subversion, TortoiseSVN clinging to those files, so I just clicked on SVN in the Eclipse menu and then disconnect. Worked for me.
You could try this registry hack:
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters]
"DeadGWDetectDefault"=dword:00000001
"KeepAliveTime"=dword:00120000
If it works, just keep increasing the KeepAliveTime
. It is currently set for 2 minutes.
Here's an updated example using Angular 4 (also compatible with Angular 5 - 8)
Routes with home route protected by AuthGuard
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/index';
import { HomeComponent } from './home/index';
import { AuthGuard } from './_guards/index';
const appRoutes: Routes = [
{ path: 'login', component: LoginComponent },
// home route protected by auth guard
{ path: '', component: HomeComponent, canActivate: [AuthGuard] },
// otherwise redirect to home
{ path: '**', redirectTo: '' }
];
export const routing = RouterModule.forRoot(appRoutes);
AuthGuard redirects to login page if user isn't logged in
Updated to pass original url in query params to login page
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (localStorage.getItem('currentUser')) {
// logged in so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}
}
For the full example and working demo you can check out this post
I've recently battled with this problem as well, and I've learned two things about the above suggestions.
The misleading aspect of this is that you now have a different value in the cell. Fortuately, when you copy/paste or export to CSV, the apostrophe is not included.
Conclusion: use the apostrophe, not the numberFormatting in order to retain the leading zeros.
If you have the milliseconds since the Epoch and want to convert them to a local date using the current local timezone, you can use
LocalDate date =
Instant.ofEpochMilli(longValue).atZone(ZoneId.systemDefault()).toLocalDate();
but keep in mind that even the system’s default time zone may change, thus the same long
value may produce different result in subsequent runs, even on the same machine.
Further, keep in mind that LocalDate
, unlike java.util.Date
, really represents a date, not a date and time.
Otherwise, you may use a LocalDateTime
:
LocalDateTime date =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());
var length = $('#mySelectList').children('option').length;
or
var length = $('#mySelectList > option').length;
This assumes your <select>
list has an ID of mySelectList
.
AttributeError is raised when attribute of the object is not available.
An attribute reference is a primary followed by a period and a name:
attributeref ::= primary "." identifier
To return a list of valid attributes for that object, use dir()
, e.g.:
dir(scipy)
So probably you need to do simply: import scipy.sparse
Generally people do like
<div className={ ['head', style.class1 , Style.class2].join(' ') }><div>
But you can choose to Create a function to do this job
function joinAll(...classes) {
return classes.join(" ")
}
then call it like:-
<div className={joinAll('head', style.class1 , style.class2)}><div>
The simplest way to get the visitor’s/client’s IP address is using the $_SERVER['REMOTE_ADDR']
or $_SERVER['REMOTE_HOST']
variables.
However, sometimes this does not return the correct IP address of the visitor, so we can use some other server variables to get the IP address.
The below both functions are equivalent with the difference only in how and from where the values are retrieved.
getenv() is used to get the value of an environment variable in PHP.
// Function to get the client IP address
function get_client_ip() {
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$ipaddress = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$ipaddress = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$ipaddress = getenv('REMOTE_ADDR');
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
$_SERVER is an array that contains server variables created by the web server.
// Function to get the client IP address
function get_client_ip() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
The only effective mechanism for passing parameters into a build is to use Java properties:
ant -Done=1 -Dtwo=2
The following example demonstrates how you can check and ensure the expected parameters have been passed into the script
<project name="check" default="build">
<condition property="params.set">
<and>
<isset property="one"/>
<isset property="two"/>
</and>
</condition>
<target name="check">
<fail unless="params.set">
Must specify the parameters: one, two
</fail>
</target>
<target name="build" depends="check">
<echo>
one = ${one}
two = ${two}
</echo>
</target>
</project>
substring
is definitely best, but here's one strsplit
alternative, since I haven't seen one yet.
> x <- 'hello stackoverflow'
> strsplit(x, '')[[1]][1]
## [1] "h"
or equivalently
> unlist(strsplit(x, ''))[1]
## [1] "h"
And you can paste
the rest of the string back together.
> paste0(strsplit(x, '')[[1]][-1], collapse = '')
## [1] "ello stackoverflow"
Take a look at the PDOStatement.fetchAll
method. You could also use fetch
in an iterator pattern.
Code sample for fetchAll
, from the PHP documentation:
<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);
Results:
Array
(
[0] => Array
(
[NAME] => pear
[COLOUR] => green
)
[1] => Array
(
[NAME] => watermelon
[COLOUR] => pink
)
)
The changed it from change
to selectionChange
.
<mat-select (change)="doSomething($event)">
is now
<mat-select (selectionChange)="doSomething($event)">
I followed this tutorial: How to install Maven on Windows
But running mvn -version
, I still got:
mvn: command not found
So, I closed the current git window, and opened a new one. Everything went okay :)
See the documentation of Pattern.
Assuming US-ASCII alphabet (a-z, A-Z), you could use \p{Alnum}
.
A regex to check that a line contains only such characters is "^[\\p{Alnum}]*$"
.
That also matches empty string. To exclude empty string: "^[\\p{Alnum}]+$"
.
For anytone who has worked in ASP as well as more modern languages, the question will provoke a chuckle. In my experience using a custom error handler (set up in IIS to handle the 500;100 errors) is the best option for ASP error handling. This article describes the approach and even gives you some sample code / database table definition.
http://www.15seconds.com/issue/020821.htm
Here is a link to Archive.org's version
I used ADAL.NET/ Microsoft Identity Platform to achieve this. The advantage of using it was that we get a nice wrapper around the code to acquire AccessToken
and we get additional features like Token Cache
out-of-the-box. From the documentation:
Why use ADAL.NET ?
ADAL.NET V3 (Active Directory Authentication Library for .NET) enables developers of .NET applications to acquire tokens in order to call secured Web APIs. These Web APIs can be the Microsoft Graph, or 3rd party Web APIs.
Here is the code snippet:
// Import Nuget package: Microsoft.Identity.Client
public class AuthenticationService
{
private readonly List<string> _scopes;
private readonly IConfidentialClientApplication _app;
public AuthenticationService(AuthenticationConfiguration authentication)
{
_app = ConfidentialClientApplicationBuilder
.Create(authentication.ClientId)
.WithClientSecret(authentication.ClientSecret)
.WithAuthority(authentication.Authority)
.Build();
_scopes = new List<string> {$"{authentication.Audience}/.default"};
}
public async Task<string> GetAccessToken()
{
var authenticationResult = await _app.AcquireTokenForClient(_scopes)
.ExecuteAsync();
return authenticationResult.AccessToken;
}
}
These articles seem to suggest that checking for 1.5
or 1.6
prefix should work, as it follows proper version naming convention.
java.version
system property"java.version
system property"It worked for me when HDD with win8.1 crashed and my new HDD has win10. Important to know - Create Legacy folder mentioned in this link. - Remember to rename the StickyNotes.snt to ThresholdNotes.snt. - Restart the app
Find details here https://www.reddit.com/r/Windows10/comments/4wxfds/transfermigrate_sticky_notes_to_new_anniversary/
Well, you can use while loop, like this,
import java.util.Scanner;
public class DecimalToBinaryExample
{
public static void main(String[] args)
{
int num;
int a = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a decimal number : ");
num = sc.nextInt();
int binary[] = new int[100];
while(num != 0)
{
binary[a] = num % 2;
num = num / 2;
a++;
}
System.out.println("The binary value is : ");
for(int b = a - 1; b >= 0; b--)
{
System.out.println("" + binary[b]);
}
sc.close();
}
}
You can refer example below for some good explanation,
convert decimal to binary example.
git remote show origin -n | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
It was tested with three different URL styles:
echo "Fetch URL: http://user@pass:gitservice.org:20080/owner/repo.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
echo "Fetch URL: Fetch URL: [email protected]:home1-oss/oss-build.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
echo "Fetch URL: https://github.com/owner/repo.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
%d
and %s
are placeholders, they work as a replaceable variable. For example, if you create 2 variables
variable_one = "Stackoverflow"
variable_two = 45
you can assign those variables to a sentence in a string using a tuple of the variables.
variable_3 = "I was searching for an answer in %s and found more than %d answers to my question"
Note that %s
works for String and %d
work for numerical or decimal variables.
if you print variable_3
it would look like this
print(variable_3 % (variable_one, variable_two))
I was searching for an answer in StackOverflow and found more than 45 answers to my question.
In batch files, as in standard C programs, argument 0 contains the path to the currently executing script. You can use %~dp0
to get only the path portion of the 0th argument (which is the current script) - this path is always a fully qualified path.
You can also get the fully qualified path of your first argument by using %~f1
, but this gives a path according to the current working directory, which is obviously not what you want.
Personally, I often use the %~dp0%~1
idiom in my batch file, which interpret the first argument relative to the path of the executing batch. It does have a shortcoming though: it miserably fails if the first argument is fully-qualified.
If you need to support both relative and absolute paths, you can make use of Frédéric Ménez's solution: temporarily change the current working directory.
Here's an example that'll demonstrate each of these techniques:
@echo off
echo %%~dp0 is "%~dp0"
echo %%0 is "%0"
echo %%~dpnx0 is "%~dpnx0"
echo %%~f1 is "%~f1"
echo %%~dp0%%~1 is "%~dp0%~1"
rem Temporarily change the current working directory, to retrieve a full path
rem to the first parameter
pushd .
cd %~dp0
echo batch-relative %%~f1 is "%~f1"
popd
If you save this as c:\temp\example.bat and the run it from c:\Users\Public as
c:\Users\Public>\temp\example.bat ..\windows
...you'll observe the following output:
%~dp0 is "C:\temp\"
%0 is "\temp\example.bat"
%~dpnx0 is "C:\temp\example.bat"
%~f1 is "C:\Users\windows"
%~dp0%~1 is "C:\temp\..\windows"
batch-relative %~f1 is "C:\Windows"
the documentation for the set of modifiers allowed on a batch argument can be found here: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/call
You can try this basic approach:
div {_x000D_
height: 100px;_x000D_
line-height: 100px;_x000D_
text-align: center;_x000D_
border: 2px dashed #f69c55;_x000D_
}
_x000D_
<div>_x000D_
Hello World!_x000D_
</div>
_x000D_
It only works for a single line of text though, because we set the line's height to the same height as the containing box element.
This is another way to align text vertically. This solution will work for a single line and multiple lines of text, but it still requires a fixed height container:
div {_x000D_
height: 100px;_x000D_
line-height: 100px;_x000D_
text-align: center;_x000D_
border: 2px dashed #f69c55;_x000D_
}_x000D_
span {_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
line-height: normal;_x000D_
}
_x000D_
<div>_x000D_
<span>Hello World!</span>_x000D_
</div>
_x000D_
The CSS just sizes the <div>
, vertically center aligns the <span>
by setting the <div>
's line-height equal to its height, and makes the <span>
an inline-block with vertical-align: middle
. Then it sets the line-height back to normal for the <span>
, so its contents will flow naturally inside the block.
And here is another option, which may not work on older browsers that don't support display: table
and display: table-cell
(basically just Internet Explorer 7). Using CSS we simulate table behavior (since tables support vertical alignment), and the HTML is the same as the second example:
div {_x000D_
display: table;_x000D_
height: 100px;_x000D_
width: 100%;_x000D_
text-align: center;_x000D_
border: 2px dashed #f69c55;_x000D_
}_x000D_
span {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<div>_x000D_
<span>Hello World!</span>_x000D_
</div>
_x000D_
This technique uses an absolutely positioned element setting top, bottom, left and right to 0. It is described in more detail in an article in Smashing Magazine, Absolute Horizontal And Vertical Centering In CSS.
div {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
height: 100px;_x000D_
width: 100%;_x000D_
border: 2px dashed #f69c55;_x000D_
}
_x000D_
<div>_x000D_
<span>Hello World!</span>_x000D_
</div>
_x000D_
Using awk
:
export INDEX=2
export VALUE=bar
awk -F, '$'$INDEX' ~ /^'$VALUE'$/ {print}' inputfile.csv
Edit: As per Dennis Williamson's excellent comment, this could be much more cleanly (and safely) written by defining awk variables using the -v
switch:
awk -F, -v index=$INDEX -v value=$VALUE '$index == value {print}' inputfile.csv
Jeez...with variables, and everything, awk is almost a real programming language...
The choice of one or another depends on what you intend to do. From what I do understand:
jsonify would be useful when you are building an API someone would query and expect json in return. E.g: The REST github API could use this method to answer your request.
dumps, is more about formating data/python object into json and work on it inside your application. For instance, I need to pass an object to my representation layer where some javascript will display graph. You'll feed javascript with the Json generated by dumps.
readFileSync()
is synchronous and blocks execution until finished. These return their results as return values.
readFile()
are asynchronous and return immediately while they function in the background. You pass a callback function which gets called when they finish.
let's take an example for non-blocking.
following method read a file as a non-blocking way
var fs = require('fs');
fs.readFile(filename, "utf8", function(err, data) {
if (err) throw err;
console.log(data);
});
following is read a file as blocking or synchronous way.
var data = fs.readFileSync(filename);
LOL...If you don't want
readFileSync()
as blocking way then take reference from the following code. (Native)
var fs = require('fs');
function readFileAsSync(){
new Promise((resolve, reject)=>{
fs.readFile(filename, "utf8", function(err, data) {
if (err) throw err;
resolve(data);
});
});
}
async function callRead(){
let data = await readFileAsSync();
console.log(data);
}
callRead();
it's mean behind scenes
readFileSync()
work same as above(promise) base.
What you could do is have the selected
attribute on the <select>
tag be an attribute of this.state
that you set in the constructor. That way, the initial value you set (the default) and when the dropdown changes you need to change your state.
constructor(){
this.state = {
selectedId: selectedOptionId
}
}
dropdownChanged(e){
this.setState({selectedId: e.target.value});
}
render(){
return(
<select value={this.selectedId} onChange={this.dropdownChanged.bind(this)}>
{option_id.map(id =>
<option key={id} value={id}>{options[id].name}</option>
)}
</select>
);
}
I can confirm it works, But You have to put html AND plist on dropbox. It works also for non-enterprise OTA, i.e. You want to share app with your dev. team.
I did:
a) on my site I made a page with this link:
.. href="https://dl.dropboxusercontent.com/u//(your DB id)/ipa.html">MyApp
b) on DropBox I wrote another HTML page:
.. https://dl.dropboxusercontent.com/u/(your DB id)/MyApp.plist"> Tap to Install MyApp
c) moved plist on DropBox but leaving it to POINT to my old server (no https)
try this
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/upkia"/>
<corners android:radius="10dp"
android:topRightRadius="0dp"
android:bottomRightRadius="0dp" />
</shape>
Bootstrap 4
More details are here https://learncodeweb.com/snippets/browse-button-in-bootstrap-4-with-select-image-preview/
Today I need to create a browse button with multi-upload files option all above snippets are not good for me.
The official Bootstrap example is also not working when I select multiple files.
I come up with this code may be will help others in the future.
<div class="container mt-5">
<h1 class="text-center">Bootstrap 4 Upload multiple files</h1>
<div class="col-sm-4 mr-auto ml-auto border p-4">
<form method="post" enctype="multipart/form-data" action="upload.php">
<div class="form-group">
<label><strong>Upload Files</strong></label>
<div class="custom-file">
<input type="file" name="files[]" multiple class="custom-file-input form-control" id="customFile">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
</div>
<div class="form-group">
<button type="submit" name="upload" value="upload" id="upload" class="btn btn-block btn-dark"><i class="fa fa-fw fa-upload"></i> Upload</button>
</div>
</form>
</div>
The js code is given below.
$(document).ready(function() {
$('input[type="file"]').on("change", function() {
let filenames = [];
let files = document.getElementById("customFile").files;
if (files.length > 1) {
filenames.push("Total Files (" + files.length + ")");
} else {
for (let i in files) {
if (files.hasOwnProperty(i)) {
filenames.push(files[i].name);
}
}
}
$(this)
.next(".custom-file-label")
.html(filenames.join(","));
});
});
The working code example is given here with bootstrap 3 and bootstrap 4.3.1.
It presents a prompt to the user (the optional arg
of raw_input([arg])
), gets input from the user and returns the data input by the user in a string. See the docs for raw_input()
.
Example:
name = raw_input("What is your name? ")
print "Hello, %s." % name
This differs from input()
in that the latter tries to interpret the input given by the user; it is usually best to avoid input()
and to stick with raw_input()
and custom parsing/conversion code.
Note: This is for Python 2.x
Just order by count(*) desc
and you'll get the highest (if you combine it with limit 1
)
The error Event
the onerror
handler receives is a simple event not containing such information:
If the user agent was required to fail the WebSocket connection or the WebSocket connection is closed with prejudice, fire a simple event named error at the WebSocket object.
You may have better luck listening for the close
event, which is a CloseEvent
and indeed has a CloseEvent.code
property containing a numerical code according to RFC 6455 11.7 and a CloseEvent.reason
string property.
Please note however, that CloseEvent.code
(and CloseEvent.reason
) are limited in such a way that network probing and other security issues are avoided.
For me it was changing.
this.name = response.data;
To what computed returns so;
this.$store.state.name = response.data;
I think it has to do with your second element in storbinary
. You are trying to open file
, but it is already a pointer to the file you opened in line file = open(local_path,'rb')
. So, try to use ftp.storbinary("STOR " + i, file)
.
You have to shrink & backup the log a several times to get the log file to reduce in size, this is because the the log file pages cannot be re-organized as data files pages can be, only truncated. For a more detailed explanation check this out.
WARNING : Detaching the db & deleting the log file is dangerous! don't do this unless you'd like data loss
Try this.
<script>
function checkIframeLoaded() {
// Get a handle to the iframe element
var iframe = document.getElementById('i_frame');
var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
// Check if loading is complete
if ( iframeDoc.readyState == 'complete' ) {
//iframe.contentWindow.alert("Hello");
iframe.contentWindow.onload = function(){
alert("I am loaded");
};
// The loading is complete, call the function we want executed once the iframe is loaded
afterLoading();
return;
}
// If we are here, it is not loaded. Set things up so we check the status again in 100 milliseconds
window.setTimeout(checkIframeLoaded, 100);
}
function afterLoading(){
alert("I am here");
}
</script>
<body onload="checkIframeLoaded();">
in "String.xml" you can notice any String or value you want to use, here are two examples:
<string name="app_name">My Calculator App
</string>
<color name="color_menu_home">#ffcccccc</color>
Used for the layout.xml: android:text="@string/app_name"
The advantage: you can use them as often you want, you only need to link them in your Layout-xml, and you can change the String-Content easily in the strings.xml, without searching in your source-code for the right position. Important for changing language, you only need to replace the strings.xml - file
to get IMEI (international mobile equipment identifier)
public String getIMEI(Activity activity) {
TelephonyManager telephonyManager = (TelephonyManager) activity
.getSystemService(Context.TELEPHONY_SERVICE);
return telephonyManager.getDeviceId();
}
to get device unique id
public String getDeviceUniqueID(Activity activity){
String device_unique_id = Secure.getString(activity.getContentResolver(),
Secure.ANDROID_ID);
return device_unique_id;
}
You need the textFX plugin. Then, just follow these instructions:
Paste the text into Notepad++ (CTRL+V). ...
Mark all the text (CTRL+A). ...
Click TextFX ? Click TextFX Tools ? Click Sort lines case insensitive (at column)
Duplicates and blank lines have been removed and the data has been sorted alphabetically.
Personally, I would use sort -i -u source >dest instead of notepad++
You should provide output file name after -o
option. In your case runexp.o
is treated as output file name, not input object file and thus your main
function is undefined.
$(".hit").click(function(){
var values = [];
var table = $(this).closest("table");
table.find("tr").each(function() {
values.push($(this).find("td:first").html());
});
alert(values);
});
You should avoid $(".hit")
it's really inefficient. Try using event delegation instead.
My 2 cents on this error, even if not related to an export/import scenario:
when adding the mobile provisioning certificate (i.e. the PROV
file), DO NOT drag the file from Finder to Keychain Access. Instead, just double click the PROV file within Finder, while keeping the Keychain Access application running somewhere.
I've actually seen my former provisioning item in Keychain (the one with yellow light) being substituted with a new, green one with same name and app ID. HTH
I would also like to add a few notes about a MySQL-to-PostgreSQL migration:
That's as far as I remember now, hope these tips can spare you a few minutes of trial and error fiddling!
simply do the select
:
Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date) AND
((@day = 'Monday' AND (Monday = 1))
OR (@day = 'Tuesday' AND (Tuesday = 1))
OR (Wednesday = 1))
.length = number of rows / column length
[0].length = number of columns / row length
I found applying the network and rebooting both the nodes did the trick for me.
kubectl apply -f [podnetwork].yaml
Had the same issue and I resolved it by using :
conda install protobuf
Ok, I faced the problem before. Since push notification requires serverside implementation, for me recreating profile was not an option. So I found this solution WITHOUT creating new provisioning profile.
Xcode is not properly selecting the correct provisioning profile although we are selecting it correctly.
First go to organizer. On the Devices tab, Provisioning profile from Library list, select the intended profile we are trying to use. Right click on it and then "Reveal Profile in Finder".
The correct profile will be selected in the opened Finder window. Note the name.
Now go to Xcode > Log Navigator. Select filter for "All" and "All Messages". Now in the last phase(Build Target) look for the step called "ProcessProductPackaging" expand it. Note the provisioning profile name. They should NOT match if you are having the error.
Now in the Opened Finder window delete the rogue provisioning profile which Xcode is using. Now build again. The error should be resolved. If not repeat the process to find another rogue profile to remove it.
Hope this helps.
If you are using Logback, just put this logback-test.xml
file into src/test/resources
directory:
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
One more way:
CREATE OR REPLACE TYPE TYPE_TABLE_OF_VARCHAR2 AS TABLE OF VARCHAR(100);
-- ...
SELECT field1, field2, field3
FROM table1
WHERE name IN (
SELECT * FROM table (SELECT CAST(? AS TYPE_TABLE_OF_VARCHAR2) FROM dual)
);
I don't consider it's optimal, but it works. The hint /*+ CARDINALITY(...) */
would be very useful because Oracle does not understand cardinality of the array passed and can't estimate optimal execution plan.
As another alternative - batch insert into temporary table and using the last in subquery for IN
predicate.
The **
syntax tells Python to collect keyword arguments into a dictionary. The save2
is passing it down as a non-keyword argument (a dictionary object). The openX
is not seeing any keyword arguments so the **args
doesn't get used. It's instead getting a third non-keyword argument (the dictionary). To fix that change the definition of the openX
function.
def openX(filename, mode, kwargs):
pass
In non-interactive env, we have to use plt.show(block=True)
The smarter_csv
gem was specifically created for this use-case: to read data from CSV file and quickly create database entries.
require 'smarter_csv'
options = {}
SmarterCSV.process('input_file.csv', options) do |chunk|
chunk.each do |data_hash|
Moulding.create!( data_hash )
end
end
You can use the option chunk_size
to read N csv-rows at a time, and then use Resque in the inner loop to generate jobs which will create the new records, rather than creating them right away - this way you can spread the load of generating entries to multiple workers.
See also: https://github.com/tilo/smarter_csv
Think of "BeforeClass" as a static initializer for your test case - use it for initializing static data - things that do not change across your test cases. You definitely want to be careful about static resources that are not thread safe.
Finally, use the "AfterClass" annotated method to clean up any setup you did in the "BeforeClass" annotated method (unless their self destruction is good enough).
"Before" & "After" are for unit test specific initialization. I typically use these methods to initialize / re-initialize the mocks of my dependencies. Obviously, this initialization is not specific to a unit test, but general to all unit tests.
Refer below code for formatting date
long strDate1 = 1346524199000;
Date date=new Date(strDate1);
try {
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
date = df2.format(format.parse("yourdate");
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Use TAB & TAB+SHIFT in a Specified container or element
we will handle TAB & TAB+SHIFT key listeners first
$(document).ready(function() {
lastIndex = 0;
$(document).keydown(function(e) {
if (e.keyCode == 9) var thisTab = $(":focus").attr("tabindex");
if (e.keyCode == 9) {
if (e.shiftKey) {
//Focus previous input
if (thisTab == startIndex) {
$("." + tabLimitInID).find('[tabindex=' + lastIndex + ']').focus();
return false;
}
} else {
if (thisTab == lastIndex) {
$("." + tabLimitInID).find('[tabindex=' + startIndex + ']').focus();
return false;
}
}
}
});
var setTabindexLimit = function(x, fancyID) {
console.log(x);
startIndex = 1;
lastIndex = x;
tabLimitInID = fancyID;
$("." + tabLimitInID).find('[tabindex=' + startIndex + ']').focus();
}
/*Taking last tabindex=10 */
setTabindexLimit(10, "limitTablJolly");
});
In HTML define tabindex
<div class="limitTablJolly">
<a tabindex=1>link</a>
<a tabindex=2>link</a>
<a tabindex=3>link</a>
<a tabindex=4>link</a>
<a tabindex=5>link</a>
<a tabindex=6>link</a>
<a tabindex=7>link</a>
<a tabindex=8>link</a>
<a tabindex=9>link</a>
<a tabindex=10>link</a>
</div>
x
is Unsigned hexadecimal integer ( 32 Bit )
p
is Pointer address
See printf on the C++ Reference. Even if both of them would write the same, I would use %p
to print a pointer.
string path= @"C:\Users\username\Desktop\FolderName"
string Dirctory = new FileInfo(path).Name.ToString();
//output FolderName
On Windows 10, for me
ngrok http 80
behaves like this:
Currently, I know about the following three ways:
1. The @Value
annotation
@Value("${<property.name>}")
private static final <datatype> PROPERTY_NAME;
null
.
For instance,
when you try to set it in a preConstruct()
method or an init()
method.
This happens because the value injection happens after the class is fully constructed.
This is why it is better to use the 3'rd option.2. The @PropertySource
annotation
<pre>@PropertySource("classpath:application.properties")
//env is an Environment variable
env.getProperty(configKey);</pre>
PropertySouce
sets values from the property source file in an Environment
variable (in your class) when the class is loaded.
So you able to fetch easily afterword.
3. The @ConfigurationProperties
annotation.
It initializes an entity based on property data.
@ConfigurationProperties
identifies the property file to load.@Configuration
creates a bean based on configuration file variables.@ConfigurationProperties(prefix = "user") @Configuration("UserData") class user { //Property & their getter / setter } @Autowired private UserData userData; userData.getPropertyName();
Array.from()
takes an iterable object to convert to an array and an optional map function. You could create an object with a .length
property as follows:
return Array.from({length: this.props.level}, (item, index) =>
<span className="indent" key={index}></span>
);
this one is working for me also for internet explorer:
<div class="col imagebox" [ngStyle]="bkUrl"></div>
...
@Input() background = '571x450img';
bkUrl = {};
ngOnInit() {
this.bkUrl = this.getBkUrl();
}
getBkUrl() {
const styles = {
'background-image': 'url(src/assets/images/' + this.background + '.jpg)'
};
console.log(styles);
return styles;
}
The vshost.exe feature was introduced with Visual Studio 2005 (to answer your comment).
The purpose of it is mostly to make debugging launch quicker - basically there's already a process with the framework running, just ready to load your application as soon as you want it to.
See this MSDN article and this blog post for more information.
Have you tried this?
<appSettings>
<add key="myurl" value="http://www.myurl.com?&cid=&sid="/>
<appSettings>
Now you can use just window.scrollTo({ top: 0, behavior: 'smooth' })
to get the page scrolled with a smooth effect.
const btn = document.getElementById('elem');_x000D_
_x000D_
btn.addEventListener('click', () => window.scrollTo({_x000D_
top: 400,_x000D_
behavior: 'smooth',_x000D_
}));
_x000D_
#x {_x000D_
height: 1000px;_x000D_
background: lightblue;_x000D_
}
_x000D_
<div id='x'>_x000D_
<button id='elem'>Click to scroll</button>_x000D_
</div>
_x000D_
You can do something like this:
var btn = document.getElementById('x');_x000D_
_x000D_
btn.addEventListener("click", function() {_x000D_
var i = 10;_x000D_
var int = setInterval(function() {_x000D_
window.scrollTo(0, i);_x000D_
i += 10;_x000D_
if (i >= 200) clearInterval(int);_x000D_
}, 20);_x000D_
})
_x000D_
body {_x000D_
background: #3a2613;_x000D_
height: 600px;_x000D_
}
_x000D_
<button id='x'>click</button>
_x000D_
ES6 recursive approach:
const btn = document.getElementById('elem');_x000D_
_x000D_
const smoothScroll = (h) => {_x000D_
let i = h || 0;_x000D_
if (i < 200) {_x000D_
setTimeout(() => {_x000D_
window.scrollTo(0, i);_x000D_
smoothScroll(i + 10);_x000D_
}, 10);_x000D_
}_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', () => smoothScroll());
_x000D_
body {_x000D_
background: #9a6432;_x000D_
height: 600px;_x000D_
}
_x000D_
<button id='elem'>click</button>
_x000D_
This version is for German language but you can modifiy the $CHARSETS and the $TESTCHARS
class CharsetDetector
{
private static $CHARSETS = array(
"ISO_8859-1",
"ISO_8859-15",
"CP850"
);
private static $TESTCHARS = array(
"€",
"ä",
"Ä",
"ö",
"Ö",
"ü",
"Ü",
"ß"
);
public static function convert($string)
{
return self::__iconv($string, self::getCharset($string));
}
public static function getCharset($string)
{
$normalized = self::__normalize($string);
if(!strlen($normalized))return "UTF-8";
$best = "UTF-8";
$charcountbest = 0;
foreach (self::$CHARSETS as $charset) {
$str = self::__iconv($normalized, $charset);
$charcount = 0;
$stop = mb_strlen( $str, "UTF-8");
for( $idx = 0; $idx < $stop; $idx++)
{
$char = mb_substr( $str, $idx, 1, "UTF-8");
foreach (self::$TESTCHARS as $testchar) {
if($char == $testchar)
{
$charcount++;
break;
}
}
}
if($charcount>$charcountbest)
{
$charcountbest=$charcount;
$best=$charset;
}
//echo $text."<br />";
}
return $best;
}
private static function __normalize($str)
{
$len = strlen($str);
$ret = "";
for($i = 0; $i < $len; $i++){
$c = ord($str[$i]);
if ($c > 128) {
if (($c > 247)) $ret .=$str[$i];
elseif ($c > 239) $bytes = 4;
elseif ($c > 223) $bytes = 3;
elseif ($c > 191) $bytes = 2;
else $ret .=$str[$i];
if (($i + $bytes) > $len) $ret .=$str[$i];
$ret2=$str[$i];
while ($bytes > 1) {
$i++;
$b = ord($str[$i]);
if ($b < 128 || $b > 191) {$ret .=$ret2; $ret2=""; $i+=$bytes-1;$bytes=1; break;}
else $ret2.=$str[$i];
$bytes--;
}
}
}
return $ret;
}
private static function __iconv($string, $charset)
{
return iconv ( $charset, "UTF-8" , $string );
}
}
If you look closely you'll see two surprising things about URLs: (1) they seem simple, but the details and corner cases are actually hard, (2) Amazingly JavaScript doesn't provide a full API for making working with them any easier. I think a full-fledged library is in order to avoid people re-inventing the wheel themselves or copying some random dude's clever, but likely buggy regex code snippet. Maybe try URI.js (http://medialize.github.io/URI.js/)
The return false is saying not to take the default action, which in the case of an <a href>
is to follow the link. When you return false to the onclick, then the href will be ignored.
you can use indexing if your enumerable type is string like below
((string[])MyEnumerableStringList)[0]
I think you'll get what you want with the -maxdepth 1
option, based on your current command structure. If not, you can try looking at the man page for find
.
Relevant entry (for convenience's sake):
-maxdepth levels
Descend at most levels (a non-negative integer) levels of direc-
tories below the command line arguments. `-maxdepth 0' means
only apply the tests and actions to the command line arguments.
Your options basically are:
# Do NOT show hidden files (beginning with ".", i.e., .*):
find DirsRoot/* -maxdepth 0 -type f
Or:
# DO show hidden files:
find DirsRoot/ -maxdepth 1 -type f
I think it should be
verify(mockBar, times(2)).doSomething(...)
Sample from mockito javadoc:
ArgumentCaptor<Person> peopleCaptor = ArgumentCaptor.forClass(Person.class);
verify(mock, times(2)).doSomething(peopleCaptor.capture());
List<Person> capturedPeople = peopleCaptor.getAllValues();
assertEquals("John", capturedPeople.get(0).getName());
assertEquals("Jane", capturedPeople.get(1).getName());
My Nexus 5 is identyfied by the id = USB\VID_18D1&PID_D001.
Use the Google USB drivers, and modify file android_winusb.inf
. Find the lines:
;Google Nexus (generic)
%SingleBootLoaderInterface% = USB_Install, USB\VID_18D1&PID_4EE0
And add below:
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_D001
Repeat it, because there are two sections to modify, [Google.NTx86]
and [Google.NTamd64]
.
If you continue with problems, try this:
Connect your Nexus 5, go to Device Manager, find the Nexus 5 on "other" and right click. Select properties, details, and in selection list, and select hardware id. Write down the short ID, and modify the line with:
%CompositeAdbInterface% = USB_Install, YOUR_SHORT_ID
I know of enabling or disabling wifi:
WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(status);
where status may be true
or false
as per requirement.
Edit:
You also need the following permissions in your manifest file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
Auto PY to EXE - A .py to .exe converter using a simple graphical interface built using Eel and PyInstaller in Python.
py2exe is probably what you want, but it only works on Windows.
PyInstaller works on Windows and Linux.
Py2app works on the Mac.
DECLARE @temp as nvarchar(20)
SET @temp = NULL
--SET @temp = ''
--SET @temp = 'Test'
SELECT IIF(ISNULL(@temp,'')='','[Empty]',@temp)
I recommend lxml for parsing HTML. See "Parsing HTML" (on the lxml site).
In my experience Beautiful Soup messes up on some complex HTML. I believe that is because Beautiful Soup is not a parser, rather a very good string analyzer.
As opposed to find() which can return 1 or more documents, findById() can only return 0 or 1 document. Document(s) can be thought of as record(s).
In mvc 4 you can easily do it like following using TextBoxFor
..
@Html.TextBoxFor(m => m.StartDate, "{0:MM/dd/yyyy}", new { @class = "form-control default-date-picker" })
So, you don't need to use any data annotation in model or view model class
Simple way to display pdf files from database and we can download it.
$resume is pdf file name which comes from database.
../resume/filename is path of folder where your file is stored.
<a href="../resumes/<?php echo $resume; ?>"/><?php echo $resume; ?></a>
A simple DIY way would be to make the grid yourself:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3], [2,3,4], 'ro')
for xmaj in ax.xaxis.get_majorticklocs():
ax.axvline(x=xmaj, ls='-')
for xmin in ax.xaxis.get_minorticklocs():
ax.axvline(x=xmin, ls='--')
for ymaj in ax.yaxis.get_majorticklocs():
ax.axhline(y=ymaj, ls='-')
for ymin in ax.yaxis.get_minorticklocs():
ax.axhline(y=ymin, ls='--')
plt.show()
Like val
, variables defined with the const
keyword are immutable. The difference here is that const
is used for variables that are known at compile-time.
Declaring a variable const
is much like using the static
keyword in Java.
Let's see how to declare a const variable in Kotlin:
const val COMMUNITY_NAME = "wiki"
And the analogous code written in Java would be:
final static String COMMUNITY_NAME = "wiki";
Adding to the answers above -
@JvmField
an be used to instruct the Kotlin compiler not to generate getters/setters for this property and expose it as a field.
@JvmField
val COMMUNITY_NAME: "Wiki"
Static fields
Kotlin properties declared in a named object or a companion object will have static backing fields either in that named object or in the class containing the companion object.
Usually these fields are private but they can be exposed in one of the following ways:
@JvmField
annotation;lateinit
modifier;const
modifier.More details here - https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#instance-fields
You don't need to use android:theme="@style/TextInputLayoutTheme"
to change the floating label color, since it's going to affect to the entire theme for the small TextView used as label. Instead, you could use app:hintTextAppearance="@style/TextInputLayout.HintText"
where:
<style name="TextInputLayout.HintText">
<item name="android:textColor">?attr/colorPrimary</item>
<item name="android:textSize">@dimen/text_tiny_size</item>
...
</style>
Let me know if the solution works :-)
This is working for me in a self contained widget.
Widget signinButton() {
return ButtonTheme(
minWidth: double.infinity,
child: new FlatButton(
onPressed: () {},
color: Colors.green[400],
textColor: Colors.white,
child: Text('Flat Button'),
),
);
}
// It can then be used in a class that contains a widget tree.
You should not use jQuery in Angular. While it is possible (see other answers for this question), it is discouraged. Why?
Angular holds an own representation of the DOM in its memory and doesn't use query-selectors (functions like document.getElementById(id)
) like jQuery. Instead all the DOM-manipulation is done by Renderer2 (and Angular-directives like *ngFor and *ngIf accessing that Renderer2 in the background/framework-code). If you manipulate DOM with jQuery yourself you will sooner or later...
If you really want to include jQuery (for duck-taping some prototype that you will 100% definitively throw away), I recommend to at least include it in your package.json with npm install --save jquery
instead of getting it from google's CDN.
TLDR: For learning how to manipulate the DOM in the Angular way please go through the official tour-of heroes tutorial first: https://angular.io/tutorial/toh-pt2 If you need to access elements higher up in the DOM hierarchy (parent or
document body
) or for some other reason directives like*ngIf
,*ngFor
, custom directives, pipes and other angular utilities like[style.background]
,[class.myOwnCustomClass]
don't satisfy your needs, use Renderer2: https://www.concretepage.com/angular-2/angular-4-renderer2-example
I strongly recommend every developer to start using strict mode now. There are enough browsers supporting it that strict mode will legitimately help save us from errors we didn’t even know were in your code.
Apparently, at the initial stage there will be errors we have never encountered before. To get the full benefit, we need to do proper testing after switching to strict mode to make sure we have caught everything. Definitely we don’t just throw use strict
in our code and assume there are no errors. So the churn is that it’s time to start using this incredibly useful language feature to write better code.
For example,
var person = {
name : 'xyz',
position : 'abc',
fullname : function () { "use strict"; return this.name; }
};
JSLint is a debugger written by Douglas Crockford. Simply paste in your script, and it’ll quickly scan for any noticeable issues and errors in your code.
stringstream.str()
returns a temporary string object that's destroyed at the end of the full expression. If you get a pointer to a C string from that (stringstream.str().c_str()
), it will point to a string which is deleted where the statement ends. That's why your code prints garbage.
You could copy that temporary string object to some other string object and take the C string from that one:
const std::string tmp = stringstream.str();
const char* cstr = tmp.c_str();
Note that I made the temporary string const
, because any changes to it might cause it to re-allocate and thus render cstr
invalid. It is therefor safer to not to store the result of the call to str()
at all and use cstr
only until the end of the full expression:
use_c_str( stringstream.str().c_str() );
Of course, the latter might not be easy and copying might be too expensive. What you can do instead is to bind the temporary to a const
reference. This will extend its lifetime to the lifetime of the reference:
{
const std::string& tmp = stringstream.str();
const char* cstr = tmp.c_str();
}
IMO that's the best solution. Unfortunately it's not very well known.
in my case i already had the maven dependency to 'spring-boot-starter-web' and the project would start fine without auto-stopping when i run it as springboot app from within the IDE. however, when i deploy it to K8s, the app would start and auto-stop immediately. So i modified my main app class to extend SpringBootServletInitializer and this seems to have fixed the auto-stopping.
@SpringBootApplication public class MyApp extends SpringBootServletInitializer { public static void main(String[] args) {
SpringApplication.run(MyApp.class, args); }}
More accurately anything that is not 0
is true.
So 1
is true, but so is 2
, 3
... etc.
Not that this is superior, but if anyone is curious it can be done on one line with:
tuple = tuple([200 if i == 0 else _ for i, _ in enumerate(tuple)])
If anyone uses Xcode ver. 3.x.x and upgrades from Mac OS 10.7 to 10.8, dev. tools will work just fine except the new codesign binary .. To fix that just copy the old codesign and codesign_allocate binaries (I hope you have backup) to /usr/bin/ folder and rename or backup the new one.
I faced the problem of gettng entire text from Text widget and following solution worked for me :
txt.get(1.0,END)
Where 1.0 means first line, zeroth character (ie before the first!) is the starting position and END is the ending position.
Thanks to Alan Gauld in this link
Do you have this namespace setup? You will have to ensure that this namespace matches the message namespace. If you can update your question with the xml input and possibly your data object that would be helpful.
[DataContract(Namespace = "http://CompanyName.com.au/ProjectName")]
public class CustomFields
{
// ...
}
Plain JavaScript:
You don't need jQuery to do something trivial like this. Just use the .removeAttribute()
method.
Assuming you are just targeting a single element, you can easily use the following: (example)
document.querySelector('#target').removeAttribute('style');
If you are targeting multiple elements, just loop through the selected collection of elements: (example)
var target = document.querySelectorAll('div');
Array.prototype.forEach.call(target, function(element){
element.removeAttribute('style');
});
Array.prototype.forEach()
- IE9 and above / .querySelectorAll()
- IE 8 (partial) IE9 and above.
Adding to assylias's answer - assylias shows us D.ITEMS is a method that returns an array. Knowing that, we don't need the variant array a(i) [See caveat below]. We just need to use the proper array syntax.
For i = 0 To d.Count - 1
s = d.Items()(i)
Debug.Print s
Next i()
KEYS works the same way
For i = 0 To d.Count - 1
Debug.Print d.Keys()(i), d.Items()(i)
Next i
This syntax is also useful for the SPLIT function which may help make this clearer. SPLIT also returns an array with lower bounds at 0. Thus, the following prints "C".
Debug.Print Split("A,B,C,D", ",")(2)
SPLIT is a function. Its parameters are in the first set of parentheses. Methods and Functions always use the first set of parentheses for parameters, even if no parameters are needed. In the example SPLIT returns the array {"A","B","C","D"}. Since it returns an array we can use a second set of parentheses to identify an element within the returned array just as we would any array.
Caveat: This shorter syntax may not be as efficient as using the variant array a() when iterating through the entire dictionary since the shorter syntax invokes the dictionary's Items method with each iteration. The shorter syntax is best for plucking a single item by number from a dictionary.
You can use this code for connect and request using http and json
try {
URL url = new URL("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet"
+ "&key="+key
+ "&access_token=" + access_token);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{ \"snippet\": {\"playlistId\": \"WL\",\"resourceId\": {\"videoId\": \""+videoId+"\",\"kind\": \"youtube#video\"},\"position\": 0}}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Can you try to change your json without data
key like below?
[{"target_id":9503123,"target_type":"user"}]
I have a quick solution for finding Waldo using OpenCV.
I used the template matching function available in OpenCV to find Waldo.
To do this a template is needed. So I cropped Waldo from the original image and used it as a template.
Next I called the cv2.matchTemplate()
function along with the normalized correlation coefficient as the method used. It returned a high probability at a single region as shown in white below (somewhere in the top left region):
The position of the highest probable region was found using cv2.minMaxLoc()
function, which I then used to draw the rectangle to highlight Waldo:
In general, fixing corrupt objects can be pretty difficult. However, in this case, we're confident that the problem is an aborted transfer, meaning that the object is in a remote repository, so we should be able to safely remove our copy and let git get it from the remote, correctly this time.
The temporary object file, with zero size, can obviously just be removed. It's not going to do us any good. The corrupt object which refers to it, d4a0e75...
, is our real problem. It can be found in .git/objects/d4/a0e75...
. As I said above, it's going to be safe to remove, but just in case, back it up first.
At this point, a fresh git pull
should succeed.
...assuming it was going to succeed in the first place. In this case, it appears that some local modifications prevented the attempted merge, so a stash
, pull
, stash pop
was in order. This could happen with any merge, though, and didn't have anything to do with the corrupted object. (Unless there was some index cleanup necessary, and the stash did that in the process... but I don't believe so.)
You can use the :not
filter selector:
$('foo:not(".someClass")')
Or not()
method:
$('foo').not(".someClass")
More Info:
Why don't you use the Notepad++ multiline editing capabilities?
Hold down Alt while selecting text (using your usual click-and-drag approach) to select text across multiple lines. This is sometimes also referred to as column editing.
You could place the cursor at the beginning of the file, Press (and hold) Alt, Shift and then just keep pressing the down-arrow or PageDown to select the lines that you want to prepend with some text :-) Easy. Multiline editing is a very useful feature of Notepad++. It's also possible in Visual Studio, in the same manner, and also in Eclipse by switching to Block Selection Mode by pressing Alt+Shift+A and then use mouse to select text across lines.
<?php
// Example API call
$data = array(array (
"REGION" => "MUMBAI",
"LOCATION" => "NA",
"STORE" => "AMAZON"));
// json encode data
$authToken = "xxxxxxxxxx";
$data_string = json_encode($data);
// set up the curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://domainyouhaveapi.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type:application/json',
'Content-Length: ' . strlen($data_string) ,
'API-TOKEN-KEY:'.$authToken )); // API-TOKEN-KEY is keyword so change according to ur key word. like authorization
// execute the request
$output = curl_exec($ch);
//echo $output;
// Check for errors
if($output === FALSE){
die(curl_error($ch));
}
echo($output) . PHP_EOL;
// close curl resource to free up system resources
curl_close($ch);
In my case I was stupid enough to create the patch file incorrectly in the first place, actually diff-ing the wrong way. I ended up with the exact same error messages.
If you're on master and do git diff branch-name > branch-name.patch
, this tries to remove all additions you want to happen and vice versa (which was impossible for git to accomplish since, obviously, never done additions cannot be removed).
So make sure you checkout to your branch and execute git diff master > branch-name.patch
You can access columns by index, by name and some other ways:
dtResult.Rows(i)("columnName") = strVerse
You should probably make sure your DataTable
has some columns first...
adb shell am broadcast -a android.intent.action.xxx
Mention xxx as the action that you mentioned in the manifest file.
No, z is undefined. item contains a list of integers.
I think what you're trying to do is this:
#z defined elsewhere
item = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in item:
if i not in z: print i
As has been stated in other answers, you may want to try using sets.
The 'self' is a reference to the class instance
class foo:
def bar(self):
print "hi"
Now we can create an instance of foo and call the method on it, the self parameter is added by Python in this case:
f = foo()
f.bar()
But it can be passed in as well if the method call isn't in the context of an instance of the class, the code below does the same thing
f = foo()
foo.bar(f)
Interestingly the variable name 'self' is just a convention. The below definition will work exactly the same.. Having said that it is very strong convention which should be followed always, but it does say something about flexible nature of the language
class foo:
def bar(s):
print "hi"
a) The year is 365.242199 days.
b) If every year was 365 days, in 100 years we would lose 24.2199 days. That's why we add 24 days per century (every 4 years EXCEPT when divisible by 100)
c) But still we lose 0.21299 days/century. So in 4 centuries we lose 0.8796 days. That's why we add 1 day per 4 centuries (every fourth century we DO count a leap year).
d) But that means we lose -0.1204 days (we go forward) per quadricentennial (4 centuries). So in 8 quadricentennial (3200 years) we DO NOT count a leap year.
e) But that means we lose 0.0368 days per 3200 years. So in 24x3200 years (=76800years) we lose 0.8832 days. That's why we DO count a leap year.
and so on... (by then we will have destroyed the planet, so it doesn't matter)
What I cannot understand though, is why we don't count a leap year every 500 years instead of 400. In that way we would converge more rapidly to the correct time (we would lose 2.3 hours/500 years).
I tried both the 32-bit and 64-bit installers of both Oracle and IBM Java on Windows, and the presence of C:\Windows\SysWOW64\java.exe seems to be a reliable way to determine that 32-bit Java is available. I haven't tested older versions of these installers, but this at least looks like it should be a reliable way to test, for the most recent versions of Java.
You can Change it from:
Menu Settings -> Style Configurator
See on screenshot:
You can do it in the web.config
<httpProtocol>
<customHeaders>
<add name="X-UA-Compatible" value="IE=7"/>
</customHeaders>
</httpProtocol>
I have better results with this over the above solutions. Not sure why this wasn't given as a solution. :)
For the text after the first =
and before the next =
cut -d "=" -f2 <<< "$your_str"
or
sed -e 's#.*=\(\)#\1#' <<< "$your_str"
For all text after the first =
regardless of if there are multiple =
cut -d "=" -f2- <<< "$your_str"
total edge case here: I had this issue installing an Arch AUR PKGBUILD file manually. In my case I needed to delete the 'pkg', 'src' and 'node_modules' folders, then it built fine without this npm error.
XSLT 1.0 does not have an integer data type, only double. You can use number()
to convert a string to a number.
tl;dr
All maven POMs inherit from a base Super POM.
The snippet below is part of the Super POM for Maven 3.5.4.
<repositories>
<repository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
$('#datetimepicker1').data("DateTimePicker").date('01/11/2016 10:23 AM')
Since that method is static, it already has everything you need to use it, so it defeats the purpose of mocking. Mocking the static methods is considered to be a bad practice.
If you try to do that, it means there is something wrong with the way you want to perform testing.
Of course you can use PowerMockito or any other framework capable of doing that, but try to rethink your approach.
For example: try to mock/provide the objects, which that static method consumes instead.
you can also connect to database as "normal" user (not postgres):
postgres=# \connect opensim Opensim_Tester localhost;
Password for user Opensim_Tester:
You are now connected to database "opensim" as user "Opensim_Tester" on host "localhost" at port "5432"
function ping($ip){
$output = shell_exec("ping $ip");
var_dump($output);
}
ping('127.0.0.1');
UPDATE: If you pass an hardcoded IP (like in this example and most of the real-case scenarios), this function can be enough.
But since some users seem to be very concerned about safety, please remind to never pass user generated inputs to the shell_exec
function:
If the IP comes from an untrusted source, at least check it with a filter before using it.
From the Active Record docs:
$this->db->where_in();
Generates a WHERE field IN ('item', 'item') SQL query joined with AND if appropriate
$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')
Use Access's VBA function Replace(text, find, replacement)
:
Dim result As String
result = Replace("Some sentence containing Avenue in it.", "Avenue", "Ave")
Put this code in a file called MY_Exceptions.php in application/core folder:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
/**
* Class dealing with errors as exceptions
*/
class MY_Exceptions extends CI_Exceptions
{
/**
* Force exception throwing on erros
*/
public function show_error($heading, $message, $template = 'error_general', $status_code = 500)
{
set_status_header($status_code);
$message = implode(" / ", (!is_array($message)) ? array($message) : $message);
throw new CiError($message);
}
}
/**
* Captured error from Code Igniter
*/
class CiError extends Exception
{
}
It will make all the Code Igniter errors to be treated as Exception (CiError). Then, turn all your database debug on:
$db['default']['db_debug'] = true;
driver.Manage().Window.Maximize();
Use the jQuery hashchange event plugin instead. Regarding your full ajax navigation, try to have SEO friendly ajax. Otherwise your pages shown nothing in browsers with JavaScript limitations.
I'd like to add a mention of the "brew" package. You can write a brew template file which would be LaTeX with placeholders, and then "brew" it up to create a .tex file to \include or \input into your LaTeX. Something like:
\begin{tabular}{l l}
A & <%= fit$A %> \\
B & <%= fit$B %> \\
\end{tabular}
The brew syntax can also handle loops, so you can create a table row for each row of a dataframe.
Create a file named tsconfig.json
in your project root and include following lines in it:
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"module": "commonjs",
"target": "ES5",
"outDir": "ts-built",
"rootDir": "src"
}
}
Please note that outDir
should be the path of the directory to receive compiled JS files, and rootDir
should be the path of the directory containing your source (.ts) files.
Open a terminal and run tsc -w
, it'll compile any .ts
file in src
directory into .js
and store them in ts-built
directory.
It seems nobody found a solution for this. I don't have one based on only css neither but by using this JavaScript trick I usually can handle disabled input fields.
Remember that disabled fields always follow the style that they got before becoming disabled. So the trick would be 1- Enabling them 2-Change the class 3- Disable them again. Since this happens very fast user cannot understand what happened.
A simple JavaScript code would be something like:
function changeDisabledClass (id, disabledClass){
var myInput=document.getElementById(id);
myInput.disabled=false; //First make sure it is not disabled
myInput.className=disabledClass; //change the class
myInput.disabled=true; //Re-disable it
}
Try:
if l[i]:
print 'Found element!'
else:
print 'Empty element.'
$.datepicker.setDefaults({
closeText: "??",
prevText: "<??",
nextText: "??>",
currentText: "??",
monthNames: [ "??","??","??","??","??","??",
"??","??","??","??","???","???" ],
monthNamesShort: [ "??","??","??","??","??","??",
"??","??","??","??","???","???" ],
dayNames: [ "???","???","???","???","???","???","???" ],
dayNamesShort: [ "??","??","??","??","??","??","??" ],
dayNamesMin: [ "?","?","?","?","?","?","?" ],
weekHeader: "?",
dateFormat: "yy-mm-dd",
firstDay: 1,
isRTL: false,
showMonthAfterYear: true,
yearSuffix: "?"
});
the i18n code could be copied from https://github.com/jquery/jquery-ui/tree/master/ui/i18n
you need to make county_ID
as index for the right frame:
frame_2.join ( frame_1.set_index( [ 'county_ID' ], verify_integrity=True ),
on=[ 'countyid' ], how='left' )
for your information, in pandas left join breaks when the right frame has non unique values on the joining column. see this bug.
so you need to verify integrity before joining by , verify_integrity=True
For me save_queries
option was turned off so,
$this->db->save_queries = TRUE; //Turn ON save_queries for temporary use.
$str = $this->db->last_query();
echo $str;
Ref: Can't get result from $this->db->last_query(); codeigniter
I don't think you can use "exists" on an integer in Perl, only on collections. Can you give an example of what you mean in Perl which matches your example in Java.
Given an expression that specifies a hash element or array element, returns true if the specified element in the hash or array has ever been initialized, even if the corresponding value is undefined.
This indicates it only applies to hash or array elements!
A few years late, but I have a solution for the most recent version of WordPress, which has this same issue (WordPress-generated .htaccess files break sites, reuslting in 403 Forbidden error messages). Here's that it looks like when WordPress creates it:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
The problem is that the conditional doesn't work. It doesn't work because the module it's looking for isn't .c
, it's .so
. I think this is a platform-specific, or configuration-specific issue, where Mac OS and Lunix Apache installations are set up for .so
AKA 'shared-object' modules. Looking for a .c
module shouldn't break the conditional, I think that's a bug, but it's the issue.
Simply change the mod_rewrite.c
to mod_rewrite.so
and you're all set to go!
# BEGIN WordPress
<IfModule mod_rewrite.so>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
I changed the content-type to "text/html" instead of "application/json" server side before returning the response. Described it in a blog post, where other solutions have also been added:
http://blog.degree.no/2012/09/jquery-json-ie8ie9-treats-response-as-downloadable-file/
I just wanted to add that "Include" is part of eager loading. It is described in Entity Framework 6 tutorial by Microsoft. Here is the link: https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-application
Excerpt from the linked page:
Here are several ways that the Entity Framework can load related data into the navigation properties of an entity:
Lazy loading. When the entity is first read, related data isn't retrieved. However, the first time you attempt to access a navigation property, the data required for that navigation property is automatically retrieved. This results in multiple queries sent to the database — one for the entity itself and one each time that related data for the entity must be retrieved. The DbContext class enables lazy loading by default.
Eager loading. When the entity is read, related data is retrieved along with it. This typically results in a single join query that retrieves all of the data that's needed. You specify eager loading by using the
Include
method.Explicit loading. This is similar to lazy loading, except that you explicitly retrieve the related data in code; it doesn't happen automatically when you access a navigation property. You load related data manually by getting the object state manager entry for an entity and calling the Collection.Load method for collections or the Reference.Load method for properties that hold a single entity. (In the following example, if you wanted to load the Administrator navigation property, you'd replace
Collection(x => x.Courses)
withReference(x => x.Administrator)
.) Typically you'd use explicit loading only when you've turned lazy loading off.Because they don't immediately retrieve the property values, lazy loading and explicit loading are also both known as deferred loading.
You should take care with readLines(...)
and big files. Reading all lines at memory can be risky. Below is a example of how to read file and process just one line at time:
processFile = function(filepath) {
con = file(filepath, "r")
while ( TRUE ) {
line = readLines(con, n = 1)
if ( length(line) == 0 ) {
break
}
print(line)
}
close(con)
}
Understand the risk of reading a line at memory too. Big files without line breaks can fill your memory too.
You need to create an instance of the type that expose the Output
method:
static void Main(string[] args)
{
var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");
var class1Type = DLL.GetType("DLL.Class1");
//Now you can use reflection or dynamic to call the method. I will show you the dynamic way
dynamic c = Activator.CreateInstance(class1Type);
c.Output(@"Hello");
Console.ReadLine();
}
Here is a way using the default ObjectId
values for _id
and a little math and logic.
// Get the "min" and "max" timestamp values from the _id in the collection and the
// diff between.
// 4-bytes from a hex string is 8 characters
var min = parseInt(db.collection.find()
.sort({ "_id": 1 }).limit(1).toArray()[0]._id.str.substr(0,8),16)*1000,
max = parseInt(db.collection.find()
.sort({ "_id": -1 })limit(1).toArray()[0]._id.str.substr(0,8),16)*1000,
diff = max - min;
// Get a random value from diff and divide/multiply be 1000 for The "_id" precision:
var random = Math.floor(Math.floor(Math.random(diff)*diff)/1000)*1000;
// Use "random" in the range and pad the hex string to a valid ObjectId
var _id = new ObjectId(((min + random)/1000).toString(16) + "0000000000000000")
// Then query for the single document:
var randomDoc = db.collection.find({ "_id": { "$gte": _id } })
.sort({ "_id": 1 }).limit(1).toArray()[0];
That's the general logic in shell representation and easily adaptable.
So in points:
Find the min and max primary key values in the collection
Generate a random number that falls between the timestamps of those documents.
Add the random number to the minimum value and find the first document that is greater than or equal to that value.
This uses "padding" from the timestamp value in "hex" to form a valid ObjectId
value since that is what we are looking for. Using integers as the _id
value is essentially simplier but the same basic idea in the points.
Simple PHP function to unzip. Please make sure you have zip extension installed on your server.
/**
* Unzip
* @param string $zip_file_path Eg - /tmp/my.zip
* @param string $extract_path Eg - /tmp/new_dir_name
* @return boolean
*/
function unzip(string $zip_file_path, string $extract_dir_path) {
$zip = new \ZipArchive;
$res = $zip->open($zip_file_path);
if ($res === TRUE) {
$zip->extractTo($extract_dir_path);
$zip->close();
return TRUE;
} else {
return FALSE;
}
}
Pass your arguments in constructor itself.
Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();
Void: the type modifier void states that the main method does not return any value. All parameters to a method are declared inside a prior of parenthesis. Here String args[ ] declares a parameter named args which contains an array of objects of the class type string.
I resolved this issue by changing the Build System to legacy in xcode.
I had the same problem but the mentioned solutions above didn't work for me. Even I had no previous app on device, I got this error when deploying on my device.
How to do:
Simply, go to menu File > Project Setting, inside Share Project Settings, change Build System from "New Build System (default)" to "Lagacy Build System".
External return type declaration to use with multiple functions:
type ValidationReturnType = string | boolean;
function isEqual(number1: number, number2: number): ValidationReturnType {
return number1 == number2 ? true : 'Numbers are not equal.';
}
Taken from a google search, add this ItemDecoration to your RecyclerView
:
public class DividerItemDecoration extends RecyclerView.ItemDecoration {
private Drawable mDivider;
private boolean mShowFirstDivider = false;
private boolean mShowLastDivider = false;
public DividerItemDecoration(Context context, AttributeSet attrs) {
final TypedArray a = context
.obtainStyledAttributes(attrs, new int[]{android.R.attr.listDivider});
mDivider = a.getDrawable(0);
a.recycle();
}
public DividerItemDecoration(Context context, AttributeSet attrs, boolean showFirstDivider,
boolean showLastDivider) {
this(context, attrs);
mShowFirstDivider = showFirstDivider;
mShowLastDivider = showLastDivider;
}
public DividerItemDecoration(Drawable divider) {
mDivider = divider;
}
public DividerItemDecoration(Drawable divider, boolean showFirstDivider,
boolean showLastDivider) {
this(divider);
mShowFirstDivider = showFirstDivider;
mShowLastDivider = showLastDivider;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
if (mDivider == null) {
return;
}
if (parent.getChildPosition(view) < 1) {
return;
}
if (getOrientation(parent) == LinearLayoutManager.VERTICAL) {
outRect.top = mDivider.getIntrinsicHeight();
} else {
outRect.left = mDivider.getIntrinsicWidth();
}
}
@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
if (mDivider == null) {
super.onDrawOver(c, parent, state);
return;
}
// Initialization needed to avoid compiler warning
int left = 0, right = 0, top = 0, bottom = 0, size;
int orientation = getOrientation(parent);
int childCount = parent.getChildCount();
if (orientation == LinearLayoutManager.VERTICAL) {
size = mDivider.getIntrinsicHeight();
left = parent.getPaddingLeft();
right = parent.getWidth() - parent.getPaddingRight();
} else { //horizontal
size = mDivider.getIntrinsicWidth();
top = parent.getPaddingTop();
bottom = parent.getHeight() - parent.getPaddingBottom();
}
for (int i = mShowFirstDivider ? 0 : 1; i < childCount; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
if (orientation == LinearLayoutManager.VERTICAL) {
top = child.getTop() - params.topMargin;
bottom = top + size;
} else { //horizontal
left = child.getLeft() - params.leftMargin;
right = left + size;
}
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
// show last divider
if (mShowLastDivider && childCount > 0) {
View child = parent.getChildAt(childCount - 1);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
if (orientation == LinearLayoutManager.VERTICAL) {
top = child.getBottom() + params.bottomMargin;
bottom = top + size;
} else { // horizontal
left = child.getRight() + params.rightMargin;
right = left + size;
}
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
private int getOrientation(RecyclerView parent) {
if (parent.getLayoutManager() instanceof LinearLayoutManager) {
LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
return layoutManager.getOrientation();
} else {
throw new IllegalStateException(
"DividerItemDecoration can only be used with a LinearLayoutManager.");
}
}
}
Add
session_start();
at the beginning of your page before any HTML
You will have something like :
<?php session_start();
include("inc/incfiles/header.inc.php")?>
<html>
<head>
<meta http-equiv="Content-Type" conte...
Don't forget to remove the space you have before
Most of my XML parsing life is spent extracting nuggets of useful information out of truckloads of XML (Amazon MWS). As such, my answer assumes you want only specific information and you know where it is located.
I find the easiest way to use XMLReader is to know which tags I want the information out of and use them. If you know the structure of the XML and it has lots of unique tags, I find that using the first case is the easy. Cases 2 and 3 are just to show you how it can be done for more complex tags. This is extremely fast; I have a discussion of speed over on What is the fastest XML parser in PHP?
The most important thing to remember when doing tag-based parsing like this is to use if ($myXML->nodeType == XMLReader::ELEMENT) {...
- which checks to be sure we're only dealing with opening nodes and not whitespace or closing nodes or whatever.
function parseMyXML ($xml) { //pass in an XML string
$myXML = new XMLReader();
$myXML->xml($xml);
while ($myXML->read()) { //start reading.
if ($myXML->nodeType == XMLReader::ELEMENT) { //only opening tags.
$tag = $myXML->name; //make $tag contain the name of the tag
switch ($tag) {
case 'Tag1': //this tag contains no child elements, only the content we need. And it's unique.
$variable = $myXML->readInnerXML(); //now variable contains the contents of tag1
break;
case 'Tag2': //this tag contains child elements, of which we only want one.
while($myXML->read()) { //so we tell it to keep reading
if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Amount') { // and when it finds the amount tag...
$variable2 = $myXML->readInnerXML(); //...put it in $variable2.
break;
}
}
break;
case 'Tag3': //tag3 also has children, which are not unique, but we need two of the children this time.
while($myXML->read()) {
if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Amount') {
$variable3 = $myXML->readInnerXML();
break;
} else if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Currency') {
$variable4 = $myXML->readInnerXML();
break;
}
}
break;
}
}
}
$myXML->close();
}
I had a really similar issue using HIVE in EMR. None of the extant solutions worked for me -- ie, none of the mapreduce configurations worked for me; and neither did setting yarn.nodemanager.vmem-check-enabled
to false.
However, what ended up working was setting tez.am.resource.memory.mb
, for example:
hive -hiveconf tez.am.resource.memory.mb=4096
Another setting to consider tweaking is yarn.app.mapreduce.am.resource.mb
like so:
BEGIN TRANSACTION;
UPDATE table_name
SET column_name=REPLACE(column_name,'text_to_find','replace_with_this');
COMMIT TRANSACTION;
Example: Replaces <script... with <a ... to eliminate javascript vulnerabilities
BEGIN TRANSACTION; UPDATE testdb
SET title=REPLACE(title,'script','a'); COMMIT TRANSACTION;
No, they don't exist.
I know that the C# team was considering them at one point (or at least Eric Lippert was) - along with extension constructors and operators (those may take a while to get your head around, but are cool...) However, I haven't seen any evidence that they'll be part of C# 4.
EDIT: They didn't appear in C# 5, and as of July 2014 it doesn't look like it's going to be in C# 6 either.
Eric Lippert, the Principal Developer on the C# compiler team at Microsoft thru November 2012, blogged about this in October of 2009:
//By using jquery json parser
var obj = $.parseJSON('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');
alert(obj['jobtitel']);
//By using javasript json parser
var t = JSON.parse('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');
alert(t['jobtitel'])
As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON strings use the native JSON.parse method instead.
First Add a Class called Win32.cs
public class Win32
{
[DllImport("User32.Dll")]
public static extern long SetCursorPos(int x, int y);
[DllImport("User32.Dll")]
public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int x;
public int y;
public POINT(int X, int Y)
{
x = X;
y = Y;
}
}
}
You can use it then like this:
Win32.POINT p = new Win32.POINT(xPos, yPos);
Win32.ClientToScreen(this.Handle, ref p);
Win32.SetCursorPos(p.x, p.y);
type MyProps = {
workoutType: string | null;
};
The method below sets a field on your object even if the field is in a superclass
/**
* Sets a field value on a given object
*
* @param targetObject the object to set the field value on
* @param fieldName exact name of the field
* @param fieldValue value to set on the field
* @return true if the value was successfully set, false otherwise
*/
public static boolean setField(Object targetObject, String fieldName, Object fieldValue) {
Field field;
try {
field = targetObject.getClass().getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
field = null;
}
Class superClass = targetObject.getClass().getSuperclass();
while (field == null && superClass != null) {
try {
field = superClass.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
superClass = superClass.getSuperclass();
}
}
if (field == null) {
return false;
}
field.setAccessible(true);
try {
field.set(targetObject, fieldValue);
return true;
} catch (IllegalAccessException e) {
return false;
}
}
Remove the '#' and do
Color c = Color.FromArgb(int.Parse("#FFFFFF".Replace("#",""),
System.Globalization.NumberStyles.AllowHexSpecifier));
I know this is not the OPs issue, but I had this happen on a project. The solution had multiple MVC projects and the wrong project was set as startup.
I had also set the configuration of the project(s) to just start process/debugger and not open a new browser window.
So on the surface it looks as if the debugger is starting up, but it does so for the wrong process. So check that and keep in mind that you can attach to multiple processes also.
Silly mistake that left me scratching my head for about 30 minutes.
C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell
is where the shortcut of PowerShell resides. It too still goes to a different location to invoke the actual 'exe' (%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe
).
Since PowerShell is user-profile driven when permissions are concerned; if your username/profile has the permissions to do something then under that profile, in PowerShell you would generally be able to do it as well. That being said, it would make sense that you would alter the shortcut located under your user profile, for example, C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell
.
Right-click and click properties. Click "Advanced" button under the "Shortcut" tab located right below the "Comments" text field adjacent to the right of two other buttons, "Open File Location" and "Change Icon", respectively.
Check the checkbox that reads, "Run as Administrator". Click OK, then Apply and OK. Once again right click the icon labeled 'Windows PowerShell' located in C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell
and select "Pin to Start Menu/Taskbar".
Now whenever you click that icon, it will invoke the UAC for escalation. After selecting 'YES', you will notice the PowerShell console open and it will be labeled "Administrator" on the top of the screen.
To go a step further... you could right click that same icon shortcut in your profile location of Windows PowerShell and assign a keyboard shortcut that will do the exact same thing as if you clicked the recently added icon. So where it says "Shortcut Key" put in a keyboard key/button combination like: Ctrl + Alt + PP (for PowerShell). Click Apply and OK.
Now all you have to do is press that button combination you assigned and you will see UAC get invoked, and after you select 'YES' you will see a PowerShell console appear and "Administrator" displayed on the title bar.
Direct Closure serialisation is not allowed by PHP. But you can use powefull class like PHP Super Closure : https://github.com/jeremeamia/super_closure
This class is really simple to use and is bundled into the laravel framework for the queue manager.
From the github documentation :
$helloWorld = new SerializableClosure(function ($name = 'World') use ($greeting) {
echo "{$greeting}, {$name}!\n";
});
$serialized = serialize($helloWorld);
Some code that allows you to use CI instance inside the helper:
function yourHelperFunction(){
$ci=& get_instance();
$ci->load->database();
$sql = "select * from table";
$query = $ci->db->query($sql);
$row = $query->result();
}
set print elements 0
set print elements
number-of-elements
Set a limit on how many elements of an array GDB will print. If GDB is printing a large array, it stops printing after it has printed the number of elements set by the set print elements
command. This limit also applies to the display of strings. When GDB starts, this limit is set to 200. Setting number-of-elements to zero means that the printing is unlimited.
Personally, I'd append the element to the form instead of hacking the serialized data, e.g.
moredata = 'your custom data here';
// do what you like with the input
$input = $('<input type="text" name="moredata"/>').val(morevalue);
// append to the form
$('#myForm').append($input);
// then..
data: $('#myForm').serialize()
That way, you don't have to worry about ?
or &
My team really got sick of trying to find the tenant ID for our O365 and Azure projects. The devs, the support team, the sales team, everyone needs it at some point and never remembers how to do it.
So we've built this small site in the same vein as whatismyip.com. Hope you find it useful!
How to find my Microsoft 365, Azure or SharePoint Online tenant ID?
I came across the same issue with a .NET application, a CMS open-source called MojoPortal. In one of my themes and skin for a particular site, when browsing or testing it would grind and slow down like it was choking.
My issue was not of the "type" attribute for the CSS but it was "that other thing". My exact change was in the Web.Config. I changed all the values to FALSE for MinifyCSS, CacheCssOnserver, and CacheCSSinBrowser.
Once that was set the web site was speedy once again in production.
That turned out to be pretty simple. I've got it occasionally. To paste a text you simply need to right mouse button click anywhere in terminal window.
Use glob. There are comprehensive guide how to open all files from dir: PHP: Using functional programming for listing files and directories
If you're using ng-view
in your Angular app you can listen for the $viewContentLoaded
event and push a tracking event to Google Analytics.
Assuming you've set up your tracking code in your main index.html file with a name of var _gaq
and MyCtrl is what you've defined in the ng-controller
directive.
function MyCtrl($scope, $location, $window) {
$scope.$on('$viewContentLoaded', function(event) {
$window._gaq.push(['_trackPageView', $location.url()]);
});
}
UPDATE: for new version of google-analytics use this one
function MyCtrl($scope, $location, $window) {
$scope.$on('$viewContentLoaded', function(event) {
$window.ga('send', 'pageview', { page: $location.url() });
});
}
std::string trimmed(std::string str ) {
if(str.length() == 0 ) { return "" ; }
else if ( str == std::string(" ") ) { return "" ; }
else {
while(str.at(0) == ' ') { str.erase(0, 1);}
while(str.at(str.length()-1) == ' ') { str.pop_back() ; }
return str ;
}
}
Here is How you can do in Spring Boot 2.0 by creating custom MongoClient adding Providing more control for Connection ,
Please follow github Link for Full Source Code
@Configuration
@EnableMongoRepositories(basePackages = { "com.frugalis.repository" })
@ComponentScan(basePackages = { "com.frugalis.*" })
@PropertySource("classpath:application.properties")
public class MongoJPAConfig extends AbstractMongoConfiguration {
@Value("${com.frugalis.mongo.database}")
private String database;
@Value("${com.frugalis.mongo.server}")
private String host;
@Value("${com.frugalis.mongo.port}")
private String port;
@Value("${com.frugalis.mongo.username}")
private String username;
@Value("${com.frugalis.mongo.password}")
private String password;
@Override
protected String getDatabaseName() {
return database;
}
@Override
protected String getMappingBasePackage() {
return "com.frugalis.entity.mongo";
}
@Bean
public MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongoClient(), getDatabaseName());
}
@Override
@Bean
public MongoClient mongoClient() {
List<MongoCredential> allCred = new ArrayList<MongoCredential>();
System.out.println("???????????????????"+username+" "+database+" "+password+" "+host+" "+port);
allCred.add(MongoCredential.createCredential(username, database, password.toCharArray()));
MongoClient client = new MongoClient((new ServerAddress(host, Integer.parseInt(port))), allCred);
client.setWriteConcern(WriteConcern.ACKNOWLEDGED);
return client;
}}
&&
and ||
take scalar inputs and short-circuit always. |
and &
take array inputs and short-circuit only in if/while statements. For assignment, the latter do not short-circuit.
See these doc pages for more information.
What is a file with extension .sh?
It is a Bourne shell script. They are used in many variations of UNIX-like operating systems. They have no "language" and are interpreted by your shell (interpreter of terminal commands) or if the first line is in the form
#!/path/to/interpreter
they will use that particular interpreter. Your file has the first line:
#!/bin/bash
and that means that it uses Bourne Again Shell, so called bash. It is for all practical purposes a replacement for good old sh.
Depending upon the interpreter you will have different language in which the file is written.
Keep in mind, that in UNIX world, it is not the extension of the file that determines what the file is (see How to execute a shell script).
If you come from the world of DOS/Windows, you will be familiar with files that have .bat or .cmd extensions (batch files). They are not similar in content, but are akin in design.
How to execute a shell script
Unlike some silly operating systems, *nix does not rely exclusively on extensions to determine what to do with a file. Permissions are also used. This means that if you attempt to run the shell script after downloading it, it will be the same as trying to "run" any text file. The ".sh" extension is there only for your convenience to recognize that file.
You will need to make the file executable. Let's assume that you have downloaded your file as file.sh
, you can then run in your terminal:
chmod +x file.sh
chmod
is a command for changing file's permissions, +x
sets execute permissions (in this case for everybody) and finally you have your file name.
You can also do it in GUI. Most of the time you can right click on the file and select properties, in XUbuntu the permissions options look like this:
If you do not wish to change the permissions. You can also force the shell to run the command. In the terminal you can run:
bash file.sh
The shell should be the same as in the first line of your script.
How safe is it?
You may find it weird that you must perform another task manually in order to execute a file. But this is partially because of strong need for security.
Basically when you download and run a bash script, it is the same thing as somebody telling you "run all these commands in sequence on your computer, I promise that the results will be good and safe". Ask yourself if you trust the party that has supplied this file, ask yourself if you are sure that have downloaded the file from the same place as you thought, maybe even have a glance inside to see if something looks out of place (although that requires that you know something about *nix commands and bash programming).
Unfortunately apart from the warning above I cannot give a step-by-step description of what you should do to prevent evil things from happening with your computer; so just keep in mind that any time you get and run an executable file from someone you're actually saying, "Sure, you can use my computer to do something".
Take a look at BackgroundWorker Class, with the OnRunWorkerCompleted you can do it.
Well in JavaScript you can check two strings for values same as integers so yo can do this:
"A" < "B"
"A" == "B"
"A" > "B"
And therefore you can make your own function that checks strings the same way as the strcmp()
.
So this would be the function that does the same:
function strcmp(a, b)
{
return (a<b?-1:(a>b?1:0));
}
At my company they didn't configure the server to provide a list of repositories, so svn list
worked for a specific repository but not at a higher level to list all repositories.
However they installed FishEye which gives you a GUI listing the repositories https://www.atlassian.com/software/fisheye
It's a paid option, so it's not for everyone, but the functionality is nice.
I think that the following example demonstrates what you need:http://www.hacksparrow.com/base64-encoding-decoding-in-node-js.html
The essence of the article is this code part:
var fs = require('fs');
// function to encode file data to base64 encoded string
function base64_encode(file) {
// read binary data
var bitmap = fs.readFileSync(file);
// convert binary data to base64 encoded string
return new Buffer(bitmap).toString('base64');
}
// function to create file from base64 encoded string
function base64_decode(base64str, file) {
// create buffer object from base64 encoded string, it is important to tell the constructor that the string is base64 encoded
var bitmap = new Buffer(base64str, 'base64');
// write buffer to file
fs.writeFileSync(file, bitmap);
console.log('******** File created from base64 encoded string ********');
}
// convert image to base64 encoded string
var base64str = base64_encode('kitten.jpg');
console.log(base64str);
// convert base64 string back to image
base64_decode(base64str, 'copy.jpg');
:%s/string/string/g will give the answer.
It's a good practice if you need them. It's also a good practice is they make sense, so future coders can understand what you're doing.
But generally, no it's not a good practice to attach 10 class names to an object because most likely whatever you're using them for, you could accomplish the same thing with far fewer classes. Probably just 1 or 2.
To qualify that statement, javascript plugins and scripts may append far more classnames to do whatever it is they're going to do. Modernizr for example appends anywhere from 5 - 25 classes to your body tag, and there's a very good reason for it. jQuery UI appends lots of classnames when you use one of the widgets in that library.
How about:
(Updated)
$("#column_select").change(function () {
$("#layout_select")
.find("option")
.show()
.not("option[value*='" + this.value + "']").hide();
$("#layout_select").val(
$("#layout_select").find("option:visible:first").val());
}).change();
(assuming the third option
should have a value col3
)
Example: http://jsfiddle.net/cL2tt/
Notes:
.change()
event to define an event handler that executes when the value of select#column_select
changes..show()
all option
s in the second select
..hide()
all option
s in the second select
whose value
does not contain the value
of the selected option in select#column_select
, using the attribute contains selector.$timeFirst = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;
You will then be able to use the seconds to find minutes, hours, days, etc.
You can use the native map method for Arrays. map Method (Array) (JavaScript)
var myData = new Array(['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0],
['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0],
['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0],
['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]);
var a = 0;
myData.map( function(aa){ a += aa[1]; return a; });
a is your result
You need to use jq 'keys[]'
. For example:
echo '{"example1" : 1, "example2" : 2, "example3" : 3}' | jq 'keys[]'
Will output a line separated list:
"example1"
"example2"
"example3"
SELECT t.ID,
t.NAME,
(SELECT t1.SOMECOLUMN
FROM TABLEB t1
WHERE t1.F_ID = T.TABLEA.ID)
FROM TABLEA t;
This will work for selecting from different table using sub query.
If You want to see file names with pdftotext use following command:
find . -name '*.pdf' -exec echo {} \; -exec pdftotext {} - \; | grep "pattern\|pdf"
The precision of float is 7 digits. If you want to keep the whole lot, you need to use the double type that keeps 15-16 digits. Regarding formatting, look at a post about formatting doubles. And you need to worry about decimal separators in C#.
This should work for you:
public int Get4LetterYear(int twoLetterYear)
{
int firstTwoDigits =
Convert.ToInt32(DateTime.Now.Year.ToString().Substring(2, 2));
return Get4LetterYear(twoLetterYear, firstTwoDigits);
}
public int Get4LetterYear(int twoLetterYear, int firstTwoDigits)
{
return Convert.ToInt32(firstTwoDigits.ToString() + twoLetterYear.ToString());
}
public int Get2LetterYear(int fourLetterYear)
{
return Convert.ToInt32(fourLetterYear.ToString().Substring(2, 2));
}
I don't think there are any special built-in stuff in .NET.
Update: It's missing some validation that you maybe should do. Validate length of inputted variables, and so on.
In web application a timer will be the best approach.
Just fyi, in desktop application I use this instead, inside an async method.
...
Await Task.Run(Sub()
System.Threading.Thread.Sleep(5000)
End Sub)
...
It work for me, importantly it doesn't freeze entire screen. But again this is on desktop, i try in web application it does freeze.
Here goes mine, make them all char*, which makes calling easier...
char *strrpc(char *str,char *oldstr,char *newstr){
char bstr[strlen(str)];
memset(bstr,0,sizeof(bstr));
int i;
for(i = 0;i < strlen(str);i++){
if(!strncmp(str+i,oldstr,strlen(oldstr))){
strcat(bstr,newstr);
i += strlen(oldstr) - 1;
}else{
strncat(bstr,str + i,1);
}
}
strcpy(str,bstr);
return str;
}
IN ES5
E.G. you have this kind of object:
var ELEMENTS = {
STEP_ELEMENT: { ID: "0", imageName: "el_0.png" },
GREEN_ELEMENT: { ID: "1", imageName: "el_1.png" },
BLUE_ELEMENT: { ID: "2", imageName: "el_2.png" },
ORANGE_ELEMENT: { ID: "3", imageName: "el_3.png" },
PURPLE_ELEMENT: { ID: "4", imageName: "el_4.png" },
YELLOW_ELEMENT: { ID: "5", imageName: "el_5.png" }
};
And now if you want to have a function that if you pass '0' as a param - to get 'STEP_ELEMENT', if '2' to get 'BLUE_ELEMENT' and so for
function(elementId) {
var element = null;
Object.keys(ELEMENTS).forEach(function(key) {
if(ELEMENTS[key].ID === elementId.toString()){
element = key;
return;
}
});
return element;
}
This is probably not the best solution to the problem but its good to give you an idea how to do it.
Cheers.
That's actually quite easy.
document.querySelector('#input-field').value = '';
This is another way to specify the range of the bit-vector.
x +: N, The start position of the vector is given by x and you count up from x by N.
There is also
x -: N, in this case the start position is x and you count down from x by N.
N is a constant and x is an expression that can contain iterators.
It has a couple of benefits -
It makes the code more readable.
You can specify an iterator when referencing bit-slices without getting a "cannot have a non-constant value" error.
readdir() does that.
Check http://perldoc.perl.org/functions/readdir.html
opendir(DIR, $some_dir) || die "can't opendir $some_dir: $!";
@dots = grep { /^\./ && -f "$some_dir/$_" } readdir(DIR);
closedir DIR;
ld
is trying to find libcrypto.so
which is not present as seen in your locate
output.
You can make a copy of the libcrypto.so.0.9.8
and name it as libcrypto.so
. Put this is your ld path. ( If you do not have root access then you can put it in a local path and specify the path manually )
Java strings are simply an array of char. So, char c = s[0] where s is string.
This helped me find the "Dynamic web project" in Eclipse 2020-12 version. Restart the eclipse and go to file->new->other->web and you will see project will be available.
What you need is properly a service:
.factory('DataLayer', ['$http',
function($http) {
var factory = {};
var locations;
factory.getLocations = function(success) {
if(locations){
success(locations);
return;
}
$http.get('locations/locations.json').success(function(data) {
locations = data;
success(locations);
});
};
return factory;
}
]);
The locations
would be cached in the service which worked as singleton model. This is the right way to fetch data.
Use this service DataLayer
in your controller and directive is ok as following:
appControllers.controller('dummyCtrl', function ($scope, DataLayer) {
DataLayer.getLocations(function(data){
$scope.locations = data;
});
});
.directive('map', function(DataLayer) {
return {
restrict: 'E',
replace: true,
template: '<div></div>',
link: function(scope, element, attrs) {
DataLayer.getLocations(function(data) {
angular.forEach(data, function(location, key){
//do something
});
});
}
};
});
Examining the pros and cons
In favor of single quotes
elem.innerHTML = '<a href="' + url + '">Hello</a>';
_x000D_
elem.innerHTML = "<a href='" + url + "'>Hello</a>";
_x000D_
Furthermore, inline HTML is normally an anti-pattern. Prefer templates.
myJson = '{ "hello world": true }';
_x000D_
Again, you shouldn’t have to construct JSON this way. JSON.stringify() is often enough. If not, use templates.
In favor of double quotes
In favor of both
There is no difference between the two in JavaScript. Therefore, you can use whatever is convenient at the moment. For example, the following string literals all produce the same string:
"He said: \"Let's go!\""_x000D_
'He said: "Let\'s go!"'_x000D_
"He said: \"Let\'s go!\""_x000D_
'He said: \"Let\'s go!\"'
_x000D_
Single quotes for internal strings and double for external. That allows you to distinguish internal constants from strings that are to be displayed to the user (or written to disk etc.). Obviously, you should avoid putting the latter in your code, but that can’t always be done.
No. Actually it's the "same" as
char array[] = {'O', 'n', 'e', ..... 'i','c','\0');
Every character is a separate element, with an additional \0
character as a string terminator.
I quoted "same", because there are some differences between char * array
and char array[]
.
If you want to read more, take a look at C: differences between char pointer and array
This could help:
public static String getCorporateID(String fileName) {
String corporateId = null;
try {
corporateId = fileName.substring(0, fileName.indexOf("_"));
// System.out.println(new Date() + ": " + "Corporate:
// "+corporateId);
return corporateId;
} catch (Exception e) {
corporateId = null;
e.printStackTrace();
}
return corporateId;
}
Here is a workaround using a flag:
//outside your event or method, but inside your class
private bool IsExecuted = false;
private async Task MethodA()
{
//Do Stuff Here
IsExecuted = true;
}
.
.
.
//Inside your event or method
{
await MethodA();
while (!isExecuted) Thread.Sleep(200); // <-------
await MethodB();
}