Seeing your loop for sending emails and the error which you provided there is only solution.
Declare the mail object out of the loop and assign fromaddress
out of the loop which you are using for sending mails. The fromaddress
field is getting assigned again and again in the loop that is your problem.
driver = webdriver.Firefox(...) # Or Chrome(), or Ie(), or Opera()
username = driver.find_element_by_id("username")
password = driver.find_element_by_id("password")
username.send_keys("YourUsername")
password.send_keys("Pa55worD")
driver.find_element_by_name("submit").click()
Notes to your code:
find_element_by_name('Username')
: Username
capitalized doesn't match anything.Select()
is used to act on a Select Element (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select)The first line of a constructor is always an invocation to another constructor. You can choose between calling a constructor from the same class with "this(...)" or a constructor from the parent clas with "super(...)". If you don't include either, the compiler includes this line for you: super();
emacs hello.c -nw
This is to open a hello.c file using Emacs inside the terminal.
I am using both in my app.
Robospice works faster than Retrofit whenever I parse the nested JSON class. Because Spice Manger will do everything for you. In Retrofit you need to create GsonConverter and deserialize it.
I created two fragments in the same activity and called the same time with two same kind of URLs.
09-23 20:12:32.830 16002-16002/com.urbanpro.seeker E/RETROFIT? RestAdapter Init
09-23 20:12:32.833 16002-16002/com.urbanpro.seeker E/RETROFIT? calling the method
09-23 20:12:32.837 16002-16002/com.urbanpro.seeker E/ROBOSPICE? initialzig spice manager
09-23 20:12:32.860 16002-16002/com.urbanpro.seeker E/ROBOSPICE? Executing the method
09-23 20:12:33.537 16002-16002/com.urbanpro.seeker E/ROBOSPICE? on SUcceess
09-23 20:12:33.553 16002-16002/com.urbanpro.seeker E/ROBOSPICE? gettting the all contents
09-23 20:12:33.601 16002-21819/com.urbanpro.seeker E/RETROFIT? deseriazation starts
09-23 20:12:33.603 16002-21819/com.urbanpro.seeker E/RETROFIT? deseriazation ends
This should do the work:
.category_table tr:first-child td {
vertical-align: top;
}
This is blatant rip-off of Christian's excellent answer. I've just made it a bit more readable:
/**
* objectInspector digs through a Javascript object
* to display all its properties
*
* @param object - a Javascript object to inspect
* @param result - a string of properties with datatypes
*
* @return result - the concatenated description of all object properties
*/
function objectInspector(object, result) {
if (typeof object != "object")
return "Invalid object";
if (typeof result == "undefined")
result = '';
if (result.length > 50)
return "[RECURSION TOO DEEP. ABORTING.]";
var rows = [];
for (var property in object) {
var datatype = typeof object[property];
var tempDescription = result+'"'+property+'"';
tempDescription += ' ('+datatype+') => ';
if (datatype == "object")
tempDescription += 'object: '+objectInspector(object[property],result+' ');
else
tempDescription += object[property];
rows.push(tempDescription);
}//Close for
return rows.join(result+"\n");
}//End objectInspector
@RequestBody MultipartFile[] submissions
should be
@RequestParam("file") MultipartFile[] submissions
The files are not the request body, they are part of it and there is no built-in HttpMessageConverter
that can convert the request to an array of MultiPartFile
.
You can also replace HttpServletRequest
with MultipartHttpServletRequest
, which gives you access to the headers of the individual parts.
Try for simple regular expression for Mobile No
[Required (ErrorMessage="Required")]
[RegularExpression(@"^(\d{10})$", ErrorMessage = "Wrong mobile")]
public string Mobile { get; set; }
String string;
for (Datapoint d : dataPointList) {
Field[] fields = d.getFields();
for (Field f : fields) {
String value = (String) g.get(d);
if (value.equals(string)) {
//Do your stuff
}
}
}
Type IF /? to get help about if, it clearly explains how to use IF EXIST.
To delete a complete tree except some folders, see the answer of this question: Windows batch script to delete everything in a folder except one
Finally copying just means calling COPY and calling another bat file can be done like this:
MYOTHERBATFILE.BAT sync.bat myprogram.ini
function full_copy( $source, $target ) {
if ( is_dir( $source ) ) {
@mkdir( $target );
$d = dir( $source );
while ( FALSE !== ( $entry = $d->read() ) ) {
if ( $entry == '.' || $entry == '..' ) {
continue;
}
$Entry = $source . '/' . $entry;
if ( is_dir( $Entry ) ) {
full_copy( $Entry, $target . '/' . $entry );
continue;
}
copy( $Entry, $target . '/' . $entry );
}
$d->close();
}else {
copy( $source, $target );
}
}
This worked for me.
SSH into your production server and cd
into your current directory, run bundle exec rake secret
or rake secret
, you will get a long string as an output, copy that string.
Now run sudo nano /etc/environment
.
Paste at the bottom of the file
export SECRET_KEY_BASE=rake secret
ruby -e 'p ENV["SECRET_KEY_BASE"]'
Where rake secret
is the string you just copied, paste that copied string in place of rake secret
.
Restart the server and test by running echo $SECRET_KEY_BASE
.
They are 3 ways you can achieve this using the py command (py-launcher) in python 3, virtual environment or configuring your default python system path. For illustration purpose, you may see tutorial https://www.youtube.com/watch?v=ynDlb0n27cw&t=38s
You have to copy in Users/user/.p2 and .eclipse from old location when it come from and older location. For example i made a copy from computer to another, and i had this error, then i copied those folders and it worked !
Debug Diagnostics Tool (DebugDiag) can be a lifesaver. It creates and analyze IIS crash dumps. I figured out my crash in minutes once I saw the call stack. https://support.microsoft.com/en-us/kb/919789
Use SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d
.
My bad, I had missed one part of the question.
Best, cleanest way is to use a UDF
.
Explanation within the code.
// create some example data...BY DataFrame
// note, third record has an empty string
case class Stuff(a:String,b:Int)
val d= sc.parallelize(Seq( ("a",1),("b",2),
("",3) ,("d",4)).map { x => Stuff(x._1,x._2) }).toDF
// now the good stuff.
import org.apache.spark.sql.functions.udf
// function that returns 0 is string empty
val func = udf( (s:String) => if(s.isEmpty) 0 else 1 )
// create new dataframe with added column named "notempty"
val r = d.select( $"a", $"b", func($"a").as("notempty") )
scala> r.show
+---+---+--------+
| a| b|notempty|
+---+---+--------+
| a| 1| 1111|
| b| 2| 1111|
| | 3| 0|
| d| 4| 1111|
+---+---+--------+
This is my Df contain 4 is repeated twice so here will remove repeated values.
scala> df.show
+-----+
|value|
+-----+
| 1|
| 4|
| 3|
| 5|
| 4|
| 18|
+-----+
scala> val newdf=df.dropDuplicates
scala> newdf.show
+-----+
|value|
+-----+
| 1|
| 3|
| 5|
| 4|
| 18|
+-----+
there is indeed an xpath contains function it should look something like:
<xsl:for-each select="item">
<xsl:variable name="hhref" select="link" />
<xsl:variable name="pdate" select="pubDate" />
<xsl:if test="not(contains(hhref,'1234'))">
<li>
<a href="{$hhref}" title="{$pdate}">
<xsl:value-of select="title"/>
</a>
</li>
</xsl:if>
Even though a bit old thread, for those who still looking for the differences:
Aside from layout (space) taken in Hidden and not taken in Collapsed, there is another difference.
If we have custom controls inside this 'Collapsed' main control, the next time we set it to Visible, it will "load" all custom controls. It will not pre-load when window is started.
As for 'Hidden', it will load all custom controls + main control which we set as hidden when the "window" is started.
@Garret Wilson Thank you so much! As a noob to android coding, I've been stuck with the preferences incompatibility issue for so many hours, and I find it so disappointing they deprecated the use of some methods/approaches for new ones that aren't supported by the older APIs thus having to resort to all sorts of workarounds to make your app work in a wide range of devices. It's really frustrating!
Your class is great, for it allows you to keep working in new APIs wih preferences the way it used to be, but it's not backward compatible. Since I'm trying to reach a wide range of devices I tinkered with it a bit to make it work in pre API 11 devices as well as in newer APIs:
import android.annotation.TargetApi;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
public class MyPrefsActivity extends PreferenceActivity
{
private static int prefs=R.xml.myprefs;
@Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try {
getClass().getMethod("getFragmentManager");
AddResourceApi11AndGreater();
} catch (NoSuchMethodException e) { //Api < 11
AddResourceApiLessThan11();
}
}
@SuppressWarnings("deprecation")
protected void AddResourceApiLessThan11()
{
addPreferencesFromResource(prefs);
}
@TargetApi(11)
protected void AddResourceApi11AndGreater()
{
getFragmentManager().beginTransaction().replace(android.R.id.content,
new PF()).commit();
}
@TargetApi(11)
public static class PF extends PreferenceFragment
{
@Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(MyPrefsActivity.prefs); //outer class
// private members seem to be visible for inner class, and
// making it static made things so much easier
}
}
}
Tested in two emulators (2.2 and 4.2) with success.
Why my code looks so crappy:
I'm a noob to android coding, and I'm not the greatest java fan.
In order to avoid the deprecated warning and to force Eclipse to allow me to compile I had to resort to annotations, but these seem to affect only classes or methods, so I had to move the code onto two new methods to take advantage of this.
I wouldn't like having to write my xml resource id twice anytime I copy&paste the class for a new PreferenceActivity, so I created a new variable to store this value.
I hope this will be useful to somebody else.
P.S.: Sorry for my opinionated views, but when you come new and find such handicaps, you can't help it but to get frustrated!
I suggest the following, let's expect a module.js:
const values = { a: 1, b: 2, c: 3 };
export { values }; // you could use default, but I'm specific here
and then you can do in an index.js:
import { values } from "module";
// directly access the object
console.log(values.a); // 1
// object destructuring
const { a, b, c } = values;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
// selective object destructering with renaming
const { a:k, c:m } = values;
console.log(k); // 1
console.log(m); // 3
// selective object destructering with renaming and default value
const { a:x, b:y, d:z = 0 } = values;
console.log(x); // 1
console.log(y); // 2
console.log(z); // 0
More examples of destructering objects: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring
If you by writing "non letters and numbers" exclude more than [A-Za-z0-9]
(ie. considering letters like åäö
to be letters to) and want to be able to accurately handle UTF-8 strings \p{L}
and \p{N}
will be of aid.
\p{N}
will match any "Number"\p{L}
will match any "Letter Character", which includes
Documentation PHP: Unicode Character Properties
$data = "Thäre!wouldn't%bé#äny";
$new_data = str_replace ("'", "", $data);
$new_data = preg_replace ('/[^\p{L}\p{N}]/u', '_', $new_data);
var_dump (
$new_data
);
output
string(23) "Thäre_wouldnt_bé_äny"
<style type="text/css">
p {margin-bottom: -1em; margin-top: 0em;}
</style>
This completely worked for me. Paragraphs were right below each other. When I used 0em for both the margins, there was still some space left in between the lines. I went for Developer tools in my browser, tried with -1em and it worked.
ChronoUnit.between
Use instances of ChronoUnit
to calculate amount of time in different units (days,months, seconds).
For Example:
ChronoUnit.DAYS.between(startDate,endDate)
I've also find this fix that zooms to fit all markers
LatLngList: an array of instances of latLng, for example:
// "map" is an instance of GMap3
var LatLngList = [
new google.maps.LatLng (52.537,-2.061),
new google.maps.LatLng (52.564,-2.017)
],
latlngbounds = new google.maps.LatLngBounds();
LatLngList.forEach(function(latLng){
latlngbounds.extend(latLng);
});
// or with ES6:
// for( var latLng of LatLngList)
// latlngbounds.extend(latLng);
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
I based this on @asawyer's answer. He doesn't seem to get a compile error, but some of us do. Here is a version which the C# compiler in Visual Studio 2010 will accept.
var timer = new System.Threading.Timer(
e => MyMethod(),
null,
TimeSpan.Zero,
TimeSpan.FromMinutes(5));
Depends on how you installed it:
brew: brew uninstall yarn
tarball: rm -rf "$HOME/.yarn"
npm: npm uninstall -g yarn
ubuntu: sudo apt-get remove yarn && sudo apt-get purge yarn
centos: yum remove yarn
windows: choco uninstall yarn
You can use JSON.stringify
like:
JSON.stringify(new_tweets);
The data
event is fired multiple times with 'chunks' of the body as they are downloaded and an end
event when all chunks have been downloaded.
With Node supporting Promises now, I created a simple wrapper to return the concatenated chunks through a Promise:
const httpGet = url => {
return new Promise((resolve, reject) => {
http.get(url, res => {
res.setEncoding('utf8');
let body = '';
res.on('data', chunk => body += chunk);
res.on('end', () => resolve(body));
}).on('error', reject);
});
};
You can call it from an async function with:
const body = await httpGet('http://www.somesite.com');
display: block
- a line break before and after the element
display: inline
- no line break before or after the element
I think the option controlling the folders from which autoloading stuff gets done has been sufficiently covered in other answers. However, in case someone else is having trouble stuff loaded though they've had their autoload paths modified as required, then this answer tries to explain what is the magic behind this autoload thing.
So when it comes to loading stuff from subdirectories there's a gotcha or a convention you should be aware. Sometimes the Ruby/Rails magic (this time mostly Rails) can make it difficult to understand why something is happening. Any module declared in the autoload paths will only be loaded if the module name corresponds to the parent directory name. So in case you try to put into lib/my_stuff/bar.rb
something like:
module Foo
class Bar
end
end
It will not be loaded automagically. Then again if you rename the parent dir to foo
thus hosting your module at path: lib/foo/bar.rb
. It will be there for you. Another option is to name the file you want autoloaded by the module name. Obviously there can only be one file by that name then. In case you need to split your stuff into many files you could of course use that one file to require other files, but I don't recommend that, because then when on development mode and you modify those other files then Rails is unable to automagically reload them for you. But if you really want you could have one file by the module name that then specifies the actual files required to use the module. So you could have two files: lib/my_stuff/bar.rb
and lib/my_stuff/foo.rb
and the former being the same as above and the latter containing a single line: require "bar"
and that would work just the same.
P.S. I feel compelled to add one more important thing. As of lately, whenever I want to have something in the lib directory that needs to get autoloaded, I tend to start thinking that if this is something that I'm actually developing specifically for this project (which it usually is, it might some day turn into a "static" snippet of code used in many projects or a git submodule, etc.. in which case it definitely should be in the lib folder) then perhaps its place is not in the lib folder at all. Perhaps it should be in a subfolder under the app folder· I have a feeling that this is the new rails way of doing things. Obviously, the same magic is in work wherever in you autoload paths you put your stuff in so it's good to these things. Anyway, this is just my thoughts on the subject. You are free to disagree. :)
UPDATE: About the type of magic..
As severin pointed out in his comment, the core "autoload a module mechanism" sure is part of Ruby, but the autoload paths stuff isn't. You don't need Rails to do autoload :Foo, File.join(Rails.root, "lib", "my_stuff", "bar")
. And when you would try to reference the module Foo for the first time then it would be loaded for you. However what Rails does is it gives us a way to try and load stuff automagically from registered folders and this has been implemented in such a way that it needs to assume something about the naming conventions. If it had not been implemented like that, then every time you reference something that's not currently loaded it would have to go through all of the files in all of the autoload folders and check if any of them contains what you were trying to reference. This in turn would defeat the idea of autoloading and autoreloading. However, with these conventions in place it can deduct from the module/class your trying to load where that might be defined and just load that.
Run -> Run configurations, select project, second tab: “Arguments”. Top box is for your program, bottom box is for VM arguments, e.g. -Dkey=value
.
While ("run as SYSTEM") works, people should be advised this means going from a minimum-permissions type account to an account which has all permissions in the world. Which is very much not a recommended setup best practices or security-wise.
If you know what you are doing and know your SQL Server will always be run in an isolated environment (i.e. not on hotel or airport wifi) it's probably fine, but this creates a very real attack vector which can completely compromise a machine if on open internets.
This seems to be an error on Microsoft's part and people should be aware of the implications of the workaround posted.
This method will determine the MAC address of the Network Interface used to connect to the specified url and port.
All the answers here are not capable of achieving this goal.
I wrote this answer years ago (in 2014). So I decided to give it a little "face lift". Please look at the updates section
/// <summary>
/// Get the MAC of the Netowrk Interface used to connect to the specified url.
/// </summary>
/// <param name="allowedURL">URL to connect to.</param>
/// <param name="port">The port to use. Default is 80.</param>
/// <returns></returns>
private static PhysicalAddress GetCurrentMAC(string allowedURL, int port = 80)
{
//create tcp client
var client = new TcpClient();
//start connection
client.Client.Connect(new IPEndPoint(Dns.GetHostAddresses(allowedURL)[0], port));
//wai while connection is established
while(!client.Connected)
{
Thread.Sleep(500);
}
//get the ip address from the connected endpoint
var ipAddress = ((IPEndPoint)client.Client.LocalEndPoint).Address;
//if the ip is ipv4 mapped to ipv6 then convert to ipv4
if(ipAddress.IsIPv4MappedToIPv6)
ipAddress = ipAddress.MapToIPv4();
Debug.WriteLine(ipAddress);
//disconnect the client and free the socket
client.Client.Disconnect(false);
//this will dispose the client and close the connection if needed
client.Close();
var allNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
//return early if no network interfaces found
if(!(allNetworkInterfaces?.Length > 0))
return null;
foreach(var networkInterface in allNetworkInterfaces)
{
//get the unicast address of the network interface
var unicastAddresses = networkInterface.GetIPProperties().UnicastAddresses;
//skip if no unicast address found
if(!(unicastAddresses?.Count > 0))
continue;
//compare the unicast addresses to see
//if any match the ip address used to connect over the network
for(var i = 0; i < unicastAddresses.Count; i++)
{
var unicastAddress = unicastAddresses[i];
//this is unlikely but if it is null just skip
if(unicastAddress.Address == null)
continue;
var ipAddressToCompare = unicastAddress.Address;
Debug.WriteLine(ipAddressToCompare);
//if the ip is ipv4 mapped to ipv6 then convert to ipv4
if(ipAddressToCompare.IsIPv4MappedToIPv6)
ipAddressToCompare = ipAddressToCompare.MapToIPv4();
Debug.WriteLine(ipAddressToCompare);
//skip if the ip does not match
if(!ipAddressToCompare.Equals(ipAddress))
continue;
//return the mac address if the ip matches
return networkInterface.GetPhysicalAddress();
}
}
//not found so return null
return null;
}
To call it you need to pass a URL to connect to like this:
var mac = GetCurrentMAC("www.google.com");
You can also specify a port number. If not specified default is 80.
UPDATES:
2020
This is one way to accomplish this using PowerShell:
<#
.SYNOPSIS
Restores (applies) a previously saved stash based on full or partial stash name.
.DESCRIPTION
Restores (applies) a previously saved stash based on full or partial stash name and then optionally drops the stash. Can be used regardless of whether "git stash save" was done or just "git stash". If no stash matches a message is given. If multiple stashes match a message is given along with matching stash info.
.PARAMETER message
A full or partial stash message name (see right side output of "git stash list"). Can also be "@stash{N}" where N is 0 based stash index.
.PARAMETER drop
If -drop is specified, the matching stash is dropped after being applied.
.EXAMPLE
Restore-Stash "Readme change"
Apply-Stash MyStashName
Apply-Stash MyStashName -drop
Apply-Stash "stash@{0}"
#>
function Restore-Stash {
[CmdletBinding()]
[Alias("Apply-Stash")]
PARAM (
[Parameter(Mandatory=$true)] $message,
[switch]$drop
)
$stashId = $null
if ($message -match "stash@{") {
$stashId = $message
}
if (!$stashId) {
$matches = git stash list | Where-Object { $_ -match $message }
if (!$matches) {
Write-Warning "No stashes found with message matching '$message' - check git stash list"
return
}
if ($matches.Count -gt 1) {
Write-Warning "Found $($matches.Count) matches for '$message'. Refine message or pass 'stash{@N}' to this function or git stash apply"
return $matches
}
$parts = $matches -split ':'
$stashId = $parts[0]
}
git stash apply ''$stashId''
if ($drop) {
git stash drop ''$stashId''
}
}
I believe that I found the correct answer through this dig How To. I was able to look up the SPF records on a specific DNS, by using the following query:
dig @ns1.nameserver1.com domain.com txt
An easy fix to this would be going to the SQL tab and just simply put in the code
ALTER TABLE `tablename`
ADD PRIMARY KEY (`id`);
Asuming that you have a row named id.
It means that in table kontakty
you have a row referencing the row in osoby
you want to delete. You have do delete that row first or set a cascade delete on the relation between tables.
Powodzenia!
I am not sure if this is what you are looking for
if var<>"" then
dosomething
or
if isempty(thisworkbook.sheets("sheet1").range("a1").value)= false then
the ISEMPTY function can be used as well
For centering an image inside a container (it could be a logo) besides some text like this:
Basically you wrap the image
.outer-frame {_x000D_
border: 1px solid red;_x000D_
min-height: 200px;_x000D_
text-align: center; /* Only to align horizontally */_x000D_
}_x000D_
_x000D_
.wrapper{_x000D_
line-height: 200px;_x000D_
border: 2px dashed blue;_x000D_
border-radius: 20px;_x000D_
margin: 50px_x000D_
}_x000D_
_x000D_
img {_x000D_
/* height: auto; */_x000D_
vertical-align: middle; /* Only to align vertically */_x000D_
}
_x000D_
<div class="outer-frame">_x000D_
<div class="wrapper">_x000D_
some text_x000D_
<img src="http://via.placeholder.com/150x150">_x000D_
</div>_x000D_
</div>
_x000D_
Here's how I test javascript using PhantomJS and Django:
mobile/test_no_js_errors.js:
var page = require('webpage').create(),
system = require('system'),
url = system.args[1],
status_code;
page.onError = function (msg, trace) {
console.log(msg);
trace.forEach(function(item) {
console.log(' ', item.file, ':', item.line);
});
};
page.onResourceReceived = function(resource) {
if (resource.url == url) {
status_code = resource.status;
}
};
page.open(url, function (status) {
if (status == "fail" || status_code != 200) {
console.log("Error: " + status_code + " for url: " + url);
phantom.exit(1);
}
phantom.exit(0);
});
mobile/tests.py:
import subprocess
from django.test import LiveServerTestCase
class MobileTest(LiveServerTestCase):
def test_mobile_js(self):
args = ["phantomjs", "mobile/test_no_js_errors.js", self.live_server_url]
result = subprocess.check_output(args)
self.assertEqual(result, "") # No result means no error
Run tests:
manage.py test mobile
Unless I misunderstand your question, you can just open a file read only. Here is a simply example, without any checks.
To get the file path from the user use this function:
Private Function get_user_specified_filepath() As String
'or use the other code example here.
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
fd.Title = "Please select the file."
get_user_specified_filepath = fd.SelectedItems(1)
End Function
Then just open the file read only and assign it to a variable:
dim wb as workbook
set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)
After reviewing Microsoft's TechNet article "Azure Active Directory Cmdlets" -> section "Install the Azure AD Module", it seems that this process has been drastically simplified, thankfully.
As of 2016/06/30, in order to successfully execute the PowerShell commands Import-Module MSOnline
and Connect-MsolService
, you will need to install the following applications (64-bit only):
7.250.4556.0
(latest)msoidcli_64.msi
D077CF49077EE133523C1D3AE9A4BF437D220B16D651005BBC12F7BDAD1BF313
AdministrationConfig-en.msi
3.0
(later versions will probably work too)Windows6.1-KB2506143-x64.msu
I've been looking for a lightweight, dependency free dual slider for some time (it seemed crazy to import jQuery just for this) and there don't seem to be many out there. I ended up modifying @Wildhoney's code a bit and really like it.
function getVals(){_x000D_
// Get slider values_x000D_
var parent = this.parentNode;_x000D_
var slides = parent.getElementsByTagName("input");_x000D_
var slide1 = parseFloat( slides[0].value );_x000D_
var slide2 = parseFloat( slides[1].value );_x000D_
// Neither slider will clip the other, so make sure we determine which is larger_x000D_
if( slide1 > slide2 ){ var tmp = slide2; slide2 = slide1; slide1 = tmp; }_x000D_
_x000D_
var displayElement = parent.getElementsByClassName("rangeValues")[0];_x000D_
displayElement.innerHTML = slide1 + " - " + slide2;_x000D_
}_x000D_
_x000D_
window.onload = function(){_x000D_
// Initialize Sliders_x000D_
var sliderSections = document.getElementsByClassName("range-slider");_x000D_
for( var x = 0; x < sliderSections.length; x++ ){_x000D_
var sliders = sliderSections[x].getElementsByTagName("input");_x000D_
for( var y = 0; y < sliders.length; y++ ){_x000D_
if( sliders[y].type ==="range" ){_x000D_
sliders[y].oninput = getVals;_x000D_
// Manually trigger event first time to display values_x000D_
sliders[y].oninput();_x000D_
}_x000D_
}_x000D_
}_x000D_
}
_x000D_
section.range-slider {_x000D_
position: relative;_x000D_
width: 200px;_x000D_
height: 35px;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
section.range-slider input {_x000D_
pointer-events: none;_x000D_
position: absolute;_x000D_
overflow: hidden;_x000D_
left: 0;_x000D_
top: 15px;_x000D_
width: 200px;_x000D_
outline: none;_x000D_
height: 18px;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
section.range-slider input::-webkit-slider-thumb {_x000D_
pointer-events: all;_x000D_
position: relative;_x000D_
z-index: 1;_x000D_
outline: 0;_x000D_
}_x000D_
_x000D_
section.range-slider input::-moz-range-thumb {_x000D_
pointer-events: all;_x000D_
position: relative;_x000D_
z-index: 10;_x000D_
-moz-appearance: none;_x000D_
width: 9px;_x000D_
}_x000D_
_x000D_
section.range-slider input::-moz-range-track {_x000D_
position: relative;_x000D_
z-index: -1;_x000D_
background-color: rgba(0, 0, 0, 1);_x000D_
border: 0;_x000D_
}_x000D_
section.range-slider input:last-of-type::-moz-range-track {_x000D_
-moz-appearance: none;_x000D_
background: none transparent;_x000D_
border: 0;_x000D_
}_x000D_
section.range-slider input[type=range]::-moz-focus-outer {_x000D_
border: 0;_x000D_
}
_x000D_
<!-- This block can be reused as many times as needed -->_x000D_
<section class="range-slider">_x000D_
<span class="rangeValues"></span>_x000D_
<input value="5" min="0" max="15" step="0.5" type="range">_x000D_
<input value="10" min="0" max="15" step="0.5" type="range">_x000D_
</section>
_x000D_
This very annoying error so what I did: Under Windows:
Edit system environment variables - > Edit Variables -> New
then fill
MAVEN_OPTS
-Xms512m -Xmx2048m -XX:MaxPermSize=512m
Then restart the console and run the maven build again. No more Maven space/perm size problems.
Removing the name from your binding will make it apply to all endpoints, and should produce the desired results. As so:
<services>
<service name="Service.IService">
<clear />
<endpoint binding="basicHttpBinding" contract="Service.IService" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647"
maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</binding>
</basicHttpBinding>
<webHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
</webHttpBinding>
</bindings>
Also note that I removed the bindingConfiguration
attribute from the endpoint node. Otherwise you would get an exception.
This same solution was found here : Problem with large requests in WCF
To round up you can use modulus.
The second part of the equation will add to True if there's a remainder. (True = 1; False = 0)
ex: 3/2
answer=$(((3 / 2) + (3 % 2 > 0)))
echo $answer
2
ex: 100 / 2
answer=$(((100 / 2) + (100 % 2 > 0)))
echo $answer
50
ex: 100 / 3
answer=$(((100 / 3) + (100 % 3 > 0)))
echo $answer
34
As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.
This is some pseudocodish JavaScript:
Client:
var websocket = new WebSocket("server address");
websocket.onmessage = function(str) {
console.log("Someone sent: ", str);
};
// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
id: "client1"
}));
// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
to: "client2",
data: "foo"
}));
Server:
var clients = {};
server.on("data", function(client, str) {
var obj = JSON.parse(str);
if("id" in obj) {
// New client, add it to the id/client object
clients[obj.id] = client;
} else {
// Send data to the client requested
clients[obj.to].send(obj.data);
}
});
In my case, upgraded from spring-securiy-web 3.1.3 to 4.2.12, the defaultHttpFirewall
was changed from DefaultHttpFirewall
to StrictHttpFirewall
by default.
So just define it in XML configuration like below:
<bean id="defaultHttpFirewall" class="org.springframework.security.web.firewall.DefaultHttpFirewall"/>
<sec:http-firewall ref="defaultHttpFirewall"/>
set HTTPFirewall
as DefaultHttpFirewall
Open your php.ini and uncomment this line:
;extension=php_gd2.dll
In the mongo shell, if the returned cursor is not assigned to a variable using the var keyword, the cursor is automatically iterated to access up to the first 20 documents that match the query. You can set the DBQuery.shellBatchSize variable to change the number of automatically iterated documents.
Reference - https://docs.mongodb.com/v3.2/reference/method/db.collection.find/
You have the field in a string, so you'll need to convert it to datetime
order by CONVERT(datetime, EventDate ) desc
Additionally if you want to know which extensions are available on your server: SELECT * FROM pg_available_extensions
Here's the C# integrated syntax version:
var items =
from list in listOfList
from item in list
select item;
function foo([a,b,c], d){
console.log(a,b,c,d);
}
foo([1,2,3], 4)
_x000D_
function foo(a, b, c, d){
console.log(a, b, c, d);
}
foo(...[1, 2, 3], 4)
_x000D_
Create a Empty Guid or New Guid Using a Class...
Default value of Guid is 00000000-0000-0000-0000-000000000000
public class clsGuid ---This is class Name
{
public Guid MyGuid { get; set; }
}
static void Main(string[] args)
{
clsGuid cs = new clsGuid();
Console.WriteLine(cs.MyGuid); --this will give empty Guid "00000000-0000-0000-0000-000000000000"
cs.MyGuid = new Guid();
Console.WriteLine(cs.MyGuid); ----this will also give empty Guid "00000000-0000-0000-0000-000000000000"
cs.MyGuid = Guid.NewGuid();
Console.WriteLine(cs.MyGuid); --this way, it will give new guid "d94828f8-7fa0-4dd0-bf91-49d81d5646af"
Console.ReadKey(); --this line holding the output screen in console application...
}
I recommend using the incredible requests
module.
http://docs.python-requests.org/en/v0.10.7/user/quickstart/#custom-headers
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
response = requests.post(url, data=json.dumps(payload), headers=headers)
sorry for reviving this thread, but thought my method was worth adding.
The list name in this example 'list'
list.sort()
print(list[-1])
That will print the highest value in the list easy as!
list.sort()
sorts the list by the value of the item in the ASCII table, so effectively sorts the list lowest to highest. I then just print the last value in the list (which will be the greatest number) by using print(list[-1])
.
Hope this helps!
In latest IntelliJ versions, you should run it from Analyze->Run Inspection By Name:
Than, pick Unused declaration:
And finally, uncheck the Include test sources:
here is a working version :
function countbackgrounds() {
var book = SpreadsheetApp.getActiveSpreadsheet();
var range_input = book.getRange("B3:B4");
var range_output = book.getRange("B6");
var cell_colors = range_input.getBackgroundColors();
var color = "#58FA58";
var count = 0;
for( var i in cell_colors ){
Logger.log(cell_colors[i][0])
if( cell_colors[i][0] == color ){ ++count }
}
range_output.setValue(count);
}
Here's another method that's unorthodox, but works*.
I recently found myself in a situation where I'd checked in breaking code, knowing that I couldn't update our production code to it until all the integration work had taken place (in retrospect this was a bad decision, but we didn't expect to get stalled out, but other projects took precedence). That was several months ago, and the integration has been stalled for that entire time. Along comes a requirement to change the base code and get it into production last week without the breaking change.
Here's what we did:
After verifying that the new requirement doesn't break anything when using the revision before my check in, I made a copy of the working directory containing the new code. Then I deleted everything in the working directory and checked out the revision I wanted to it. Then I deleted all the files I'd just checked out, and copied in the files from the working copy. Then I committed that change, effectively wiping out the breaking change from the repository and getting the production code in place as the head revision. We still have the breaking change available, but it's no longer in the head revision so we can move forward to production.
*I don't recommend this method, but if you find yourself in a similar situation, it's a way out that's not too painful.
I had a problem with this because my server ABSOLUTELY had to have its date in MM/dd/yyyy format, while I wanted the directory to be in YYYY-MM-DD format for neatness sake. Here's how to get it in YYYY-MM-DD format, no matter what your regional settings are set as.
Find out what gets displayed when you use %DATE%:
From a command prompt type:
ECHO %DATE%
Mine came out 03/06/2013 (as in 6th March 2013)
Therefore, to get a directory name as 2013-03-06, code this into your batch file:
SET dirname="%date:~6,4%-%date:~0,2%-%date:~3,2%"
mkdir %dirname%
You can use the focusout event to detect keyboard dismissal. It's like blur, but bubbles. It will fire when the keyboard closes (but also in other cases, of course). In Safari and Chrome the event can only be registered with addEventListener, not with legacy methods. Here is an example I used to restore a Phonegap app after keyboard dismissal.
document.addEventListener('focusout', function(e) {window.scrollTo(0, 0)});
Without this snippet, the app container stayed in the up-scrolled position until page refresh.
int var = 20;
cout << &var << endl;
cout << (int)&var << endl;
cout << std::hex << "0x" << (int)&var << endl << std::dec; // output in hex, reset back to dec
0x69fec4 (address)
6946500 (address to dec)
0x69fec4 (address to dec, output in hex)
instinctively went with this...
int address = (int)&var;
saw this elsewhere...
unsigned long address = reinterpret_cast(&var);
comment told me this is correct...
int address = (int)&var;
speaking of well covered lightness, where are you at? they're getting too many likes!
We have developed a process that treats load and performance measurenment as a first-class concern - as you say, leaving it to the end of the project tends to lead to disappointment...
So, during development, we include very basic multi-user testing (using selenium), which checks for basic craziness like broken session management, obvious concurrency issues, and obvious resource contention problems. Non-trivial projects include this in the continuous integration process, so we get very regular feedback.
For projects that don't have extreme performance requirements, we include basic performance testing in our testing; usually, we script out the tests using BadBoy, and import them into JMeter, replacing the login details and other thread-specific things. We then ramp these up to the level that the server is dealing with 100 requests per second; if the response time is less than 1 second, that's usually sufficient. We launch and move on with our lives.
For projects with extreme performance requirements, we still use BadBoy and JMeter, but put a lot of energy into understanding the bottlenecks on the servers on our test rig(web and database servers, usually). There's a good tool for analyzing Microsoft event logs which helps a lot with this. We typically find unexpected bottlenecks, which we optimize if possible; that gives us an application that is as fast as it can be on "1 web server, 1 database server". We then usually deploy to our target infrastructure, and use one of the "Jmeter in the cloud" services to re-run the tests at scale.
Again, PAL reports help to analyze what happened during the tests - you often see very different bottlenecks on production environments.
The key is to make sure you don't just run your stress tests, but also that you collect the information you need to understand the performance of your application.
Drawing text in plain OpenGL isn't a straigth-forward task. You should probably have a look at libraries for doing this (either by using a library or as an example implementation).
Some good starting points could be GLFont, OpenGL Font Survey and NeHe Tutorial for Bitmap Fonts (Windows).
Note that bitmaps are not the only way of achieving text in OpenGL as mentioned in the font survey.
You can also test them as a couple.
if (i,ii)==(5,10):
print "i is 5 and ii is 10"
make sure that your schema name is in the connection string?
Few hints to handle such error/exception for Android Apps:
Activities & Application have methods like:
tag in Manifest can have attribute 'largeHeap' set to TRUE, which requests more heap for App sandbox.
Managing in-memory caching & disk caching:
Use of WeakReference, SoftReference of Java instance creation , specifically to files.
If so many images, use proper library/data structure which can manage memory, use samling of images loaded, handle disk-caching.
Handle OutOfMemory exception
Follow best practices for coding
Minimize activity stack e.g. number of activities in stack (Don't hold everything on context/activty)
Minimize the use of statics, many more singletons.
Take care of OS basic memory fundametals
Involk GC.Collect() manually sometimes when you are sure that in-memory caching no more needed.
Here is some weak adobe documentation on different flash 9 wmode settings.
A note of caution on wmode transparent is here in the adobe bug trac.
And new for flash 10, are two new wmodes: gpu and direct. Please refer to Adobe Knowledge Base about wmode.
you need to cast from long
to int
explicitly
in case of i = i + l
then it will compile and give correct output. like
i = i + (int)l;
or
i = (int)((long)i + l); // this is what happens in case of += , dont need (long) casting since upper casting is done implicitly.
but in case of +=
it just works fine because the operator implicitly does the type casting from type of right variable to type of left variable so need not cast explicitly.
This happens when you specify the incorrect position for the notifyItemChanged , notifyItemRangeInserted etc.For me :
Before : (Erroneous)
public void addData(List<ChannelItem> list) {
int initialSize = list.size();
mChannelItemList.addAll(list);
notifyItemRangeChanged(initialSize - 1, mChannelItemList.size());
}
After : (Correct)
public void addData(List<ChannelItem> list) {
int initialSize = mChannelItemList.size();
mChannelItemList.addAll(list);
notifyItemRangeInserted(initialSize, mChannelItemList.size()-1); //Correct position
}
I think Michal's approach is better. But, there is one more way to get the result out of the native query.
@Query(value = "SELECT g.*, gm.* FROM group g LEFT JOIN group_members gm ON g.group_id = gm.group_id and gm.user_id = :userId WHERE g.group_id = :groupId", nativeQuery = true)
String[][] getGroupDetails(@Param("userId") Integer userId, @Param("groupId") Integer groupId);
Now, you can convert this 2D string array into your desired entity.
One more thing that I would definitely like to highlight as logit is just a raw output, generally the output of last layer. This can be a negative value as well. If we use it as it's for "cross entropy" evaluation as mentioned below:
-tf.reduce_sum(y_true * tf.log(logits))
then it wont work. As log of -ve is not defined. So using o softmax activation, will overcome this problem.
This is my understanding, please correct me if Im wrong.
To add to the answer.
declare
v_result clob;
begin
---- some operation on v_result
dbms_lob.substr( v_result, 4000 ,length(v_result) - 3999 );
end;
/
In dbms_lob.substr
first parameter
is clob
which you want to extract .
Second parameter
is how much length of clob you want to extract.
Third parameter
is from which word you want to extract .
In above example i know my clob size is more than 50000 , so i want last 4000 character .
In regards to problems with Qt4, I couldn't use the qmake moc option mentioned above. But that wasn't the problem anyway. I had the following code in the class definition:
class ScreenWidget : public QGLWidget
{
Q_OBJECT // must include this if you use Qt signals/slots
...
};
I had to remove the line "Q_OBJECT" because I had no signals or slots defined.
A snippet I found at http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=21021 that helped me:
select t.name TableName, i.rows Records
from sysobjects t, sysindexes i
where t.xtype = 'U' and i.id = t.id and i.indid in (0,1)
order by TableName;
As many times I have to copy data from SQL to excel, I've created function to deal with with new line and also tab characters (which make shifts in columns after pasting to Excel).
CREATE FUNCTION XLS(@String NVARCHAR(MAX) )
RETURNS NVARCHAR(MAX)
AS
BEGIN
SET @String = REPLACE (@String, CHAR(9), ' ')
SET @String = REPLACE (@String, CHAR(10), ' ')
SET @String = REPLACE (@String, CHAR(13), ' ')
RETURN @String
END
CREATE FUNCTION XLS(@String NVARCHAR(MAX) )
RETURNS NVARCHAR(MAX)
AS
BEGIN
SET @String = REPLACE (@String, CHAR(9), ' ')
SET @String = REPLACE (@String, CHAR(10), ' ')
SET @String = REPLACE (@String, CHAR(13), ' ')
RETURN @String
END
Example usage:
SELECT dbo.XLS(Description) FROM Server_Inventory
You could just use list comprehension:
property_asel = [val for is_good, val in zip(good_objects, property_a) if is_good]
or
property_asel = [property_a[i] for i in good_indices]
The latter one is faster because there are fewer good_indices
than the length of property_a
, assuming good_indices
are precomputed instead of generated on-the-fly.
Edit: The first option is equivalent to itertools.compress
available since Python 2.7/3.1. See @Gary Kerr's answer.
property_asel = list(itertools.compress(property_a, good_objects))
Neither hacking PYTHONPATH
nor sys.path
is a good idea due to the before mentioned reasons. And for linking the current project into the site-packages folder there is actually a better way than python setup.py develop
, as explained here:
pip install --editable path/to/project
If you don't already have a setup.py in your project's root folder, this one is good enough to start with:
from setuptools import setup
setup('project')
You can build your HttpContent
using the combination of JObject
to avoid and JProperty
and then call ToString()
on it when building the StringContent
:
/*{
"agent": {
"name": "Agent Name",
"version": 1
},
"username": "Username",
"password": "User Password",
"token": "xxxxxx"
}*/
JObject payLoad = new JObject(
new JProperty("agent",
new JObject(
new JProperty("name", "Agent Name"),
new JProperty("version", 1)
),
new JProperty("username", "Username"),
new JProperty("password", "User Password"),
new JProperty("token", "xxxxxx")
)
);
using (HttpClient client = new HttpClient())
{
var httpContent = new StringContent(payLoad.ToString(), Encoding.UTF8, "application/json");
using (HttpResponseMessage response = await client.PostAsync(requestUri, httpContent))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return JObject.Parse(responseBody);
}
}
I create a temporary file during execution.
This is how I do it:
#!/bin/sh
# check if lock file exists
if [ -e /tmp/script.lock ]; then
echo "script is already running"
else
# create a lock file
touch /tmp/script.lock
echo "run script..."
#remove lock file
rm /tmp/script.lock
fi
I had the same problem. At least I could solve it with this:
sudo yum install gcc gcc-c++
Hope it solves your problem too.
I wanted to pick up specific links within a DOM element on a page, send those users to a redirect page on a timer and then pass them onto the original clicked URL. This is how I did it using regular javascript incorporating one of the methods above.
Page with links: Head
function replaceLinks() {
var content = document.getElementById('mainContent');
var nodes = content.getElementsByTagName('a');
for (var i = 0; i < document.getElementsByTagName('a').length; i++) {
{
href = nodes[i].href;
if (href.indexOf("thisurl.com") != -1) {
nodes[i].href="http://www.thisurl.com/redirect.aspx" + "?url=" + nodes[i];
nodes[i].target="_blank";
}
}
}
}
Body
<body onload="replaceLinks()">
Redirect page Head
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
function delayer(){
window.location = getQueryVariable('url')
}
Body
<body onload="setTimeout('delayer()', 1000)">
I recently had to resolve this issue and here's what I did :
First of all, this solution is around tuning Apache server.
Second main think is that there's a bug in the IE9 which means that the meta tag will not work, instead of this solution try this
uncomment/or add the following line
LoadModule headers_module modules/mod_headers.so
add the following lines
<IfModule headers_module>
Header set X-UA-Compatible: IE=EmulateIE8
</IfModule>
save/restart your Apache server,
String w1 ="Sarat";
String w2 ="Sarat";
String w3 = new String("Sarat");
System.out.println(w1.hashCode()); //3254818
System.out.println(w2.hashCode()); //3254818
System.out.println(w3.hashCode()); //3254818
System.out.println(System.identityHashCode(w1)); //prints 705927765
System.out.println(System.identityHashCode(w2)); //prints 705927765
System.out.println(System.identityHashCode(w3)); //prints 366712642
if(w1==w2) // (705927765==705927765)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
//prints true
if(w2==w3) // (705927765==366712642)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
//prints false
if(w2.equals(w3)) // (Content of 705927765== Content of 366712642)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
//prints true
I'm surprised no one offered this answer. It's not as "built-in" as Ruby's ||=
but it's basically equivalent and still a one-liner:
foo = foo if 'foo' in locals() else 'default'
Of course, locals()
is just a dictionary, so you can do:
foo = locals().get('foo', 'default')
Typing SHOW GRANTS FOR 'root'@'localhost';
showed me some obscured password, so I logged into mysql of that system using HeidiSQL on another system (using root
as the username and the corresponding password) and typed
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY 'thepassword' WITH GRANT OPTION;
and it worked when I went back to the system and logged on using
mysql -uroot -pthepassword;
I ran into a similar issue today - my ruby version didn't match my rvm installs.
> ruby -v
ruby 2.0.0p481
> rvm list
rvm rubies
ruby-2.1.2 [ x86_64 ]
=* ruby-2.2.1 [ x86_64 ]
ruby-2.2.3 [ x86_64 ]
Also, rvm current
failed.
> rvm current
Warning! PATH is not properly set up, '/Users/randallreed/.rvm/gems/ruby-2.2.1/bin' is not at first place...
The error message recommended this useful command, which resolved the issue for me:
> rvm get stable --auto-dotfiles
If you're using the assigned generator, using merge
instead of persist
can cause a redundant SQL statement, therefore affecting performance.
Also, calling merge
for managed entities is also a mistake since managed entities are automatically managed by Hibernate, and their state is synchronized with the database record by the dirty checking mechanism upon flushing the Persistence Context.
To understand how all this works, you should first know that Hibernate shifts the developer mindset from SQL statements to entity state transitions.
Once an entity is actively managed by Hibernate, all changes are going to be automatically propagated to the database.
Hibernate monitors currently attached entities. But for an entity to become managed, it must be in the right entity state.
To understand the JPA state transitions better, you can visualize the following diagram:
Or if you use the Hibernate specific API:
As illustrated by the above diagrams, an entity can be in one of the following four states:
A newly created object that hasn’t ever been associated with a Hibernate Session
(a.k.a Persistence Context
) and is not mapped to any database table row is considered to be in the New (Transient) state.
To become persisted we need to either explicitly call the EntityManager#persist
method or make use of the transitive persistence mechanism.
Persistent (Managed)
A persistent entity has been associated with a database table row and it’s being managed by the currently running Persistence Context. Any change made to such an entity is going to be detected and propagated to the database (during the Session flush-time).
With Hibernate, we no longer have to execute INSERT/UPDATE/DELETE statements. Hibernate employs a transactional write-behind working style and changes are synchronized at the very last responsible moment, during the current Session
flush-time.
Detached
Once the currently running Persistence Context is closed all the previously managed entities become detached. Successive changes will no longer be tracked and no automatic database synchronization is going to happen.
To associate a detached entity to an active Hibernate Session, you can choose one of the following options:
Reattaching
Hibernate (but not JPA 2.1) supports reattaching through the Session#update method.
A Hibernate Session can only associate one Entity object for a given database row. This is because the Persistence Context acts as an in-memory cache (first level cache) and only one value (entity) is associated with a given key (entity type and database identifier).
An entity can be reattached only if there is no other JVM object (matching the same database row) already associated with the current Hibernate Session.
Merging
The merge is going to copy the detached entity state (source) to a managed entity instance (destination). If the merging entity has no equivalent in the current Session, one will be fetched from the database.
The detached object instance will continue to remain detached even after the merge operation.
Remove
Although JPA demands that managed entities only are allowed to be removed, Hibernate can also delete detached entities (but only through a Session#delete method call).
A removed entity is only scheduled for deletion and the actual database DELETE statement will be executed during Session flush-time.
For Visual Studio for Mac users (e.g. who installed Android SDK together with VS):
You can find JDK, Android NDK and Android SDK localizations there (if installed and selected). If no Android SDK path found, you may try to find it using Android Studio (if it is installed)
In Linux every process has its own folder in /proc
. So you could use getpid()
to get the pid of the running process and then join it with the path /proc
to get the folder you hopefully need.
Here's a short example in Python:
import os
print os.path.join('/proc', str(os.getpid()))
Here's the example in ANSI C as well:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int
main(int argc, char **argv)
{
pid_t pid = getpid();
fprintf(stdout, "Path to current process: '/proc/%d/'\n", (int)pid);
return EXIT_SUCCESS;
}
Compile it with:
gcc -Wall -Werror -g -ansi -pedantic process_path.c -oprocess_path
def get_dict_from_pd(df, key_col, row_col):
result = dict()
for i in set(df[key_col].values):
is_i = df[key_col] == i
result[i] = list(df[is_i][row_col].values)
return result
this is my sloution, a basic loop
As a late corolloary to the earlier answers here, you probably end up in situations where you want some but not all variables to be interpolated. You can solve that by using backslashes to escape dollar signs and backticks; or you can put the static text in a variable.
Name='Rich Ba$tard'
dough='$$$dollars$$$'
cat <<____HERE
$Name, you can win a lot of $dough this week!
Notice that \`backticks' need escaping if you want
literal text, not `pwd`, just like in variables like
\$HOME (current value: $HOME)
____HERE
Demo: https://ideone.com/rMF2XA
Note that any of the quoting mechanisms -- \____HERE
or "____HERE"
or '____HERE'
-- will disable all variable interpolation, and turn the here-document into a piece of literal text.
A common task is to combine local variables with script which should be evaluated by a different shell, programming language, or remote host.
local=$(uname)
ssh -t remote <<:
echo "$local is the value from the host which ran the ssh command"
# Prevent here doc from expanding locally; remote won't see backslash
remote=\$(uname)
# Same here
echo "\$remote is the value from the host we ssh:ed to"
:
If you want the entire package name with it, call:
String name = MyClass.class.getCanonicalName();
If you only want the last element, call:
String name = MyClass.class.getSimpleName();
I'm using SourceTree along with TortoiseMerge/Diff, which is very easy and convinient diff/merge tool.
If you'd like to use it as well, then:
Get standalone version of TortoiseMerge/Diff (quite old, since it doesn't ship standalone since version 1.6.7 of TortosieSVN, that is since July 2011). Links and details in this answer.
Unzip TortoiseIDiff.exe
and TortoiseMerge.exe
to any folder (c:\Program Files (x86)\Atlassian\SourceTree\extras\
in my case).
In SourceTree open Tools > Options > Diff > External Diff / Merge
. Select TortoiseMerge
in both dropdown lists.
Hit OK
and point SourceTree to your location of TortoiseIDiff.exe
and TortoiseMerge.exe
.
After that, you can select Resolve Conflicts > Launch External Merge Tool
from context menu on each conflicted file in your local repository. This will open up TortoiseMerge, where you can easily deal with all the conflicts, you have. Once finished, simply close TortoiseMerge (you don't even need to save changes, this will probably be done automatically) and after few seconds SourceTree should handle that gracefully.
The only problem is, that it automatically creates backup copy, even though proper option is unchecked.
if($('#testElement').is(':visible')){
//what you want to do when is visible
}
in my case was a wrong path in a config file: file was not found (path was wrong) and it came out with this exception:
Error configuring from input stream. Initial cause was The processing instruction target matching "[xX][mM][lL]" is not allowed.
I was using folder name As test&demo so it was giving this problem (VM terminated without saying properly goodbye. VM crash or System.exit called),but When i gave folder name as test_demo then it solved this issue.(this problem is there with windows OS with "&" symbol.)
Replace "&" to "_"
This problem may cause with some special symbol or extra space in folder name.
UPDATE: Supposedly, zIndex
has been added to the react-native
library. I've been trying to get it to work without success. Check here for details of the fix.
This piece of code is incorrect.
while 1:
(clientsocket, address) = serversocket.accept()
print ("connection found!")
data = clientsocket.recv(1024).decode()
print (data)
r='REceieve'
clientsocket.send(r.encode())
The call on accept()
on the serversocket
blocks until there's a client connection. When you first connect to the server from the client, it accepts the connection and receives data. However, when it enters the loop again, it is waiting for another connection and thus blocks as there are no other clients that are trying to connect.
That's the reason the recv
works correct only the first time. What you should do is find out how you can handle the communication with a client that has been accepted - maybe by creating a new Thread to handle communication with that client and continue accepting new clients in the loop, handling them in the same way.
Tip: If you want to work on creating your own chat application, you should look at a networking engine like Twisted. It will help you understand the whole concept better too.
One possibility is to delete to cookie you are looking for the expiration date from and rewrite it. Then you'll know the expiration date.
I keep looking for a built in solution to this problem like there is in AngularJS. But until then this solution works for me, It's simple, and preserves back button functionality.
app.component.html
<router-outlet (deactivate)="onDeactivate()"></router-outlet>
app.component.ts
onDeactivate() {
document.body.scrollTop = 0;
// Alternatively, you can scroll to top by using this other call:
// window.scrollTo(0, 0)
}
Answer from zurfyx original post
I've been wondering if there was a simple way to download a file in a more ... "generic" way. I came up with this.
It's a simple ActionResult
that will allow you to download a file from a controller call that returns an IHttpActionResult
.
The file is stored in the byte[] Content
. You can turn it into a stream if needs be.
I used this to return files stored in a database's varbinary column.
public class FileHttpActionResult : IHttpActionResult
{
public HttpRequestMessage Request { get; set; }
public string FileName { get; set; }
public string MediaType { get; set; }
public HttpStatusCode StatusCode { get; set; }
public byte[] Content { get; set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
HttpResponseMessage response = new HttpResponseMessage(StatusCode);
response.StatusCode = StatusCode;
response.Content = new StreamContent(new MemoryStream(Content));
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = FileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue(MediaType);
return Task.FromResult(response);
}
}
From what I've been able to piece together, you have to add the view using LayoutParams.
LinearLayout linearLayout = new LinearLayout(this);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
relativeParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
parentView.addView(linearLayout, relativeParams);
All credit to sechastain, to relatively position your items programmatically you have to assign ids to them.
TextView tv1 = new TextView(this);
tv1.setId(1);
TextView tv2 = new TextView(this);
tv2.setId(2);
Then addRule(RelativeLayout.RIGHT_OF, tv1.getId());
This is an adaptable version of the amazing solution provided by @Gildas.Tambo elsewhere in this page. Simply change the values of the variables at the top to change the size of the "X".
Credit for the solution itself goes to Gildas. All I've done is given it adaptable math.
:root {
/* Width and height of the box containing the "X" */
--BUTTON_W: 40px;
/* This is the length of either of the 2 lines which form the "X", as a
percentage of the width of the button. */
--CLOSE_X_W: 95%;
/* Thickness of the lines of the "X" */
--CLOSE_X_THICKNESS: 4px;
}
body{
background:blue;
}
div{
width: var(--BUTTON_W);
height: var(--BUTTON_W);
background-color:red;
position: relative;
border-radius: 6px;
box-shadow: 2px 2px 4px 0 white;
}
/* The "X" in the button. "before" and "after" each represent one of the two lines of the "X" */
div:before,div:after{
content: '';
position: absolute;
width: var(--CLOSE_X_W);
height: var(--CLOSE_X_THICKNESS);
background-color:white;
border-radius: 2px;
top: calc(50% - var(--CLOSE_X_THICKNESS) / 2);
box-shadow: 0 0 2px 0 #ccc;
}
/* One line of the "X" */
div:before{
-webkit-transform:rotate(45deg);
-moz-transform: rotate(45deg);
transform: rotate(45deg);
left: calc((100% - var(--CLOSE_X_W)) / 2);
}
/* The other line of the "X" */
div:after{
-webkit-transform:rotate(-45deg);
-moz-transform: rotate(-45deg);
transform: rotate(-45deg);
right: calc((100% - var(--CLOSE_X_W)) / 2);
}
_x000D_
<div></div>
_x000D_
Run into the same issue when i switch to ubuntu from windows 10.. the following worked for me.. this after googling and trying numerous suggestions for 2 hours...
sudo apt-get install libpq-dev, then pip3 install psycopg2
I hope this helps someone who has encountered the same problem especially when switching for windows OS to linux(ubuntu).
This function should do what you want:
char* readLine( FILE* file )
{
char buffer[1024];
char* result = 0;
int length = 0;
while( !feof(file) )
{
fgets( buffer, sizeof(buffer), file );
int len = strlen(buffer);
buffer[len] = 0;
length += len;
char* tmp = (char*)malloc(length+1);
tmp[0] = 0;
if( result )
{
strcpy( tmp, result );
free( result );
result = tmp;
}
strcat( result, buffer );
if( strstr( buffer, "\n" ) break;
}
return result;
}
char* line = readLine( stdin );
/* Use it */
free( line );
I hope this helps.
Bootstrap Tokenfield seems good too: http://sliptree.github.io/bootstrap-tokenfield/
As of July 2018 and the release of RxJS 6
, the new way to get an Observable from a value is to import the of
operator like so:
import { of } from 'rxjs';
and then create the observable from the value, like so:
of(someValue);
Note, that you used to have to do Observable.of(someValue)
like in the currently accepted answer. There is a good article on the other RxJS 6 changes here.
Create a new "Empty Project" , Add your Cpp file to the new project, delete the line that includes stdafx.
Done.
The project no longer needs the stdafx. It is added automatically when you create projects with installed templates.
The JSON reference states:
any-Unicode-character- except-"-or-\\-or- control-character
Then lists the standard escape codes:
\" Standard JSON quote \\ Backslash (Escape char) \/ Forward slash \b Backspace (ascii code 08) \f Form feed (ascii code 0C) \n Newline \r Carriage return \t Horizontal Tab \u four-hex-digits
From this I assumed that I needed to escape all the listed ones and all the other ones are optional. You can choose to encode all characters into \uXXXX
if you so wished, or you could only do any non-printable 7-bit ASCII characters or characters with Unicode value not in \u0020 <= x <= \u007E
range (32 - 126)
. Preferably do the standard characters first for shorter escape codes and thus better readability and performance.
Additionally you can read point 2.5 (Strings) from RFC 4627.
You may (or may not) want to (further) escape other characters depending on where you embed that JSON string, but that is outside the scope of this question.
Try: Window -> Preferences -> Android -> LogCat. Change field "Show logcat view if ..." the value "VERBOSE". It helped me.
Got similar issue while trying Azure Sample first-serverless-app.
Here is the info of how i resolved by removing \ at front of $web.
Note: $web container was created automatically while enable static website. Never seen $root container anywhere.
//getting Invalid URI error while following tutorial as-is
az storage blob upload-batch -s . -d \$web --account-name firststgaccount01
//Remove "\" @destination param
az storage blob upload-batch -s . -d $web --account-name firststgaccount01
Edit: it seems nginx now supports error_log stderr;
as mentioned in Anon's answer.
You can send the logs to /dev/stdout
. In nginx.conf
:
daemon off;
error_log /dev/stdout info;
http {
access_log /dev/stdout;
...
}
edit: May need to run ln -sf /proc/self/fd /dev/ if using running certain docker containers, then use /dev/fd/1
or /dev/fd/2
The fact that the ternary operator is an expression, not a statement, allows it to be used in macro expansions for function-like macros that are used as part of an expression. Const may not have been part of original C, but the macro pre-processor goes way back.
One place where I've seen it used is in an array package that used macros for bound-checked array accesses. The syntax for a checked reference was something like aref(arrayname, type, index)
, where arrayname was actually a pointer to a struct that included the array bounds and an unsigned char array for the data, type was the actual type of the data, and index was the index. The expansion of this was quite hairy (and I'm not going to do it from memory), but it used some ternary operators to do the bound checking.
You can't do this as a function call in C because of the need for polymorphism of the returned object. So a macro was needed to do the type casting in the expression. In C++ you could do this as a templated overloaded function call (probably for operator[]), but C doesn't have such features.
Edit: Here's the example I was talking about, from the Berkeley CAD array package (glu 1.4 edition). The documentation of the array_fetch usage is:
type
array_fetch(type, array, position)
typeof type;
array_t *array;
int position;
Fetch an element from an array. A runtime error occurs on an attempt to reference outside the bounds of the array. There is no type-checking that the value at the given position is actually of the type used when dereferencing the array.
and here is the macro defintion of array_fetch (note the use of the ternary operator and the comma sequencing operator to execute all the subexpressions with the right values in the right order as part of a single expression):
#define array_fetch(type, a, i) \
(array_global_index = (i), \
(array_global_index >= (a)->num) ? array_abort((a),1) : 0,\
*((type *) ((a)->space + array_global_index * (a)->obj_size)))
The expansion for array_insert ( which grows the array if necessary, like a C++ vector) is even hairier, involving multiple nested ternary operators.
You also can replace large text for email template at run time, here is an simple example for that.
DECLARE @xml NVARCHAR(MAX)
SET @xml = CAST((SELECT [column] AS 'td','',
,[StartDate] AS 'td'
FROM [table]
FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))
select REPLACE((EmailTemplate), '[@xml]', @xml) as Newtemplate
FROM [dbo].[template] where id = 1
You can easily use ng-show such as :
<div ng-repeater="item in items">
<div>{{item.description}}</div>
<div ng-show="isExists(item)">available</div>
<div ng-show="!isExists(item)">oh no, you don't have it</div>
</div>
For more complex tests, you can use ng-switch statements :
<div ng-repeater="item in items">
<div>{{item.description}}</div>
<div ng-switch on="isExists(item)">
<span ng-switch-when="true">Available</span>
<span ng-switch-default>oh no, you don't have it</span>
</div>
</div>
Here are some ways to edit the text and the size of the box:
rows="insertNumber"
cols="insertNumber"
style="font-size:12pt"
Example:
<textarea rows="5" cols="30" style="font-size: 12pt" id="myText">Enter
Text Here</textarea>
I think random.choice()
is a better option.
import numpy as np
mylist = [13,23,14,52,6,23]
np.random.choice(mylist, 3, replace=False)
the function returns an array of 3 randomly chosen values from the list
I just ran into this problem and stumbled across a different situation. Although it's probably just a unicorn, I thought I'd lay it out.
I had one session that was smaller, and I noticed that the font sizes were different: the smaller session had the smaller fonts. Apparently, I had changed window font sizes for some reason.
So in OS X, I just did Cmd-+
on the smaller sized session, and it snapped back into place.
There are three approaches
Use SublimeCodeIntel plug-in
Use CTags plug-in
Generate .sublime-completion file manually
Approaches are described in detail in this blog post (of mine): http://opensourcehacker.com/2013/03/04/javascript-autocompletions-and-having-one-for-sublime-text-2/
The only difference between Equal and == is on object type comparison. in other cases, such as reference types and value types, they are almost the same(either both are bit-wise equality or both are reference equality).
object: Equals: bit-wise equality ==: reference equality
string: (equals and == are the same for string, but if one of string changed to object, then comparison result will be different) Equals: bit-wise equality == : bit-wise equality
See here for more explanation.
First of all, you should never use the money datatype. If you do any calculations you will get truncated results. Run the following to see what I mean
DECLARE
@mon1 MONEY,
@mon2 MONEY,
@mon3 MONEY,
@mon4 MONEY,
@num1 DECIMAL(19,4),
@num2 DECIMAL(19,4),
@num3 DECIMAL(19,4),
@num4 DECIMAL(19,4)
SELECT
@mon1 = 100, @mon2 = 339, @mon3 = 10000,
@num1 = 100, @num2 = 339, @num3 = 10000
SET @mon4 = @mon1/@mon2*@mon3
SET @num4 = @num1/@num2*@num3
SELECT @mon4 AS moneyresult,
@num4 AS numericresult
Output: 2949.0000 2949.8525
Now to answer your question (it was a little vague), the money datatype always has two places after the decimal point. Use the integer datatype if you don't want the fractional part or convert to int.
Perhaps you want to use the decimal or numeric datatype?
I have had good success over the last two years or so using Navicat for MySQL. The UI could use a little updating, but all of the tools and options they provide make the cost justifiable for me.
js-uri (available on Google Code) takes a string URL and resolves a URI object from it:
var some_uri = new URI("http://www.example.com/foo/bar");
alert(some_uri.authority); // www.example.com
alert(some_uri); // http://www.example.com/foo/bar
var blah = new URI("blah");
var blah_full = blah.resolve(some_uri);
alert(blah_full); // http://www.example.com/foo/blah
In case you want the difference recursively going deep into items of your list, I have written a package for python: https://github.com/erasmose/deepdiff
Install from PyPi:
pip install deepdiff
If you are Python3 you need to also install:
pip install future six
>>> from deepdiff import DeepDiff
>>> from pprint import pprint
>>> from __future__ import print_function
Same object returns empty
>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = t1
>>> ddiff = DeepDiff(t1, t2)
>>> print (ddiff.changes)
{}
Type of an item has changed
>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:"2", 3:3}
>>> ddiff = DeepDiff(t1, t2)
>>> print (ddiff.changes)
{'type_changes': ["root[2]: 2=<type 'int'> vs. 2=<type 'str'>"]}
Value of an item has changed
>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:4, 3:3}
>>> ddiff = DeepDiff(t1, t2)
>>> print (ddiff.changes)
{'values_changed': ['root[2]: 2 ====>> 4']}
Item added and/or removed
>>> t1 = {1:1, 2:2, 3:3, 4:4}
>>> t2 = {1:1, 2:4, 3:3, 5:5, 6:6}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff.changes)
{'dic_item_added': ['root[5, 6]'],
'dic_item_removed': ['root[4]'],
'values_changed': ['root[2]: 2 ====>> 4']}
String difference
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world"}}
>>> t2 = {1:1, 2:4, 3:3, 4:{"a":"hello", "b":"world!"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
{ 'values_changed': [ 'root[2]: 2 ====>> 4',
"root[4]['b']:\n--- \n+++ \n@@ -1 +1 @@\n-world\n+world!"]}
>>>
>>> print (ddiff.changes['values_changed'][1])
root[4]['b']:
---
+++
@@ -1 +1 @@
-world
+world!
String difference 2
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world!\nGoodbye!\n1\n2\nEnd"}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n1\n2\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
{ 'values_changed': [ "root[4]['b']:\n--- \n+++ \n@@ -1,5 +1,4 @@\n-world!\n-Goodbye!\n+world\n 1\n 2\n End"]}
>>>
>>> print (ddiff.changes['values_changed'][0])
root[4]['b']:
---
+++
@@ -1,5 +1,4 @@
-world!
-Goodbye!
+world
1
2
End
Type change
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n\n\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
{ 'type_changes': [ "root[4]['b']: [1, 2, 3]=<type 'list'> vs. world\n\n\nEnd=<type 'str'>"]}
List difference
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
{ 'list_removed': ["root[4]['b']: [3]"]}
List difference 2: Note that it DOES NOT take order into account
>>> # Note that it DOES NOT take order into account
... t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
{ }
List that contains dictionary:
>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:1, 2:2}]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:3}]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff.changes, indent = 2)
{ 'dic_item_removed': ["root[4]['b'][2][2]"],
'values_changed': ["root[4]['b'][2][1]: 1 ====>> 3"]}
You can use iconSize
like this:
floatingActionButton: FloatingActionButton(
onPressed: () {
// Add your onPressed code here
},
child: IconButton(
icon: isPlaying
? Icon(
Icons.pause_circle_outline,
)
: Icon(
Icons.play_circle_outline,
),
iconSize: 40,
onPressed: () {
setState(() {
isPlaying = !isPlaying;
});
},
),
),
I looked at a lot of these solutions and didn't like many of them. Mostly because the annoying step of having to identify your known hosts. That and JSCH is at a ridiculously low level relative to the scp command.
I found a library that doesn't require this but it's bundled up and used as a command line tool. https://code.google.com/p/scp-java-client/
I looked through the source code and discovered how to use it without the command line. Here's an example of uploading:
uk.co.marcoratto.scp.SCP scp = new uk.co.marcoratto.scp.SCP(new uk.co.marcoratto.scp.listeners.SCPListenerPrintStream());
scp.setUsername("root");
scp.setPassword("blah");
scp.setTrust(true);
scp.setFromUri(file.getAbsolutePath());
scp.setToUri("root@host:/path/on/remote");
scp.execute();
The biggest downside is that it's not in a maven repo (that I could find). But, the ease of use is worth it to me.
I was working with spring boot jpa and fixed by implementing @EnableTransactionManagement
Simple, make a simple asp page with the designer (just for the beginning) Lets say the body is something like this:
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
<p>
<asp:Button ID="Button1" runat="server" Text="Button" />
</p>
</form>
</body>
Great, now every asp object IS an object. So you can access it in the asp's CS code. The asp's CS code is triggered by events (mostly). The class will probably inherit from System.Web.UI.Page
If you go to the cs file of the asp page, you'll see a protected void Page_Load(object sender, EventArgs e) ... That's the load event, you can use that to populate data into your objects when the page loads.
Now, go to the button in your designer (Button1) and look at its properties, you can design it, or add events from there. Just change to the events view, and create a method for the event.
The button is a web control Button Add a Click event to the button call it Button1Click:
void Button1Click(Object sender,EventArgs e) { }
Now when you click the button, this method will be called. Because ASP is object oriented, you can think of the page as the actual class, and the objects will hold the actual current data.
So if for example you want to access the text in TextBox1
you just need to call that object in the C# code:
String firstBox = TextBox1.Text;
In the same way you can populate the objects when event occur.
Now that you have the data the user posted in the textboxes , you can use regular C# SQL connections to add the data to your database.
When someone asks for "the number of processors/cores" there are 2 answers being requested. The number of "processors" would be the physical number installed in sockets on the machine.
The number of "cores" would be physical cores. Hyperthreaded (virtual) cores would not be included (at least to my mind). As someone who writes a lot of programs with thread pools, you really need to know the count of physical cores vs cores/hyperthreads. That said, you can modify the following script to get the answers that you need.
#!/bin/bash
MODEL=`cat /cpu/procinfo | grep "model name" | sort | uniq`
ALL=`cat /proc/cpuinfo | grep "bogo" | wc -l`
PHYSICAL=`cat /proc/cpuinfo | grep "physical id" | sort | uniq | wc -l`
CORES=`cat /proc/cpuinfo | grep "cpu cores" | sort | uniq | cut -d':' -f2`
PHY_CORES=$(($PHYSICAL * $CORES))
echo "Type $MODEL"
echo "Processors $PHYSICAL"
echo "Physical cores $PHY_CORES"
echo "Including hyperthreading cores $ALL"
The result on a machine with 2 model Xeon X5650 physical processors each with 6 physical cores that also support hyperthreading:
Type model name : Intel(R) Xeon(R) CPU X5650 @ 2.67GHz
Processors 2
Physical cores 12
Including hyperthreading cores 24
On a machine with 2 mdeol Xeon E5472 processors each with 4 physical cores that doesn't support hyperthreading
Type model name : Intel(R) Xeon(R) CPU E5472 @ 3.00GHz
Processors 2
Physical cores 8
Including hyperthreading cores 8
You need to import the module datetime
first:
>>> import datetime
After that it works:
>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2013, 11, 12)
There are many ways to download files. Following I will post most common ways; it is up to you to decide which method is better for your app.
AsyncTask
and show the download progress in a dialogThis method will allow you to execute some background processes and update the UI at the same time (in this case, we'll update a progress bar).
Imports:
import android.os.PowerManager;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
This is an example code:
// declare the dialog as a member field of your activity
ProgressDialog mProgressDialog;
// instantiate it within the onCreate method
mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
// execute this when the downloader must be fired
final DownloadTask downloadTask = new DownloadTask(YourActivity.this);
downloadTask.execute("the url to the file you want to download");
mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true); //cancel the task
}
});
The AsyncTask
will look like this:
// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
@Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
The method above (doInBackground
) runs always on a background thread. You shouldn't do any UI tasks there. On the other hand, the onProgressUpdate
and onPreExecute
run on the UI thread, so there you can change the progress bar:
@Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mProgressDialog.show();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
@Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null)
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
}
For this to run, you need the WAKE_LOCK permission.
<uses-permission android:name="android.permission.WAKE_LOCK" />
The big question here is: how do I update my activity from a service?. In the next example we are going to use two classes you may not be aware of: ResultReceiver
and IntentService
. ResultReceiver
is the one that will allow us to update our thread from a service; IntentService
is a subclass of Service
which spawns a thread to do background work from there (you should know that a Service
runs actually in the same thread of your app; when you extends Service
, you must manually spawn new threads to run CPU blocking operations).
Download service can look like this:
public class DownloadService extends IntentService {
public static final int UPDATE_PROGRESS = 8344;
public DownloadService() {
super("DownloadService");
}
@Override
protected void onHandleIntent(Intent intent) {
String urlToDownload = intent.getStringExtra("url");
ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
try {
//create url and connect
URL url = new URL(urlToDownload);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(connection.getInputStream());
String path = "/sdcard/BarcodeScanner-debug.apk" ;
OutputStream output = new FileOutputStream(path);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
Bundle resultData = new Bundle();
resultData.putInt("progress" ,(int) (total * 100 / fileLength));
receiver.send(UPDATE_PROGRESS, resultData);
output.write(data, 0, count);
}
// close streams
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
Bundle resultData = new Bundle();
resultData.putInt("progress" ,100);
receiver.send(UPDATE_PROGRESS, resultData);
}
}
Add the service to your manifest:
<service android:name=".DownloadService"/>
And the activity will look like this:
// initialize the progress dialog like in the first example
// this is how you fire the downloader
mProgressDialog.show();
Intent intent = new Intent(this, DownloadService.class);
intent.putExtra("url", "url of the file to download");
intent.putExtra("receiver", new DownloadReceiver(new Handler()));
startService(intent);
Here is were ResultReceiver
comes to play:
private class DownloadReceiver extends ResultReceiver{
public DownloadReceiver(Handler handler) {
super(handler);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == DownloadService.UPDATE_PROGRESS) {
int progress = resultData.getInt("progress"); //get the progress
dialog.setProgress(progress);
if (progress == 100) {
dialog.dismiss();
}
}
}
}
Groundy is a library that basically helps you run pieces of code in a background service, and it is based on the ResultReceiver
concept shown above. This library is deprecated at the moment. This is how the whole code would look like:
The activity where you are showing the dialog...
public class MainActivity extends Activity {
private ProgressDialog mProgressDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.btn_download).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String url = ((EditText) findViewById(R.id.edit_url)).getText().toString().trim();
Bundle extras = new Bundler().add(DownloadTask.PARAM_URL, url).build();
Groundy.create(DownloadExample.this, DownloadTask.class)
.receiver(mReceiver)
.params(extras)
.queue();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
});
}
private ResultReceiver mReceiver = new ResultReceiver(new Handler()) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
switch (resultCode) {
case Groundy.STATUS_PROGRESS:
mProgressDialog.setProgress(resultData.getInt(Groundy.KEY_PROGRESS));
break;
case Groundy.STATUS_FINISHED:
Toast.makeText(DownloadExample.this, R.string.file_downloaded, Toast.LENGTH_LONG);
mProgressDialog.dismiss();
break;
case Groundy.STATUS_ERROR:
Toast.makeText(DownloadExample.this, resultData.getString(Groundy.KEY_ERROR), Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
break;
}
}
};
}
A GroundyTask
implementation used by Groundy to download the file and show the progress:
public class DownloadTask extends GroundyTask {
public static final String PARAM_URL = "com.groundy.sample.param.url";
@Override
protected boolean doInBackground() {
try {
String url = getParameters().getString(PARAM_URL);
File dest = new File(getContext().getFilesDir(), new File(url).getName());
DownloadUtils.downloadFile(getContext(), url, dest, DownloadUtils.getDownloadListenerForTask(this));
return true;
} catch (Exception pokemon) {
return false;
}
}
}
And just add this to the manifest:
<service android:name="com.codeslap.groundy.GroundyService"/>
It couldn't be easier I think. Just grab the latest jar from Github and you are ready to go. Keep in mind that Groundy's main purpose is to make calls to external REST apis in a background service and post results to the UI with easily. If you are doing something like that in your app, it could be really useful.
DownloadManager
class (GingerBread
and newer only)GingerBread brought a new feature, DownloadManager
, which allows you to download files easily and delegate the hard work of handling threads, streams, etc. to the system.
First, let's see a utility method:
/**
* @param context used to check the device version and DownloadManager information
* @return true if the download manager is available
*/
public static boolean isDownloadManagerAvailable(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
return true;
}
return false;
}
Method's name explains it all. Once you are sure DownloadManager
is available, you can do something like this:
String url = "url you want to download";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Some descrition");
request.setTitle("Some title");
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "name-of-the-file.ext");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
Download progress will be showing in the notification bar.
First and second methods are just the tip of the iceberg. There are lots of things you have to keep in mind if you want your app to be robust. Here is a brief list:
INTERNET
and WRITE_EXTERNAL_STORAGE
); also ACCESS_NETWORK_STATE
if you want to check internet availability.Unless you need detailed control of the download process, then consider using DownloadManager
(3) because it already handles most of the items listed above.
But also consider that your needs may change. For example, DownloadManager
does no response caching. It will blindly download the same big file multiple times. There's no easy way to fix it after the fact. Where if you start with a basic HttpURLConnection
(1, 2), then all you need is to add an HttpResponseCache
. So the initial effort of learning the basic, standard tools can be a good investment.
This class was deprecated in API level 26. ProgressDialog is a modal dialog, which prevents the user from interacting with the app. Instead of using this class, you should use a progress indicator like ProgressBar, which can be embedded in your app's UI. Alternatively, you can use a notification to inform the user of the task's progress. For more details Link
<?php
// Initialize the session.
session_start();
// Unset all of the session variables.
unset($_SESSION['username']);
// Finally, destroy the session.
session_destroy();
// Include URL for Login page to login again.
header("Location: login.php");
exit;
?>
I usually use Criteria when I don't know what the inputs will be used on which pieces of data. Like on a search form where the user can enter any of 1 to 50 items and I don't know what they will be searching for. It is very easy to just append more to the criteria as I go through checking for what the user is searching for. I think it would be a little more troublesome to put an HQL query in that circumstance. HQL is great though when I know exactly what I want.
I know it's not an exact answer to the OP, but as answers have already be given...
Do you really need to do this in PHP ?
What I mean is : if you need to convert a lot of images, doing it in PHP might not be the best way : you'll be confronted to memory_limit
, max_execution_time
, ...
I would also say GD might not get you the best quality/size ratio ; but not sure about that (if you do a comparison between GD and other solutions, I am very interested by the results ;-) )
Another approach, not using PHP, would be to use Image Magick via the command line (and not as a PHP extension like other people suggested)
You'd have to write a shell-script that goes through all .png
files, and gives them to either
convert
to create a new .jpg
file for each .png
filemogrify
to directly work on the original file and override it.
As a sidenote : if you are doing this directly on your production server, you could put some sleep time between bunches of conversions, to let it cool down a bit sometimes ^^
I've use the shell script + convert
/mogrify
a few times (having them run for something like 10 hours one time), and they do the job really well :-)
Modules Preconditions:
The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (
precondition="managedHandler"
) only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />
If you remove the attribute
precondition="managedHandler"
, Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "
managedHandler
" precondition.To enable all managed modules to run for all requests without configuring each module entry to remove the "
managedHandler
" precondition, use therunAllManagedModulesForAllRequests
property in the<modules>
section:<modules runAllManagedModulesForAllRequests="true" />
When you use this property, the "
managedHandler
" precondition has no effect and all managed modules run for all requests.
Copied from IIS Modules Overview: Preconditions
Here's how i'd do it:
FN=someletters_12345_moreleters.ext
[[ ${FN} =~ _([[:digit:]]{5})_ ]] && NUM=${BASH_REMATCH[1]}
Explanation:
Bash-specific:
[[ ]]
indicates a conditional expression=~
indicates the condition is a regular expression&&
chains the commands if the prior command was successfulRegular Expressions (RE): _([[:digit:]]{5})_
_
are literals to demarcate/anchor matching boundaries for the string being matched()
create a capture group[[:digit:]]
is a character class, i think it speaks for itself{5}
means exactly five of the prior character, class (as in this example), or group must matchIn english, you can think of it behaving like this: the FN
string is iterated character by character until we see an _
at which point the capture group is opened and we attempt to match five digits. If that matching is successful to this point, the capture group saves the five digits traversed. If the next character is an _
, the condition is successful, the capture group is made available in BASH_REMATCH
, and the next NUM=
statement can execute. If any part of the matching fails, saved details are disposed of and character by character processing continues after the _
. e.g. if FN
where _1 _12 _123 _1234 _12345_
, there would be four false starts before it found a match.
Try this command
msiexec /x {product-id} /qr
How to get the First and Last Record time different in sql server....
....
Select EmployeeId,EmployeeName,AttendenceDate,MIN(Intime) as Intime ,MAX(OutTime) as OutTime,
DATEDIFF(MINUTE, MIN(Intime), MAX(OutTime)) as TotalWorkingHours
FROM ViewAttendenceReport WHERE AttendenceDate >='1/20/2020 12:00:00 AM' AND AttendenceDate <='1/20/2020 23:59:59 PM'
GROUP BY EmployeeId,EmployeeName,AttendenceDate;
The URL http://fakedomain.com/smilemachine/html.css
in your <link>
Tag is wrong. File not Found.
If your list got large enough and you only expected to find the value in a sparse number of indices, consider that this code could execute much faster because you don't have to iterate every value in the list.
lookingFor = 1
i = 0
index = 0
try:
while i < len(testlist):
index = testlist.index(lookingFor,i)
i = index + 1
print index
except ValueError: #testlist.index() cannot find lookingFor
pass
If you expect to find the value a lot you should probably just append "index" to a list and print the list at the end to save time per iteration.
I added this to my package.json:
"build": "npm build",
"clean": "rm -rf node_modules",
"reinstall": "npm run clean && npm install",
"rebuild": "npm run clean && npm install && npm run build",
Seems to work well.
$fname = str_replace('/','',$fname);
Since users might use the slash to separate two words it would be better to replace with a dash instead of NULL
?his is a working code and it works fine:
var els = document.getElementsByTagName('input'), i;
var invnum = new Array();
var k = els.length;
for(i = 0; i < k; i++){invnum.push(new Array(els[i].id,els[i].value))}
Another easy method in Netbeans is also avaiable here, There are libraries inside Netbeans itself,where the solutions for this type of situations are available.Select the relevant one as well.It is much easier.After doing the prescribed steps in the link,please restart Netbeans.
Step1:- Select Tools->Palette->Swing/AWT Components
Step2:- Click 'Add from JAR'in Palette Manager
Step3:- Browse to [NETBEANS HOME]\ide\modules\ext and select swingx-0.9.5.jar
Step4:- This will bring up a list of all the components available for the palette. Lots of goodies here! Select JXDatePicker.
Step5:- Select Swing Controls & click finish
Step6:- Restart NetBeans IDE and see the magic :)
You can do this:
E[] arr = (E[])new Object[INITIAL_ARRAY_LENGTH];
This is one of the suggested ways of implementing a generic collection in Effective Java; Item 26. No type errors, no need to cast the array repeatedly. However this triggers a warning because it is potentially dangerous, and should be used with caution. As detailed in the comments, this Object[]
is now masquerading as our E[]
type, and can cause unexpected errors or ClassCastException
s if used unsafely.
As a rule of thumb, this behavior is safe as long as the cast array is used internally (e.g. to back a data structure), and not returned or exposed to client code. Should you need to return an array of a generic type to other code, the reflection Array
class you mention is the right way to go.
Worth mentioning that wherever possible, you'll have a much happier time working with List
s rather than arrays if you're using generics. Certainly sometimes you don't have a choice, but using the collections framework is far more robust.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception {
ProcessBuilder pb = new ProcessBuilder("script.bat");
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader logReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String logLine = null;
while ( (logLine = logReader.readLine()) != null) {
System.out.println("Script output: " + logLine);
}
}
}
By using this line: pb.redirectErrorStream(true);
we can combine InputStream and ErrorStream
Here is the code
.showme{ _x000D_
display: none;_x000D_
}_x000D_
.showhim:hover .showme{_x000D_
display : block;_x000D_
}_x000D_
.showhim:hover .ok{_x000D_
display : none;_x000D_
}
_x000D_
<div class="showhim">_x000D_
HOVER ME_x000D_
<div class="showme">hai</div>_x000D_
<div class="ok">ok</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
You could use substr, I guess:
$string2 = substr($string1, 0, 100);
or mb_substr for multi-byte strings:
$string2 = mb_substr($string1, 0, 100);
You could create a function wich uses this function and appends for instance '...'
to indicate that it was shortened. (I guess there's allready a hundred similar replies when this is posted...)
David Bradshaw wrote a nice little library that solves this problem. It can be used with or without jQuery.
Available here: https://github.com/davidjbradshaw/imagemap-resizer
Use the string's .replace
method with a regex of \D
, which is a shorthand character class that matches all non-digits:
myString = myString.replace(/\D/g,'');
Make sure you have qmake in your path (which qmake), and that it works (qmake -v) (IF you have to kill it with ctr-c then there is something wrong with your environment).
Then follow this: http://developer.qt.nokia.com/doc/qt-4.8/gettingstartedqt.html
use google Guava and do it in 2 lines:
import java.util.Map;
import com.google.common.base.Splitter;
public class Parser {
public static void main(String... args) {
String uri = "https://google.com.ua/oauth/authorize?client_id=SS&response_type=code&scope=N_FULL&access_type=offline&redirect_uri=http://localhost/Callback";
String query = uri.split("\\?")[1];
final Map<String, String> map = Splitter.on('&').trimResults().withKeyValueSeparator('=').split(query);
System.out.println(map);
}
}
which gives you
{client_id=SS, response_type=code, scope=N_FULL, access_type=offline, redirect_uri=http://localhost/Callback}
One way, using regular expressions:
>>> s = "how much for the maple syrup? $20.99? That's ridiculous!!!"
>>> re.sub(r'[^\w]', ' ', s)
'how much for the maple syrup 20 99 That s ridiculous '
\w
will match alphanumeric characters and underscores
[^\w]
will match anything that's not alphanumeric or underscore
This is the error line:
if (called_from.equalsIgnoreCase("add")) { --->38th error line
This means that called_from
is null. Simple check if it is null above:
String called_from = getIntent().getStringExtra("called");
if(called_from == null) {
called_from = "empty string";
}
if (called_from.equalsIgnoreCase("add")) {
// do whatever
} else {
// do whatever
}
That way, if called_from
is null, it'll execute the else
part of your if statement.
As discussed, there are several ways to search:
/pattern
?pattern
* (and g*, which I sometimes use in macros)
# (and g#)
plus, navigating prev/next with N and n.
You can also edit/recall your search history by pulling up the search prompt with /
and then cycle with C-p
/C-n
. Even more useful is q/
, which takes you to a window where you can navigate the search history.
Also for consideration is the all-important 'hlsearch'
(type :hls
to enable). This makes it much easier to find multiple instances of your pattern. You might even want make your matches extra bright with something like:
hi Search ctermfg=yellow ctermbg=red guifg=...
But then you might go crazy with constant yellow matches all over your screen. So you’ll often find yourself using :noh
. This is so common that a mapping is in order:
nmap <leader>z :noh<CR>
I easily remember this one as z
since I used to constantly type /zz<CR>
(which is a fast-to-type uncommon occurrence) to clear my highlighting. But the :noh
mapping is way better.
Following worked for me:
If you get the following error In order to install Windows Azure Active Directory Module for Windows PowerShell, you must have Microsoft Online Services Sign-In Assistant version 7.0 or greater installed on this computer, then install the Microsoft Online Services Sign-In Assistant for IT Professionals BETA: http://www.microsoft.com/en-us/download/details.aspx?id=39267
C:\Windows\System32\WindowsPowerShell\v1.0\Modules\
to the folder
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\
https://stackoverflow.com/a/16018733/5810078.
(But I have actually copied all the possible files from
C:\Windows\System32\WindowsPowerShell\v1.0\
to
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\
(For copying you need to alter the security permissions of that folder))
Using try/except is the best way to test for a variable's existence. But there's almost certainly a better way of doing whatever it is you're doing than setting/testing global variables.
For example, if you want to initialize a module-level variable the first time you call some function, you're better off with code something like this:
my_variable = None
def InitMyVariable():
global my_variable
if my_variable is None:
my_variable = ...
I think you are looking for this function:
http://doc.qt.io/qt-5/qdatetime.html#toTime_t
uint QDateTime::toTime_t () const
Returns the datetime as the number of seconds that have passed since 1970-01-01T00:00:00, > Coordinated Universal Time (Qt::UTC).
On systems that do not support time zones, this function will behave as if local time were Qt::UTC.
See also setTime_t().
First I would suggest putting a Log in each case of your switch to be sure that your code is being called.
Then I would check that the layouts are actually different.
Interestingly enough, very often len(unique())
is a few times (3x-15x) faster than nunique()
.
Updated Answer:
KeyDown
KeyPress
KeyUp
This is the behavior in both addEventListener
and jQuery
.
https://jsbin.com/vebaholamu/1/edit?js,console,output <-- try example
(answer has been edited with correct response, screenshot & example)
There's a good open source version called Obfuscar. Seems to work fine. Types, properties, fields, methods can be excluded. The original is here: https://code.google.com/p/obfuscar/, but since it seems to not be updated anymore
Two easy ways:
Using hive conf
hive> set USER_NAME='FOO';
hive> select * from foobar where NAME = '${hiveconf:USER_NAME}';
Using hive vars
On your CLI set vars and then use them in hive
set hivevar:USER_NAME='FOO';
hive> select * from foobar where NAME = '${USER_NAME}';
hive> select * from foobar where NAME = '${hivevar:USER_NAME}';
Documentation: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+VariableSubstitution
If I understand you correctly, You have two folders, one houses your php script that you want to include
into a file that is in another folder?
If this is the case, you just have to follow the trail the right way. Let's assume your folders are set up like this:
root
includes
php_scripts
script.php
blog
content
index.php
If this is the proposed folder structure, and you are trying to include the "Script.php" file into your "index.php" folder, you need to include it this way:
include("../../../includes/php_scripts/script.php");
The way I do it is visual. I put my mouse pointer on the index.php (looking at the file structure), then every time I go UP a folder, I type another "../" Then you have to make sure you go UP the folder structure ABOVE the folders that you want to start going DOWN into. After that, it's just normal folder hierarchy.
As for example usages of unsigned char:
unsigned char
is often used in computer graphics, which very often (though not always) assigns a single byte to each colour component. It is common to see an RGB (or RGBA) colour represented as 24 (or 32) bits, each an unsigned char
. Since unsigned char
values fall in the range [0,255], the values are typically interpreted as:
So you would end up with RGB red as (255,0,0) -> (100% red, 0% green, 0% blue).
Why not use a signed char
? Arithmetic and bit shifting becomes problematic. As explained already, a signed char
's range is essentially shifted by -128. A very simple and naive (mostly unused) method for converting RGB to grayscale is to average all three colour components, but this runs into problems when the values of the colour components are negative. Red (255, 0, 0) averages to (85, 85, 85) when using unsigned char
arithmetic. However, if the values were signed char
s (127,-128,-128), we would end up with (-99, -99, -99), which would be (29, 29, 29) in our unsigned char
space, which is incorrect.
In the definition of your Card
class, a declaration for a default construction appears:
class Card
{
// ...
Card(); // <== Declaration of default constructor!
// ...
};
But no corresponding definition is given. In fact, this function definition (from card.cpp
):
void Card() {
//nothing
}
Does not define a constructor, but rather a global function called Card
that returns void
. You probably meant to write this instead:
Card::Card() {
//nothing
}
Unless you do that, since the default constructor is declared but not defined, the linker will produce error about undefined references when a call to the default constructor is found.
The same applies to your constructor accepting two arguments. This:
void Card(Card::Rank rank, Card::Suit suit) {
cardRank = rank;
cardSuit = suit;
}
Should be rewritten into this:
Card::Card(Card::Rank rank, Card::Suit suit) {
cardRank = rank;
cardSuit = suit;
}
And the same also applies for other member functions: it seems you did not add the Card::
qualifier before the member function names in their definitions. Without it, those functions are global functions rather than definitions of member functions.
Your destructor, on the other hand, is declared but never defined. Just provide a definition for it in card.cpp
:
Card::~Card() { }
If you want to check the changed files you need to take care of many small things like which will be best to use , like if you want to check which of the files changed just type
git status -- it will show the files with changes
then if you want to know what changes are to be made it can be checked in ways ,
git diff -- will show all the changes in all files
it is good only when only one file is modified
and if you want to check particular file then use
git diff
By design, getRequestURL()
gives you the full URL, missing only the query string.
In HttpServletRequest
, you can get individual parts of the URI using the methods below:
// Example: http://myhost:8080/people?lastname=Fox&age=30
String uri = request.getScheme() + "://" + // "http" + "://
request.getServerName() + // "myhost"
":" + // ":"
request.getServerPort() + // "8080"
request.getRequestURI() + // "/people"
"?" + // "?"
request.getQueryString(); // "lastname=Fox&age=30"
.getScheme()
will give you "https"
if it was a https://domain
request..getServerName()
gives domain
on http(s)://domain
..getServerPort()
will give you the port.String uri = request.getScheme() + "://" +
request.getServerName() +
("http".equals(request.getScheme()) && request.getServerPort() == 80 || "https".equals(request.getScheme()) && request.getServerPort() == 443 ? "" : ":" + request.getServerPort() ) +
request.getRequestURI() +
(request.getQueryString() != null ? "?" + request.getQueryString() : "");
This snippet above will get the full URI, hiding the port if the default one was used, and not adding the "?"
and the query string if the latter was not provided.
Note, that if your request passes through a proxy, you need to look at the X-Forwarded-Proto
header since the scheme might be altered:
request.getHeader("X-Forwarded-Proto")
Also, a common header is X-Forwarded-For
, which show the original request IP instead of the proxys IP.
request.getHeader("X-Forwarded-For")
If you are responsible for the configuration of the proxy/load balancer yourself, you need to ensure that these headers are set upon forwarding.
On Debian 9 I had to:
$ sudo update-ca-certificates --fresh
$ export SSL_CERT_DIR=/etc/ssl/certs
I'm not sure why, but this enviroment variable was never set.
var createPassword = function() {
var passAt = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
var passArray = Array.from({length: 15})
return passArray.map(function(_, index) {
return index % 4 == 3 ? '-' : passAt.charAt(Math.random() * passAt.length)
}).join('')
}
result like:
L5X-La0-bN0-UQO
9eW-svG-OdS-8Xf
ick-u73-2s0-TMX
5ri-PRP-MNO-Z1j
You can use the System.Diagnostics.Debug.Write
or System.Runtime.InteropServices
method to write messages to the Output Window.
\s
means "one space", and \s+
means "one or more spaces".
But, because you're using the /g
flag (replace all occurrences) and replacing with the empty string, your two expressions have the same effect.
I was having the same problem while running bulk tests for an assignment. Turns out when I relocated some iostream operations (printing to console) from class constructor to a method in class it was solved.
I assume it was something to do with iostream manipulations in the constructor.
Here is the fix:
// Before
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {
cout << "Some text I was printing.." << endl;
};
// After
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {
};
Please feel free to explain more what the error is behind the scenes since it goes beyond my cpp knowledge.
When I had this same problem with mysql5.6.20 installed with Homebrew, I solved it by going into my.cnf
nano /usr/local/Cellar/mysql/5.6.20_1/my.cnf
Find the line that looks like so:
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
Comment above line out and restart mysql server
mysql.server restart
Error gone!
Try to use https in repo url: https://repo1.maven.org/maven2
If you use jdk1.7 or above and your network restrict protocols to newer TLS version then enable TLS1.2: -Dhttps.protocols=TLSv1,TLSv1.1,TLSv1.2
On Windows, I got this error when running under a non-administrator command prompt. When I ran this as administrator, the error went away.
Consider an array of pointers. A pointer is really an address; so when you initialize the array, you are analogously telling the computer, "allocate this block of memory to hold these X numbers (which are addresses of other items)." Then if you change one of the pointers, you are just changing what it points to; it is still a numerical address which is itself sitting in the same spot.
A reference is analogous to an alias. If you were to declare an array of references, you would basically be telling the computer, "allocate this amorphous blob of memory consisting of all these different items scattered around."
You have to close all tags like , etc for this to not show.
Just try Clean Project & Rebuild Project.
How do I check if an element exists
if ($("#mydiv").length){ }
If it is 0
, it will evaluate to false
, anything more than that true
.
There is no need for a greater than, less than comparison.
Dependency
dependencies {
implementation 'com.squareup.picasso:picasso:2.71828'
}
//Java Code for Image Loading into imageView
Picasso.get().load(werURL).into(imageView);
An inner class has access to all members of the outer class, but it does not have an implicit reference to a parent class instance (unlike some weirdness with Java). So if you pass a reference to the outer class to the inner class, it can reference anything in the outer class instance.
If You're using JSX inside a function with curly braces you need to modify it to parenthesis.
Wrong Code
return this.props.todos.map((todo) => {
<h3> {todo.author} </h3>;
});
Correct Code
//Change Curly Brace To Paranthesis change {} to => ()
return this.props.todos.map((todo) => (
<h3> {todo.author} </h3>;
));
Old answer that is not correct:
arr.sort((a, b) => a.name > b.name)
UPDATE
From Beauchamp's comment:
arr.sort((a, b) => a.name < b.name ? -1 : (a.name > b.name ? 1 : 0))
More readable format:
arr.sort((a, b) => {
if (a.name < b.name) return -1
return a.name > b.name ? 1 : 0
})
Without nested ternaries:
arr.sort((a, b) => a.name < b.name ? - 1 : Number(a.name > b.name))
Explanation: Number()
will cast true
to 1
and false
to 0
.
import React from 'react'; <--as normal
import PropTypes from 'prop-types'; <--add this as a second line
App.propTypes = {
monkey: PropTypes.string, <--omit "React."
cat: PropTypes.number.isRequired <--omit "React."
};
Wrong: React.PropTypes.string
Right: PropTypes.string
late answer, but use this package to to check. Package Name: data_connection_checker
in you pubspec.yuml file:
dependencies:
data_connection_checker: ^0.3.4
create a file called connection.dart or any name you want. import the package:
import 'package:data_connection_checker/data_connection_checker.dart';
check if there is internet connection or not:
print(await DataConnectionChecker().hasConnection);
you can do it in two ways using
Serializable
Parcelable.
This examle will show you how to implement it with serializable
class Customer implements Serializable
{
// properties, getter setters & constructor
}
// This is your custom object
Customer customer = new Customer(name, address, zip);
Intent intent = new Intent();
intent.setClass(SourceActivity.this, TargetActivity.this);
intent.putExtra("customer", customer);
startActivity(intent);
// Now in your TargetActivity
Bundle extras = getIntent().getExtras();
if (extras != null)
{
Customer customer = (Customer)extras.getSerializable("customer");
// do something with the customer
}
Now have a look at this. This link will give you a brief overview of how to implement it with Parcelable.
Look at this.. This discussion will let you know which is much better way to implement it.
Thanks.
If your grep supports -R
, do:
grep -R 'string' dir/
If not, then use find
:
find dir/ -type f -exec grep -H 'string' {} +
Try using this. Instead of zmq, we can use any package instead of zmq.
sudo apt-get install python3-pip
sudo apt-get update
python3 -m pip install zmq
I was was not able to install this zmq package in my docker image because of the same issue i was getting. So tried this as another way to install and it worked fine for me.
The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).
You can use the GUI to do the installation, or you can script the installation of msbuild:
vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet
Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:
You can find documentation about the other available CLI switches here.
The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet
there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin
.
If you don't see them there, try running without --quiet
to see any error messages that may occur during installation.
Try with your IP Address , I think you can access it by internet.
Trying to do the same thing consistently with arrays and hashes might just be a code smell, but, at the risk of my being branded as a codorous half-monkey-patcher, if you're looking for consistent behaviour, would this do the trick?:
class Hash
def each_pairwise
self.each { | x, y |
yield [x, y]
}
end
end
class Array
def each_pairwise
self.each_with_index { | x, y |
yield [y, x]
}
end
end
["a","b","c"].each_pairwise { |x,y|
puts "#{x} => #{y}"
}
{"a" => "Aardvark","b" => "Bogle","c" => "Catastrophe"}.each_pairwise { |x,y|
puts "#{x} => #{y}"
}
How about
SELECT id, COUNT(IF status=42 THEN 1 ENDIF) AS cnt
FROM table
GROUP BY table
Shorter than CASE
:)
Works because COUNT()
doesn't count null values, and IF
/CASE
return null when condition is not met and there is no ELSE
.
I think it's better than using SUM()
.